* c-c++-common/ubsan/float-cast-overflow-6.c: Add i?86-*-* target.
[official-gcc.git] / gcc / tree-scalar-evolution.c
blob4d038969bab19a372d245c68a9827b0e054a0fba
1 /* Scalar evolution detector.
2 Copyright (C) 2003-2014 Free Software Foundation, Inc.
3 Contributed by Sebastian Pop <s.pop@laposte.net>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
22 Description:
24 This pass analyzes the evolution of scalar variables in loop
25 structures. The algorithm is based on the SSA representation,
26 and on the loop hierarchy tree. This algorithm is not based on
27 the notion of versions of a variable, as it was the case for the
28 previous implementations of the scalar evolution algorithm, but
29 it assumes that each defined name is unique.
31 The notation used in this file is called "chains of recurrences",
32 and has been proposed by Eugene Zima, Robert Van Engelen, and
33 others for describing induction variables in programs. For example
34 "b -> {0, +, 2}_1" means that the scalar variable "b" is equal to 0
35 when entering in the loop_1 and has a step 2 in this loop, in other
36 words "for (b = 0; b < N; b+=2);". Note that the coefficients of
37 this chain of recurrence (or chrec [shrek]) can contain the name of
38 other variables, in which case they are called parametric chrecs.
39 For example, "b -> {a, +, 2}_1" means that the initial value of "b"
40 is the value of "a". In most of the cases these parametric chrecs
41 are fully instantiated before their use because symbolic names can
42 hide some difficult cases such as self-references described later
43 (see the Fibonacci example).
45 A short sketch of the algorithm is:
47 Given a scalar variable to be analyzed, follow the SSA edge to
48 its definition:
50 - When the definition is a GIMPLE_ASSIGN: if the right hand side
51 (RHS) of the definition cannot be statically analyzed, the answer
52 of the analyzer is: "don't know".
53 Otherwise, for all the variables that are not yet analyzed in the
54 RHS, try to determine their evolution, and finally try to
55 evaluate the operation of the RHS that gives the evolution
56 function of the analyzed variable.
58 - When the definition is a condition-phi-node: determine the
59 evolution function for all the branches of the phi node, and
60 finally merge these evolutions (see chrec_merge).
62 - When the definition is a loop-phi-node: determine its initial
63 condition, that is the SSA edge defined in an outer loop, and
64 keep it symbolic. Then determine the SSA edges that are defined
65 in the body of the loop. Follow the inner edges until ending on
66 another loop-phi-node of the same analyzed loop. If the reached
67 loop-phi-node is not the starting loop-phi-node, then we keep
68 this definition under a symbolic form. If the reached
69 loop-phi-node is the same as the starting one, then we compute a
70 symbolic stride on the return path. The result is then the
71 symbolic chrec {initial_condition, +, symbolic_stride}_loop.
73 Examples:
75 Example 1: Illustration of the basic algorithm.
77 | a = 3
78 | loop_1
79 | b = phi (a, c)
80 | c = b + 1
81 | if (c > 10) exit_loop
82 | endloop
84 Suppose that we want to know the number of iterations of the
85 loop_1. The exit_loop is controlled by a COND_EXPR (c > 10). We
86 ask the scalar evolution analyzer two questions: what's the
87 scalar evolution (scev) of "c", and what's the scev of "10". For
88 "10" the answer is "10" since it is a scalar constant. For the
89 scalar variable "c", it follows the SSA edge to its definition,
90 "c = b + 1", and then asks again what's the scev of "b".
91 Following the SSA edge, we end on a loop-phi-node "b = phi (a,
92 c)", where the initial condition is "a", and the inner loop edge
93 is "c". The initial condition is kept under a symbolic form (it
94 may be the case that the copy constant propagation has done its
95 work and we end with the constant "3" as one of the edges of the
96 loop-phi-node). The update edge is followed to the end of the
97 loop, and until reaching again the starting loop-phi-node: b -> c
98 -> b. At this point we have drawn a path from "b" to "b" from
99 which we compute the stride in the loop: in this example it is
100 "+1". The resulting scev for "b" is "b -> {a, +, 1}_1". Now
101 that the scev for "b" is known, it is possible to compute the
102 scev for "c", that is "c -> {a + 1, +, 1}_1". In order to
103 determine the number of iterations in the loop_1, we have to
104 instantiate_parameters (loop_1, {a + 1, +, 1}_1), that gives after some
105 more analysis the scev {4, +, 1}_1, or in other words, this is
106 the function "f (x) = x + 4", where x is the iteration count of
107 the loop_1. Now we have to solve the inequality "x + 4 > 10",
108 and take the smallest iteration number for which the loop is
109 exited: x = 7. This loop runs from x = 0 to x = 7, and in total
110 there are 8 iterations. In terms of loop normalization, we have
111 created a variable that is implicitly defined, "x" or just "_1",
112 and all the other analyzed scalars of the loop are defined in
113 function of this variable:
115 a -> 3
116 b -> {3, +, 1}_1
117 c -> {4, +, 1}_1
119 or in terms of a C program:
121 | a = 3
122 | for (x = 0; x <= 7; x++)
124 | b = x + 3
125 | c = x + 4
128 Example 2a: Illustration of the algorithm on nested loops.
130 | loop_1
131 | a = phi (1, b)
132 | c = a + 2
133 | loop_2 10 times
134 | b = phi (c, d)
135 | d = b + 3
136 | endloop
137 | endloop
139 For analyzing the scalar evolution of "a", the algorithm follows
140 the SSA edge into the loop's body: "a -> b". "b" is an inner
141 loop-phi-node, and its analysis as in Example 1, gives:
143 b -> {c, +, 3}_2
144 d -> {c + 3, +, 3}_2
146 Following the SSA edge for the initial condition, we end on "c = a
147 + 2", and then on the starting loop-phi-node "a". From this point,
148 the loop stride is computed: back on "c = a + 2" we get a "+2" in
149 the loop_1, then on the loop-phi-node "b" we compute the overall
150 effect of the inner loop that is "b = c + 30", and we get a "+30"
151 in the loop_1. That means that the overall stride in loop_1 is
152 equal to "+32", and the result is:
154 a -> {1, +, 32}_1
155 c -> {3, +, 32}_1
157 Example 2b: Multivariate chains of recurrences.
159 | loop_1
160 | k = phi (0, k + 1)
161 | loop_2 4 times
162 | j = phi (0, j + 1)
163 | loop_3 4 times
164 | i = phi (0, i + 1)
165 | A[j + k] = ...
166 | endloop
167 | endloop
168 | endloop
170 Analyzing the access function of array A with
171 instantiate_parameters (loop_1, "j + k"), we obtain the
172 instantiation and the analysis of the scalar variables "j" and "k"
173 in loop_1. This leads to the scalar evolution {4, +, 1}_1: the end
174 value of loop_2 for "j" is 4, and the evolution of "k" in loop_1 is
175 {0, +, 1}_1. To obtain the evolution function in loop_3 and
176 instantiate the scalar variables up to loop_1, one has to use:
177 instantiate_scev (block_before_loop (loop_1), loop_3, "j + k").
178 The result of this call is {{0, +, 1}_1, +, 1}_2.
180 Example 3: Higher degree polynomials.
182 | loop_1
183 | a = phi (2, b)
184 | c = phi (5, d)
185 | b = a + 1
186 | d = c + a
187 | endloop
189 a -> {2, +, 1}_1
190 b -> {3, +, 1}_1
191 c -> {5, +, a}_1
192 d -> {5 + a, +, a}_1
194 instantiate_parameters (loop_1, {5, +, a}_1) -> {5, +, 2, +, 1}_1
195 instantiate_parameters (loop_1, {5 + a, +, a}_1) -> {7, +, 3, +, 1}_1
197 Example 4: Lucas, Fibonacci, or mixers in general.
199 | loop_1
200 | a = phi (1, b)
201 | c = phi (3, d)
202 | b = c
203 | d = c + a
204 | endloop
206 a -> (1, c)_1
207 c -> {3, +, a}_1
209 The syntax "(1, c)_1" stands for a PEELED_CHREC that has the
210 following semantics: during the first iteration of the loop_1, the
211 variable contains the value 1, and then it contains the value "c".
212 Note that this syntax is close to the syntax of the loop-phi-node:
213 "a -> (1, c)_1" vs. "a = phi (1, c)".
215 The symbolic chrec representation contains all the semantics of the
216 original code. What is more difficult is to use this information.
218 Example 5: Flip-flops, or exchangers.
220 | loop_1
221 | a = phi (1, b)
222 | c = phi (3, d)
223 | b = c
224 | d = a
225 | endloop
227 a -> (1, c)_1
228 c -> (3, a)_1
230 Based on these symbolic chrecs, it is possible to refine this
231 information into the more precise PERIODIC_CHRECs:
233 a -> |1, 3|_1
234 c -> |3, 1|_1
236 This transformation is not yet implemented.
238 Further readings:
240 You can find a more detailed description of the algorithm in:
241 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.pdf
242 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.ps.gz. But note that
243 this is a preliminary report and some of the details of the
244 algorithm have changed. I'm working on a research report that
245 updates the description of the algorithms to reflect the design
246 choices used in this implementation.
248 A set of slides show a high level overview of the algorithm and run
249 an example through the scalar evolution analyzer:
250 http://cri.ensmp.fr/~pop/gcc/mar04/slides.pdf
252 The slides that I have presented at the GCC Summit'04 are available
253 at: http://cri.ensmp.fr/~pop/gcc/20040604/gccsummit-lno-spop.pdf
256 #include "config.h"
257 #include "system.h"
258 #include "coretypes.h"
259 #include "tree.h"
260 #include "expr.h"
261 #include "gimple-pretty-print.h"
262 #include "predict.h"
263 #include "vec.h"
264 #include "hashtab.h"
265 #include "hash-set.h"
266 #include "machmode.h"
267 #include "tm.h"
268 #include "hard-reg-set.h"
269 #include "input.h"
270 #include "function.h"
271 #include "dominance.h"
272 #include "cfg.h"
273 #include "basic-block.h"
274 #include "tree-ssa-alias.h"
275 #include "internal-fn.h"
276 #include "gimple-expr.h"
277 #include "is-a.h"
278 #include "gimple.h"
279 #include "gimplify.h"
280 #include "gimple-iterator.h"
281 #include "gimplify-me.h"
282 #include "gimple-ssa.h"
283 #include "tree-cfg.h"
284 #include "tree-phinodes.h"
285 #include "stringpool.h"
286 #include "tree-ssanames.h"
287 #include "tree-ssa-loop-ivopts.h"
288 #include "tree-ssa-loop-manip.h"
289 #include "tree-ssa-loop-niter.h"
290 #include "tree-ssa-loop.h"
291 #include "tree-ssa.h"
292 #include "cfgloop.h"
293 #include "tree-chrec.h"
294 #include "tree-affine.h"
295 #include "tree-scalar-evolution.h"
296 #include "dumpfile.h"
297 #include "params.h"
298 #include "tree-ssa-propagate.h"
299 #include "gimple-fold.h"
300 #include "gimplify-me.h"
302 static tree analyze_scalar_evolution_1 (struct loop *, tree, tree);
303 static tree analyze_scalar_evolution_for_address_of (struct loop *loop,
304 tree var);
306 /* The cached information about an SSA name with version NAME_VERSION,
307 claiming that below basic block with index INSTANTIATED_BELOW, the
308 value of the SSA name can be expressed as CHREC. */
310 struct GTY(()) scev_info_str {
311 unsigned int name_version;
312 int instantiated_below;
313 tree chrec;
316 /* Counters for the scev database. */
317 static unsigned nb_set_scev = 0;
318 static unsigned nb_get_scev = 0;
320 /* The following trees are unique elements. Thus the comparison of
321 another element to these elements should be done on the pointer to
322 these trees, and not on their value. */
324 /* The SSA_NAMEs that are not yet analyzed are qualified with NULL_TREE. */
325 tree chrec_not_analyzed_yet;
327 /* Reserved to the cases where the analyzer has detected an
328 undecidable property at compile time. */
329 tree chrec_dont_know;
331 /* When the analyzer has detected that a property will never
332 happen, then it qualifies it with chrec_known. */
333 tree chrec_known;
335 static GTY ((param_is (struct scev_info_str))) htab_t scalar_evolution_info;
338 /* Constructs a new SCEV_INFO_STR structure for VAR and INSTANTIATED_BELOW. */
340 static inline struct scev_info_str *
341 new_scev_info_str (basic_block instantiated_below, tree var)
343 struct scev_info_str *res;
345 res = ggc_alloc<scev_info_str> ();
346 res->name_version = SSA_NAME_VERSION (var);
347 res->chrec = chrec_not_analyzed_yet;
348 res->instantiated_below = instantiated_below->index;
350 return res;
353 /* Computes a hash function for database element ELT. */
355 static inline hashval_t
356 hash_scev_info (const void *elt_)
358 const struct scev_info_str *elt = (const struct scev_info_str *) elt_;
359 return elt->name_version ^ elt->instantiated_below;
362 /* Compares database elements E1 and E2. */
364 static inline int
365 eq_scev_info (const void *e1, const void *e2)
367 const struct scev_info_str *elt1 = (const struct scev_info_str *) e1;
368 const struct scev_info_str *elt2 = (const struct scev_info_str *) e2;
370 return (elt1->name_version == elt2->name_version
371 && elt1->instantiated_below == elt2->instantiated_below);
374 /* Deletes database element E. */
376 static void
377 del_scev_info (void *e)
379 ggc_free (e);
383 /* Get the scalar evolution of VAR for INSTANTIATED_BELOW basic block.
384 A first query on VAR returns chrec_not_analyzed_yet. */
386 static tree *
387 find_var_scev_info (basic_block instantiated_below, tree var)
389 struct scev_info_str *res;
390 struct scev_info_str tmp;
391 PTR *slot;
393 tmp.name_version = SSA_NAME_VERSION (var);
394 tmp.instantiated_below = instantiated_below->index;
395 slot = htab_find_slot (scalar_evolution_info, &tmp, INSERT);
397 if (!*slot)
398 *slot = new_scev_info_str (instantiated_below, var);
399 res = (struct scev_info_str *) *slot;
401 return &res->chrec;
404 /* Return true when CHREC contains symbolic names defined in
405 LOOP_NB. */
407 bool
408 chrec_contains_symbols_defined_in_loop (const_tree chrec, unsigned loop_nb)
410 int i, n;
412 if (chrec == NULL_TREE)
413 return false;
415 if (is_gimple_min_invariant (chrec))
416 return false;
418 if (TREE_CODE (chrec) == SSA_NAME)
420 gimple def;
421 loop_p def_loop, loop;
423 if (SSA_NAME_IS_DEFAULT_DEF (chrec))
424 return false;
426 def = SSA_NAME_DEF_STMT (chrec);
427 def_loop = loop_containing_stmt (def);
428 loop = get_loop (cfun, loop_nb);
430 if (def_loop == NULL)
431 return false;
433 if (loop == def_loop || flow_loop_nested_p (loop, def_loop))
434 return true;
436 return false;
439 n = TREE_OPERAND_LENGTH (chrec);
440 for (i = 0; i < n; i++)
441 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, i),
442 loop_nb))
443 return true;
444 return false;
447 /* Return true when PHI is a loop-phi-node. */
449 static bool
450 loop_phi_node_p (gimple phi)
452 /* The implementation of this function is based on the following
453 property: "all the loop-phi-nodes of a loop are contained in the
454 loop's header basic block". */
456 return loop_containing_stmt (phi)->header == gimple_bb (phi);
459 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
460 In general, in the case of multivariate evolutions we want to get
461 the evolution in different loops. LOOP specifies the level for
462 which to get the evolution.
464 Example:
466 | for (j = 0; j < 100; j++)
468 | for (k = 0; k < 100; k++)
470 | i = k + j; - Here the value of i is a function of j, k.
472 | ... = i - Here the value of i is a function of j.
474 | ... = i - Here the value of i is a scalar.
476 Example:
478 | i_0 = ...
479 | loop_1 10 times
480 | i_1 = phi (i_0, i_2)
481 | i_2 = i_1 + 2
482 | endloop
484 This loop has the same effect as:
485 LOOP_1 has the same effect as:
487 | i_1 = i_0 + 20
489 The overall effect of the loop, "i_0 + 20" in the previous example,
490 is obtained by passing in the parameters: LOOP = 1,
491 EVOLUTION_FN = {i_0, +, 2}_1.
494 tree
495 compute_overall_effect_of_inner_loop (struct loop *loop, tree evolution_fn)
497 bool val = false;
499 if (evolution_fn == chrec_dont_know)
500 return chrec_dont_know;
502 else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
504 struct loop *inner_loop = get_chrec_loop (evolution_fn);
506 if (inner_loop == loop
507 || flow_loop_nested_p (loop, inner_loop))
509 tree nb_iter = number_of_latch_executions (inner_loop);
511 if (nb_iter == chrec_dont_know)
512 return chrec_dont_know;
513 else
515 tree res;
517 /* evolution_fn is the evolution function in LOOP. Get
518 its value in the nb_iter-th iteration. */
519 res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
521 if (chrec_contains_symbols_defined_in_loop (res, loop->num))
522 res = instantiate_parameters (loop, res);
524 /* Continue the computation until ending on a parent of LOOP. */
525 return compute_overall_effect_of_inner_loop (loop, res);
528 else
529 return evolution_fn;
532 /* If the evolution function is an invariant, there is nothing to do. */
533 else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
534 return evolution_fn;
536 else
537 return chrec_dont_know;
540 /* Associate CHREC to SCALAR. */
542 static void
543 set_scalar_evolution (basic_block instantiated_below, tree scalar, tree chrec)
545 tree *scalar_info;
547 if (TREE_CODE (scalar) != SSA_NAME)
548 return;
550 scalar_info = find_var_scev_info (instantiated_below, scalar);
552 if (dump_file)
554 if (dump_flags & TDF_SCEV)
556 fprintf (dump_file, "(set_scalar_evolution \n");
557 fprintf (dump_file, " instantiated_below = %d \n",
558 instantiated_below->index);
559 fprintf (dump_file, " (scalar = ");
560 print_generic_expr (dump_file, scalar, 0);
561 fprintf (dump_file, ")\n (scalar_evolution = ");
562 print_generic_expr (dump_file, chrec, 0);
563 fprintf (dump_file, "))\n");
565 if (dump_flags & TDF_STATS)
566 nb_set_scev++;
569 *scalar_info = chrec;
572 /* Retrieve the chrec associated to SCALAR instantiated below
573 INSTANTIATED_BELOW block. */
575 static tree
576 get_scalar_evolution (basic_block instantiated_below, tree scalar)
578 tree res;
580 if (dump_file)
582 if (dump_flags & TDF_SCEV)
584 fprintf (dump_file, "(get_scalar_evolution \n");
585 fprintf (dump_file, " (scalar = ");
586 print_generic_expr (dump_file, scalar, 0);
587 fprintf (dump_file, ")\n");
589 if (dump_flags & TDF_STATS)
590 nb_get_scev++;
593 switch (TREE_CODE (scalar))
595 case SSA_NAME:
596 res = *find_var_scev_info (instantiated_below, scalar);
597 break;
599 case REAL_CST:
600 case FIXED_CST:
601 case INTEGER_CST:
602 res = scalar;
603 break;
605 default:
606 res = chrec_not_analyzed_yet;
607 break;
610 if (dump_file && (dump_flags & TDF_SCEV))
612 fprintf (dump_file, " (scalar_evolution = ");
613 print_generic_expr (dump_file, res, 0);
614 fprintf (dump_file, "))\n");
617 return res;
620 /* Helper function for add_to_evolution. Returns the evolution
621 function for an assignment of the form "a = b + c", where "a" and
622 "b" are on the strongly connected component. CHREC_BEFORE is the
623 information that we already have collected up to this point.
624 TO_ADD is the evolution of "c".
626 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
627 evolution the expression TO_ADD, otherwise construct an evolution
628 part for this loop. */
630 static tree
631 add_to_evolution_1 (unsigned loop_nb, tree chrec_before, tree to_add,
632 gimple at_stmt)
634 tree type, left, right;
635 struct loop *loop = get_loop (cfun, loop_nb), *chloop;
637 switch (TREE_CODE (chrec_before))
639 case POLYNOMIAL_CHREC:
640 chloop = get_chrec_loop (chrec_before);
641 if (chloop == loop
642 || flow_loop_nested_p (chloop, loop))
644 unsigned var;
646 type = chrec_type (chrec_before);
648 /* When there is no evolution part in this loop, build it. */
649 if (chloop != loop)
651 var = loop_nb;
652 left = chrec_before;
653 right = SCALAR_FLOAT_TYPE_P (type)
654 ? build_real (type, dconst0)
655 : build_int_cst (type, 0);
657 else
659 var = CHREC_VARIABLE (chrec_before);
660 left = CHREC_LEFT (chrec_before);
661 right = CHREC_RIGHT (chrec_before);
664 to_add = chrec_convert (type, to_add, at_stmt);
665 right = chrec_convert_rhs (type, right, at_stmt);
666 right = chrec_fold_plus (chrec_type (right), right, to_add);
667 return build_polynomial_chrec (var, left, right);
669 else
671 gcc_assert (flow_loop_nested_p (loop, chloop));
673 /* Search the evolution in LOOP_NB. */
674 left = add_to_evolution_1 (loop_nb, CHREC_LEFT (chrec_before),
675 to_add, at_stmt);
676 right = CHREC_RIGHT (chrec_before);
677 right = chrec_convert_rhs (chrec_type (left), right, at_stmt);
678 return build_polynomial_chrec (CHREC_VARIABLE (chrec_before),
679 left, right);
682 default:
683 /* These nodes do not depend on a loop. */
684 if (chrec_before == chrec_dont_know)
685 return chrec_dont_know;
687 left = chrec_before;
688 right = chrec_convert_rhs (chrec_type (left), to_add, at_stmt);
689 return build_polynomial_chrec (loop_nb, left, right);
693 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
694 of LOOP_NB.
696 Description (provided for completeness, for those who read code in
697 a plane, and for my poor 62 bytes brain that would have forgotten
698 all this in the next two or three months):
700 The algorithm of translation of programs from the SSA representation
701 into the chrecs syntax is based on a pattern matching. After having
702 reconstructed the overall tree expression for a loop, there are only
703 two cases that can arise:
705 1. a = loop-phi (init, a + expr)
706 2. a = loop-phi (init, expr)
708 where EXPR is either a scalar constant with respect to the analyzed
709 loop (this is a degree 0 polynomial), or an expression containing
710 other loop-phi definitions (these are higher degree polynomials).
712 Examples:
715 | init = ...
716 | loop_1
717 | a = phi (init, a + 5)
718 | endloop
721 | inita = ...
722 | initb = ...
723 | loop_1
724 | a = phi (inita, 2 * b + 3)
725 | b = phi (initb, b + 1)
726 | endloop
728 For the first case, the semantics of the SSA representation is:
730 | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
732 that is, there is a loop index "x" that determines the scalar value
733 of the variable during the loop execution. During the first
734 iteration, the value is that of the initial condition INIT, while
735 during the subsequent iterations, it is the sum of the initial
736 condition with the sum of all the values of EXPR from the initial
737 iteration to the before last considered iteration.
739 For the second case, the semantics of the SSA program is:
741 | a (x) = init, if x = 0;
742 | expr (x - 1), otherwise.
744 The second case corresponds to the PEELED_CHREC, whose syntax is
745 close to the syntax of a loop-phi-node:
747 | phi (init, expr) vs. (init, expr)_x
749 The proof of the translation algorithm for the first case is a
750 proof by structural induction based on the degree of EXPR.
752 Degree 0:
753 When EXPR is a constant with respect to the analyzed loop, or in
754 other words when EXPR is a polynomial of degree 0, the evolution of
755 the variable A in the loop is an affine function with an initial
756 condition INIT, and a step EXPR. In order to show this, we start
757 from the semantics of the SSA representation:
759 f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
761 and since "expr (j)" is a constant with respect to "j",
763 f (x) = init + x * expr
765 Finally, based on the semantics of the pure sum chrecs, by
766 identification we get the corresponding chrecs syntax:
768 f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
769 f (x) -> {init, +, expr}_x
771 Higher degree:
772 Suppose that EXPR is a polynomial of degree N with respect to the
773 analyzed loop_x for which we have already determined that it is
774 written under the chrecs syntax:
776 | expr (x) -> {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
778 We start from the semantics of the SSA program:
780 | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
782 | f (x) = init + \sum_{j = 0}^{x - 1}
783 | (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
785 | f (x) = init + \sum_{j = 0}^{x - 1}
786 | \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
788 | f (x) = init + \sum_{k = 0}^{n - 1}
789 | (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
791 | f (x) = init + \sum_{k = 0}^{n - 1}
792 | (b_k * \binom{x}{k + 1})
794 | f (x) = init + b_0 * \binom{x}{1} + ...
795 | + b_{n-1} * \binom{x}{n}
797 | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
798 | + b_{n-1} * \binom{x}{n}
801 And finally from the definition of the chrecs syntax, we identify:
802 | f (x) -> {init, +, b_0, +, ..., +, b_{n-1}}_x
804 This shows the mechanism that stands behind the add_to_evolution
805 function. An important point is that the use of symbolic
806 parameters avoids the need of an analysis schedule.
808 Example:
810 | inita = ...
811 | initb = ...
812 | loop_1
813 | a = phi (inita, a + 2 + b)
814 | b = phi (initb, b + 1)
815 | endloop
817 When analyzing "a", the algorithm keeps "b" symbolically:
819 | a -> {inita, +, 2 + b}_1
821 Then, after instantiation, the analyzer ends on the evolution:
823 | a -> {inita, +, 2 + initb, +, 1}_1
827 static tree
828 add_to_evolution (unsigned loop_nb, tree chrec_before, enum tree_code code,
829 tree to_add, gimple at_stmt)
831 tree type = chrec_type (to_add);
832 tree res = NULL_TREE;
834 if (to_add == NULL_TREE)
835 return chrec_before;
837 /* TO_ADD is either a scalar, or a parameter. TO_ADD is not
838 instantiated at this point. */
839 if (TREE_CODE (to_add) == POLYNOMIAL_CHREC)
840 /* This should not happen. */
841 return chrec_dont_know;
843 if (dump_file && (dump_flags & TDF_SCEV))
845 fprintf (dump_file, "(add_to_evolution \n");
846 fprintf (dump_file, " (loop_nb = %d)\n", loop_nb);
847 fprintf (dump_file, " (chrec_before = ");
848 print_generic_expr (dump_file, chrec_before, 0);
849 fprintf (dump_file, ")\n (to_add = ");
850 print_generic_expr (dump_file, to_add, 0);
851 fprintf (dump_file, ")\n");
854 if (code == MINUS_EXPR)
855 to_add = chrec_fold_multiply (type, to_add, SCALAR_FLOAT_TYPE_P (type)
856 ? build_real (type, dconstm1)
857 : build_int_cst_type (type, -1));
859 res = add_to_evolution_1 (loop_nb, chrec_before, to_add, at_stmt);
861 if (dump_file && (dump_flags & TDF_SCEV))
863 fprintf (dump_file, " (res = ");
864 print_generic_expr (dump_file, res, 0);
865 fprintf (dump_file, "))\n");
868 return res;
873 /* This section selects the loops that will be good candidates for the
874 scalar evolution analysis. For the moment, greedily select all the
875 loop nests we could analyze. */
877 /* For a loop with a single exit edge, return the COND_EXPR that
878 guards the exit edge. If the expression is too difficult to
879 analyze, then give up. */
881 gimple
882 get_loop_exit_condition (const struct loop *loop)
884 gimple res = NULL;
885 edge exit_edge = single_exit (loop);
887 if (dump_file && (dump_flags & TDF_SCEV))
888 fprintf (dump_file, "(get_loop_exit_condition \n ");
890 if (exit_edge)
892 gimple stmt;
894 stmt = last_stmt (exit_edge->src);
895 if (gimple_code (stmt) == GIMPLE_COND)
896 res = stmt;
899 if (dump_file && (dump_flags & TDF_SCEV))
901 print_gimple_stmt (dump_file, res, 0, 0);
902 fprintf (dump_file, ")\n");
905 return res;
909 /* Depth first search algorithm. */
911 typedef enum t_bool {
912 t_false,
913 t_true,
914 t_dont_know
915 } t_bool;
918 static t_bool follow_ssa_edge (struct loop *loop, gimple, gimple, tree *, int);
920 /* Follow the ssa edge into the binary expression RHS0 CODE RHS1.
921 Return true if the strongly connected component has been found. */
923 static t_bool
924 follow_ssa_edge_binary (struct loop *loop, gimple at_stmt,
925 tree type, tree rhs0, enum tree_code code, tree rhs1,
926 gimple halting_phi, tree *evolution_of_loop, int limit)
928 t_bool res = t_false;
929 tree evol;
931 switch (code)
933 case POINTER_PLUS_EXPR:
934 case PLUS_EXPR:
935 if (TREE_CODE (rhs0) == SSA_NAME)
937 if (TREE_CODE (rhs1) == SSA_NAME)
939 /* Match an assignment under the form:
940 "a = b + c". */
942 /* We want only assignments of form "name + name" contribute to
943 LIMIT, as the other cases do not necessarily contribute to
944 the complexity of the expression. */
945 limit++;
947 evol = *evolution_of_loop;
948 res = follow_ssa_edge
949 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi, &evol, limit);
951 if (res == t_true)
952 *evolution_of_loop = add_to_evolution
953 (loop->num,
954 chrec_convert (type, evol, at_stmt),
955 code, rhs1, at_stmt);
957 else if (res == t_false)
959 res = follow_ssa_edge
960 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
961 evolution_of_loop, limit);
963 if (res == t_true)
964 *evolution_of_loop = add_to_evolution
965 (loop->num,
966 chrec_convert (type, *evolution_of_loop, at_stmt),
967 code, rhs0, at_stmt);
969 else if (res == t_dont_know)
970 *evolution_of_loop = chrec_dont_know;
973 else if (res == t_dont_know)
974 *evolution_of_loop = chrec_dont_know;
977 else
979 /* Match an assignment under the form:
980 "a = b + ...". */
981 res = follow_ssa_edge
982 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
983 evolution_of_loop, limit);
984 if (res == t_true)
985 *evolution_of_loop = add_to_evolution
986 (loop->num, chrec_convert (type, *evolution_of_loop,
987 at_stmt),
988 code, rhs1, at_stmt);
990 else if (res == t_dont_know)
991 *evolution_of_loop = chrec_dont_know;
995 else if (TREE_CODE (rhs1) == SSA_NAME)
997 /* Match an assignment under the form:
998 "a = ... + c". */
999 res = follow_ssa_edge
1000 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1001 evolution_of_loop, limit);
1002 if (res == t_true)
1003 *evolution_of_loop = add_to_evolution
1004 (loop->num, chrec_convert (type, *evolution_of_loop,
1005 at_stmt),
1006 code, rhs0, at_stmt);
1008 else if (res == t_dont_know)
1009 *evolution_of_loop = chrec_dont_know;
1012 else
1013 /* Otherwise, match an assignment under the form:
1014 "a = ... + ...". */
1015 /* And there is nothing to do. */
1016 res = t_false;
1017 break;
1019 case MINUS_EXPR:
1020 /* This case is under the form "opnd0 = rhs0 - rhs1". */
1021 if (TREE_CODE (rhs0) == SSA_NAME)
1023 /* Match an assignment under the form:
1024 "a = b - ...". */
1026 /* We want only assignments of form "name - name" contribute to
1027 LIMIT, as the other cases do not necessarily contribute to
1028 the complexity of the expression. */
1029 if (TREE_CODE (rhs1) == SSA_NAME)
1030 limit++;
1032 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1033 evolution_of_loop, limit);
1034 if (res == t_true)
1035 *evolution_of_loop = add_to_evolution
1036 (loop->num, chrec_convert (type, *evolution_of_loop, at_stmt),
1037 MINUS_EXPR, rhs1, at_stmt);
1039 else if (res == t_dont_know)
1040 *evolution_of_loop = chrec_dont_know;
1042 else
1043 /* Otherwise, match an assignment under the form:
1044 "a = ... - ...". */
1045 /* And there is nothing to do. */
1046 res = t_false;
1047 break;
1049 default:
1050 res = t_false;
1053 return res;
1056 /* Follow the ssa edge into the expression EXPR.
1057 Return true if the strongly connected component has been found. */
1059 static t_bool
1060 follow_ssa_edge_expr (struct loop *loop, gimple at_stmt, tree expr,
1061 gimple halting_phi, tree *evolution_of_loop, int limit)
1063 enum tree_code code = TREE_CODE (expr);
1064 tree type = TREE_TYPE (expr), rhs0, rhs1;
1065 t_bool res;
1067 /* The EXPR is one of the following cases:
1068 - an SSA_NAME,
1069 - an INTEGER_CST,
1070 - a PLUS_EXPR,
1071 - a POINTER_PLUS_EXPR,
1072 - a MINUS_EXPR,
1073 - an ASSERT_EXPR,
1074 - other cases are not yet handled. */
1076 switch (code)
1078 CASE_CONVERT:
1079 /* This assignment is under the form "a_1 = (cast) rhs. */
1080 res = follow_ssa_edge_expr (loop, at_stmt, TREE_OPERAND (expr, 0),
1081 halting_phi, evolution_of_loop, limit);
1082 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, at_stmt);
1083 break;
1085 case INTEGER_CST:
1086 /* This assignment is under the form "a_1 = 7". */
1087 res = t_false;
1088 break;
1090 case SSA_NAME:
1091 /* This assignment is under the form: "a_1 = b_2". */
1092 res = follow_ssa_edge
1093 (loop, SSA_NAME_DEF_STMT (expr), halting_phi, evolution_of_loop, limit);
1094 break;
1096 case POINTER_PLUS_EXPR:
1097 case PLUS_EXPR:
1098 case MINUS_EXPR:
1099 /* This case is under the form "rhs0 +- rhs1". */
1100 rhs0 = TREE_OPERAND (expr, 0);
1101 rhs1 = TREE_OPERAND (expr, 1);
1102 type = TREE_TYPE (rhs0);
1103 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1104 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1105 res = follow_ssa_edge_binary (loop, at_stmt, type, rhs0, code, rhs1,
1106 halting_phi, evolution_of_loop, limit);
1107 break;
1109 case ADDR_EXPR:
1110 /* Handle &MEM[ptr + CST] which is equivalent to POINTER_PLUS_EXPR. */
1111 if (TREE_CODE (TREE_OPERAND (expr, 0)) == MEM_REF)
1113 expr = TREE_OPERAND (expr, 0);
1114 rhs0 = TREE_OPERAND (expr, 0);
1115 rhs1 = TREE_OPERAND (expr, 1);
1116 type = TREE_TYPE (rhs0);
1117 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1118 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1119 res = follow_ssa_edge_binary (loop, at_stmt, type,
1120 rhs0, POINTER_PLUS_EXPR, rhs1,
1121 halting_phi, evolution_of_loop, limit);
1123 else
1124 res = t_false;
1125 break;
1127 case ASSERT_EXPR:
1128 /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1129 It must be handled as a copy assignment of the form a_1 = a_2. */
1130 rhs0 = ASSERT_EXPR_VAR (expr);
1131 if (TREE_CODE (rhs0) == SSA_NAME)
1132 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0),
1133 halting_phi, evolution_of_loop, limit);
1134 else
1135 res = t_false;
1136 break;
1138 default:
1139 res = t_false;
1140 break;
1143 return res;
1146 /* Follow the ssa edge into the right hand side of an assignment STMT.
1147 Return true if the strongly connected component has been found. */
1149 static t_bool
1150 follow_ssa_edge_in_rhs (struct loop *loop, gimple stmt,
1151 gimple halting_phi, tree *evolution_of_loop, int limit)
1153 enum tree_code code = gimple_assign_rhs_code (stmt);
1154 tree type = gimple_expr_type (stmt), rhs1, rhs2;
1155 t_bool res;
1157 switch (code)
1159 CASE_CONVERT:
1160 /* This assignment is under the form "a_1 = (cast) rhs. */
1161 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1162 halting_phi, evolution_of_loop, limit);
1163 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, stmt);
1164 break;
1166 case POINTER_PLUS_EXPR:
1167 case PLUS_EXPR:
1168 case MINUS_EXPR:
1169 rhs1 = gimple_assign_rhs1 (stmt);
1170 rhs2 = gimple_assign_rhs2 (stmt);
1171 type = TREE_TYPE (rhs1);
1172 res = follow_ssa_edge_binary (loop, stmt, type, rhs1, code, rhs2,
1173 halting_phi, evolution_of_loop, limit);
1174 break;
1176 default:
1177 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1178 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1179 halting_phi, evolution_of_loop, limit);
1180 else
1181 res = t_false;
1182 break;
1185 return res;
1188 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1190 static bool
1191 backedge_phi_arg_p (gimple phi, int i)
1193 const_edge e = gimple_phi_arg_edge (phi, i);
1195 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1196 about updating it anywhere, and this should work as well most of the
1197 time. */
1198 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1199 return true;
1201 return false;
1204 /* Helper function for one branch of the condition-phi-node. Return
1205 true if the strongly connected component has been found following
1206 this path. */
1208 static inline t_bool
1209 follow_ssa_edge_in_condition_phi_branch (int i,
1210 struct loop *loop,
1211 gimple condition_phi,
1212 gimple halting_phi,
1213 tree *evolution_of_branch,
1214 tree init_cond, int limit)
1216 tree branch = PHI_ARG_DEF (condition_phi, i);
1217 *evolution_of_branch = chrec_dont_know;
1219 /* Do not follow back edges (they must belong to an irreducible loop, which
1220 we really do not want to worry about). */
1221 if (backedge_phi_arg_p (condition_phi, i))
1222 return t_false;
1224 if (TREE_CODE (branch) == SSA_NAME)
1226 *evolution_of_branch = init_cond;
1227 return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1228 evolution_of_branch, limit);
1231 /* This case occurs when one of the condition branches sets
1232 the variable to a constant: i.e. a phi-node like
1233 "a_2 = PHI <a_7(5), 2(6)>;".
1235 FIXME: This case have to be refined correctly:
1236 in some cases it is possible to say something better than
1237 chrec_dont_know, for example using a wrap-around notation. */
1238 return t_false;
1241 /* This function merges the branches of a condition-phi-node in a
1242 loop. */
1244 static t_bool
1245 follow_ssa_edge_in_condition_phi (struct loop *loop,
1246 gimple condition_phi,
1247 gimple halting_phi,
1248 tree *evolution_of_loop, int limit)
1250 int i, n;
1251 tree init = *evolution_of_loop;
1252 tree evolution_of_branch;
1253 t_bool res = follow_ssa_edge_in_condition_phi_branch (0, loop, condition_phi,
1254 halting_phi,
1255 &evolution_of_branch,
1256 init, limit);
1257 if (res == t_false || res == t_dont_know)
1258 return res;
1260 *evolution_of_loop = evolution_of_branch;
1262 n = gimple_phi_num_args (condition_phi);
1263 for (i = 1; i < n; i++)
1265 /* Quickly give up when the evolution of one of the branches is
1266 not known. */
1267 if (*evolution_of_loop == chrec_dont_know)
1268 return t_true;
1270 /* Increase the limit by the PHI argument number to avoid exponential
1271 time and memory complexity. */
1272 res = follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1273 halting_phi,
1274 &evolution_of_branch,
1275 init, limit + i);
1276 if (res == t_false || res == t_dont_know)
1277 return res;
1279 *evolution_of_loop = chrec_merge (*evolution_of_loop,
1280 evolution_of_branch);
1283 return t_true;
1286 /* Follow an SSA edge in an inner loop. It computes the overall
1287 effect of the loop, and following the symbolic initial conditions,
1288 it follows the edges in the parent loop. The inner loop is
1289 considered as a single statement. */
1291 static t_bool
1292 follow_ssa_edge_inner_loop_phi (struct loop *outer_loop,
1293 gimple loop_phi_node,
1294 gimple halting_phi,
1295 tree *evolution_of_loop, int limit)
1297 struct loop *loop = loop_containing_stmt (loop_phi_node);
1298 tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1300 /* Sometimes, the inner loop is too difficult to analyze, and the
1301 result of the analysis is a symbolic parameter. */
1302 if (ev == PHI_RESULT (loop_phi_node))
1304 t_bool res = t_false;
1305 int i, n = gimple_phi_num_args (loop_phi_node);
1307 for (i = 0; i < n; i++)
1309 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1310 basic_block bb;
1312 /* Follow the edges that exit the inner loop. */
1313 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1314 if (!flow_bb_inside_loop_p (loop, bb))
1315 res = follow_ssa_edge_expr (outer_loop, loop_phi_node,
1316 arg, halting_phi,
1317 evolution_of_loop, limit);
1318 if (res == t_true)
1319 break;
1322 /* If the path crosses this loop-phi, give up. */
1323 if (res == t_true)
1324 *evolution_of_loop = chrec_dont_know;
1326 return res;
1329 /* Otherwise, compute the overall effect of the inner loop. */
1330 ev = compute_overall_effect_of_inner_loop (loop, ev);
1331 return follow_ssa_edge_expr (outer_loop, loop_phi_node, ev, halting_phi,
1332 evolution_of_loop, limit);
1335 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1336 path that is analyzed on the return walk. */
1338 static t_bool
1339 follow_ssa_edge (struct loop *loop, gimple def, gimple halting_phi,
1340 tree *evolution_of_loop, int limit)
1342 struct loop *def_loop;
1344 if (gimple_nop_p (def))
1345 return t_false;
1347 /* Give up if the path is longer than the MAX that we allow. */
1348 if (limit > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_COMPLEXITY))
1349 return t_dont_know;
1351 def_loop = loop_containing_stmt (def);
1353 switch (gimple_code (def))
1355 case GIMPLE_PHI:
1356 if (!loop_phi_node_p (def))
1357 /* DEF is a condition-phi-node. Follow the branches, and
1358 record their evolutions. Finally, merge the collected
1359 information and set the approximation to the main
1360 variable. */
1361 return follow_ssa_edge_in_condition_phi
1362 (loop, def, halting_phi, evolution_of_loop, limit);
1364 /* When the analyzed phi is the halting_phi, the
1365 depth-first search is over: we have found a path from
1366 the halting_phi to itself in the loop. */
1367 if (def == halting_phi)
1368 return t_true;
1370 /* Otherwise, the evolution of the HALTING_PHI depends
1371 on the evolution of another loop-phi-node, i.e. the
1372 evolution function is a higher degree polynomial. */
1373 if (def_loop == loop)
1374 return t_false;
1376 /* Inner loop. */
1377 if (flow_loop_nested_p (loop, def_loop))
1378 return follow_ssa_edge_inner_loop_phi
1379 (loop, def, halting_phi, evolution_of_loop, limit + 1);
1381 /* Outer loop. */
1382 return t_false;
1384 case GIMPLE_ASSIGN:
1385 return follow_ssa_edge_in_rhs (loop, def, halting_phi,
1386 evolution_of_loop, limit);
1388 default:
1389 /* At this level of abstraction, the program is just a set
1390 of GIMPLE_ASSIGNs and PHI_NODEs. In principle there is no
1391 other node to be handled. */
1392 return t_false;
1397 /* Simplify PEELED_CHREC represented by (init_cond, arg) in LOOP.
1398 Handle below case and return the corresponding POLYNOMIAL_CHREC:
1400 # i_17 = PHI <i_13(5), 0(3)>
1401 # _20 = PHI <_5(5), start_4(D)(3)>
1403 i_13 = i_17 + 1;
1404 _5 = start_4(D) + i_13;
1406 Though variable _20 appears as a PEELED_CHREC in the form of
1407 (start_4, _5)_LOOP, it's a POLYNOMIAL_CHREC like {start_4, 1}_LOOP.
1409 See PR41488. */
1411 static tree
1412 simplify_peeled_chrec (struct loop *loop, tree arg, tree init_cond)
1414 aff_tree aff1, aff2;
1415 tree ev, left, right, type, step_val;
1416 hash_map<tree, name_expansion *> *peeled_chrec_map = NULL;
1418 ev = instantiate_parameters (loop, analyze_scalar_evolution (loop, arg));
1419 if (ev == NULL_TREE || TREE_CODE (ev) != POLYNOMIAL_CHREC)
1420 return chrec_dont_know;
1422 left = CHREC_LEFT (ev);
1423 right = CHREC_RIGHT (ev);
1424 type = TREE_TYPE (left);
1425 step_val = chrec_fold_plus (type, init_cond, right);
1427 /* Transform (init, {left, right}_LOOP)_LOOP to {init, right}_LOOP
1428 if "left" equals to "init + right". */
1429 if (operand_equal_p (left, step_val, 0))
1431 if (dump_file && (dump_flags & TDF_SCEV))
1432 fprintf (dump_file, "Simplify PEELED_CHREC into POLYNOMIAL_CHREC.\n");
1434 return build_polynomial_chrec (loop->num, init_cond, right);
1437 /* Try harder to check if they are equal. */
1438 tree_to_aff_combination_expand (left, type, &aff1, &peeled_chrec_map);
1439 tree_to_aff_combination_expand (step_val, type, &aff2, &peeled_chrec_map);
1440 free_affine_expand_cache (&peeled_chrec_map);
1441 aff_combination_scale (&aff2, -1);
1442 aff_combination_add (&aff1, &aff2);
1444 /* Transform (init, {left, right}_LOOP)_LOOP to {init, right}_LOOP
1445 if "left" equals to "init + right". */
1446 if (aff_combination_zero_p (&aff1))
1448 if (dump_file && (dump_flags & TDF_SCEV))
1449 fprintf (dump_file, "Simplify PEELED_CHREC into POLYNOMIAL_CHREC.\n");
1451 return build_polynomial_chrec (loop->num, init_cond, right);
1453 return chrec_dont_know;
1456 /* Given a LOOP_PHI_NODE, this function determines the evolution
1457 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1459 static tree
1460 analyze_evolution_in_loop (gimple loop_phi_node,
1461 tree init_cond)
1463 int i, n = gimple_phi_num_args (loop_phi_node);
1464 tree evolution_function = chrec_not_analyzed_yet;
1465 struct loop *loop = loop_containing_stmt (loop_phi_node);
1466 basic_block bb;
1467 static bool simplify_peeled_chrec_p = true;
1469 if (dump_file && (dump_flags & TDF_SCEV))
1471 fprintf (dump_file, "(analyze_evolution_in_loop \n");
1472 fprintf (dump_file, " (loop_phi_node = ");
1473 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1474 fprintf (dump_file, ")\n");
1477 for (i = 0; i < n; i++)
1479 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1480 gimple ssa_chain;
1481 tree ev_fn;
1482 t_bool res;
1484 /* Select the edges that enter the loop body. */
1485 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1486 if (!flow_bb_inside_loop_p (loop, bb))
1487 continue;
1489 if (TREE_CODE (arg) == SSA_NAME)
1491 bool val = false;
1493 ssa_chain = SSA_NAME_DEF_STMT (arg);
1495 /* Pass in the initial condition to the follow edge function. */
1496 ev_fn = init_cond;
1497 res = follow_ssa_edge (loop, ssa_chain, loop_phi_node, &ev_fn, 0);
1499 /* If ev_fn has no evolution in the inner loop, and the
1500 init_cond is not equal to ev_fn, then we have an
1501 ambiguity between two possible values, as we cannot know
1502 the number of iterations at this point. */
1503 if (TREE_CODE (ev_fn) != POLYNOMIAL_CHREC
1504 && no_evolution_in_loop_p (ev_fn, loop->num, &val) && val
1505 && !operand_equal_p (init_cond, ev_fn, 0))
1506 ev_fn = chrec_dont_know;
1508 else
1509 res = t_false;
1511 /* When it is impossible to go back on the same
1512 loop_phi_node by following the ssa edges, the
1513 evolution is represented by a peeled chrec, i.e. the
1514 first iteration, EV_FN has the value INIT_COND, then
1515 all the other iterations it has the value of ARG.
1516 For the moment, PEELED_CHREC nodes are not built. */
1517 if (res != t_true)
1519 ev_fn = chrec_dont_know;
1520 /* Try to recognize POLYNOMIAL_CHREC which appears in
1521 the form of PEELED_CHREC, but guard the process with
1522 a bool variable to keep the analyzer from infinite
1523 recurrence for real PEELED_RECs. */
1524 if (simplify_peeled_chrec_p && TREE_CODE (arg) == SSA_NAME)
1526 simplify_peeled_chrec_p = false;
1527 ev_fn = simplify_peeled_chrec (loop, arg, init_cond);
1528 simplify_peeled_chrec_p = true;
1532 /* When there are multiple back edges of the loop (which in fact never
1533 happens currently, but nevertheless), merge their evolutions. */
1534 evolution_function = chrec_merge (evolution_function, ev_fn);
1537 if (dump_file && (dump_flags & TDF_SCEV))
1539 fprintf (dump_file, " (evolution_function = ");
1540 print_generic_expr (dump_file, evolution_function, 0);
1541 fprintf (dump_file, "))\n");
1544 return evolution_function;
1547 /* Given a loop-phi-node, return the initial conditions of the
1548 variable on entry of the loop. When the CCP has propagated
1549 constants into the loop-phi-node, the initial condition is
1550 instantiated, otherwise the initial condition is kept symbolic.
1551 This analyzer does not analyze the evolution outside the current
1552 loop, and leaves this task to the on-demand tree reconstructor. */
1554 static tree
1555 analyze_initial_condition (gimple loop_phi_node)
1557 int i, n;
1558 tree init_cond = chrec_not_analyzed_yet;
1559 struct loop *loop = loop_containing_stmt (loop_phi_node);
1561 if (dump_file && (dump_flags & TDF_SCEV))
1563 fprintf (dump_file, "(analyze_initial_condition \n");
1564 fprintf (dump_file, " (loop_phi_node = \n");
1565 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1566 fprintf (dump_file, ")\n");
1569 n = gimple_phi_num_args (loop_phi_node);
1570 for (i = 0; i < n; i++)
1572 tree branch = PHI_ARG_DEF (loop_phi_node, i);
1573 basic_block bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1575 /* When the branch is oriented to the loop's body, it does
1576 not contribute to the initial condition. */
1577 if (flow_bb_inside_loop_p (loop, bb))
1578 continue;
1580 if (init_cond == chrec_not_analyzed_yet)
1582 init_cond = branch;
1583 continue;
1586 if (TREE_CODE (branch) == SSA_NAME)
1588 init_cond = chrec_dont_know;
1589 break;
1592 init_cond = chrec_merge (init_cond, branch);
1595 /* Ooops -- a loop without an entry??? */
1596 if (init_cond == chrec_not_analyzed_yet)
1597 init_cond = chrec_dont_know;
1599 /* During early loop unrolling we do not have fully constant propagated IL.
1600 Handle degenerate PHIs here to not miss important unrollings. */
1601 if (TREE_CODE (init_cond) == SSA_NAME)
1603 gimple def = SSA_NAME_DEF_STMT (init_cond);
1604 tree res;
1605 if (gimple_code (def) == GIMPLE_PHI
1606 && (res = degenerate_phi_result (def)) != NULL_TREE
1607 /* Only allow invariants here, otherwise we may break
1608 loop-closed SSA form. */
1609 && is_gimple_min_invariant (res))
1610 init_cond = res;
1613 if (dump_file && (dump_flags & TDF_SCEV))
1615 fprintf (dump_file, " (init_cond = ");
1616 print_generic_expr (dump_file, init_cond, 0);
1617 fprintf (dump_file, "))\n");
1620 return init_cond;
1623 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1625 static tree
1626 interpret_loop_phi (struct loop *loop, gimple loop_phi_node)
1628 tree res;
1629 struct loop *phi_loop = loop_containing_stmt (loop_phi_node);
1630 tree init_cond;
1632 if (phi_loop != loop)
1634 struct loop *subloop;
1635 tree evolution_fn = analyze_scalar_evolution
1636 (phi_loop, PHI_RESULT (loop_phi_node));
1638 /* Dive one level deeper. */
1639 subloop = superloop_at_depth (phi_loop, loop_depth (loop) + 1);
1641 /* Interpret the subloop. */
1642 res = compute_overall_effect_of_inner_loop (subloop, evolution_fn);
1643 return res;
1646 /* Otherwise really interpret the loop phi. */
1647 init_cond = analyze_initial_condition (loop_phi_node);
1648 res = analyze_evolution_in_loop (loop_phi_node, init_cond);
1650 /* Verify we maintained the correct initial condition throughout
1651 possible conversions in the SSA chain. */
1652 if (res != chrec_dont_know)
1654 tree new_init = res;
1655 if (CONVERT_EXPR_P (res)
1656 && TREE_CODE (TREE_OPERAND (res, 0)) == POLYNOMIAL_CHREC)
1657 new_init = fold_convert (TREE_TYPE (res),
1658 CHREC_LEFT (TREE_OPERAND (res, 0)));
1659 else if (TREE_CODE (res) == POLYNOMIAL_CHREC)
1660 new_init = CHREC_LEFT (res);
1661 STRIP_USELESS_TYPE_CONVERSION (new_init);
1662 if (TREE_CODE (new_init) == POLYNOMIAL_CHREC
1663 || !operand_equal_p (init_cond, new_init, 0))
1664 return chrec_dont_know;
1667 return res;
1670 /* This function merges the branches of a condition-phi-node,
1671 contained in the outermost loop, and whose arguments are already
1672 analyzed. */
1674 static tree
1675 interpret_condition_phi (struct loop *loop, gimple condition_phi)
1677 int i, n = gimple_phi_num_args (condition_phi);
1678 tree res = chrec_not_analyzed_yet;
1680 for (i = 0; i < n; i++)
1682 tree branch_chrec;
1684 if (backedge_phi_arg_p (condition_phi, i))
1686 res = chrec_dont_know;
1687 break;
1690 branch_chrec = analyze_scalar_evolution
1691 (loop, PHI_ARG_DEF (condition_phi, i));
1693 res = chrec_merge (res, branch_chrec);
1696 return res;
1699 /* Interpret the operation RHS1 OP RHS2. If we didn't
1700 analyze this node before, follow the definitions until ending
1701 either on an analyzed GIMPLE_ASSIGN, or on a loop-phi-node. On the
1702 return path, this function propagates evolutions (ala constant copy
1703 propagation). OPND1 is not a GIMPLE expression because we could
1704 analyze the effect of an inner loop: see interpret_loop_phi. */
1706 static tree
1707 interpret_rhs_expr (struct loop *loop, gimple at_stmt,
1708 tree type, tree rhs1, enum tree_code code, tree rhs2)
1710 tree res, chrec1, chrec2;
1711 gimple def;
1713 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1715 if (is_gimple_min_invariant (rhs1))
1716 return chrec_convert (type, rhs1, at_stmt);
1718 if (code == SSA_NAME)
1719 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1720 at_stmt);
1722 if (code == ASSERT_EXPR)
1724 rhs1 = ASSERT_EXPR_VAR (rhs1);
1725 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1726 at_stmt);
1730 switch (code)
1732 case ADDR_EXPR:
1733 if (TREE_CODE (TREE_OPERAND (rhs1, 0)) == MEM_REF
1734 || handled_component_p (TREE_OPERAND (rhs1, 0)))
1736 machine_mode mode;
1737 HOST_WIDE_INT bitsize, bitpos;
1738 int unsignedp;
1739 int volatilep = 0;
1740 tree base, offset;
1741 tree chrec3;
1742 tree unitpos;
1744 base = get_inner_reference (TREE_OPERAND (rhs1, 0),
1745 &bitsize, &bitpos, &offset,
1746 &mode, &unsignedp, &volatilep, false);
1748 if (TREE_CODE (base) == MEM_REF)
1750 rhs2 = TREE_OPERAND (base, 1);
1751 rhs1 = TREE_OPERAND (base, 0);
1753 chrec1 = analyze_scalar_evolution (loop, rhs1);
1754 chrec2 = analyze_scalar_evolution (loop, rhs2);
1755 chrec1 = chrec_convert (type, chrec1, at_stmt);
1756 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1757 chrec1 = instantiate_parameters (loop, chrec1);
1758 chrec2 = instantiate_parameters (loop, chrec2);
1759 res = chrec_fold_plus (type, chrec1, chrec2);
1761 else
1763 chrec1 = analyze_scalar_evolution_for_address_of (loop, base);
1764 chrec1 = chrec_convert (type, chrec1, at_stmt);
1765 res = chrec1;
1768 if (offset != NULL_TREE)
1770 chrec2 = analyze_scalar_evolution (loop, offset);
1771 chrec2 = chrec_convert (TREE_TYPE (offset), chrec2, at_stmt);
1772 chrec2 = instantiate_parameters (loop, chrec2);
1773 res = chrec_fold_plus (type, res, chrec2);
1776 if (bitpos != 0)
1778 gcc_assert ((bitpos % BITS_PER_UNIT) == 0);
1780 unitpos = size_int (bitpos / BITS_PER_UNIT);
1781 chrec3 = analyze_scalar_evolution (loop, unitpos);
1782 chrec3 = chrec_convert (TREE_TYPE (unitpos), chrec3, at_stmt);
1783 chrec3 = instantiate_parameters (loop, chrec3);
1784 res = chrec_fold_plus (type, res, chrec3);
1787 else
1788 res = chrec_dont_know;
1789 break;
1791 case POINTER_PLUS_EXPR:
1792 chrec1 = analyze_scalar_evolution (loop, rhs1);
1793 chrec2 = analyze_scalar_evolution (loop, rhs2);
1794 chrec1 = chrec_convert (type, chrec1, at_stmt);
1795 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1796 chrec1 = instantiate_parameters (loop, chrec1);
1797 chrec2 = instantiate_parameters (loop, chrec2);
1798 res = chrec_fold_plus (type, chrec1, chrec2);
1799 break;
1801 case PLUS_EXPR:
1802 chrec1 = analyze_scalar_evolution (loop, rhs1);
1803 chrec2 = analyze_scalar_evolution (loop, rhs2);
1804 chrec1 = chrec_convert (type, chrec1, at_stmt);
1805 chrec2 = chrec_convert (type, chrec2, at_stmt);
1806 chrec1 = instantiate_parameters (loop, chrec1);
1807 chrec2 = instantiate_parameters (loop, chrec2);
1808 res = chrec_fold_plus (type, chrec1, chrec2);
1809 break;
1811 case MINUS_EXPR:
1812 chrec1 = analyze_scalar_evolution (loop, rhs1);
1813 chrec2 = analyze_scalar_evolution (loop, rhs2);
1814 chrec1 = chrec_convert (type, chrec1, at_stmt);
1815 chrec2 = chrec_convert (type, chrec2, at_stmt);
1816 chrec1 = instantiate_parameters (loop, chrec1);
1817 chrec2 = instantiate_parameters (loop, chrec2);
1818 res = chrec_fold_minus (type, chrec1, chrec2);
1819 break;
1821 case NEGATE_EXPR:
1822 chrec1 = analyze_scalar_evolution (loop, rhs1);
1823 chrec1 = chrec_convert (type, chrec1, at_stmt);
1824 /* TYPE may be integer, real or complex, so use fold_convert. */
1825 chrec1 = instantiate_parameters (loop, chrec1);
1826 res = chrec_fold_multiply (type, chrec1,
1827 fold_convert (type, integer_minus_one_node));
1828 break;
1830 case BIT_NOT_EXPR:
1831 /* Handle ~X as -1 - X. */
1832 chrec1 = analyze_scalar_evolution (loop, rhs1);
1833 chrec1 = chrec_convert (type, chrec1, at_stmt);
1834 chrec1 = instantiate_parameters (loop, chrec1);
1835 res = chrec_fold_minus (type,
1836 fold_convert (type, integer_minus_one_node),
1837 chrec1);
1838 break;
1840 case MULT_EXPR:
1841 chrec1 = analyze_scalar_evolution (loop, rhs1);
1842 chrec2 = analyze_scalar_evolution (loop, rhs2);
1843 chrec1 = chrec_convert (type, chrec1, at_stmt);
1844 chrec2 = chrec_convert (type, chrec2, at_stmt);
1845 chrec1 = instantiate_parameters (loop, chrec1);
1846 chrec2 = instantiate_parameters (loop, chrec2);
1847 res = chrec_fold_multiply (type, chrec1, chrec2);
1848 break;
1850 CASE_CONVERT:
1851 /* In case we have a truncation of a widened operation that in
1852 the truncated type has undefined overflow behavior analyze
1853 the operation done in an unsigned type of the same precision
1854 as the final truncation. We cannot derive a scalar evolution
1855 for the widened operation but for the truncated result. */
1856 if (TREE_CODE (type) == INTEGER_TYPE
1857 && TREE_CODE (TREE_TYPE (rhs1)) == INTEGER_TYPE
1858 && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (rhs1))
1859 && TYPE_OVERFLOW_UNDEFINED (type)
1860 && TREE_CODE (rhs1) == SSA_NAME
1861 && (def = SSA_NAME_DEF_STMT (rhs1))
1862 && is_gimple_assign (def)
1863 && TREE_CODE_CLASS (gimple_assign_rhs_code (def)) == tcc_binary
1864 && TREE_CODE (gimple_assign_rhs2 (def)) == INTEGER_CST)
1866 tree utype = unsigned_type_for (type);
1867 chrec1 = interpret_rhs_expr (loop, at_stmt, utype,
1868 gimple_assign_rhs1 (def),
1869 gimple_assign_rhs_code (def),
1870 gimple_assign_rhs2 (def));
1872 else
1873 chrec1 = analyze_scalar_evolution (loop, rhs1);
1874 res = chrec_convert (type, chrec1, at_stmt);
1875 break;
1877 default:
1878 res = chrec_dont_know;
1879 break;
1882 return res;
1885 /* Interpret the expression EXPR. */
1887 static tree
1888 interpret_expr (struct loop *loop, gimple at_stmt, tree expr)
1890 enum tree_code code;
1891 tree type = TREE_TYPE (expr), op0, op1;
1893 if (automatically_generated_chrec_p (expr))
1894 return expr;
1896 if (TREE_CODE (expr) == POLYNOMIAL_CHREC
1897 || get_gimple_rhs_class (TREE_CODE (expr)) == GIMPLE_TERNARY_RHS)
1898 return chrec_dont_know;
1900 extract_ops_from_tree (expr, &code, &op0, &op1);
1902 return interpret_rhs_expr (loop, at_stmt, type,
1903 op0, code, op1);
1906 /* Interpret the rhs of the assignment STMT. */
1908 static tree
1909 interpret_gimple_assign (struct loop *loop, gimple stmt)
1911 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1912 enum tree_code code = gimple_assign_rhs_code (stmt);
1914 return interpret_rhs_expr (loop, stmt, type,
1915 gimple_assign_rhs1 (stmt), code,
1916 gimple_assign_rhs2 (stmt));
1921 /* This section contains all the entry points:
1922 - number_of_iterations_in_loop,
1923 - analyze_scalar_evolution,
1924 - instantiate_parameters.
1927 /* Compute and return the evolution function in WRTO_LOOP, the nearest
1928 common ancestor of DEF_LOOP and USE_LOOP. */
1930 static tree
1931 compute_scalar_evolution_in_loop (struct loop *wrto_loop,
1932 struct loop *def_loop,
1933 tree ev)
1935 bool val;
1936 tree res;
1938 if (def_loop == wrto_loop)
1939 return ev;
1941 def_loop = superloop_at_depth (def_loop, loop_depth (wrto_loop) + 1);
1942 res = compute_overall_effect_of_inner_loop (def_loop, ev);
1944 if (no_evolution_in_loop_p (res, wrto_loop->num, &val) && val)
1945 return res;
1947 return analyze_scalar_evolution_1 (wrto_loop, res, chrec_not_analyzed_yet);
1950 /* Helper recursive function. */
1952 static tree
1953 analyze_scalar_evolution_1 (struct loop *loop, tree var, tree res)
1955 tree type = TREE_TYPE (var);
1956 gimple def;
1957 basic_block bb;
1958 struct loop *def_loop;
1960 if (loop == NULL || TREE_CODE (type) == VECTOR_TYPE)
1961 return chrec_dont_know;
1963 if (TREE_CODE (var) != SSA_NAME)
1964 return interpret_expr (loop, NULL, var);
1966 def = SSA_NAME_DEF_STMT (var);
1967 bb = gimple_bb (def);
1968 def_loop = bb ? bb->loop_father : NULL;
1970 if (bb == NULL
1971 || !flow_bb_inside_loop_p (loop, bb))
1973 /* Keep the symbolic form. */
1974 res = var;
1975 goto set_and_end;
1978 if (res != chrec_not_analyzed_yet)
1980 if (loop != bb->loop_father)
1981 res = compute_scalar_evolution_in_loop
1982 (find_common_loop (loop, bb->loop_father), bb->loop_father, res);
1984 goto set_and_end;
1987 if (loop != def_loop)
1989 res = analyze_scalar_evolution_1 (def_loop, var, chrec_not_analyzed_yet);
1990 res = compute_scalar_evolution_in_loop (loop, def_loop, res);
1992 goto set_and_end;
1995 switch (gimple_code (def))
1997 case GIMPLE_ASSIGN:
1998 res = interpret_gimple_assign (loop, def);
1999 break;
2001 case GIMPLE_PHI:
2002 if (loop_phi_node_p (def))
2003 res = interpret_loop_phi (loop, def);
2004 else
2005 res = interpret_condition_phi (loop, def);
2006 break;
2008 default:
2009 res = chrec_dont_know;
2010 break;
2013 set_and_end:
2015 /* Keep the symbolic form. */
2016 if (res == chrec_dont_know)
2017 res = var;
2019 if (loop == def_loop)
2020 set_scalar_evolution (block_before_loop (loop), var, res);
2022 return res;
2025 /* Analyzes and returns the scalar evolution of the ssa_name VAR in
2026 LOOP. LOOP is the loop in which the variable is used.
2028 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
2029 pointer to the statement that uses this variable, in order to
2030 determine the evolution function of the variable, use the following
2031 calls:
2033 loop_p loop = loop_containing_stmt (stmt);
2034 tree chrec_with_symbols = analyze_scalar_evolution (loop, var);
2035 tree chrec_instantiated = instantiate_parameters (loop, chrec_with_symbols);
2038 tree
2039 analyze_scalar_evolution (struct loop *loop, tree var)
2041 tree res;
2043 if (dump_file && (dump_flags & TDF_SCEV))
2045 fprintf (dump_file, "(analyze_scalar_evolution \n");
2046 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
2047 fprintf (dump_file, " (scalar = ");
2048 print_generic_expr (dump_file, var, 0);
2049 fprintf (dump_file, ")\n");
2052 res = get_scalar_evolution (block_before_loop (loop), var);
2053 res = analyze_scalar_evolution_1 (loop, var, res);
2055 if (dump_file && (dump_flags & TDF_SCEV))
2056 fprintf (dump_file, ")\n");
2058 return res;
2061 /* Analyzes and returns the scalar evolution of VAR address in LOOP. */
2063 static tree
2064 analyze_scalar_evolution_for_address_of (struct loop *loop, tree var)
2066 return analyze_scalar_evolution (loop, build_fold_addr_expr (var));
2069 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
2070 WRTO_LOOP (which should be a superloop of USE_LOOP)
2072 FOLDED_CASTS is set to true if resolve_mixers used
2073 chrec_convert_aggressive (TODO -- not really, we are way too conservative
2074 at the moment in order to keep things simple).
2076 To illustrate the meaning of USE_LOOP and WRTO_LOOP, consider the following
2077 example:
2079 for (i = 0; i < 100; i++) -- loop 1
2081 for (j = 0; j < 100; j++) -- loop 2
2083 k1 = i;
2084 k2 = j;
2086 use2 (k1, k2);
2088 for (t = 0; t < 100; t++) -- loop 3
2089 use3 (k1, k2);
2092 use1 (k1, k2);
2095 Both k1 and k2 are invariants in loop3, thus
2096 analyze_scalar_evolution_in_loop (loop3, loop3, k1) = k1
2097 analyze_scalar_evolution_in_loop (loop3, loop3, k2) = k2
2099 As they are invariant, it does not matter whether we consider their
2100 usage in loop 3 or loop 2, hence
2101 analyze_scalar_evolution_in_loop (loop2, loop3, k1) =
2102 analyze_scalar_evolution_in_loop (loop2, loop2, k1) = i
2103 analyze_scalar_evolution_in_loop (loop2, loop3, k2) =
2104 analyze_scalar_evolution_in_loop (loop2, loop2, k2) = [0,+,1]_2
2106 Similarly for their evolutions with respect to loop 1. The values of K2
2107 in the use in loop 2 vary independently on loop 1, thus we cannot express
2108 the evolution with respect to loop 1:
2109 analyze_scalar_evolution_in_loop (loop1, loop3, k1) =
2110 analyze_scalar_evolution_in_loop (loop1, loop2, k1) = [0,+,1]_1
2111 analyze_scalar_evolution_in_loop (loop1, loop3, k2) =
2112 analyze_scalar_evolution_in_loop (loop1, loop2, k2) = dont_know
2114 The value of k2 in the use in loop 1 is known, though:
2115 analyze_scalar_evolution_in_loop (loop1, loop1, k1) = [0,+,1]_1
2116 analyze_scalar_evolution_in_loop (loop1, loop1, k2) = 100
2119 static tree
2120 analyze_scalar_evolution_in_loop (struct loop *wrto_loop, struct loop *use_loop,
2121 tree version, bool *folded_casts)
2123 bool val = false;
2124 tree ev = version, tmp;
2126 /* We cannot just do
2128 tmp = analyze_scalar_evolution (use_loop, version);
2129 ev = resolve_mixers (wrto_loop, tmp);
2131 as resolve_mixers would query the scalar evolution with respect to
2132 wrto_loop. For example, in the situation described in the function
2133 comment, suppose that wrto_loop = loop1, use_loop = loop3 and
2134 version = k2. Then
2136 analyze_scalar_evolution (use_loop, version) = k2
2138 and resolve_mixers (loop1, k2) finds that the value of k2 in loop 1
2139 is 100, which is a wrong result, since we are interested in the
2140 value in loop 3.
2142 Instead, we need to proceed from use_loop to wrto_loop loop by loop,
2143 each time checking that there is no evolution in the inner loop. */
2145 if (folded_casts)
2146 *folded_casts = false;
2147 while (1)
2149 tmp = analyze_scalar_evolution (use_loop, ev);
2150 ev = resolve_mixers (use_loop, tmp);
2152 if (folded_casts && tmp != ev)
2153 *folded_casts = true;
2155 if (use_loop == wrto_loop)
2156 return ev;
2158 /* If the value of the use changes in the inner loop, we cannot express
2159 its value in the outer loop (we might try to return interval chrec,
2160 but we do not have a user for it anyway) */
2161 if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
2162 || !val)
2163 return chrec_dont_know;
2165 use_loop = loop_outer (use_loop);
2170 /* Hashtable helpers for a temporary hash-table used when
2171 instantiating a CHREC or resolving mixers. For this use
2172 instantiated_below is always the same. */
2174 struct instantiate_cache_type
2176 htab_t map;
2177 vec<scev_info_str> entries;
2179 instantiate_cache_type () : map (NULL), entries (vNULL) {}
2180 ~instantiate_cache_type ();
2181 tree get (unsigned slot) { return entries[slot].chrec; }
2182 void set (unsigned slot, tree chrec) { entries[slot].chrec = chrec; }
2185 instantiate_cache_type::~instantiate_cache_type ()
2187 if (map != NULL)
2189 htab_delete (map);
2190 entries.release ();
2194 /* Cache to avoid infinite recursion when instantiating an SSA name.
2195 Live during the outermost instantiate_scev or resolve_mixers call. */
2196 static instantiate_cache_type *global_cache;
2198 /* Computes a hash function for database element ELT. */
2200 static inline hashval_t
2201 hash_idx_scev_info (const void *elt_)
2203 unsigned idx = ((size_t) elt_) - 2;
2204 return hash_scev_info (&global_cache->entries[idx]);
2207 /* Compares database elements E1 and E2. */
2209 static inline int
2210 eq_idx_scev_info (const void *e1, const void *e2)
2212 unsigned idx1 = ((size_t) e1) - 2;
2213 return eq_scev_info (&global_cache->entries[idx1], e2);
2216 /* Returns from CACHE the slot number of the cached chrec for NAME. */
2218 static unsigned
2219 get_instantiated_value_entry (instantiate_cache_type &cache,
2220 tree name, basic_block instantiate_below)
2222 if (!cache.map)
2224 cache.map = htab_create (10, hash_idx_scev_info, eq_idx_scev_info, NULL);
2225 cache.entries.create (10);
2228 scev_info_str e;
2229 e.name_version = SSA_NAME_VERSION (name);
2230 e.instantiated_below = instantiate_below->index;
2231 void **slot = htab_find_slot_with_hash (cache.map, &e,
2232 hash_scev_info (&e), INSERT);
2233 if (!*slot)
2235 e.chrec = chrec_not_analyzed_yet;
2236 *slot = (void *)(size_t)(cache.entries.length () + 2);
2237 cache.entries.safe_push (e);
2240 return ((size_t)*slot) - 2;
2244 /* Return the closed_loop_phi node for VAR. If there is none, return
2245 NULL_TREE. */
2247 static tree
2248 loop_closed_phi_def (tree var)
2250 struct loop *loop;
2251 edge exit;
2252 gimple phi;
2253 gimple_stmt_iterator psi;
2255 if (var == NULL_TREE
2256 || TREE_CODE (var) != SSA_NAME)
2257 return NULL_TREE;
2259 loop = loop_containing_stmt (SSA_NAME_DEF_STMT (var));
2260 exit = single_exit (loop);
2261 if (!exit)
2262 return NULL_TREE;
2264 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
2266 phi = gsi_stmt (psi);
2267 if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == var)
2268 return PHI_RESULT (phi);
2271 return NULL_TREE;
2274 static tree instantiate_scev_r (basic_block, struct loop *, struct loop *,
2275 tree, bool, int);
2277 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2278 and EVOLUTION_LOOP, that were left under a symbolic form.
2280 CHREC is an SSA_NAME to be instantiated.
2282 CACHE is the cache of already instantiated values.
2284 FOLD_CONVERSIONS should be set to true when the conversions that
2285 may wrap in signed/pointer type are folded, as long as the value of
2286 the chrec is preserved.
2288 SIZE_EXPR is used for computing the size of the expression to be
2289 instantiated, and to stop if it exceeds some limit. */
2291 static tree
2292 instantiate_scev_name (basic_block instantiate_below,
2293 struct loop *evolution_loop, struct loop *inner_loop,
2294 tree chrec,
2295 bool fold_conversions,
2296 int size_expr)
2298 tree res;
2299 struct loop *def_loop;
2300 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (chrec));
2302 /* A parameter (or loop invariant and we do not want to include
2303 evolutions in outer loops), nothing to do. */
2304 if (!def_bb
2305 || loop_depth (def_bb->loop_father) == 0
2306 || dominated_by_p (CDI_DOMINATORS, instantiate_below, def_bb))
2307 return chrec;
2309 /* We cache the value of instantiated variable to avoid exponential
2310 time complexity due to reevaluations. We also store the convenient
2311 value in the cache in order to prevent infinite recursion -- we do
2312 not want to instantiate the SSA_NAME if it is in a mixer
2313 structure. This is used for avoiding the instantiation of
2314 recursively defined functions, such as:
2316 | a_2 -> {0, +, 1, +, a_2}_1 */
2318 unsigned si = get_instantiated_value_entry (*global_cache,
2319 chrec, instantiate_below);
2320 if (global_cache->get (si) != chrec_not_analyzed_yet)
2321 return global_cache->get (si);
2323 /* On recursion return chrec_dont_know. */
2324 global_cache->set (si, chrec_dont_know);
2326 def_loop = find_common_loop (evolution_loop, def_bb->loop_father);
2328 /* If the analysis yields a parametric chrec, instantiate the
2329 result again. */
2330 res = analyze_scalar_evolution (def_loop, chrec);
2332 /* Don't instantiate default definitions. */
2333 if (TREE_CODE (res) == SSA_NAME
2334 && SSA_NAME_IS_DEFAULT_DEF (res))
2337 /* Don't instantiate loop-closed-ssa phi nodes. */
2338 else if (TREE_CODE (res) == SSA_NAME
2339 && loop_depth (loop_containing_stmt (SSA_NAME_DEF_STMT (res)))
2340 > loop_depth (def_loop))
2342 if (res == chrec)
2343 res = loop_closed_phi_def (chrec);
2344 else
2345 res = chrec;
2347 /* When there is no loop_closed_phi_def, it means that the
2348 variable is not used after the loop: try to still compute the
2349 value of the variable when exiting the loop. */
2350 if (res == NULL_TREE)
2352 loop_p loop = loop_containing_stmt (SSA_NAME_DEF_STMT (chrec));
2353 res = analyze_scalar_evolution (loop, chrec);
2354 res = compute_overall_effect_of_inner_loop (loop, res);
2355 res = instantiate_scev_r (instantiate_below, evolution_loop,
2356 inner_loop, res,
2357 fold_conversions, size_expr);
2359 else if (!dominated_by_p (CDI_DOMINATORS, instantiate_below,
2360 gimple_bb (SSA_NAME_DEF_STMT (res))))
2361 res = chrec_dont_know;
2364 else if (res != chrec_dont_know)
2366 if (inner_loop
2367 && def_bb->loop_father != inner_loop
2368 && !flow_loop_nested_p (def_bb->loop_father, inner_loop))
2369 /* ??? We could try to compute the overall effect of the loop here. */
2370 res = chrec_dont_know;
2371 else
2372 res = instantiate_scev_r (instantiate_below, evolution_loop,
2373 inner_loop, res,
2374 fold_conversions, size_expr);
2377 /* Store the correct value to the cache. */
2378 global_cache->set (si, res);
2379 return res;
2382 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2383 and EVOLUTION_LOOP, that were left under a symbolic form.
2385 CHREC is a polynomial chain of recurrence to be instantiated.
2387 CACHE is the cache of already instantiated values.
2389 FOLD_CONVERSIONS should be set to true when the conversions that
2390 may wrap in signed/pointer type are folded, as long as the value of
2391 the chrec is preserved.
2393 SIZE_EXPR is used for computing the size of the expression to be
2394 instantiated, and to stop if it exceeds some limit. */
2396 static tree
2397 instantiate_scev_poly (basic_block instantiate_below,
2398 struct loop *evolution_loop, struct loop *,
2399 tree chrec, bool fold_conversions, int size_expr)
2401 tree op1;
2402 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2403 get_chrec_loop (chrec),
2404 CHREC_LEFT (chrec), fold_conversions,
2405 size_expr);
2406 if (op0 == chrec_dont_know)
2407 return chrec_dont_know;
2409 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2410 get_chrec_loop (chrec),
2411 CHREC_RIGHT (chrec), fold_conversions,
2412 size_expr);
2413 if (op1 == chrec_dont_know)
2414 return chrec_dont_know;
2416 if (CHREC_LEFT (chrec) != op0
2417 || CHREC_RIGHT (chrec) != op1)
2419 op1 = chrec_convert_rhs (chrec_type (op0), op1, NULL);
2420 chrec = build_polynomial_chrec (CHREC_VARIABLE (chrec), op0, op1);
2423 return chrec;
2426 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2427 and EVOLUTION_LOOP, that were left under a symbolic form.
2429 "C0 CODE C1" is a binary expression of type TYPE to be instantiated.
2431 CACHE is the cache of already instantiated values.
2433 FOLD_CONVERSIONS should be set to true when the conversions that
2434 may wrap in signed/pointer type are folded, as long as the value of
2435 the chrec is preserved.
2437 SIZE_EXPR is used for computing the size of the expression to be
2438 instantiated, and to stop if it exceeds some limit. */
2440 static tree
2441 instantiate_scev_binary (basic_block instantiate_below,
2442 struct loop *evolution_loop, struct loop *inner_loop,
2443 tree chrec, enum tree_code code,
2444 tree type, tree c0, tree c1,
2445 bool fold_conversions, int size_expr)
2447 tree op1;
2448 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2449 c0, fold_conversions, size_expr);
2450 if (op0 == chrec_dont_know)
2451 return chrec_dont_know;
2453 op1 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2454 c1, fold_conversions, size_expr);
2455 if (op1 == chrec_dont_know)
2456 return chrec_dont_know;
2458 if (c0 != op0
2459 || c1 != op1)
2461 op0 = chrec_convert (type, op0, NULL);
2462 op1 = chrec_convert_rhs (type, op1, NULL);
2464 switch (code)
2466 case POINTER_PLUS_EXPR:
2467 case PLUS_EXPR:
2468 return chrec_fold_plus (type, op0, op1);
2470 case MINUS_EXPR:
2471 return chrec_fold_minus (type, op0, op1);
2473 case MULT_EXPR:
2474 return chrec_fold_multiply (type, op0, op1);
2476 default:
2477 gcc_unreachable ();
2481 return chrec ? chrec : fold_build2 (code, type, c0, c1);
2484 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2485 and EVOLUTION_LOOP, that were left under a symbolic form.
2487 "CHREC" is an array reference to be instantiated.
2489 CACHE is the cache of already instantiated values.
2491 FOLD_CONVERSIONS should be set to true when the conversions that
2492 may wrap in signed/pointer type are folded, as long as the value of
2493 the chrec is preserved.
2495 SIZE_EXPR is used for computing the size of the expression to be
2496 instantiated, and to stop if it exceeds some limit. */
2498 static tree
2499 instantiate_array_ref (basic_block instantiate_below,
2500 struct loop *evolution_loop, struct loop *inner_loop,
2501 tree chrec, bool fold_conversions, int size_expr)
2503 tree res;
2504 tree index = TREE_OPERAND (chrec, 1);
2505 tree op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2506 inner_loop, index,
2507 fold_conversions, size_expr);
2509 if (op1 == chrec_dont_know)
2510 return chrec_dont_know;
2512 if (chrec && op1 == index)
2513 return chrec;
2515 res = unshare_expr (chrec);
2516 TREE_OPERAND (res, 1) = op1;
2517 return res;
2520 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2521 and EVOLUTION_LOOP, that were left under a symbolic form.
2523 "CHREC" that stands for a convert expression "(TYPE) OP" is to be
2524 instantiated.
2526 CACHE is the cache of already instantiated values.
2528 FOLD_CONVERSIONS should be set to true when the conversions that
2529 may wrap in signed/pointer type are folded, as long as the value of
2530 the chrec is preserved.
2532 SIZE_EXPR is used for computing the size of the expression to be
2533 instantiated, and to stop if it exceeds some limit. */
2535 static tree
2536 instantiate_scev_convert (basic_block instantiate_below,
2537 struct loop *evolution_loop, struct loop *inner_loop,
2538 tree chrec, tree type, tree op,
2539 bool fold_conversions, int size_expr)
2541 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2542 inner_loop, op,
2543 fold_conversions, size_expr);
2545 if (op0 == chrec_dont_know)
2546 return chrec_dont_know;
2548 if (fold_conversions)
2550 tree tmp = chrec_convert_aggressive (type, op0);
2551 if (tmp)
2552 return tmp;
2555 if (chrec && op0 == op)
2556 return chrec;
2558 /* If we used chrec_convert_aggressive, we can no longer assume that
2559 signed chrecs do not overflow, as chrec_convert does, so avoid
2560 calling it in that case. */
2561 if (fold_conversions)
2562 return fold_convert (type, op0);
2564 return chrec_convert (type, op0, NULL);
2567 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2568 and EVOLUTION_LOOP, that were left under a symbolic form.
2570 CHREC is a BIT_NOT_EXPR or a NEGATE_EXPR expression to be instantiated.
2571 Handle ~X as -1 - X.
2572 Handle -X as -1 * X.
2574 CACHE is the cache of already instantiated values.
2576 FOLD_CONVERSIONS should be set to true when the conversions that
2577 may wrap in signed/pointer type are folded, as long as the value of
2578 the chrec is preserved.
2580 SIZE_EXPR is used for computing the size of the expression to be
2581 instantiated, and to stop if it exceeds some limit. */
2583 static tree
2584 instantiate_scev_not (basic_block instantiate_below,
2585 struct loop *evolution_loop, struct loop *inner_loop,
2586 tree chrec,
2587 enum tree_code code, tree type, tree op,
2588 bool fold_conversions, int size_expr)
2590 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2591 inner_loop, op,
2592 fold_conversions, size_expr);
2594 if (op0 == chrec_dont_know)
2595 return chrec_dont_know;
2597 if (op != op0)
2599 op0 = chrec_convert (type, op0, NULL);
2601 switch (code)
2603 case BIT_NOT_EXPR:
2604 return chrec_fold_minus
2605 (type, fold_convert (type, integer_minus_one_node), op0);
2607 case NEGATE_EXPR:
2608 return chrec_fold_multiply
2609 (type, fold_convert (type, integer_minus_one_node), op0);
2611 default:
2612 gcc_unreachable ();
2616 return chrec ? chrec : fold_build1 (code, type, op0);
2619 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2620 and EVOLUTION_LOOP, that were left under a symbolic form.
2622 CHREC is an expression with 3 operands to be instantiated.
2624 CACHE is the cache of already instantiated values.
2626 FOLD_CONVERSIONS should be set to true when the conversions that
2627 may wrap in signed/pointer type are folded, as long as the value of
2628 the chrec is preserved.
2630 SIZE_EXPR is used for computing the size of the expression to be
2631 instantiated, and to stop if it exceeds some limit. */
2633 static tree
2634 instantiate_scev_3 (basic_block instantiate_below,
2635 struct loop *evolution_loop, struct loop *inner_loop,
2636 tree chrec,
2637 bool fold_conversions, int size_expr)
2639 tree op1, op2;
2640 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2641 inner_loop, TREE_OPERAND (chrec, 0),
2642 fold_conversions, size_expr);
2643 if (op0 == chrec_dont_know)
2644 return chrec_dont_know;
2646 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2647 inner_loop, TREE_OPERAND (chrec, 1),
2648 fold_conversions, size_expr);
2649 if (op1 == chrec_dont_know)
2650 return chrec_dont_know;
2652 op2 = instantiate_scev_r (instantiate_below, evolution_loop,
2653 inner_loop, TREE_OPERAND (chrec, 2),
2654 fold_conversions, size_expr);
2655 if (op2 == chrec_dont_know)
2656 return chrec_dont_know;
2658 if (op0 == TREE_OPERAND (chrec, 0)
2659 && op1 == TREE_OPERAND (chrec, 1)
2660 && op2 == TREE_OPERAND (chrec, 2))
2661 return chrec;
2663 return fold_build3 (TREE_CODE (chrec),
2664 TREE_TYPE (chrec), op0, op1, op2);
2667 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2668 and EVOLUTION_LOOP, that were left under a symbolic form.
2670 CHREC is an expression with 2 operands to be instantiated.
2672 CACHE is the cache of already instantiated values.
2674 FOLD_CONVERSIONS should be set to true when the conversions that
2675 may wrap in signed/pointer type are folded, as long as the value of
2676 the chrec is preserved.
2678 SIZE_EXPR is used for computing the size of the expression to be
2679 instantiated, and to stop if it exceeds some limit. */
2681 static tree
2682 instantiate_scev_2 (basic_block instantiate_below,
2683 struct loop *evolution_loop, struct loop *inner_loop,
2684 tree chrec,
2685 bool fold_conversions, int size_expr)
2687 tree op1;
2688 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2689 inner_loop, TREE_OPERAND (chrec, 0),
2690 fold_conversions, size_expr);
2691 if (op0 == chrec_dont_know)
2692 return chrec_dont_know;
2694 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2695 inner_loop, TREE_OPERAND (chrec, 1),
2696 fold_conversions, size_expr);
2697 if (op1 == chrec_dont_know)
2698 return chrec_dont_know;
2700 if (op0 == TREE_OPERAND (chrec, 0)
2701 && op1 == TREE_OPERAND (chrec, 1))
2702 return chrec;
2704 return fold_build2 (TREE_CODE (chrec), TREE_TYPE (chrec), op0, op1);
2707 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2708 and EVOLUTION_LOOP, that were left under a symbolic form.
2710 CHREC is an expression with 2 operands to be instantiated.
2712 CACHE is the cache of already instantiated values.
2714 FOLD_CONVERSIONS should be set to true when the conversions that
2715 may wrap in signed/pointer type are folded, as long as the value of
2716 the chrec is preserved.
2718 SIZE_EXPR is used for computing the size of the expression to be
2719 instantiated, and to stop if it exceeds some limit. */
2721 static tree
2722 instantiate_scev_1 (basic_block instantiate_below,
2723 struct loop *evolution_loop, struct loop *inner_loop,
2724 tree chrec,
2725 bool fold_conversions, int size_expr)
2727 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2728 inner_loop, TREE_OPERAND (chrec, 0),
2729 fold_conversions, size_expr);
2731 if (op0 == chrec_dont_know)
2732 return chrec_dont_know;
2734 if (op0 == TREE_OPERAND (chrec, 0))
2735 return chrec;
2737 return fold_build1 (TREE_CODE (chrec), TREE_TYPE (chrec), op0);
2740 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2741 and EVOLUTION_LOOP, that were left under a symbolic form.
2743 CHREC is the scalar evolution to instantiate.
2745 CACHE is the cache of already instantiated values.
2747 FOLD_CONVERSIONS should be set to true when the conversions that
2748 may wrap in signed/pointer type are folded, as long as the value of
2749 the chrec is preserved.
2751 SIZE_EXPR is used for computing the size of the expression to be
2752 instantiated, and to stop if it exceeds some limit. */
2754 static tree
2755 instantiate_scev_r (basic_block instantiate_below,
2756 struct loop *evolution_loop, struct loop *inner_loop,
2757 tree chrec,
2758 bool fold_conversions, int size_expr)
2760 /* Give up if the expression is larger than the MAX that we allow. */
2761 if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
2762 return chrec_dont_know;
2764 if (chrec == NULL_TREE
2765 || automatically_generated_chrec_p (chrec)
2766 || is_gimple_min_invariant (chrec))
2767 return chrec;
2769 switch (TREE_CODE (chrec))
2771 case SSA_NAME:
2772 return instantiate_scev_name (instantiate_below, evolution_loop,
2773 inner_loop, chrec,
2774 fold_conversions, size_expr);
2776 case POLYNOMIAL_CHREC:
2777 return instantiate_scev_poly (instantiate_below, evolution_loop,
2778 inner_loop, chrec,
2779 fold_conversions, size_expr);
2781 case POINTER_PLUS_EXPR:
2782 case PLUS_EXPR:
2783 case MINUS_EXPR:
2784 case MULT_EXPR:
2785 return instantiate_scev_binary (instantiate_below, evolution_loop,
2786 inner_loop, chrec,
2787 TREE_CODE (chrec), chrec_type (chrec),
2788 TREE_OPERAND (chrec, 0),
2789 TREE_OPERAND (chrec, 1),
2790 fold_conversions, size_expr);
2792 CASE_CONVERT:
2793 return instantiate_scev_convert (instantiate_below, evolution_loop,
2794 inner_loop, chrec,
2795 TREE_TYPE (chrec), TREE_OPERAND (chrec, 0),
2796 fold_conversions, size_expr);
2798 case NEGATE_EXPR:
2799 case BIT_NOT_EXPR:
2800 return instantiate_scev_not (instantiate_below, evolution_loop,
2801 inner_loop, chrec,
2802 TREE_CODE (chrec), TREE_TYPE (chrec),
2803 TREE_OPERAND (chrec, 0),
2804 fold_conversions, size_expr);
2806 case ADDR_EXPR:
2807 case SCEV_NOT_KNOWN:
2808 return chrec_dont_know;
2810 case SCEV_KNOWN:
2811 return chrec_known;
2813 case ARRAY_REF:
2814 return instantiate_array_ref (instantiate_below, evolution_loop,
2815 inner_loop, chrec,
2816 fold_conversions, size_expr);
2818 default:
2819 break;
2822 if (VL_EXP_CLASS_P (chrec))
2823 return chrec_dont_know;
2825 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
2827 case 3:
2828 return instantiate_scev_3 (instantiate_below, evolution_loop,
2829 inner_loop, chrec,
2830 fold_conversions, size_expr);
2832 case 2:
2833 return instantiate_scev_2 (instantiate_below, evolution_loop,
2834 inner_loop, chrec,
2835 fold_conversions, size_expr);
2837 case 1:
2838 return instantiate_scev_1 (instantiate_below, evolution_loop,
2839 inner_loop, chrec,
2840 fold_conversions, size_expr);
2842 case 0:
2843 return chrec;
2845 default:
2846 break;
2849 /* Too complicated to handle. */
2850 return chrec_dont_know;
2853 /* Analyze all the parameters of the chrec that were left under a
2854 symbolic form. INSTANTIATE_BELOW is the basic block that stops the
2855 recursive instantiation of parameters: a parameter is a variable
2856 that is defined in a basic block that dominates INSTANTIATE_BELOW or
2857 a function parameter. */
2859 tree
2860 instantiate_scev (basic_block instantiate_below, struct loop *evolution_loop,
2861 tree chrec)
2863 tree res;
2865 if (dump_file && (dump_flags & TDF_SCEV))
2867 fprintf (dump_file, "(instantiate_scev \n");
2868 fprintf (dump_file, " (instantiate_below = %d)\n", instantiate_below->index);
2869 fprintf (dump_file, " (evolution_loop = %d)\n", evolution_loop->num);
2870 fprintf (dump_file, " (chrec = ");
2871 print_generic_expr (dump_file, chrec, 0);
2872 fprintf (dump_file, ")\n");
2875 bool destr = false;
2876 if (!global_cache)
2878 global_cache = new instantiate_cache_type;
2879 destr = true;
2882 res = instantiate_scev_r (instantiate_below, evolution_loop,
2883 NULL, chrec, false, 0);
2885 if (destr)
2887 delete global_cache;
2888 global_cache = NULL;
2891 if (dump_file && (dump_flags & TDF_SCEV))
2893 fprintf (dump_file, " (res = ");
2894 print_generic_expr (dump_file, res, 0);
2895 fprintf (dump_file, "))\n");
2898 return res;
2901 /* Similar to instantiate_parameters, but does not introduce the
2902 evolutions in outer loops for LOOP invariants in CHREC, and does not
2903 care about causing overflows, as long as they do not affect value
2904 of an expression. */
2906 tree
2907 resolve_mixers (struct loop *loop, tree chrec)
2909 bool destr = false;
2910 if (!global_cache)
2912 global_cache = new instantiate_cache_type;
2913 destr = true;
2916 tree ret = instantiate_scev_r (block_before_loop (loop), loop, NULL,
2917 chrec, true, 0);
2919 if (destr)
2921 delete global_cache;
2922 global_cache = NULL;
2925 return ret;
2928 /* Entry point for the analysis of the number of iterations pass.
2929 This function tries to safely approximate the number of iterations
2930 the loop will run. When this property is not decidable at compile
2931 time, the result is chrec_dont_know. Otherwise the result is a
2932 scalar or a symbolic parameter. When the number of iterations may
2933 be equal to zero and the property cannot be determined at compile
2934 time, the result is a COND_EXPR that represents in a symbolic form
2935 the conditions under which the number of iterations is not zero.
2937 Example of analysis: suppose that the loop has an exit condition:
2939 "if (b > 49) goto end_loop;"
2941 and that in a previous analysis we have determined that the
2942 variable 'b' has an evolution function:
2944 "EF = {23, +, 5}_2".
2946 When we evaluate the function at the point 5, i.e. the value of the
2947 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2948 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2949 the loop body has been executed 6 times. */
2951 tree
2952 number_of_latch_executions (struct loop *loop)
2954 edge exit;
2955 struct tree_niter_desc niter_desc;
2956 tree may_be_zero;
2957 tree res;
2959 /* Determine whether the number of iterations in loop has already
2960 been computed. */
2961 res = loop->nb_iterations;
2962 if (res)
2963 return res;
2965 may_be_zero = NULL_TREE;
2967 if (dump_file && (dump_flags & TDF_SCEV))
2968 fprintf (dump_file, "(number_of_iterations_in_loop = \n");
2970 res = chrec_dont_know;
2971 exit = single_exit (loop);
2973 if (exit && number_of_iterations_exit (loop, exit, &niter_desc, false))
2975 may_be_zero = niter_desc.may_be_zero;
2976 res = niter_desc.niter;
2979 if (res == chrec_dont_know
2980 || !may_be_zero
2981 || integer_zerop (may_be_zero))
2983 else if (integer_nonzerop (may_be_zero))
2984 res = build_int_cst (TREE_TYPE (res), 0);
2986 else if (COMPARISON_CLASS_P (may_be_zero))
2987 res = fold_build3 (COND_EXPR, TREE_TYPE (res), may_be_zero,
2988 build_int_cst (TREE_TYPE (res), 0), res);
2989 else
2990 res = chrec_dont_know;
2992 if (dump_file && (dump_flags & TDF_SCEV))
2994 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
2995 print_generic_expr (dump_file, res, 0);
2996 fprintf (dump_file, "))\n");
2999 loop->nb_iterations = res;
3000 return res;
3004 /* Counters for the stats. */
3006 struct chrec_stats
3008 unsigned nb_chrecs;
3009 unsigned nb_affine;
3010 unsigned nb_affine_multivar;
3011 unsigned nb_higher_poly;
3012 unsigned nb_chrec_dont_know;
3013 unsigned nb_undetermined;
3016 /* Reset the counters. */
3018 static inline void
3019 reset_chrecs_counters (struct chrec_stats *stats)
3021 stats->nb_chrecs = 0;
3022 stats->nb_affine = 0;
3023 stats->nb_affine_multivar = 0;
3024 stats->nb_higher_poly = 0;
3025 stats->nb_chrec_dont_know = 0;
3026 stats->nb_undetermined = 0;
3029 /* Dump the contents of a CHREC_STATS structure. */
3031 static void
3032 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
3034 fprintf (file, "\n(\n");
3035 fprintf (file, "-----------------------------------------\n");
3036 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
3037 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
3038 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
3039 stats->nb_higher_poly);
3040 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
3041 fprintf (file, "-----------------------------------------\n");
3042 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
3043 fprintf (file, "%d\twith undetermined coefficients\n",
3044 stats->nb_undetermined);
3045 fprintf (file, "-----------------------------------------\n");
3046 fprintf (file, "%d\tchrecs in the scev database\n",
3047 (int) htab_elements (scalar_evolution_info));
3048 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
3049 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
3050 fprintf (file, "-----------------------------------------\n");
3051 fprintf (file, ")\n\n");
3054 /* Gather statistics about CHREC. */
3056 static void
3057 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
3059 if (dump_file && (dump_flags & TDF_STATS))
3061 fprintf (dump_file, "(classify_chrec ");
3062 print_generic_expr (dump_file, chrec, 0);
3063 fprintf (dump_file, "\n");
3066 stats->nb_chrecs++;
3068 if (chrec == NULL_TREE)
3070 stats->nb_undetermined++;
3071 return;
3074 switch (TREE_CODE (chrec))
3076 case POLYNOMIAL_CHREC:
3077 if (evolution_function_is_affine_p (chrec))
3079 if (dump_file && (dump_flags & TDF_STATS))
3080 fprintf (dump_file, " affine_univariate\n");
3081 stats->nb_affine++;
3083 else if (evolution_function_is_affine_multivariate_p (chrec, 0))
3085 if (dump_file && (dump_flags & TDF_STATS))
3086 fprintf (dump_file, " affine_multivariate\n");
3087 stats->nb_affine_multivar++;
3089 else
3091 if (dump_file && (dump_flags & TDF_STATS))
3092 fprintf (dump_file, " higher_degree_polynomial\n");
3093 stats->nb_higher_poly++;
3096 break;
3098 default:
3099 break;
3102 if (chrec_contains_undetermined (chrec))
3104 if (dump_file && (dump_flags & TDF_STATS))
3105 fprintf (dump_file, " undetermined\n");
3106 stats->nb_undetermined++;
3109 if (dump_file && (dump_flags & TDF_STATS))
3110 fprintf (dump_file, ")\n");
3113 /* Callback for htab_traverse, gathers information on chrecs in the
3114 hashtable. */
3116 static int
3117 gather_stats_on_scev_database_1 (void **slot, void *stats)
3119 struct scev_info_str *entry = (struct scev_info_str *) *slot;
3121 gather_chrec_stats (entry->chrec, (struct chrec_stats *) stats);
3123 return 1;
3126 /* Classify the chrecs of the whole database. */
3128 void
3129 gather_stats_on_scev_database (void)
3131 struct chrec_stats stats;
3133 if (!dump_file)
3134 return;
3136 reset_chrecs_counters (&stats);
3138 htab_traverse (scalar_evolution_info, gather_stats_on_scev_database_1,
3139 &stats);
3141 dump_chrecs_stats (dump_file, &stats);
3146 /* Initializer. */
3148 static void
3149 initialize_scalar_evolutions_analyzer (void)
3151 /* The elements below are unique. */
3152 if (chrec_dont_know == NULL_TREE)
3154 chrec_not_analyzed_yet = NULL_TREE;
3155 chrec_dont_know = make_node (SCEV_NOT_KNOWN);
3156 chrec_known = make_node (SCEV_KNOWN);
3157 TREE_TYPE (chrec_dont_know) = void_type_node;
3158 TREE_TYPE (chrec_known) = void_type_node;
3162 /* Initialize the analysis of scalar evolutions for LOOPS. */
3164 void
3165 scev_initialize (void)
3167 struct loop *loop;
3169 scalar_evolution_info = htab_create_ggc (100, hash_scev_info, eq_scev_info,
3170 del_scev_info);
3172 initialize_scalar_evolutions_analyzer ();
3174 FOR_EACH_LOOP (loop, 0)
3176 loop->nb_iterations = NULL_TREE;
3180 /* Return true if SCEV is initialized. */
3182 bool
3183 scev_initialized_p (void)
3185 return scalar_evolution_info != NULL;
3188 /* Cleans up the information cached by the scalar evolutions analysis
3189 in the hash table. */
3191 void
3192 scev_reset_htab (void)
3194 if (!scalar_evolution_info)
3195 return;
3197 htab_empty (scalar_evolution_info);
3200 /* Cleans up the information cached by the scalar evolutions analysis
3201 in the hash table and in the loop->nb_iterations. */
3203 void
3204 scev_reset (void)
3206 struct loop *loop;
3208 scev_reset_htab ();
3210 FOR_EACH_LOOP (loop, 0)
3212 loop->nb_iterations = NULL_TREE;
3216 /* Checks whether use of OP in USE_LOOP behaves as a simple affine iv with
3217 respect to WRTO_LOOP and returns its base and step in IV if possible
3218 (see analyze_scalar_evolution_in_loop for more details on USE_LOOP
3219 and WRTO_LOOP). If ALLOW_NONCONSTANT_STEP is true, we want step to be
3220 invariant in LOOP. Otherwise we require it to be an integer constant.
3222 IV->no_overflow is set to true if we are sure the iv cannot overflow (e.g.
3223 because it is computed in signed arithmetics). Consequently, adding an
3224 induction variable
3226 for (i = IV->base; ; i += IV->step)
3228 is only safe if IV->no_overflow is false, or TYPE_OVERFLOW_UNDEFINED is
3229 false for the type of the induction variable, or you can prove that i does
3230 not wrap by some other argument. Otherwise, this might introduce undefined
3231 behavior, and
3233 for (i = iv->base; ; i = (type) ((unsigned type) i + (unsigned type) iv->step))
3235 must be used instead. */
3237 bool
3238 simple_iv (struct loop *wrto_loop, struct loop *use_loop, tree op,
3239 affine_iv *iv, bool allow_nonconstant_step)
3241 tree type, ev;
3242 bool folded_casts;
3244 iv->base = NULL_TREE;
3245 iv->step = NULL_TREE;
3246 iv->no_overflow = false;
3248 type = TREE_TYPE (op);
3249 if (!POINTER_TYPE_P (type)
3250 && !INTEGRAL_TYPE_P (type))
3251 return false;
3253 ev = analyze_scalar_evolution_in_loop (wrto_loop, use_loop, op,
3254 &folded_casts);
3255 if (chrec_contains_undetermined (ev)
3256 || chrec_contains_symbols_defined_in_loop (ev, wrto_loop->num))
3257 return false;
3259 if (tree_does_not_contain_chrecs (ev))
3261 iv->base = ev;
3262 iv->step = build_int_cst (TREE_TYPE (ev), 0);
3263 iv->no_overflow = true;
3264 return true;
3267 if (TREE_CODE (ev) != POLYNOMIAL_CHREC
3268 || CHREC_VARIABLE (ev) != (unsigned) wrto_loop->num)
3269 return false;
3271 iv->step = CHREC_RIGHT (ev);
3272 if ((!allow_nonconstant_step && TREE_CODE (iv->step) != INTEGER_CST)
3273 || tree_contains_chrecs (iv->step, NULL))
3274 return false;
3276 iv->base = CHREC_LEFT (ev);
3277 if (tree_contains_chrecs (iv->base, NULL))
3278 return false;
3280 iv->no_overflow = !folded_casts && TYPE_OVERFLOW_UNDEFINED (type);
3282 return true;
3285 /* Finalize the scalar evolution analysis. */
3287 void
3288 scev_finalize (void)
3290 if (!scalar_evolution_info)
3291 return;
3292 htab_delete (scalar_evolution_info);
3293 scalar_evolution_info = NULL;
3296 /* Returns true if the expression EXPR is considered to be too expensive
3297 for scev_const_prop. */
3299 bool
3300 expression_expensive_p (tree expr)
3302 enum tree_code code;
3304 if (is_gimple_val (expr))
3305 return false;
3307 code = TREE_CODE (expr);
3308 if (code == TRUNC_DIV_EXPR
3309 || code == CEIL_DIV_EXPR
3310 || code == FLOOR_DIV_EXPR
3311 || code == ROUND_DIV_EXPR
3312 || code == TRUNC_MOD_EXPR
3313 || code == CEIL_MOD_EXPR
3314 || code == FLOOR_MOD_EXPR
3315 || code == ROUND_MOD_EXPR
3316 || code == EXACT_DIV_EXPR)
3318 /* Division by power of two is usually cheap, so we allow it.
3319 Forbid anything else. */
3320 if (!integer_pow2p (TREE_OPERAND (expr, 1)))
3321 return true;
3324 switch (TREE_CODE_CLASS (code))
3326 case tcc_binary:
3327 case tcc_comparison:
3328 if (expression_expensive_p (TREE_OPERAND (expr, 1)))
3329 return true;
3331 /* Fallthru. */
3332 case tcc_unary:
3333 return expression_expensive_p (TREE_OPERAND (expr, 0));
3335 default:
3336 return true;
3340 /* Replace ssa names for that scev can prove they are constant by the
3341 appropriate constants. Also perform final value replacement in loops,
3342 in case the replacement expressions are cheap.
3344 We only consider SSA names defined by phi nodes; rest is left to the
3345 ordinary constant propagation pass. */
3347 unsigned int
3348 scev_const_prop (void)
3350 basic_block bb;
3351 tree name, type, ev;
3352 gimple phi, ass;
3353 struct loop *loop, *ex_loop;
3354 bitmap ssa_names_to_remove = NULL;
3355 unsigned i;
3356 gimple_stmt_iterator psi;
3358 if (number_of_loops (cfun) <= 1)
3359 return 0;
3361 FOR_EACH_BB_FN (bb, cfun)
3363 loop = bb->loop_father;
3365 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
3367 phi = gsi_stmt (psi);
3368 name = PHI_RESULT (phi);
3370 if (virtual_operand_p (name))
3371 continue;
3373 type = TREE_TYPE (name);
3375 if (!POINTER_TYPE_P (type)
3376 && !INTEGRAL_TYPE_P (type))
3377 continue;
3379 ev = resolve_mixers (loop, analyze_scalar_evolution (loop, name));
3380 if (!is_gimple_min_invariant (ev)
3381 || !may_propagate_copy (name, ev))
3382 continue;
3384 /* Replace the uses of the name. */
3385 if (name != ev)
3386 replace_uses_by (name, ev);
3388 if (!ssa_names_to_remove)
3389 ssa_names_to_remove = BITMAP_ALLOC (NULL);
3390 bitmap_set_bit (ssa_names_to_remove, SSA_NAME_VERSION (name));
3394 /* Remove the ssa names that were replaced by constants. We do not
3395 remove them directly in the previous cycle, since this
3396 invalidates scev cache. */
3397 if (ssa_names_to_remove)
3399 bitmap_iterator bi;
3401 EXECUTE_IF_SET_IN_BITMAP (ssa_names_to_remove, 0, i, bi)
3403 gimple_stmt_iterator psi;
3404 name = ssa_name (i);
3405 phi = SSA_NAME_DEF_STMT (name);
3407 gcc_assert (gimple_code (phi) == GIMPLE_PHI);
3408 psi = gsi_for_stmt (phi);
3409 remove_phi_node (&psi, true);
3412 BITMAP_FREE (ssa_names_to_remove);
3413 scev_reset ();
3416 /* Now the regular final value replacement. */
3417 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
3419 edge exit;
3420 tree def, rslt, niter;
3421 gimple_stmt_iterator gsi;
3423 /* If we do not know exact number of iterations of the loop, we cannot
3424 replace the final value. */
3425 exit = single_exit (loop);
3426 if (!exit)
3427 continue;
3429 niter = number_of_latch_executions (loop);
3430 if (niter == chrec_dont_know)
3431 continue;
3433 /* Ensure that it is possible to insert new statements somewhere. */
3434 if (!single_pred_p (exit->dest))
3435 split_loop_exit_edge (exit);
3436 gsi = gsi_after_labels (exit->dest);
3438 ex_loop = superloop_at_depth (loop,
3439 loop_depth (exit->dest->loop_father) + 1);
3441 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); )
3443 phi = gsi_stmt (psi);
3444 rslt = PHI_RESULT (phi);
3445 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
3446 if (virtual_operand_p (def))
3448 gsi_next (&psi);
3449 continue;
3452 if (!POINTER_TYPE_P (TREE_TYPE (def))
3453 && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
3455 gsi_next (&psi);
3456 continue;
3459 bool folded_casts;
3460 def = analyze_scalar_evolution_in_loop (ex_loop, loop, def,
3461 &folded_casts);
3462 def = compute_overall_effect_of_inner_loop (ex_loop, def);
3463 if (!tree_does_not_contain_chrecs (def)
3464 || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
3465 /* Moving the computation from the loop may prolong life range
3466 of some ssa names, which may cause problems if they appear
3467 on abnormal edges. */
3468 || contains_abnormal_ssa_name_p (def)
3469 /* Do not emit expensive expressions. The rationale is that
3470 when someone writes a code like
3472 while (n > 45) n -= 45;
3474 he probably knows that n is not large, and does not want it
3475 to be turned into n %= 45. */
3476 || expression_expensive_p (def))
3478 if (dump_file && (dump_flags & TDF_DETAILS))
3480 fprintf (dump_file, "not replacing:\n ");
3481 print_gimple_stmt (dump_file, phi, 0, 0);
3482 fprintf (dump_file, "\n");
3484 gsi_next (&psi);
3485 continue;
3488 /* Eliminate the PHI node and replace it by a computation outside
3489 the loop. */
3490 if (dump_file)
3492 fprintf (dump_file, "\nfinal value replacement:\n ");
3493 print_gimple_stmt (dump_file, phi, 0, 0);
3494 fprintf (dump_file, " with\n ");
3496 def = unshare_expr (def);
3497 remove_phi_node (&psi, false);
3499 /* If def's type has undefined overflow and there were folded
3500 casts, rewrite all stmts added for def into arithmetics
3501 with defined overflow behavior. */
3502 if (folded_casts && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (def)))
3504 gimple_seq stmts;
3505 gimple_stmt_iterator gsi2;
3506 def = force_gimple_operand (def, &stmts, true, NULL_TREE);
3507 gsi2 = gsi_start (stmts);
3508 while (!gsi_end_p (gsi2))
3510 gimple stmt = gsi_stmt (gsi2);
3511 gimple_stmt_iterator gsi3 = gsi2;
3512 gsi_next (&gsi2);
3513 gsi_remove (&gsi3, false);
3514 if (is_gimple_assign (stmt)
3515 && arith_code_with_undefined_signed_overflow
3516 (gimple_assign_rhs_code (stmt)))
3517 gsi_insert_seq_before (&gsi,
3518 rewrite_to_defined_overflow (stmt),
3519 GSI_SAME_STMT);
3520 else
3521 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
3524 else
3525 def = force_gimple_operand_gsi (&gsi, def, false, NULL_TREE,
3526 true, GSI_SAME_STMT);
3528 ass = gimple_build_assign (rslt, def);
3529 gsi_insert_before (&gsi, ass, GSI_SAME_STMT);
3530 if (dump_file)
3532 print_gimple_stmt (dump_file, ass, 0, 0);
3533 fprintf (dump_file, "\n");
3537 return 0;
3540 #include "gt-tree-scalar-evolution.h"