[Ada] New aspect/pragma No_Caching for analysis of volatile data
[official-gcc.git] / gcc / tree-scalar-evolution.c
blob4b72a25d350a1c766ca726346d18d4575ed9e8ff
1 /* Scalar evolution detector.
2 Copyright (C) 2003-2019 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 "backend.h"
260 #include "target.h"
261 #include "rtl.h"
262 #include "optabs-query.h"
263 #include "tree.h"
264 #include "gimple.h"
265 #include "ssa.h"
266 #include "gimple-pretty-print.h"
267 #include "fold-const.h"
268 #include "gimplify.h"
269 #include "gimple-iterator.h"
270 #include "gimplify-me.h"
271 #include "tree-cfg.h"
272 #include "tree-ssa-loop-ivopts.h"
273 #include "tree-ssa-loop-manip.h"
274 #include "tree-ssa-loop-niter.h"
275 #include "tree-ssa-loop.h"
276 #include "tree-ssa.h"
277 #include "cfgloop.h"
278 #include "tree-chrec.h"
279 #include "tree-affine.h"
280 #include "tree-scalar-evolution.h"
281 #include "dumpfile.h"
282 #include "params.h"
283 #include "tree-ssa-propagate.h"
284 #include "gimple-fold.h"
285 #include "tree-into-ssa.h"
286 #include "builtins.h"
287 #include "case-cfn-macros.h"
289 static tree analyze_scalar_evolution_1 (class loop *, tree);
290 static tree analyze_scalar_evolution_for_address_of (class loop *loop,
291 tree var);
293 /* The cached information about an SSA name with version NAME_VERSION,
294 claiming that below basic block with index INSTANTIATED_BELOW, the
295 value of the SSA name can be expressed as CHREC. */
297 struct GTY((for_user)) scev_info_str {
298 unsigned int name_version;
299 int instantiated_below;
300 tree chrec;
303 /* Counters for the scev database. */
304 static unsigned nb_set_scev = 0;
305 static unsigned nb_get_scev = 0;
307 struct scev_info_hasher : ggc_ptr_hash<scev_info_str>
309 static hashval_t hash (scev_info_str *i);
310 static bool equal (const scev_info_str *a, const scev_info_str *b);
313 static GTY (()) hash_table<scev_info_hasher> *scalar_evolution_info;
316 /* Constructs a new SCEV_INFO_STR structure for VAR and INSTANTIATED_BELOW. */
318 static inline struct scev_info_str *
319 new_scev_info_str (basic_block instantiated_below, tree var)
321 struct scev_info_str *res;
323 res = ggc_alloc<scev_info_str> ();
324 res->name_version = SSA_NAME_VERSION (var);
325 res->chrec = chrec_not_analyzed_yet;
326 res->instantiated_below = instantiated_below->index;
328 return res;
331 /* Computes a hash function for database element ELT. */
333 hashval_t
334 scev_info_hasher::hash (scev_info_str *elt)
336 return elt->name_version ^ elt->instantiated_below;
339 /* Compares database elements E1 and E2. */
341 bool
342 scev_info_hasher::equal (const scev_info_str *elt1, const scev_info_str *elt2)
344 return (elt1->name_version == elt2->name_version
345 && elt1->instantiated_below == elt2->instantiated_below);
348 /* Get the scalar evolution of VAR for INSTANTIATED_BELOW basic block.
349 A first query on VAR returns chrec_not_analyzed_yet. */
351 static tree *
352 find_var_scev_info (basic_block instantiated_below, tree var)
354 struct scev_info_str *res;
355 struct scev_info_str tmp;
357 tmp.name_version = SSA_NAME_VERSION (var);
358 tmp.instantiated_below = instantiated_below->index;
359 scev_info_str **slot = scalar_evolution_info->find_slot (&tmp, INSERT);
361 if (!*slot)
362 *slot = new_scev_info_str (instantiated_below, var);
363 res = *slot;
365 return &res->chrec;
369 /* Hashtable helpers for a temporary hash-table used when
370 analyzing a scalar evolution, instantiating a CHREC or
371 resolving mixers. */
373 class instantiate_cache_type
375 public:
376 htab_t map;
377 vec<scev_info_str> entries;
379 instantiate_cache_type () : map (NULL), entries (vNULL) {}
380 ~instantiate_cache_type ();
381 tree get (unsigned slot) { return entries[slot].chrec; }
382 void set (unsigned slot, tree chrec) { entries[slot].chrec = chrec; }
385 instantiate_cache_type::~instantiate_cache_type ()
387 if (map != NULL)
389 htab_delete (map);
390 entries.release ();
394 /* Cache to avoid infinite recursion when instantiating an SSA name.
395 Live during the outermost analyze_scalar_evolution, instantiate_scev
396 or resolve_mixers call. */
397 static instantiate_cache_type *global_cache;
400 /* Return true when PHI is a loop-phi-node. */
402 static bool
403 loop_phi_node_p (gimple *phi)
405 /* The implementation of this function is based on the following
406 property: "all the loop-phi-nodes of a loop are contained in the
407 loop's header basic block". */
409 return loop_containing_stmt (phi)->header == gimple_bb (phi);
412 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
413 In general, in the case of multivariate evolutions we want to get
414 the evolution in different loops. LOOP specifies the level for
415 which to get the evolution.
417 Example:
419 | for (j = 0; j < 100; j++)
421 | for (k = 0; k < 100; k++)
423 | i = k + j; - Here the value of i is a function of j, k.
425 | ... = i - Here the value of i is a function of j.
427 | ... = i - Here the value of i is a scalar.
429 Example:
431 | i_0 = ...
432 | loop_1 10 times
433 | i_1 = phi (i_0, i_2)
434 | i_2 = i_1 + 2
435 | endloop
437 This loop has the same effect as:
438 LOOP_1 has the same effect as:
440 | i_1 = i_0 + 20
442 The overall effect of the loop, "i_0 + 20" in the previous example,
443 is obtained by passing in the parameters: LOOP = 1,
444 EVOLUTION_FN = {i_0, +, 2}_1.
447 tree
448 compute_overall_effect_of_inner_loop (class loop *loop, tree evolution_fn)
450 bool val = false;
452 if (evolution_fn == chrec_dont_know)
453 return chrec_dont_know;
455 else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
457 class loop *inner_loop = get_chrec_loop (evolution_fn);
459 if (inner_loop == loop
460 || flow_loop_nested_p (loop, inner_loop))
462 tree nb_iter = number_of_latch_executions (inner_loop);
464 if (nb_iter == chrec_dont_know)
465 return chrec_dont_know;
466 else
468 tree res;
470 /* evolution_fn is the evolution function in LOOP. Get
471 its value in the nb_iter-th iteration. */
472 res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
474 if (chrec_contains_symbols_defined_in_loop (res, loop->num))
475 res = instantiate_parameters (loop, res);
477 /* Continue the computation until ending on a parent of LOOP. */
478 return compute_overall_effect_of_inner_loop (loop, res);
481 else
482 return evolution_fn;
485 /* If the evolution function is an invariant, there is nothing to do. */
486 else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
487 return evolution_fn;
489 else
490 return chrec_dont_know;
493 /* Associate CHREC to SCALAR. */
495 static void
496 set_scalar_evolution (basic_block instantiated_below, tree scalar, tree chrec)
498 tree *scalar_info;
500 if (TREE_CODE (scalar) != SSA_NAME)
501 return;
503 scalar_info = find_var_scev_info (instantiated_below, scalar);
505 if (dump_file)
507 if (dump_flags & TDF_SCEV)
509 fprintf (dump_file, "(set_scalar_evolution \n");
510 fprintf (dump_file, " instantiated_below = %d \n",
511 instantiated_below->index);
512 fprintf (dump_file, " (scalar = ");
513 print_generic_expr (dump_file, scalar);
514 fprintf (dump_file, ")\n (scalar_evolution = ");
515 print_generic_expr (dump_file, chrec);
516 fprintf (dump_file, "))\n");
518 if (dump_flags & TDF_STATS)
519 nb_set_scev++;
522 *scalar_info = chrec;
525 /* Retrieve the chrec associated to SCALAR instantiated below
526 INSTANTIATED_BELOW block. */
528 static tree
529 get_scalar_evolution (basic_block instantiated_below, tree scalar)
531 tree res;
533 if (dump_file)
535 if (dump_flags & TDF_SCEV)
537 fprintf (dump_file, "(get_scalar_evolution \n");
538 fprintf (dump_file, " (scalar = ");
539 print_generic_expr (dump_file, scalar);
540 fprintf (dump_file, ")\n");
542 if (dump_flags & TDF_STATS)
543 nb_get_scev++;
546 if (VECTOR_TYPE_P (TREE_TYPE (scalar))
547 || TREE_CODE (TREE_TYPE (scalar)) == COMPLEX_TYPE)
548 /* For chrec_dont_know we keep the symbolic form. */
549 res = scalar;
550 else
551 switch (TREE_CODE (scalar))
553 case SSA_NAME:
554 if (SSA_NAME_IS_DEFAULT_DEF (scalar))
555 res = scalar;
556 else
557 res = *find_var_scev_info (instantiated_below, scalar);
558 break;
560 case REAL_CST:
561 case FIXED_CST:
562 case INTEGER_CST:
563 res = scalar;
564 break;
566 default:
567 res = chrec_not_analyzed_yet;
568 break;
571 if (dump_file && (dump_flags & TDF_SCEV))
573 fprintf (dump_file, " (scalar_evolution = ");
574 print_generic_expr (dump_file, res);
575 fprintf (dump_file, "))\n");
578 return res;
581 /* Helper function for add_to_evolution. Returns the evolution
582 function for an assignment of the form "a = b + c", where "a" and
583 "b" are on the strongly connected component. CHREC_BEFORE is the
584 information that we already have collected up to this point.
585 TO_ADD is the evolution of "c".
587 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
588 evolution the expression TO_ADD, otherwise construct an evolution
589 part for this loop. */
591 static tree
592 add_to_evolution_1 (unsigned loop_nb, tree chrec_before, tree to_add,
593 gimple *at_stmt)
595 tree type, left, right;
596 class loop *loop = get_loop (cfun, loop_nb), *chloop;
598 switch (TREE_CODE (chrec_before))
600 case POLYNOMIAL_CHREC:
601 chloop = get_chrec_loop (chrec_before);
602 if (chloop == loop
603 || flow_loop_nested_p (chloop, loop))
605 unsigned var;
607 type = chrec_type (chrec_before);
609 /* When there is no evolution part in this loop, build it. */
610 if (chloop != loop)
612 var = loop_nb;
613 left = chrec_before;
614 right = SCALAR_FLOAT_TYPE_P (type)
615 ? build_real (type, dconst0)
616 : build_int_cst (type, 0);
618 else
620 var = CHREC_VARIABLE (chrec_before);
621 left = CHREC_LEFT (chrec_before);
622 right = CHREC_RIGHT (chrec_before);
625 to_add = chrec_convert (type, to_add, at_stmt);
626 right = chrec_convert_rhs (type, right, at_stmt);
627 right = chrec_fold_plus (chrec_type (right), right, to_add);
628 return build_polynomial_chrec (var, left, right);
630 else
632 gcc_assert (flow_loop_nested_p (loop, chloop));
634 /* Search the evolution in LOOP_NB. */
635 left = add_to_evolution_1 (loop_nb, CHREC_LEFT (chrec_before),
636 to_add, at_stmt);
637 right = CHREC_RIGHT (chrec_before);
638 right = chrec_convert_rhs (chrec_type (left), right, at_stmt);
639 return build_polynomial_chrec (CHREC_VARIABLE (chrec_before),
640 left, right);
643 default:
644 /* These nodes do not depend on a loop. */
645 if (chrec_before == chrec_dont_know)
646 return chrec_dont_know;
648 left = chrec_before;
649 right = chrec_convert_rhs (chrec_type (left), to_add, at_stmt);
650 return build_polynomial_chrec (loop_nb, left, right);
654 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
655 of LOOP_NB.
657 Description (provided for completeness, for those who read code in
658 a plane, and for my poor 62 bytes brain that would have forgotten
659 all this in the next two or three months):
661 The algorithm of translation of programs from the SSA representation
662 into the chrecs syntax is based on a pattern matching. After having
663 reconstructed the overall tree expression for a loop, there are only
664 two cases that can arise:
666 1. a = loop-phi (init, a + expr)
667 2. a = loop-phi (init, expr)
669 where EXPR is either a scalar constant with respect to the analyzed
670 loop (this is a degree 0 polynomial), or an expression containing
671 other loop-phi definitions (these are higher degree polynomials).
673 Examples:
676 | init = ...
677 | loop_1
678 | a = phi (init, a + 5)
679 | endloop
682 | inita = ...
683 | initb = ...
684 | loop_1
685 | a = phi (inita, 2 * b + 3)
686 | b = phi (initb, b + 1)
687 | endloop
689 For the first case, the semantics of the SSA representation is:
691 | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
693 that is, there is a loop index "x" that determines the scalar value
694 of the variable during the loop execution. During the first
695 iteration, the value is that of the initial condition INIT, while
696 during the subsequent iterations, it is the sum of the initial
697 condition with the sum of all the values of EXPR from the initial
698 iteration to the before last considered iteration.
700 For the second case, the semantics of the SSA program is:
702 | a (x) = init, if x = 0;
703 | expr (x - 1), otherwise.
705 The second case corresponds to the PEELED_CHREC, whose syntax is
706 close to the syntax of a loop-phi-node:
708 | phi (init, expr) vs. (init, expr)_x
710 The proof of the translation algorithm for the first case is a
711 proof by structural induction based on the degree of EXPR.
713 Degree 0:
714 When EXPR is a constant with respect to the analyzed loop, or in
715 other words when EXPR is a polynomial of degree 0, the evolution of
716 the variable A in the loop is an affine function with an initial
717 condition INIT, and a step EXPR. In order to show this, we start
718 from the semantics of the SSA representation:
720 f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
722 and since "expr (j)" is a constant with respect to "j",
724 f (x) = init + x * expr
726 Finally, based on the semantics of the pure sum chrecs, by
727 identification we get the corresponding chrecs syntax:
729 f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
730 f (x) -> {init, +, expr}_x
732 Higher degree:
733 Suppose that EXPR is a polynomial of degree N with respect to the
734 analyzed loop_x for which we have already determined that it is
735 written under the chrecs syntax:
737 | expr (x) -> {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
739 We start from the semantics of the SSA program:
741 | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
743 | f (x) = init + \sum_{j = 0}^{x - 1}
744 | (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
746 | f (x) = init + \sum_{j = 0}^{x - 1}
747 | \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
749 | f (x) = init + \sum_{k = 0}^{n - 1}
750 | (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
752 | f (x) = init + \sum_{k = 0}^{n - 1}
753 | (b_k * \binom{x}{k + 1})
755 | f (x) = init + b_0 * \binom{x}{1} + ...
756 | + b_{n-1} * \binom{x}{n}
758 | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
759 | + b_{n-1} * \binom{x}{n}
762 And finally from the definition of the chrecs syntax, we identify:
763 | f (x) -> {init, +, b_0, +, ..., +, b_{n-1}}_x
765 This shows the mechanism that stands behind the add_to_evolution
766 function. An important point is that the use of symbolic
767 parameters avoids the need of an analysis schedule.
769 Example:
771 | inita = ...
772 | initb = ...
773 | loop_1
774 | a = phi (inita, a + 2 + b)
775 | b = phi (initb, b + 1)
776 | endloop
778 When analyzing "a", the algorithm keeps "b" symbolically:
780 | a -> {inita, +, 2 + b}_1
782 Then, after instantiation, the analyzer ends on the evolution:
784 | a -> {inita, +, 2 + initb, +, 1}_1
788 static tree
789 add_to_evolution (unsigned loop_nb, tree chrec_before, enum tree_code code,
790 tree to_add, gimple *at_stmt)
792 tree type = chrec_type (to_add);
793 tree res = NULL_TREE;
795 if (to_add == NULL_TREE)
796 return chrec_before;
798 /* TO_ADD is either a scalar, or a parameter. TO_ADD is not
799 instantiated at this point. */
800 if (TREE_CODE (to_add) == POLYNOMIAL_CHREC)
801 /* This should not happen. */
802 return chrec_dont_know;
804 if (dump_file && (dump_flags & TDF_SCEV))
806 fprintf (dump_file, "(add_to_evolution \n");
807 fprintf (dump_file, " (loop_nb = %d)\n", loop_nb);
808 fprintf (dump_file, " (chrec_before = ");
809 print_generic_expr (dump_file, chrec_before);
810 fprintf (dump_file, ")\n (to_add = ");
811 print_generic_expr (dump_file, to_add);
812 fprintf (dump_file, ")\n");
815 if (code == MINUS_EXPR)
816 to_add = chrec_fold_multiply (type, to_add, SCALAR_FLOAT_TYPE_P (type)
817 ? build_real (type, dconstm1)
818 : build_int_cst_type (type, -1));
820 res = add_to_evolution_1 (loop_nb, chrec_before, to_add, at_stmt);
822 if (dump_file && (dump_flags & TDF_SCEV))
824 fprintf (dump_file, " (res = ");
825 print_generic_expr (dump_file, res);
826 fprintf (dump_file, "))\n");
829 return res;
834 /* This section selects the loops that will be good candidates for the
835 scalar evolution analysis. For the moment, greedily select all the
836 loop nests we could analyze. */
838 /* For a loop with a single exit edge, return the COND_EXPR that
839 guards the exit edge. If the expression is too difficult to
840 analyze, then give up. */
842 gcond *
843 get_loop_exit_condition (const class loop *loop)
845 gcond *res = NULL;
846 edge exit_edge = single_exit (loop);
848 if (dump_file && (dump_flags & TDF_SCEV))
849 fprintf (dump_file, "(get_loop_exit_condition \n ");
851 if (exit_edge)
853 gimple *stmt;
855 stmt = last_stmt (exit_edge->src);
856 if (gcond *cond_stmt = safe_dyn_cast <gcond *> (stmt))
857 res = cond_stmt;
860 if (dump_file && (dump_flags & TDF_SCEV))
862 print_gimple_stmt (dump_file, res, 0);
863 fprintf (dump_file, ")\n");
866 return res;
870 /* Depth first search algorithm. */
872 enum t_bool {
873 t_false,
874 t_true,
875 t_dont_know
879 static t_bool follow_ssa_edge (class loop *loop, gimple *, gphi *,
880 tree *, int);
882 /* Follow the ssa edge into the binary expression RHS0 CODE RHS1.
883 Return true if the strongly connected component has been found. */
885 static t_bool
886 follow_ssa_edge_binary (class loop *loop, gimple *at_stmt,
887 tree type, tree rhs0, enum tree_code code, tree rhs1,
888 gphi *halting_phi, tree *evolution_of_loop,
889 int limit)
891 t_bool res = t_false;
892 tree evol;
894 switch (code)
896 case POINTER_PLUS_EXPR:
897 case PLUS_EXPR:
898 if (TREE_CODE (rhs0) == SSA_NAME)
900 if (TREE_CODE (rhs1) == SSA_NAME)
902 /* Match an assignment under the form:
903 "a = b + c". */
905 /* We want only assignments of form "name + name" contribute to
906 LIMIT, as the other cases do not necessarily contribute to
907 the complexity of the expression. */
908 limit++;
910 evol = *evolution_of_loop;
911 evol = add_to_evolution
912 (loop->num,
913 chrec_convert (type, evol, at_stmt),
914 code, rhs1, at_stmt);
915 res = follow_ssa_edge
916 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi, &evol, limit);
917 if (res == t_true)
918 *evolution_of_loop = evol;
919 else if (res == t_false)
921 *evolution_of_loop = add_to_evolution
922 (loop->num,
923 chrec_convert (type, *evolution_of_loop, at_stmt),
924 code, rhs0, at_stmt);
925 res = follow_ssa_edge
926 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
927 evolution_of_loop, limit);
928 if (res == t_true)
930 else if (res == t_dont_know)
931 *evolution_of_loop = chrec_dont_know;
934 else if (res == t_dont_know)
935 *evolution_of_loop = chrec_dont_know;
938 else
940 /* Match an assignment under the form:
941 "a = b + ...". */
942 *evolution_of_loop = add_to_evolution
943 (loop->num, chrec_convert (type, *evolution_of_loop,
944 at_stmt),
945 code, rhs1, at_stmt);
946 res = follow_ssa_edge
947 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
948 evolution_of_loop, limit);
949 if (res == t_true)
951 else if (res == t_dont_know)
952 *evolution_of_loop = chrec_dont_know;
956 else if (TREE_CODE (rhs1) == SSA_NAME)
958 /* Match an assignment under the form:
959 "a = ... + c". */
960 *evolution_of_loop = add_to_evolution
961 (loop->num, chrec_convert (type, *evolution_of_loop,
962 at_stmt),
963 code, rhs0, at_stmt);
964 res = follow_ssa_edge
965 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
966 evolution_of_loop, limit);
967 if (res == t_true)
969 else if (res == t_dont_know)
970 *evolution_of_loop = chrec_dont_know;
973 else
974 /* Otherwise, match an assignment under the form:
975 "a = ... + ...". */
976 /* And there is nothing to do. */
977 res = t_false;
978 break;
980 case MINUS_EXPR:
981 /* This case is under the form "opnd0 = rhs0 - rhs1". */
982 if (TREE_CODE (rhs0) == SSA_NAME)
984 /* Match an assignment under the form:
985 "a = b - ...". */
987 /* We want only assignments of form "name - name" contribute to
988 LIMIT, as the other cases do not necessarily contribute to
989 the complexity of the expression. */
990 if (TREE_CODE (rhs1) == SSA_NAME)
991 limit++;
993 *evolution_of_loop = add_to_evolution
994 (loop->num, chrec_convert (type, *evolution_of_loop, at_stmt),
995 MINUS_EXPR, rhs1, at_stmt);
996 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
997 evolution_of_loop, limit);
998 if (res == t_true)
1000 else if (res == t_dont_know)
1001 *evolution_of_loop = chrec_dont_know;
1003 else
1004 /* Otherwise, match an assignment under the form:
1005 "a = ... - ...". */
1006 /* And there is nothing to do. */
1007 res = t_false;
1008 break;
1010 default:
1011 res = t_false;
1014 return res;
1017 /* Follow the ssa edge into the expression EXPR.
1018 Return true if the strongly connected component has been found. */
1020 static t_bool
1021 follow_ssa_edge_expr (class loop *loop, gimple *at_stmt, tree expr,
1022 gphi *halting_phi, tree *evolution_of_loop,
1023 int limit)
1025 enum tree_code code = TREE_CODE (expr);
1026 tree type = TREE_TYPE (expr), rhs0, rhs1;
1027 t_bool res;
1029 /* The EXPR is one of the following cases:
1030 - an SSA_NAME,
1031 - an INTEGER_CST,
1032 - a PLUS_EXPR,
1033 - a POINTER_PLUS_EXPR,
1034 - a MINUS_EXPR,
1035 - an ASSERT_EXPR,
1036 - other cases are not yet handled. */
1038 switch (code)
1040 CASE_CONVERT:
1041 /* This assignment is under the form "a_1 = (cast) rhs. */
1042 res = follow_ssa_edge_expr (loop, at_stmt, TREE_OPERAND (expr, 0),
1043 halting_phi, evolution_of_loop, limit);
1044 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, at_stmt);
1045 break;
1047 case INTEGER_CST:
1048 /* This assignment is under the form "a_1 = 7". */
1049 res = t_false;
1050 break;
1052 case SSA_NAME:
1053 /* This assignment is under the form: "a_1 = b_2". */
1054 res = follow_ssa_edge
1055 (loop, SSA_NAME_DEF_STMT (expr), halting_phi, evolution_of_loop, limit);
1056 break;
1058 case POINTER_PLUS_EXPR:
1059 case PLUS_EXPR:
1060 case MINUS_EXPR:
1061 /* This case is under the form "rhs0 +- rhs1". */
1062 rhs0 = TREE_OPERAND (expr, 0);
1063 rhs1 = TREE_OPERAND (expr, 1);
1064 type = TREE_TYPE (rhs0);
1065 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1066 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1067 res = follow_ssa_edge_binary (loop, at_stmt, type, rhs0, code, rhs1,
1068 halting_phi, evolution_of_loop, limit);
1069 break;
1071 case ADDR_EXPR:
1072 /* Handle &MEM[ptr + CST] which is equivalent to POINTER_PLUS_EXPR. */
1073 if (TREE_CODE (TREE_OPERAND (expr, 0)) == MEM_REF)
1075 expr = TREE_OPERAND (expr, 0);
1076 rhs0 = TREE_OPERAND (expr, 0);
1077 rhs1 = TREE_OPERAND (expr, 1);
1078 type = TREE_TYPE (rhs0);
1079 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1080 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1081 res = follow_ssa_edge_binary (loop, at_stmt, type,
1082 rhs0, POINTER_PLUS_EXPR, rhs1,
1083 halting_phi, evolution_of_loop, limit);
1085 else
1086 res = t_false;
1087 break;
1089 case ASSERT_EXPR:
1090 /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1091 It must be handled as a copy assignment of the form a_1 = a_2. */
1092 rhs0 = ASSERT_EXPR_VAR (expr);
1093 if (TREE_CODE (rhs0) == SSA_NAME)
1094 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0),
1095 halting_phi, evolution_of_loop, limit);
1096 else
1097 res = t_false;
1098 break;
1100 default:
1101 res = t_false;
1102 break;
1105 return res;
1108 /* Follow the ssa edge into the right hand side of an assignment STMT.
1109 Return true if the strongly connected component has been found. */
1111 static t_bool
1112 follow_ssa_edge_in_rhs (class loop *loop, gimple *stmt,
1113 gphi *halting_phi, tree *evolution_of_loop,
1114 int limit)
1116 enum tree_code code = gimple_assign_rhs_code (stmt);
1117 tree type = gimple_expr_type (stmt), rhs1, rhs2;
1118 t_bool res;
1120 switch (code)
1122 CASE_CONVERT:
1123 /* This assignment is under the form "a_1 = (cast) rhs. */
1124 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1125 halting_phi, evolution_of_loop, limit);
1126 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, stmt);
1127 break;
1129 case POINTER_PLUS_EXPR:
1130 case PLUS_EXPR:
1131 case MINUS_EXPR:
1132 rhs1 = gimple_assign_rhs1 (stmt);
1133 rhs2 = gimple_assign_rhs2 (stmt);
1134 type = TREE_TYPE (rhs1);
1135 res = follow_ssa_edge_binary (loop, stmt, type, rhs1, code, rhs2,
1136 halting_phi, evolution_of_loop, limit);
1137 break;
1139 default:
1140 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1141 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1142 halting_phi, evolution_of_loop, limit);
1143 else
1144 res = t_false;
1145 break;
1148 return res;
1151 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1153 static bool
1154 backedge_phi_arg_p (gphi *phi, int i)
1156 const_edge e = gimple_phi_arg_edge (phi, i);
1158 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1159 about updating it anywhere, and this should work as well most of the
1160 time. */
1161 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1162 return true;
1164 return false;
1167 /* Helper function for one branch of the condition-phi-node. Return
1168 true if the strongly connected component has been found following
1169 this path. */
1171 static inline t_bool
1172 follow_ssa_edge_in_condition_phi_branch (int i,
1173 class loop *loop,
1174 gphi *condition_phi,
1175 gphi *halting_phi,
1176 tree *evolution_of_branch,
1177 tree init_cond, int limit)
1179 tree branch = PHI_ARG_DEF (condition_phi, i);
1180 *evolution_of_branch = chrec_dont_know;
1182 /* Do not follow back edges (they must belong to an irreducible loop, which
1183 we really do not want to worry about). */
1184 if (backedge_phi_arg_p (condition_phi, i))
1185 return t_false;
1187 if (TREE_CODE (branch) == SSA_NAME)
1189 *evolution_of_branch = init_cond;
1190 return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1191 evolution_of_branch, limit);
1194 /* This case occurs when one of the condition branches sets
1195 the variable to a constant: i.e. a phi-node like
1196 "a_2 = PHI <a_7(5), 2(6)>;".
1198 FIXME: This case have to be refined correctly:
1199 in some cases it is possible to say something better than
1200 chrec_dont_know, for example using a wrap-around notation. */
1201 return t_false;
1204 /* This function merges the branches of a condition-phi-node in a
1205 loop. */
1207 static t_bool
1208 follow_ssa_edge_in_condition_phi (class loop *loop,
1209 gphi *condition_phi,
1210 gphi *halting_phi,
1211 tree *evolution_of_loop, int limit)
1213 int i, n;
1214 tree init = *evolution_of_loop;
1215 tree evolution_of_branch;
1216 t_bool res = follow_ssa_edge_in_condition_phi_branch (0, loop, condition_phi,
1217 halting_phi,
1218 &evolution_of_branch,
1219 init, limit);
1220 if (res == t_false || res == t_dont_know)
1221 return res;
1223 *evolution_of_loop = evolution_of_branch;
1225 n = gimple_phi_num_args (condition_phi);
1226 for (i = 1; i < n; i++)
1228 /* Quickly give up when the evolution of one of the branches is
1229 not known. */
1230 if (*evolution_of_loop == chrec_dont_know)
1231 return t_true;
1233 /* Increase the limit by the PHI argument number to avoid exponential
1234 time and memory complexity. */
1235 res = follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1236 halting_phi,
1237 &evolution_of_branch,
1238 init, limit + i);
1239 if (res == t_false || res == t_dont_know)
1240 return res;
1242 *evolution_of_loop = chrec_merge (*evolution_of_loop,
1243 evolution_of_branch);
1246 return t_true;
1249 /* Follow an SSA edge in an inner loop. It computes the overall
1250 effect of the loop, and following the symbolic initial conditions,
1251 it follows the edges in the parent loop. The inner loop is
1252 considered as a single statement. */
1254 static t_bool
1255 follow_ssa_edge_inner_loop_phi (class loop *outer_loop,
1256 gphi *loop_phi_node,
1257 gphi *halting_phi,
1258 tree *evolution_of_loop, int limit)
1260 class loop *loop = loop_containing_stmt (loop_phi_node);
1261 tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1263 /* Sometimes, the inner loop is too difficult to analyze, and the
1264 result of the analysis is a symbolic parameter. */
1265 if (ev == PHI_RESULT (loop_phi_node))
1267 t_bool res = t_false;
1268 int i, n = gimple_phi_num_args (loop_phi_node);
1270 for (i = 0; i < n; i++)
1272 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1273 basic_block bb;
1275 /* Follow the edges that exit the inner loop. */
1276 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1277 if (!flow_bb_inside_loop_p (loop, bb))
1278 res = follow_ssa_edge_expr (outer_loop, loop_phi_node,
1279 arg, halting_phi,
1280 evolution_of_loop, limit);
1281 if (res == t_true)
1282 break;
1285 /* If the path crosses this loop-phi, give up. */
1286 if (res == t_true)
1287 *evolution_of_loop = chrec_dont_know;
1289 return res;
1292 /* Otherwise, compute the overall effect of the inner loop. */
1293 ev = compute_overall_effect_of_inner_loop (loop, ev);
1294 return follow_ssa_edge_expr (outer_loop, loop_phi_node, ev, halting_phi,
1295 evolution_of_loop, limit);
1298 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1299 path that is analyzed on the return walk. */
1301 static t_bool
1302 follow_ssa_edge (class loop *loop, gimple *def, gphi *halting_phi,
1303 tree *evolution_of_loop, int limit)
1305 class loop *def_loop;
1307 if (gimple_nop_p (def))
1308 return t_false;
1310 /* Give up if the path is longer than the MAX that we allow. */
1311 if (limit > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_COMPLEXITY))
1312 return t_dont_know;
1314 def_loop = loop_containing_stmt (def);
1316 switch (gimple_code (def))
1318 case GIMPLE_PHI:
1319 if (!loop_phi_node_p (def))
1320 /* DEF is a condition-phi-node. Follow the branches, and
1321 record their evolutions. Finally, merge the collected
1322 information and set the approximation to the main
1323 variable. */
1324 return follow_ssa_edge_in_condition_phi
1325 (loop, as_a <gphi *> (def), halting_phi, evolution_of_loop,
1326 limit);
1328 /* When the analyzed phi is the halting_phi, the
1329 depth-first search is over: we have found a path from
1330 the halting_phi to itself in the loop. */
1331 if (def == halting_phi)
1332 return t_true;
1334 /* Otherwise, the evolution of the HALTING_PHI depends
1335 on the evolution of another loop-phi-node, i.e. the
1336 evolution function is a higher degree polynomial. */
1337 if (def_loop == loop)
1338 return t_false;
1340 /* Inner loop. */
1341 if (flow_loop_nested_p (loop, def_loop))
1342 return follow_ssa_edge_inner_loop_phi
1343 (loop, as_a <gphi *> (def), halting_phi, evolution_of_loop,
1344 limit + 1);
1346 /* Outer loop. */
1347 return t_false;
1349 case GIMPLE_ASSIGN:
1350 return follow_ssa_edge_in_rhs (loop, def, halting_phi,
1351 evolution_of_loop, limit);
1353 default:
1354 /* At this level of abstraction, the program is just a set
1355 of GIMPLE_ASSIGNs and PHI_NODEs. In principle there is no
1356 other node to be handled. */
1357 return t_false;
1362 /* Simplify PEELED_CHREC represented by (init_cond, arg) in LOOP.
1363 Handle below case and return the corresponding POLYNOMIAL_CHREC:
1365 # i_17 = PHI <i_13(5), 0(3)>
1366 # _20 = PHI <_5(5), start_4(D)(3)>
1368 i_13 = i_17 + 1;
1369 _5 = start_4(D) + i_13;
1371 Though variable _20 appears as a PEELED_CHREC in the form of
1372 (start_4, _5)_LOOP, it's a POLYNOMIAL_CHREC like {start_4, 1}_LOOP.
1374 See PR41488. */
1376 static tree
1377 simplify_peeled_chrec (class loop *loop, tree arg, tree init_cond)
1379 aff_tree aff1, aff2;
1380 tree ev, left, right, type, step_val;
1381 hash_map<tree, name_expansion *> *peeled_chrec_map = NULL;
1383 ev = instantiate_parameters (loop, analyze_scalar_evolution (loop, arg));
1384 if (ev == NULL_TREE || TREE_CODE (ev) != POLYNOMIAL_CHREC)
1385 return chrec_dont_know;
1387 left = CHREC_LEFT (ev);
1388 right = CHREC_RIGHT (ev);
1389 type = TREE_TYPE (left);
1390 step_val = chrec_fold_plus (type, init_cond, right);
1392 /* Transform (init, {left, right}_LOOP)_LOOP to {init, right}_LOOP
1393 if "left" equals to "init + right". */
1394 if (operand_equal_p (left, step_val, 0))
1396 if (dump_file && (dump_flags & TDF_SCEV))
1397 fprintf (dump_file, "Simplify PEELED_CHREC into POLYNOMIAL_CHREC.\n");
1399 return build_polynomial_chrec (loop->num, init_cond, right);
1402 /* The affine code only deals with pointer and integer types. */
1403 if (!POINTER_TYPE_P (type)
1404 && !INTEGRAL_TYPE_P (type))
1405 return chrec_dont_know;
1407 /* Try harder to check if they are equal. */
1408 tree_to_aff_combination_expand (left, type, &aff1, &peeled_chrec_map);
1409 tree_to_aff_combination_expand (step_val, type, &aff2, &peeled_chrec_map);
1410 free_affine_expand_cache (&peeled_chrec_map);
1411 aff_combination_scale (&aff2, -1);
1412 aff_combination_add (&aff1, &aff2);
1414 /* Transform (init, {left, right}_LOOP)_LOOP to {init, right}_LOOP
1415 if "left" equals to "init + right". */
1416 if (aff_combination_zero_p (&aff1))
1418 if (dump_file && (dump_flags & TDF_SCEV))
1419 fprintf (dump_file, "Simplify PEELED_CHREC into POLYNOMIAL_CHREC.\n");
1421 return build_polynomial_chrec (loop->num, init_cond, right);
1423 return chrec_dont_know;
1426 /* Given a LOOP_PHI_NODE, this function determines the evolution
1427 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1429 static tree
1430 analyze_evolution_in_loop (gphi *loop_phi_node,
1431 tree init_cond)
1433 int i, n = gimple_phi_num_args (loop_phi_node);
1434 tree evolution_function = chrec_not_analyzed_yet;
1435 class loop *loop = loop_containing_stmt (loop_phi_node);
1436 basic_block bb;
1437 static bool simplify_peeled_chrec_p = true;
1439 if (dump_file && (dump_flags & TDF_SCEV))
1441 fprintf (dump_file, "(analyze_evolution_in_loop \n");
1442 fprintf (dump_file, " (loop_phi_node = ");
1443 print_gimple_stmt (dump_file, loop_phi_node, 0);
1444 fprintf (dump_file, ")\n");
1447 for (i = 0; i < n; i++)
1449 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1450 gimple *ssa_chain;
1451 tree ev_fn;
1452 t_bool res;
1454 /* Select the edges that enter the loop body. */
1455 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1456 if (!flow_bb_inside_loop_p (loop, bb))
1457 continue;
1459 if (TREE_CODE (arg) == SSA_NAME)
1461 bool val = false;
1463 ssa_chain = SSA_NAME_DEF_STMT (arg);
1465 /* Pass in the initial condition to the follow edge function. */
1466 ev_fn = init_cond;
1467 res = follow_ssa_edge (loop, ssa_chain, loop_phi_node, &ev_fn, 0);
1469 /* If ev_fn has no evolution in the inner loop, and the
1470 init_cond is not equal to ev_fn, then we have an
1471 ambiguity between two possible values, as we cannot know
1472 the number of iterations at this point. */
1473 if (TREE_CODE (ev_fn) != POLYNOMIAL_CHREC
1474 && no_evolution_in_loop_p (ev_fn, loop->num, &val) && val
1475 && !operand_equal_p (init_cond, ev_fn, 0))
1476 ev_fn = chrec_dont_know;
1478 else
1479 res = t_false;
1481 /* When it is impossible to go back on the same
1482 loop_phi_node by following the ssa edges, the
1483 evolution is represented by a peeled chrec, i.e. the
1484 first iteration, EV_FN has the value INIT_COND, then
1485 all the other iterations it has the value of ARG.
1486 For the moment, PEELED_CHREC nodes are not built. */
1487 if (res != t_true)
1489 ev_fn = chrec_dont_know;
1490 /* Try to recognize POLYNOMIAL_CHREC which appears in
1491 the form of PEELED_CHREC, but guard the process with
1492 a bool variable to keep the analyzer from infinite
1493 recurrence for real PEELED_RECs. */
1494 if (simplify_peeled_chrec_p && TREE_CODE (arg) == SSA_NAME)
1496 simplify_peeled_chrec_p = false;
1497 ev_fn = simplify_peeled_chrec (loop, arg, init_cond);
1498 simplify_peeled_chrec_p = true;
1502 /* When there are multiple back edges of the loop (which in fact never
1503 happens currently, but nevertheless), merge their evolutions. */
1504 evolution_function = chrec_merge (evolution_function, ev_fn);
1506 if (evolution_function == chrec_dont_know)
1507 break;
1510 if (dump_file && (dump_flags & TDF_SCEV))
1512 fprintf (dump_file, " (evolution_function = ");
1513 print_generic_expr (dump_file, evolution_function);
1514 fprintf (dump_file, "))\n");
1517 return evolution_function;
1520 /* Looks to see if VAR is a copy of a constant (via straightforward assignments
1521 or degenerate phi's). If so, returns the constant; else, returns VAR. */
1523 static tree
1524 follow_copies_to_constant (tree var)
1526 tree res = var;
1527 while (TREE_CODE (res) == SSA_NAME
1528 /* We face not updated SSA form in multiple places and this walk
1529 may end up in sibling loops so we have to guard it. */
1530 && !name_registered_for_update_p (res))
1532 gimple *def = SSA_NAME_DEF_STMT (res);
1533 if (gphi *phi = dyn_cast <gphi *> (def))
1535 if (tree rhs = degenerate_phi_result (phi))
1536 res = rhs;
1537 else
1538 break;
1540 else if (gimple_assign_single_p (def))
1541 /* Will exit loop if not an SSA_NAME. */
1542 res = gimple_assign_rhs1 (def);
1543 else
1544 break;
1546 if (CONSTANT_CLASS_P (res))
1547 return res;
1548 return var;
1551 /* Given a loop-phi-node, return the initial conditions of the
1552 variable on entry of the loop. When the CCP has propagated
1553 constants into the loop-phi-node, the initial condition is
1554 instantiated, otherwise the initial condition is kept symbolic.
1555 This analyzer does not analyze the evolution outside the current
1556 loop, and leaves this task to the on-demand tree reconstructor. */
1558 static tree
1559 analyze_initial_condition (gphi *loop_phi_node)
1561 int i, n;
1562 tree init_cond = chrec_not_analyzed_yet;
1563 class loop *loop = loop_containing_stmt (loop_phi_node);
1565 if (dump_file && (dump_flags & TDF_SCEV))
1567 fprintf (dump_file, "(analyze_initial_condition \n");
1568 fprintf (dump_file, " (loop_phi_node = \n");
1569 print_gimple_stmt (dump_file, loop_phi_node, 0);
1570 fprintf (dump_file, ")\n");
1573 n = gimple_phi_num_args (loop_phi_node);
1574 for (i = 0; i < n; i++)
1576 tree branch = PHI_ARG_DEF (loop_phi_node, i);
1577 basic_block bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1579 /* When the branch is oriented to the loop's body, it does
1580 not contribute to the initial condition. */
1581 if (flow_bb_inside_loop_p (loop, bb))
1582 continue;
1584 if (init_cond == chrec_not_analyzed_yet)
1586 init_cond = branch;
1587 continue;
1590 if (TREE_CODE (branch) == SSA_NAME)
1592 init_cond = chrec_dont_know;
1593 break;
1596 init_cond = chrec_merge (init_cond, branch);
1599 /* Ooops -- a loop without an entry??? */
1600 if (init_cond == chrec_not_analyzed_yet)
1601 init_cond = chrec_dont_know;
1603 /* We may not have fully constant propagated IL. Handle degenerate PHIs here
1604 to not miss important early loop unrollings. */
1605 init_cond = follow_copies_to_constant (init_cond);
1607 if (dump_file && (dump_flags & TDF_SCEV))
1609 fprintf (dump_file, " (init_cond = ");
1610 print_generic_expr (dump_file, init_cond);
1611 fprintf (dump_file, "))\n");
1614 return init_cond;
1617 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1619 static tree
1620 interpret_loop_phi (class loop *loop, gphi *loop_phi_node)
1622 tree res;
1623 class loop *phi_loop = loop_containing_stmt (loop_phi_node);
1624 tree init_cond;
1626 gcc_assert (phi_loop == loop);
1628 /* Otherwise really interpret the loop phi. */
1629 init_cond = analyze_initial_condition (loop_phi_node);
1630 res = analyze_evolution_in_loop (loop_phi_node, init_cond);
1632 /* Verify we maintained the correct initial condition throughout
1633 possible conversions in the SSA chain. */
1634 if (res != chrec_dont_know)
1636 tree new_init = res;
1637 if (CONVERT_EXPR_P (res)
1638 && TREE_CODE (TREE_OPERAND (res, 0)) == POLYNOMIAL_CHREC)
1639 new_init = fold_convert (TREE_TYPE (res),
1640 CHREC_LEFT (TREE_OPERAND (res, 0)));
1641 else if (TREE_CODE (res) == POLYNOMIAL_CHREC)
1642 new_init = CHREC_LEFT (res);
1643 STRIP_USELESS_TYPE_CONVERSION (new_init);
1644 if (TREE_CODE (new_init) == POLYNOMIAL_CHREC
1645 || !operand_equal_p (init_cond, new_init, 0))
1646 return chrec_dont_know;
1649 return res;
1652 /* This function merges the branches of a condition-phi-node,
1653 contained in the outermost loop, and whose arguments are already
1654 analyzed. */
1656 static tree
1657 interpret_condition_phi (class loop *loop, gphi *condition_phi)
1659 int i, n = gimple_phi_num_args (condition_phi);
1660 tree res = chrec_not_analyzed_yet;
1662 for (i = 0; i < n; i++)
1664 tree branch_chrec;
1666 if (backedge_phi_arg_p (condition_phi, i))
1668 res = chrec_dont_know;
1669 break;
1672 branch_chrec = analyze_scalar_evolution
1673 (loop, PHI_ARG_DEF (condition_phi, i));
1675 res = chrec_merge (res, branch_chrec);
1676 if (res == chrec_dont_know)
1677 break;
1680 return res;
1683 /* Interpret the operation RHS1 OP RHS2. If we didn't
1684 analyze this node before, follow the definitions until ending
1685 either on an analyzed GIMPLE_ASSIGN, or on a loop-phi-node. On the
1686 return path, this function propagates evolutions (ala constant copy
1687 propagation). OPND1 is not a GIMPLE expression because we could
1688 analyze the effect of an inner loop: see interpret_loop_phi. */
1690 static tree
1691 interpret_rhs_expr (class loop *loop, gimple *at_stmt,
1692 tree type, tree rhs1, enum tree_code code, tree rhs2)
1694 tree res, chrec1, chrec2, ctype;
1695 gimple *def;
1697 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1699 if (is_gimple_min_invariant (rhs1))
1700 return chrec_convert (type, rhs1, at_stmt);
1702 if (code == SSA_NAME)
1703 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1704 at_stmt);
1706 if (code == ASSERT_EXPR)
1708 rhs1 = ASSERT_EXPR_VAR (rhs1);
1709 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1710 at_stmt);
1714 switch (code)
1716 case ADDR_EXPR:
1717 if (TREE_CODE (TREE_OPERAND (rhs1, 0)) == MEM_REF
1718 || handled_component_p (TREE_OPERAND (rhs1, 0)))
1720 machine_mode mode;
1721 poly_int64 bitsize, bitpos;
1722 int unsignedp, reversep;
1723 int volatilep = 0;
1724 tree base, offset;
1725 tree chrec3;
1726 tree unitpos;
1728 base = get_inner_reference (TREE_OPERAND (rhs1, 0),
1729 &bitsize, &bitpos, &offset, &mode,
1730 &unsignedp, &reversep, &volatilep);
1732 if (TREE_CODE (base) == MEM_REF)
1734 rhs2 = TREE_OPERAND (base, 1);
1735 rhs1 = TREE_OPERAND (base, 0);
1737 chrec1 = analyze_scalar_evolution (loop, rhs1);
1738 chrec2 = analyze_scalar_evolution (loop, rhs2);
1739 chrec1 = chrec_convert (type, chrec1, at_stmt);
1740 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1741 chrec1 = instantiate_parameters (loop, chrec1);
1742 chrec2 = instantiate_parameters (loop, chrec2);
1743 res = chrec_fold_plus (type, chrec1, chrec2);
1745 else
1747 chrec1 = analyze_scalar_evolution_for_address_of (loop, base);
1748 chrec1 = chrec_convert (type, chrec1, at_stmt);
1749 res = chrec1;
1752 if (offset != NULL_TREE)
1754 chrec2 = analyze_scalar_evolution (loop, offset);
1755 chrec2 = chrec_convert (TREE_TYPE (offset), chrec2, at_stmt);
1756 chrec2 = instantiate_parameters (loop, chrec2);
1757 res = chrec_fold_plus (type, res, chrec2);
1760 if (maybe_ne (bitpos, 0))
1762 unitpos = size_int (exact_div (bitpos, BITS_PER_UNIT));
1763 chrec3 = analyze_scalar_evolution (loop, unitpos);
1764 chrec3 = chrec_convert (TREE_TYPE (unitpos), chrec3, at_stmt);
1765 chrec3 = instantiate_parameters (loop, chrec3);
1766 res = chrec_fold_plus (type, res, chrec3);
1769 else
1770 res = chrec_dont_know;
1771 break;
1773 case POINTER_PLUS_EXPR:
1774 chrec1 = analyze_scalar_evolution (loop, rhs1);
1775 chrec2 = analyze_scalar_evolution (loop, rhs2);
1776 chrec1 = chrec_convert (type, chrec1, at_stmt);
1777 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1778 chrec1 = instantiate_parameters (loop, chrec1);
1779 chrec2 = instantiate_parameters (loop, chrec2);
1780 res = chrec_fold_plus (type, chrec1, chrec2);
1781 break;
1783 case PLUS_EXPR:
1784 chrec1 = analyze_scalar_evolution (loop, rhs1);
1785 chrec2 = analyze_scalar_evolution (loop, rhs2);
1786 ctype = type;
1787 /* When the stmt is conditionally executed re-write the CHREC
1788 into a form that has well-defined behavior on overflow. */
1789 if (at_stmt
1790 && INTEGRAL_TYPE_P (type)
1791 && ! TYPE_OVERFLOW_WRAPS (type)
1792 && ! dominated_by_p (CDI_DOMINATORS, loop->latch,
1793 gimple_bb (at_stmt)))
1794 ctype = unsigned_type_for (type);
1795 chrec1 = chrec_convert (ctype, chrec1, at_stmt);
1796 chrec2 = chrec_convert (ctype, chrec2, at_stmt);
1797 chrec1 = instantiate_parameters (loop, chrec1);
1798 chrec2 = instantiate_parameters (loop, chrec2);
1799 res = chrec_fold_plus (ctype, chrec1, chrec2);
1800 if (type != ctype)
1801 res = chrec_convert (type, res, at_stmt);
1802 break;
1804 case MINUS_EXPR:
1805 chrec1 = analyze_scalar_evolution (loop, rhs1);
1806 chrec2 = analyze_scalar_evolution (loop, rhs2);
1807 ctype = type;
1808 /* When the stmt is conditionally executed re-write the CHREC
1809 into a form that has well-defined behavior on overflow. */
1810 if (at_stmt
1811 && INTEGRAL_TYPE_P (type)
1812 && ! TYPE_OVERFLOW_WRAPS (type)
1813 && ! dominated_by_p (CDI_DOMINATORS,
1814 loop->latch, gimple_bb (at_stmt)))
1815 ctype = unsigned_type_for (type);
1816 chrec1 = chrec_convert (ctype, chrec1, at_stmt);
1817 chrec2 = chrec_convert (ctype, chrec2, at_stmt);
1818 chrec1 = instantiate_parameters (loop, chrec1);
1819 chrec2 = instantiate_parameters (loop, chrec2);
1820 res = chrec_fold_minus (ctype, chrec1, chrec2);
1821 if (type != ctype)
1822 res = chrec_convert (type, res, at_stmt);
1823 break;
1825 case NEGATE_EXPR:
1826 chrec1 = analyze_scalar_evolution (loop, rhs1);
1827 ctype = type;
1828 /* When the stmt is conditionally executed re-write the CHREC
1829 into a form that has well-defined behavior on overflow. */
1830 if (at_stmt
1831 && INTEGRAL_TYPE_P (type)
1832 && ! TYPE_OVERFLOW_WRAPS (type)
1833 && ! dominated_by_p (CDI_DOMINATORS,
1834 loop->latch, gimple_bb (at_stmt)))
1835 ctype = unsigned_type_for (type);
1836 chrec1 = chrec_convert (ctype, chrec1, at_stmt);
1837 /* TYPE may be integer, real or complex, so use fold_convert. */
1838 chrec1 = instantiate_parameters (loop, chrec1);
1839 res = chrec_fold_multiply (ctype, chrec1,
1840 fold_convert (ctype, integer_minus_one_node));
1841 if (type != ctype)
1842 res = chrec_convert (type, res, at_stmt);
1843 break;
1845 case BIT_NOT_EXPR:
1846 /* Handle ~X as -1 - X. */
1847 chrec1 = analyze_scalar_evolution (loop, rhs1);
1848 chrec1 = chrec_convert (type, chrec1, at_stmt);
1849 chrec1 = instantiate_parameters (loop, chrec1);
1850 res = chrec_fold_minus (type,
1851 fold_convert (type, integer_minus_one_node),
1852 chrec1);
1853 break;
1855 case MULT_EXPR:
1856 chrec1 = analyze_scalar_evolution (loop, rhs1);
1857 chrec2 = analyze_scalar_evolution (loop, rhs2);
1858 ctype = type;
1859 /* When the stmt is conditionally executed re-write the CHREC
1860 into a form that has well-defined behavior on overflow. */
1861 if (at_stmt
1862 && INTEGRAL_TYPE_P (type)
1863 && ! TYPE_OVERFLOW_WRAPS (type)
1864 && ! dominated_by_p (CDI_DOMINATORS,
1865 loop->latch, gimple_bb (at_stmt)))
1866 ctype = unsigned_type_for (type);
1867 chrec1 = chrec_convert (ctype, chrec1, at_stmt);
1868 chrec2 = chrec_convert (ctype, chrec2, at_stmt);
1869 chrec1 = instantiate_parameters (loop, chrec1);
1870 chrec2 = instantiate_parameters (loop, chrec2);
1871 res = chrec_fold_multiply (ctype, chrec1, chrec2);
1872 if (type != ctype)
1873 res = chrec_convert (type, res, at_stmt);
1874 break;
1876 case LSHIFT_EXPR:
1878 /* Handle A<<B as A * (1<<B). */
1879 tree uns = unsigned_type_for (type);
1880 chrec1 = analyze_scalar_evolution (loop, rhs1);
1881 chrec2 = analyze_scalar_evolution (loop, rhs2);
1882 chrec1 = chrec_convert (uns, chrec1, at_stmt);
1883 chrec1 = instantiate_parameters (loop, chrec1);
1884 chrec2 = instantiate_parameters (loop, chrec2);
1886 tree one = build_int_cst (uns, 1);
1887 chrec2 = fold_build2 (LSHIFT_EXPR, uns, one, chrec2);
1888 res = chrec_fold_multiply (uns, chrec1, chrec2);
1889 res = chrec_convert (type, res, at_stmt);
1891 break;
1893 CASE_CONVERT:
1894 /* In case we have a truncation of a widened operation that in
1895 the truncated type has undefined overflow behavior analyze
1896 the operation done in an unsigned type of the same precision
1897 as the final truncation. We cannot derive a scalar evolution
1898 for the widened operation but for the truncated result. */
1899 if (TREE_CODE (type) == INTEGER_TYPE
1900 && TREE_CODE (TREE_TYPE (rhs1)) == INTEGER_TYPE
1901 && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (rhs1))
1902 && TYPE_OVERFLOW_UNDEFINED (type)
1903 && TREE_CODE (rhs1) == SSA_NAME
1904 && (def = SSA_NAME_DEF_STMT (rhs1))
1905 && is_gimple_assign (def)
1906 && TREE_CODE_CLASS (gimple_assign_rhs_code (def)) == tcc_binary
1907 && TREE_CODE (gimple_assign_rhs2 (def)) == INTEGER_CST)
1909 tree utype = unsigned_type_for (type);
1910 chrec1 = interpret_rhs_expr (loop, at_stmt, utype,
1911 gimple_assign_rhs1 (def),
1912 gimple_assign_rhs_code (def),
1913 gimple_assign_rhs2 (def));
1915 else
1916 chrec1 = analyze_scalar_evolution (loop, rhs1);
1917 res = chrec_convert (type, chrec1, at_stmt, true, rhs1);
1918 break;
1920 case BIT_AND_EXPR:
1921 /* Given int variable A, handle A&0xffff as (int)(unsigned short)A.
1922 If A is SCEV and its value is in the range of representable set
1923 of type unsigned short, the result expression is a (no-overflow)
1924 SCEV. */
1925 res = chrec_dont_know;
1926 if (tree_fits_uhwi_p (rhs2))
1928 int precision;
1929 unsigned HOST_WIDE_INT val = tree_to_uhwi (rhs2);
1931 val ++;
1932 /* Skip if value of rhs2 wraps in unsigned HOST_WIDE_INT or
1933 it's not the maximum value of a smaller type than rhs1. */
1934 if (val != 0
1935 && (precision = exact_log2 (val)) > 0
1936 && (unsigned) precision < TYPE_PRECISION (TREE_TYPE (rhs1)))
1938 tree utype = build_nonstandard_integer_type (precision, 1);
1940 if (TYPE_PRECISION (utype) < TYPE_PRECISION (TREE_TYPE (rhs1)))
1942 chrec1 = analyze_scalar_evolution (loop, rhs1);
1943 chrec1 = chrec_convert (utype, chrec1, at_stmt);
1944 res = chrec_convert (TREE_TYPE (rhs1), chrec1, at_stmt);
1948 break;
1950 default:
1951 res = chrec_dont_know;
1952 break;
1955 return res;
1958 /* Interpret the expression EXPR. */
1960 static tree
1961 interpret_expr (class loop *loop, gimple *at_stmt, tree expr)
1963 enum tree_code code;
1964 tree type = TREE_TYPE (expr), op0, op1;
1966 if (automatically_generated_chrec_p (expr))
1967 return expr;
1969 if (TREE_CODE (expr) == POLYNOMIAL_CHREC
1970 || TREE_CODE (expr) == CALL_EXPR
1971 || get_gimple_rhs_class (TREE_CODE (expr)) == GIMPLE_TERNARY_RHS)
1972 return chrec_dont_know;
1974 extract_ops_from_tree (expr, &code, &op0, &op1);
1976 return interpret_rhs_expr (loop, at_stmt, type,
1977 op0, code, op1);
1980 /* Interpret the rhs of the assignment STMT. */
1982 static tree
1983 interpret_gimple_assign (class loop *loop, gimple *stmt)
1985 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1986 enum tree_code code = gimple_assign_rhs_code (stmt);
1988 return interpret_rhs_expr (loop, stmt, type,
1989 gimple_assign_rhs1 (stmt), code,
1990 gimple_assign_rhs2 (stmt));
1995 /* This section contains all the entry points:
1996 - number_of_iterations_in_loop,
1997 - analyze_scalar_evolution,
1998 - instantiate_parameters.
2001 /* Helper recursive function. */
2003 static tree
2004 analyze_scalar_evolution_1 (class loop *loop, tree var)
2006 gimple *def;
2007 basic_block bb;
2008 class loop *def_loop;
2009 tree res;
2011 if (TREE_CODE (var) != SSA_NAME)
2012 return interpret_expr (loop, NULL, var);
2014 def = SSA_NAME_DEF_STMT (var);
2015 bb = gimple_bb (def);
2016 def_loop = bb->loop_father;
2018 if (!flow_bb_inside_loop_p (loop, bb))
2020 /* Keep symbolic form, but look through obvious copies for constants. */
2021 res = follow_copies_to_constant (var);
2022 goto set_and_end;
2025 if (loop != def_loop)
2027 res = analyze_scalar_evolution_1 (def_loop, var);
2028 class loop *loop_to_skip = superloop_at_depth (def_loop,
2029 loop_depth (loop) + 1);
2030 res = compute_overall_effect_of_inner_loop (loop_to_skip, res);
2031 if (chrec_contains_symbols_defined_in_loop (res, loop->num))
2032 res = analyze_scalar_evolution_1 (loop, res);
2033 goto set_and_end;
2036 switch (gimple_code (def))
2038 case GIMPLE_ASSIGN:
2039 res = interpret_gimple_assign (loop, def);
2040 break;
2042 case GIMPLE_PHI:
2043 if (loop_phi_node_p (def))
2044 res = interpret_loop_phi (loop, as_a <gphi *> (def));
2045 else
2046 res = interpret_condition_phi (loop, as_a <gphi *> (def));
2047 break;
2049 default:
2050 res = chrec_dont_know;
2051 break;
2054 set_and_end:
2056 /* Keep the symbolic form. */
2057 if (res == chrec_dont_know)
2058 res = var;
2060 if (loop == def_loop)
2061 set_scalar_evolution (block_before_loop (loop), var, res);
2063 return res;
2066 /* Analyzes and returns the scalar evolution of the ssa_name VAR in
2067 LOOP. LOOP is the loop in which the variable is used.
2069 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
2070 pointer to the statement that uses this variable, in order to
2071 determine the evolution function of the variable, use the following
2072 calls:
2074 loop_p loop = loop_containing_stmt (stmt);
2075 tree chrec_with_symbols = analyze_scalar_evolution (loop, var);
2076 tree chrec_instantiated = instantiate_parameters (loop, chrec_with_symbols);
2079 tree
2080 analyze_scalar_evolution (class loop *loop, tree var)
2082 tree res;
2084 /* ??? Fix callers. */
2085 if (! loop)
2086 return var;
2088 if (dump_file && (dump_flags & TDF_SCEV))
2090 fprintf (dump_file, "(analyze_scalar_evolution \n");
2091 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
2092 fprintf (dump_file, " (scalar = ");
2093 print_generic_expr (dump_file, var);
2094 fprintf (dump_file, ")\n");
2097 res = get_scalar_evolution (block_before_loop (loop), var);
2098 if (res == chrec_not_analyzed_yet)
2100 /* We'll recurse into instantiate_scev, avoid tearing down the
2101 instantiate cache repeatedly and keep it live from here. */
2102 bool destr = false;
2103 if (!global_cache)
2105 global_cache = new instantiate_cache_type;
2106 destr = true;
2108 res = analyze_scalar_evolution_1 (loop, var);
2109 if (destr)
2111 delete global_cache;
2112 global_cache = NULL;
2116 if (dump_file && (dump_flags & TDF_SCEV))
2117 fprintf (dump_file, ")\n");
2119 return res;
2122 /* Analyzes and returns the scalar evolution of VAR address in LOOP. */
2124 static tree
2125 analyze_scalar_evolution_for_address_of (class loop *loop, tree var)
2127 return analyze_scalar_evolution (loop, build_fold_addr_expr (var));
2130 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
2131 WRTO_LOOP (which should be a superloop of USE_LOOP)
2133 FOLDED_CASTS is set to true if resolve_mixers used
2134 chrec_convert_aggressive (TODO -- not really, we are way too conservative
2135 at the moment in order to keep things simple).
2137 To illustrate the meaning of USE_LOOP and WRTO_LOOP, consider the following
2138 example:
2140 for (i = 0; i < 100; i++) -- loop 1
2142 for (j = 0; j < 100; j++) -- loop 2
2144 k1 = i;
2145 k2 = j;
2147 use2 (k1, k2);
2149 for (t = 0; t < 100; t++) -- loop 3
2150 use3 (k1, k2);
2153 use1 (k1, k2);
2156 Both k1 and k2 are invariants in loop3, thus
2157 analyze_scalar_evolution_in_loop (loop3, loop3, k1) = k1
2158 analyze_scalar_evolution_in_loop (loop3, loop3, k2) = k2
2160 As they are invariant, it does not matter whether we consider their
2161 usage in loop 3 or loop 2, hence
2162 analyze_scalar_evolution_in_loop (loop2, loop3, k1) =
2163 analyze_scalar_evolution_in_loop (loop2, loop2, k1) = i
2164 analyze_scalar_evolution_in_loop (loop2, loop3, k2) =
2165 analyze_scalar_evolution_in_loop (loop2, loop2, k2) = [0,+,1]_2
2167 Similarly for their evolutions with respect to loop 1. The values of K2
2168 in the use in loop 2 vary independently on loop 1, thus we cannot express
2169 the evolution with respect to loop 1:
2170 analyze_scalar_evolution_in_loop (loop1, loop3, k1) =
2171 analyze_scalar_evolution_in_loop (loop1, loop2, k1) = [0,+,1]_1
2172 analyze_scalar_evolution_in_loop (loop1, loop3, k2) =
2173 analyze_scalar_evolution_in_loop (loop1, loop2, k2) = dont_know
2175 The value of k2 in the use in loop 1 is known, though:
2176 analyze_scalar_evolution_in_loop (loop1, loop1, k1) = [0,+,1]_1
2177 analyze_scalar_evolution_in_loop (loop1, loop1, k2) = 100
2180 static tree
2181 analyze_scalar_evolution_in_loop (class loop *wrto_loop, class loop *use_loop,
2182 tree version, bool *folded_casts)
2184 bool val = false;
2185 tree ev = version, tmp;
2187 /* We cannot just do
2189 tmp = analyze_scalar_evolution (use_loop, version);
2190 ev = resolve_mixers (wrto_loop, tmp, folded_casts);
2192 as resolve_mixers would query the scalar evolution with respect to
2193 wrto_loop. For example, in the situation described in the function
2194 comment, suppose that wrto_loop = loop1, use_loop = loop3 and
2195 version = k2. Then
2197 analyze_scalar_evolution (use_loop, version) = k2
2199 and resolve_mixers (loop1, k2, folded_casts) finds that the value of
2200 k2 in loop 1 is 100, which is a wrong result, since we are interested
2201 in the value in loop 3.
2203 Instead, we need to proceed from use_loop to wrto_loop loop by loop,
2204 each time checking that there is no evolution in the inner loop. */
2206 if (folded_casts)
2207 *folded_casts = false;
2208 while (1)
2210 tmp = analyze_scalar_evolution (use_loop, ev);
2211 ev = resolve_mixers (use_loop, tmp, folded_casts);
2213 if (use_loop == wrto_loop)
2214 return ev;
2216 /* If the value of the use changes in the inner loop, we cannot express
2217 its value in the outer loop (we might try to return interval chrec,
2218 but we do not have a user for it anyway) */
2219 if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
2220 || !val)
2221 return chrec_dont_know;
2223 use_loop = loop_outer (use_loop);
2228 /* Computes a hash function for database element ELT. */
2230 static inline hashval_t
2231 hash_idx_scev_info (const void *elt_)
2233 unsigned idx = ((size_t) elt_) - 2;
2234 return scev_info_hasher::hash (&global_cache->entries[idx]);
2237 /* Compares database elements E1 and E2. */
2239 static inline int
2240 eq_idx_scev_info (const void *e1, const void *e2)
2242 unsigned idx1 = ((size_t) e1) - 2;
2243 return scev_info_hasher::equal (&global_cache->entries[idx1],
2244 (const scev_info_str *) e2);
2247 /* Returns from CACHE the slot number of the cached chrec for NAME. */
2249 static unsigned
2250 get_instantiated_value_entry (instantiate_cache_type &cache,
2251 tree name, edge instantiate_below)
2253 if (!cache.map)
2255 cache.map = htab_create (10, hash_idx_scev_info, eq_idx_scev_info, NULL);
2256 cache.entries.create (10);
2259 scev_info_str e;
2260 e.name_version = SSA_NAME_VERSION (name);
2261 e.instantiated_below = instantiate_below->dest->index;
2262 void **slot = htab_find_slot_with_hash (cache.map, &e,
2263 scev_info_hasher::hash (&e), INSERT);
2264 if (!*slot)
2266 e.chrec = chrec_not_analyzed_yet;
2267 *slot = (void *)(size_t)(cache.entries.length () + 2);
2268 cache.entries.safe_push (e);
2271 return ((size_t)*slot) - 2;
2275 /* Return the closed_loop_phi node for VAR. If there is none, return
2276 NULL_TREE. */
2278 static tree
2279 loop_closed_phi_def (tree var)
2281 class loop *loop;
2282 edge exit;
2283 gphi *phi;
2284 gphi_iterator psi;
2286 if (var == NULL_TREE
2287 || TREE_CODE (var) != SSA_NAME)
2288 return NULL_TREE;
2290 loop = loop_containing_stmt (SSA_NAME_DEF_STMT (var));
2291 exit = single_exit (loop);
2292 if (!exit)
2293 return NULL_TREE;
2295 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
2297 phi = psi.phi ();
2298 if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == var)
2299 return PHI_RESULT (phi);
2302 return NULL_TREE;
2305 static tree instantiate_scev_r (edge, class loop *, class loop *,
2306 tree, bool *, int);
2308 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2309 and EVOLUTION_LOOP, that were left under a symbolic form.
2311 CHREC is an SSA_NAME to be instantiated.
2313 CACHE is the cache of already instantiated values.
2315 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2316 conversions that may wrap in signed/pointer type are folded, as long
2317 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2318 then we don't do such fold.
2320 SIZE_EXPR is used for computing the size of the expression to be
2321 instantiated, and to stop if it exceeds some limit. */
2323 static tree
2324 instantiate_scev_name (edge instantiate_below,
2325 class loop *evolution_loop, class loop *inner_loop,
2326 tree chrec,
2327 bool *fold_conversions,
2328 int size_expr)
2330 tree res;
2331 class loop *def_loop;
2332 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (chrec));
2334 /* A parameter, nothing to do. */
2335 if (!def_bb
2336 || !dominated_by_p (CDI_DOMINATORS, def_bb, instantiate_below->dest))
2337 return chrec;
2339 /* We cache the value of instantiated variable to avoid exponential
2340 time complexity due to reevaluations. We also store the convenient
2341 value in the cache in order to prevent infinite recursion -- we do
2342 not want to instantiate the SSA_NAME if it is in a mixer
2343 structure. This is used for avoiding the instantiation of
2344 recursively defined functions, such as:
2346 | a_2 -> {0, +, 1, +, a_2}_1 */
2348 unsigned si = get_instantiated_value_entry (*global_cache,
2349 chrec, instantiate_below);
2350 if (global_cache->get (si) != chrec_not_analyzed_yet)
2351 return global_cache->get (si);
2353 /* On recursion return chrec_dont_know. */
2354 global_cache->set (si, chrec_dont_know);
2356 def_loop = find_common_loop (evolution_loop, def_bb->loop_father);
2358 if (! dominated_by_p (CDI_DOMINATORS,
2359 def_loop->header, instantiate_below->dest))
2361 gimple *def = SSA_NAME_DEF_STMT (chrec);
2362 if (gassign *ass = dyn_cast <gassign *> (def))
2364 switch (gimple_assign_rhs_class (ass))
2366 case GIMPLE_UNARY_RHS:
2368 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2369 inner_loop, gimple_assign_rhs1 (ass),
2370 fold_conversions, size_expr);
2371 if (op0 == chrec_dont_know)
2372 return chrec_dont_know;
2373 res = fold_build1 (gimple_assign_rhs_code (ass),
2374 TREE_TYPE (chrec), op0);
2375 break;
2377 case GIMPLE_BINARY_RHS:
2379 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2380 inner_loop, gimple_assign_rhs1 (ass),
2381 fold_conversions, size_expr);
2382 if (op0 == chrec_dont_know)
2383 return chrec_dont_know;
2384 tree op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2385 inner_loop, gimple_assign_rhs2 (ass),
2386 fold_conversions, size_expr);
2387 if (op1 == chrec_dont_know)
2388 return chrec_dont_know;
2389 res = fold_build2 (gimple_assign_rhs_code (ass),
2390 TREE_TYPE (chrec), op0, op1);
2391 break;
2393 default:
2394 res = chrec_dont_know;
2397 else
2398 res = chrec_dont_know;
2399 global_cache->set (si, res);
2400 return res;
2403 /* If the analysis yields a parametric chrec, instantiate the
2404 result again. */
2405 res = analyze_scalar_evolution (def_loop, chrec);
2407 /* Don't instantiate default definitions. */
2408 if (TREE_CODE (res) == SSA_NAME
2409 && SSA_NAME_IS_DEFAULT_DEF (res))
2412 /* Don't instantiate loop-closed-ssa phi nodes. */
2413 else if (TREE_CODE (res) == SSA_NAME
2414 && loop_depth (loop_containing_stmt (SSA_NAME_DEF_STMT (res)))
2415 > loop_depth (def_loop))
2417 if (res == chrec)
2418 res = loop_closed_phi_def (chrec);
2419 else
2420 res = chrec;
2422 /* When there is no loop_closed_phi_def, it means that the
2423 variable is not used after the loop: try to still compute the
2424 value of the variable when exiting the loop. */
2425 if (res == NULL_TREE)
2427 loop_p loop = loop_containing_stmt (SSA_NAME_DEF_STMT (chrec));
2428 res = analyze_scalar_evolution (loop, chrec);
2429 res = compute_overall_effect_of_inner_loop (loop, res);
2430 res = instantiate_scev_r (instantiate_below, evolution_loop,
2431 inner_loop, res,
2432 fold_conversions, size_expr);
2434 else if (dominated_by_p (CDI_DOMINATORS,
2435 gimple_bb (SSA_NAME_DEF_STMT (res)),
2436 instantiate_below->dest))
2437 res = chrec_dont_know;
2440 else if (res != chrec_dont_know)
2442 if (inner_loop
2443 && def_bb->loop_father != inner_loop
2444 && !flow_loop_nested_p (def_bb->loop_father, inner_loop))
2445 /* ??? We could try to compute the overall effect of the loop here. */
2446 res = chrec_dont_know;
2447 else
2448 res = instantiate_scev_r (instantiate_below, evolution_loop,
2449 inner_loop, res,
2450 fold_conversions, size_expr);
2453 /* Store the correct value to the cache. */
2454 global_cache->set (si, res);
2455 return res;
2458 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2459 and EVOLUTION_LOOP, that were left under a symbolic form.
2461 CHREC is a polynomial chain of recurrence to be instantiated.
2463 CACHE is the cache of already instantiated values.
2465 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2466 conversions that may wrap in signed/pointer type are folded, as long
2467 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2468 then we don't do such fold.
2470 SIZE_EXPR is used for computing the size of the expression to be
2471 instantiated, and to stop if it exceeds some limit. */
2473 static tree
2474 instantiate_scev_poly (edge instantiate_below,
2475 class loop *evolution_loop, class loop *,
2476 tree chrec, bool *fold_conversions, int size_expr)
2478 tree op1;
2479 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2480 get_chrec_loop (chrec),
2481 CHREC_LEFT (chrec), fold_conversions,
2482 size_expr);
2483 if (op0 == chrec_dont_know)
2484 return chrec_dont_know;
2486 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2487 get_chrec_loop (chrec),
2488 CHREC_RIGHT (chrec), fold_conversions,
2489 size_expr);
2490 if (op1 == chrec_dont_know)
2491 return chrec_dont_know;
2493 if (CHREC_LEFT (chrec) != op0
2494 || CHREC_RIGHT (chrec) != op1)
2496 op1 = chrec_convert_rhs (chrec_type (op0), op1, NULL);
2497 chrec = build_polynomial_chrec (CHREC_VARIABLE (chrec), op0, op1);
2500 return chrec;
2503 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2504 and EVOLUTION_LOOP, that were left under a symbolic form.
2506 "C0 CODE C1" is a binary expression of type TYPE to be instantiated.
2508 CACHE is the cache of already instantiated values.
2510 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2511 conversions that may wrap in signed/pointer type are folded, as long
2512 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2513 then we don't do such fold.
2515 SIZE_EXPR is used for computing the size of the expression to be
2516 instantiated, and to stop if it exceeds some limit. */
2518 static tree
2519 instantiate_scev_binary (edge instantiate_below,
2520 class loop *evolution_loop, class loop *inner_loop,
2521 tree chrec, enum tree_code code,
2522 tree type, tree c0, tree c1,
2523 bool *fold_conversions, int size_expr)
2525 tree op1;
2526 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2527 c0, fold_conversions, size_expr);
2528 if (op0 == chrec_dont_know)
2529 return chrec_dont_know;
2531 /* While we eventually compute the same op1 if c0 == c1 the process
2532 of doing this is expensive so the following short-cut prevents
2533 exponential compile-time behavior. */
2534 if (c0 != c1)
2536 op1 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2537 c1, fold_conversions, size_expr);
2538 if (op1 == chrec_dont_know)
2539 return chrec_dont_know;
2541 else
2542 op1 = op0;
2544 if (c0 != op0
2545 || c1 != op1)
2547 op0 = chrec_convert (type, op0, NULL);
2548 op1 = chrec_convert_rhs (type, op1, NULL);
2550 switch (code)
2552 case POINTER_PLUS_EXPR:
2553 case PLUS_EXPR:
2554 return chrec_fold_plus (type, op0, op1);
2556 case MINUS_EXPR:
2557 return chrec_fold_minus (type, op0, op1);
2559 case MULT_EXPR:
2560 return chrec_fold_multiply (type, op0, op1);
2562 default:
2563 gcc_unreachable ();
2567 return chrec ? chrec : fold_build2 (code, type, c0, c1);
2570 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2571 and EVOLUTION_LOOP, that were left under a symbolic form.
2573 "CHREC" that stands for a convert expression "(TYPE) OP" is to be
2574 instantiated.
2576 CACHE is the cache of already instantiated values.
2578 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2579 conversions that may wrap in signed/pointer type are folded, as long
2580 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2581 then we don't do such fold.
2583 SIZE_EXPR is used for computing the size of the expression to be
2584 instantiated, and to stop if it exceeds some limit. */
2586 static tree
2587 instantiate_scev_convert (edge instantiate_below,
2588 class loop *evolution_loop, class loop *inner_loop,
2589 tree chrec, tree type, tree op,
2590 bool *fold_conversions, int size_expr)
2592 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2593 inner_loop, op,
2594 fold_conversions, size_expr);
2596 if (op0 == chrec_dont_know)
2597 return chrec_dont_know;
2599 if (fold_conversions)
2601 tree tmp = chrec_convert_aggressive (type, op0, fold_conversions);
2602 if (tmp)
2603 return tmp;
2605 /* If we used chrec_convert_aggressive, we can no longer assume that
2606 signed chrecs do not overflow, as chrec_convert does, so avoid
2607 calling it in that case. */
2608 if (*fold_conversions)
2610 if (chrec && op0 == op)
2611 return chrec;
2613 return fold_convert (type, op0);
2617 return chrec_convert (type, op0, NULL);
2620 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2621 and EVOLUTION_LOOP, that were left under a symbolic form.
2623 CHREC is a BIT_NOT_EXPR or a NEGATE_EXPR expression to be instantiated.
2624 Handle ~X as -1 - X.
2625 Handle -X as -1 * X.
2627 CACHE is the cache of already instantiated values.
2629 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2630 conversions that may wrap in signed/pointer type are folded, as long
2631 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2632 then we don't do such fold.
2634 SIZE_EXPR is used for computing the size of the expression to be
2635 instantiated, and to stop if it exceeds some limit. */
2637 static tree
2638 instantiate_scev_not (edge instantiate_below,
2639 class loop *evolution_loop, class loop *inner_loop,
2640 tree chrec,
2641 enum tree_code code, tree type, tree op,
2642 bool *fold_conversions, int size_expr)
2644 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2645 inner_loop, op,
2646 fold_conversions, size_expr);
2648 if (op0 == chrec_dont_know)
2649 return chrec_dont_know;
2651 if (op != op0)
2653 op0 = chrec_convert (type, op0, NULL);
2655 switch (code)
2657 case BIT_NOT_EXPR:
2658 return chrec_fold_minus
2659 (type, fold_convert (type, integer_minus_one_node), op0);
2661 case NEGATE_EXPR:
2662 return chrec_fold_multiply
2663 (type, fold_convert (type, integer_minus_one_node), op0);
2665 default:
2666 gcc_unreachable ();
2670 return chrec ? chrec : fold_build1 (code, type, op0);
2673 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2674 and EVOLUTION_LOOP, that were left under a symbolic form.
2676 CHREC is the scalar evolution to instantiate.
2678 CACHE is the cache of already instantiated values.
2680 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2681 conversions that may wrap in signed/pointer type are folded, as long
2682 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2683 then we don't do such fold.
2685 SIZE_EXPR is used for computing the size of the expression to be
2686 instantiated, and to stop if it exceeds some limit. */
2688 static tree
2689 instantiate_scev_r (edge instantiate_below,
2690 class loop *evolution_loop, class loop *inner_loop,
2691 tree chrec,
2692 bool *fold_conversions, int size_expr)
2694 /* Give up if the expression is larger than the MAX that we allow. */
2695 if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
2696 return chrec_dont_know;
2698 if (chrec == NULL_TREE
2699 || automatically_generated_chrec_p (chrec)
2700 || is_gimple_min_invariant (chrec))
2701 return chrec;
2703 switch (TREE_CODE (chrec))
2705 case SSA_NAME:
2706 return instantiate_scev_name (instantiate_below, evolution_loop,
2707 inner_loop, chrec,
2708 fold_conversions, size_expr);
2710 case POLYNOMIAL_CHREC:
2711 return instantiate_scev_poly (instantiate_below, evolution_loop,
2712 inner_loop, chrec,
2713 fold_conversions, size_expr);
2715 case POINTER_PLUS_EXPR:
2716 case PLUS_EXPR:
2717 case MINUS_EXPR:
2718 case MULT_EXPR:
2719 return instantiate_scev_binary (instantiate_below, evolution_loop,
2720 inner_loop, chrec,
2721 TREE_CODE (chrec), chrec_type (chrec),
2722 TREE_OPERAND (chrec, 0),
2723 TREE_OPERAND (chrec, 1),
2724 fold_conversions, size_expr);
2726 CASE_CONVERT:
2727 return instantiate_scev_convert (instantiate_below, evolution_loop,
2728 inner_loop, chrec,
2729 TREE_TYPE (chrec), TREE_OPERAND (chrec, 0),
2730 fold_conversions, size_expr);
2732 case NEGATE_EXPR:
2733 case BIT_NOT_EXPR:
2734 return instantiate_scev_not (instantiate_below, evolution_loop,
2735 inner_loop, chrec,
2736 TREE_CODE (chrec), TREE_TYPE (chrec),
2737 TREE_OPERAND (chrec, 0),
2738 fold_conversions, size_expr);
2740 case ADDR_EXPR:
2741 if (is_gimple_min_invariant (chrec))
2742 return chrec;
2743 /* Fallthru. */
2744 case SCEV_NOT_KNOWN:
2745 return chrec_dont_know;
2747 case SCEV_KNOWN:
2748 return chrec_known;
2750 default:
2751 if (CONSTANT_CLASS_P (chrec))
2752 return chrec;
2753 return chrec_dont_know;
2757 /* Analyze all the parameters of the chrec that were left under a
2758 symbolic form. INSTANTIATE_BELOW is the basic block that stops the
2759 recursive instantiation of parameters: a parameter is a variable
2760 that is defined in a basic block that dominates INSTANTIATE_BELOW or
2761 a function parameter. */
2763 tree
2764 instantiate_scev (edge instantiate_below, class loop *evolution_loop,
2765 tree chrec)
2767 tree res;
2769 if (dump_file && (dump_flags & TDF_SCEV))
2771 fprintf (dump_file, "(instantiate_scev \n");
2772 fprintf (dump_file, " (instantiate_below = %d -> %d)\n",
2773 instantiate_below->src->index, instantiate_below->dest->index);
2774 if (evolution_loop)
2775 fprintf (dump_file, " (evolution_loop = %d)\n", evolution_loop->num);
2776 fprintf (dump_file, " (chrec = ");
2777 print_generic_expr (dump_file, chrec);
2778 fprintf (dump_file, ")\n");
2781 bool destr = false;
2782 if (!global_cache)
2784 global_cache = new instantiate_cache_type;
2785 destr = true;
2788 res = instantiate_scev_r (instantiate_below, evolution_loop,
2789 NULL, chrec, NULL, 0);
2791 if (destr)
2793 delete global_cache;
2794 global_cache = NULL;
2797 if (dump_file && (dump_flags & TDF_SCEV))
2799 fprintf (dump_file, " (res = ");
2800 print_generic_expr (dump_file, res);
2801 fprintf (dump_file, "))\n");
2804 return res;
2807 /* Similar to instantiate_parameters, but does not introduce the
2808 evolutions in outer loops for LOOP invariants in CHREC, and does not
2809 care about causing overflows, as long as they do not affect value
2810 of an expression. */
2812 tree
2813 resolve_mixers (class loop *loop, tree chrec, bool *folded_casts)
2815 bool destr = false;
2816 bool fold_conversions = false;
2817 if (!global_cache)
2819 global_cache = new instantiate_cache_type;
2820 destr = true;
2823 tree ret = instantiate_scev_r (loop_preheader_edge (loop), loop, NULL,
2824 chrec, &fold_conversions, 0);
2826 if (folded_casts && !*folded_casts)
2827 *folded_casts = fold_conversions;
2829 if (destr)
2831 delete global_cache;
2832 global_cache = NULL;
2835 return ret;
2838 /* Entry point for the analysis of the number of iterations pass.
2839 This function tries to safely approximate the number of iterations
2840 the loop will run. When this property is not decidable at compile
2841 time, the result is chrec_dont_know. Otherwise the result is a
2842 scalar or a symbolic parameter. When the number of iterations may
2843 be equal to zero and the property cannot be determined at compile
2844 time, the result is a COND_EXPR that represents in a symbolic form
2845 the conditions under which the number of iterations is not zero.
2847 Example of analysis: suppose that the loop has an exit condition:
2849 "if (b > 49) goto end_loop;"
2851 and that in a previous analysis we have determined that the
2852 variable 'b' has an evolution function:
2854 "EF = {23, +, 5}_2".
2856 When we evaluate the function at the point 5, i.e. the value of the
2857 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2858 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2859 the loop body has been executed 6 times. */
2861 tree
2862 number_of_latch_executions (class loop *loop)
2864 edge exit;
2865 class tree_niter_desc niter_desc;
2866 tree may_be_zero;
2867 tree res;
2869 /* Determine whether the number of iterations in loop has already
2870 been computed. */
2871 res = loop->nb_iterations;
2872 if (res)
2873 return res;
2875 may_be_zero = NULL_TREE;
2877 if (dump_file && (dump_flags & TDF_SCEV))
2878 fprintf (dump_file, "(number_of_iterations_in_loop = \n");
2880 res = chrec_dont_know;
2881 exit = single_exit (loop);
2883 if (exit && number_of_iterations_exit (loop, exit, &niter_desc, false))
2885 may_be_zero = niter_desc.may_be_zero;
2886 res = niter_desc.niter;
2889 if (res == chrec_dont_know
2890 || !may_be_zero
2891 || integer_zerop (may_be_zero))
2893 else if (integer_nonzerop (may_be_zero))
2894 res = build_int_cst (TREE_TYPE (res), 0);
2896 else if (COMPARISON_CLASS_P (may_be_zero))
2897 res = fold_build3 (COND_EXPR, TREE_TYPE (res), may_be_zero,
2898 build_int_cst (TREE_TYPE (res), 0), res);
2899 else
2900 res = chrec_dont_know;
2902 if (dump_file && (dump_flags & TDF_SCEV))
2904 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
2905 print_generic_expr (dump_file, res);
2906 fprintf (dump_file, "))\n");
2909 loop->nb_iterations = res;
2910 return res;
2914 /* Counters for the stats. */
2916 struct chrec_stats
2918 unsigned nb_chrecs;
2919 unsigned nb_affine;
2920 unsigned nb_affine_multivar;
2921 unsigned nb_higher_poly;
2922 unsigned nb_chrec_dont_know;
2923 unsigned nb_undetermined;
2926 /* Reset the counters. */
2928 static inline void
2929 reset_chrecs_counters (struct chrec_stats *stats)
2931 stats->nb_chrecs = 0;
2932 stats->nb_affine = 0;
2933 stats->nb_affine_multivar = 0;
2934 stats->nb_higher_poly = 0;
2935 stats->nb_chrec_dont_know = 0;
2936 stats->nb_undetermined = 0;
2939 /* Dump the contents of a CHREC_STATS structure. */
2941 static void
2942 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
2944 fprintf (file, "\n(\n");
2945 fprintf (file, "-----------------------------------------\n");
2946 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
2947 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
2948 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
2949 stats->nb_higher_poly);
2950 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
2951 fprintf (file, "-----------------------------------------\n");
2952 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
2953 fprintf (file, "%d\twith undetermined coefficients\n",
2954 stats->nb_undetermined);
2955 fprintf (file, "-----------------------------------------\n");
2956 fprintf (file, "%d\tchrecs in the scev database\n",
2957 (int) scalar_evolution_info->elements ());
2958 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
2959 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
2960 fprintf (file, "-----------------------------------------\n");
2961 fprintf (file, ")\n\n");
2964 /* Gather statistics about CHREC. */
2966 static void
2967 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
2969 if (dump_file && (dump_flags & TDF_STATS))
2971 fprintf (dump_file, "(classify_chrec ");
2972 print_generic_expr (dump_file, chrec);
2973 fprintf (dump_file, "\n");
2976 stats->nb_chrecs++;
2978 if (chrec == NULL_TREE)
2980 stats->nb_undetermined++;
2981 return;
2984 switch (TREE_CODE (chrec))
2986 case POLYNOMIAL_CHREC:
2987 if (evolution_function_is_affine_p (chrec))
2989 if (dump_file && (dump_flags & TDF_STATS))
2990 fprintf (dump_file, " affine_univariate\n");
2991 stats->nb_affine++;
2993 else if (evolution_function_is_affine_multivariate_p (chrec, 0))
2995 if (dump_file && (dump_flags & TDF_STATS))
2996 fprintf (dump_file, " affine_multivariate\n");
2997 stats->nb_affine_multivar++;
2999 else
3001 if (dump_file && (dump_flags & TDF_STATS))
3002 fprintf (dump_file, " higher_degree_polynomial\n");
3003 stats->nb_higher_poly++;
3006 break;
3008 default:
3009 break;
3012 if (chrec_contains_undetermined (chrec))
3014 if (dump_file && (dump_flags & TDF_STATS))
3015 fprintf (dump_file, " undetermined\n");
3016 stats->nb_undetermined++;
3019 if (dump_file && (dump_flags & TDF_STATS))
3020 fprintf (dump_file, ")\n");
3023 /* Classify the chrecs of the whole database. */
3025 void
3026 gather_stats_on_scev_database (void)
3028 struct chrec_stats stats;
3030 if (!dump_file)
3031 return;
3033 reset_chrecs_counters (&stats);
3035 hash_table<scev_info_hasher>::iterator iter;
3036 scev_info_str *elt;
3037 FOR_EACH_HASH_TABLE_ELEMENT (*scalar_evolution_info, elt, scev_info_str *,
3038 iter)
3039 gather_chrec_stats (elt->chrec, &stats);
3041 dump_chrecs_stats (dump_file, &stats);
3045 /* Initialize the analysis of scalar evolutions for LOOPS. */
3047 void
3048 scev_initialize (void)
3050 class loop *loop;
3052 gcc_assert (! scev_initialized_p ());
3054 scalar_evolution_info = hash_table<scev_info_hasher>::create_ggc (100);
3056 FOR_EACH_LOOP (loop, 0)
3058 loop->nb_iterations = NULL_TREE;
3062 /* Return true if SCEV is initialized. */
3064 bool
3065 scev_initialized_p (void)
3067 return scalar_evolution_info != NULL;
3070 /* Cleans up the information cached by the scalar evolutions analysis
3071 in the hash table. */
3073 void
3074 scev_reset_htab (void)
3076 if (!scalar_evolution_info)
3077 return;
3079 scalar_evolution_info->empty ();
3082 /* Cleans up the information cached by the scalar evolutions analysis
3083 in the hash table and in the loop->nb_iterations. */
3085 void
3086 scev_reset (void)
3088 class loop *loop;
3090 scev_reset_htab ();
3092 FOR_EACH_LOOP (loop, 0)
3094 loop->nb_iterations = NULL_TREE;
3098 /* Return true if the IV calculation in TYPE can overflow based on the knowledge
3099 of the upper bound on the number of iterations of LOOP, the BASE and STEP
3100 of IV.
3102 We do not use information whether TYPE can overflow so it is safe to
3103 use this test even for derived IVs not computed every iteration or
3104 hypotetical IVs to be inserted into code. */
3106 bool
3107 iv_can_overflow_p (class loop *loop, tree type, tree base, tree step)
3109 widest_int nit;
3110 wide_int base_min, base_max, step_min, step_max, type_min, type_max;
3111 signop sgn = TYPE_SIGN (type);
3113 if (integer_zerop (step))
3114 return false;
3116 if (TREE_CODE (base) == INTEGER_CST)
3117 base_min = base_max = wi::to_wide (base);
3118 else if (TREE_CODE (base) == SSA_NAME
3119 && INTEGRAL_TYPE_P (TREE_TYPE (base))
3120 && get_range_info (base, &base_min, &base_max) == VR_RANGE)
3122 else
3123 return true;
3125 if (TREE_CODE (step) == INTEGER_CST)
3126 step_min = step_max = wi::to_wide (step);
3127 else if (TREE_CODE (step) == SSA_NAME
3128 && INTEGRAL_TYPE_P (TREE_TYPE (step))
3129 && get_range_info (step, &step_min, &step_max) == VR_RANGE)
3131 else
3132 return true;
3134 if (!get_max_loop_iterations (loop, &nit))
3135 return true;
3137 type_min = wi::min_value (type);
3138 type_max = wi::max_value (type);
3140 /* Just sanity check that we don't see values out of the range of the type.
3141 In this case the arithmetics bellow would overflow. */
3142 gcc_checking_assert (wi::ge_p (base_min, type_min, sgn)
3143 && wi::le_p (base_max, type_max, sgn));
3145 /* Account the possible increment in the last ieration. */
3146 wi::overflow_type overflow = wi::OVF_NONE;
3147 nit = wi::add (nit, 1, SIGNED, &overflow);
3148 if (overflow)
3149 return true;
3151 /* NIT is typeless and can exceed the precision of the type. In this case
3152 overflow is always possible, because we know STEP is non-zero. */
3153 if (wi::min_precision (nit, UNSIGNED) > TYPE_PRECISION (type))
3154 return true;
3155 wide_int nit2 = wide_int::from (nit, TYPE_PRECISION (type), UNSIGNED);
3157 /* If step can be positive, check that nit*step <= type_max-base.
3158 This can be done by unsigned arithmetic and we only need to watch overflow
3159 in the multiplication. The right hand side can always be represented in
3160 the type. */
3161 if (sgn == UNSIGNED || !wi::neg_p (step_max))
3163 wi::overflow_type overflow = wi::OVF_NONE;
3164 if (wi::gtu_p (wi::mul (step_max, nit2, UNSIGNED, &overflow),
3165 type_max - base_max)
3166 || overflow)
3167 return true;
3169 /* If step can be negative, check that nit*(-step) <= base_min-type_min. */
3170 if (sgn == SIGNED && wi::neg_p (step_min))
3172 wi::overflow_type overflow, overflow2;
3173 overflow = overflow2 = wi::OVF_NONE;
3174 if (wi::gtu_p (wi::mul (wi::neg (step_min, &overflow2),
3175 nit2, UNSIGNED, &overflow),
3176 base_min - type_min)
3177 || overflow || overflow2)
3178 return true;
3181 return false;
3184 /* Given EV with form of "(type) {inner_base, inner_step}_loop", this
3185 function tries to derive condition under which it can be simplified
3186 into "{(type)inner_base, (type)inner_step}_loop". The condition is
3187 the maximum number that inner iv can iterate. */
3189 static tree
3190 derive_simple_iv_with_niters (tree ev, tree *niters)
3192 if (!CONVERT_EXPR_P (ev))
3193 return ev;
3195 tree inner_ev = TREE_OPERAND (ev, 0);
3196 if (TREE_CODE (inner_ev) != POLYNOMIAL_CHREC)
3197 return ev;
3199 tree init = CHREC_LEFT (inner_ev);
3200 tree step = CHREC_RIGHT (inner_ev);
3201 if (TREE_CODE (init) != INTEGER_CST
3202 || TREE_CODE (step) != INTEGER_CST || integer_zerop (step))
3203 return ev;
3205 tree type = TREE_TYPE (ev);
3206 tree inner_type = TREE_TYPE (inner_ev);
3207 if (TYPE_PRECISION (inner_type) >= TYPE_PRECISION (type))
3208 return ev;
3210 /* Type conversion in "(type) {inner_base, inner_step}_loop" can be
3211 folded only if inner iv won't overflow. We compute the maximum
3212 number the inner iv can iterate before overflowing and return the
3213 simplified affine iv. */
3214 tree delta;
3215 init = fold_convert (type, init);
3216 step = fold_convert (type, step);
3217 ev = build_polynomial_chrec (CHREC_VARIABLE (inner_ev), init, step);
3218 if (tree_int_cst_sign_bit (step))
3220 tree bound = lower_bound_in_type (inner_type, inner_type);
3221 delta = fold_build2 (MINUS_EXPR, type, init, fold_convert (type, bound));
3222 step = fold_build1 (NEGATE_EXPR, type, step);
3224 else
3226 tree bound = upper_bound_in_type (inner_type, inner_type);
3227 delta = fold_build2 (MINUS_EXPR, type, fold_convert (type, bound), init);
3229 *niters = fold_build2 (FLOOR_DIV_EXPR, type, delta, step);
3230 return ev;
3233 /* Checks whether use of OP in USE_LOOP behaves as a simple affine iv with
3234 respect to WRTO_LOOP and returns its base and step in IV if possible
3235 (see analyze_scalar_evolution_in_loop for more details on USE_LOOP
3236 and WRTO_LOOP). If ALLOW_NONCONSTANT_STEP is true, we want step to be
3237 invariant in LOOP. Otherwise we require it to be an integer constant.
3239 IV->no_overflow is set to true if we are sure the iv cannot overflow (e.g.
3240 because it is computed in signed arithmetics). Consequently, adding an
3241 induction variable
3243 for (i = IV->base; ; i += IV->step)
3245 is only safe if IV->no_overflow is false, or TYPE_OVERFLOW_UNDEFINED is
3246 false for the type of the induction variable, or you can prove that i does
3247 not wrap by some other argument. Otherwise, this might introduce undefined
3248 behavior, and
3250 i = iv->base;
3251 for (; ; i = (type) ((unsigned type) i + (unsigned type) iv->step))
3253 must be used instead.
3255 When IV_NITERS is not NULL, this function also checks case in which OP
3256 is a conversion of an inner simple iv of below form:
3258 (outer_type){inner_base, inner_step}_loop.
3260 If type of inner iv has smaller precision than outer_type, it can't be
3261 folded into {(outer_type)inner_base, (outer_type)inner_step}_loop because
3262 the inner iv could overflow/wrap. In this case, we derive a condition
3263 under which the inner iv won't overflow/wrap and do the simplification.
3264 The derived condition normally is the maximum number the inner iv can
3265 iterate, and will be stored in IV_NITERS. This is useful in loop niter
3266 analysis, to derive break conditions when a loop must terminate, when is
3267 infinite. */
3269 bool
3270 simple_iv_with_niters (class loop *wrto_loop, class loop *use_loop,
3271 tree op, affine_iv *iv, tree *iv_niters,
3272 bool allow_nonconstant_step)
3274 enum tree_code code;
3275 tree type, ev, base, e;
3276 wide_int extreme;
3277 bool folded_casts;
3279 iv->base = NULL_TREE;
3280 iv->step = NULL_TREE;
3281 iv->no_overflow = false;
3283 type = TREE_TYPE (op);
3284 if (!POINTER_TYPE_P (type)
3285 && !INTEGRAL_TYPE_P (type))
3286 return false;
3288 ev = analyze_scalar_evolution_in_loop (wrto_loop, use_loop, op,
3289 &folded_casts);
3290 if (chrec_contains_undetermined (ev)
3291 || chrec_contains_symbols_defined_in_loop (ev, wrto_loop->num))
3292 return false;
3294 if (tree_does_not_contain_chrecs (ev))
3296 iv->base = ev;
3297 iv->step = build_int_cst (TREE_TYPE (ev), 0);
3298 iv->no_overflow = true;
3299 return true;
3302 /* If we can derive valid scalar evolution with assumptions. */
3303 if (iv_niters && TREE_CODE (ev) != POLYNOMIAL_CHREC)
3304 ev = derive_simple_iv_with_niters (ev, iv_niters);
3306 if (TREE_CODE (ev) != POLYNOMIAL_CHREC)
3307 return false;
3309 if (CHREC_VARIABLE (ev) != (unsigned) wrto_loop->num)
3310 return false;
3312 iv->step = CHREC_RIGHT (ev);
3313 if ((!allow_nonconstant_step && TREE_CODE (iv->step) != INTEGER_CST)
3314 || tree_contains_chrecs (iv->step, NULL))
3315 return false;
3317 iv->base = CHREC_LEFT (ev);
3318 if (tree_contains_chrecs (iv->base, NULL))
3319 return false;
3321 iv->no_overflow = !folded_casts && nowrap_type_p (type);
3323 if (!iv->no_overflow
3324 && !iv_can_overflow_p (wrto_loop, type, iv->base, iv->step))
3325 iv->no_overflow = true;
3327 /* Try to simplify iv base:
3329 (signed T) ((unsigned T)base + step) ;; TREE_TYPE (base) == signed T
3330 == (signed T)(unsigned T)base + step
3331 == base + step
3333 If we can prove operation (base + step) doesn't overflow or underflow.
3334 Specifically, we try to prove below conditions are satisfied:
3336 base <= UPPER_BOUND (type) - step ;;step > 0
3337 base >= LOWER_BOUND (type) - step ;;step < 0
3339 This is done by proving the reverse conditions are false using loop's
3340 initial conditions.
3342 The is necessary to make loop niter, or iv overflow analysis easier
3343 for below example:
3345 int foo (int *a, signed char s, signed char l)
3347 signed char i;
3348 for (i = s; i < l; i++)
3349 a[i] = 0;
3350 return 0;
3353 Note variable I is firstly converted to type unsigned char, incremented,
3354 then converted back to type signed char. */
3356 if (wrto_loop->num != use_loop->num)
3357 return true;
3359 if (!CONVERT_EXPR_P (iv->base) || TREE_CODE (iv->step) != INTEGER_CST)
3360 return true;
3362 type = TREE_TYPE (iv->base);
3363 e = TREE_OPERAND (iv->base, 0);
3364 if (TREE_CODE (e) != PLUS_EXPR
3365 || TREE_CODE (TREE_OPERAND (e, 1)) != INTEGER_CST
3366 || !tree_int_cst_equal (iv->step,
3367 fold_convert (type, TREE_OPERAND (e, 1))))
3368 return true;
3369 e = TREE_OPERAND (e, 0);
3370 if (!CONVERT_EXPR_P (e))
3371 return true;
3372 base = TREE_OPERAND (e, 0);
3373 if (!useless_type_conversion_p (type, TREE_TYPE (base)))
3374 return true;
3376 if (tree_int_cst_sign_bit (iv->step))
3378 code = LT_EXPR;
3379 extreme = wi::min_value (type);
3381 else
3383 code = GT_EXPR;
3384 extreme = wi::max_value (type);
3386 wi::overflow_type overflow = wi::OVF_NONE;
3387 extreme = wi::sub (extreme, wi::to_wide (iv->step),
3388 TYPE_SIGN (type), &overflow);
3389 if (overflow)
3390 return true;
3391 e = fold_build2 (code, boolean_type_node, base,
3392 wide_int_to_tree (type, extreme));
3393 e = simplify_using_initial_conditions (use_loop, e);
3394 if (!integer_zerop (e))
3395 return true;
3397 if (POINTER_TYPE_P (TREE_TYPE (base)))
3398 code = POINTER_PLUS_EXPR;
3399 else
3400 code = PLUS_EXPR;
3402 iv->base = fold_build2 (code, TREE_TYPE (base), base, iv->step);
3403 return true;
3406 /* Like simple_iv_with_niters, but return TRUE when OP behaves as a simple
3407 affine iv unconditionally. */
3409 bool
3410 simple_iv (class loop *wrto_loop, class loop *use_loop, tree op,
3411 affine_iv *iv, bool allow_nonconstant_step)
3413 return simple_iv_with_niters (wrto_loop, use_loop, op, iv,
3414 NULL, allow_nonconstant_step);
3417 /* Finalize the scalar evolution analysis. */
3419 void
3420 scev_finalize (void)
3422 if (!scalar_evolution_info)
3423 return;
3424 scalar_evolution_info->empty ();
3425 scalar_evolution_info = NULL;
3426 free_numbers_of_iterations_estimates (cfun);
3429 /* Returns true if the expression EXPR is considered to be too expensive
3430 for scev_const_prop. */
3432 static bool
3433 expression_expensive_p (tree expr, hash_map<tree, uint64_t> &cache,
3434 uint64_t &cost)
3436 enum tree_code code;
3438 if (is_gimple_val (expr))
3439 return false;
3441 code = TREE_CODE (expr);
3442 if (code == TRUNC_DIV_EXPR
3443 || code == CEIL_DIV_EXPR
3444 || code == FLOOR_DIV_EXPR
3445 || code == ROUND_DIV_EXPR
3446 || code == TRUNC_MOD_EXPR
3447 || code == CEIL_MOD_EXPR
3448 || code == FLOOR_MOD_EXPR
3449 || code == ROUND_MOD_EXPR
3450 || code == EXACT_DIV_EXPR)
3452 /* Division by power of two is usually cheap, so we allow it.
3453 Forbid anything else. */
3454 if (!integer_pow2p (TREE_OPERAND (expr, 1)))
3455 return true;
3458 bool visited_p;
3459 uint64_t &local_cost = cache.get_or_insert (expr, &visited_p);
3460 if (visited_p)
3462 uint64_t tem = cost + local_cost;
3463 if (tem < cost)
3464 return true;
3465 cost = tem;
3466 return false;
3468 local_cost = 1;
3470 uint64_t op_cost = 0;
3471 if (code == CALL_EXPR)
3473 tree arg;
3474 call_expr_arg_iterator iter;
3475 /* Even though is_inexpensive_builtin might say true, we will get a
3476 library call for popcount when backend does not have an instruction
3477 to do so. We consider this to be expenseive and generate
3478 __builtin_popcount only when backend defines it. */
3479 combined_fn cfn = get_call_combined_fn (expr);
3480 switch (cfn)
3482 CASE_CFN_POPCOUNT:
3483 /* Check if opcode for popcount is available in the mode required. */
3484 if (optab_handler (popcount_optab,
3485 TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (expr, 0))))
3486 == CODE_FOR_nothing)
3488 machine_mode mode;
3489 mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (expr, 0)));
3490 scalar_int_mode int_mode;
3492 /* If the mode is of 2 * UNITS_PER_WORD size, we can handle
3493 double-word popcount by emitting two single-word popcount
3494 instructions. */
3495 if (is_a <scalar_int_mode> (mode, &int_mode)
3496 && GET_MODE_SIZE (int_mode) == 2 * UNITS_PER_WORD
3497 && (optab_handler (popcount_optab, word_mode)
3498 != CODE_FOR_nothing))
3499 break;
3500 return true;
3502 default:
3503 break;
3506 if (!is_inexpensive_builtin (get_callee_fndecl (expr)))
3507 return true;
3508 FOR_EACH_CALL_EXPR_ARG (arg, iter, expr)
3509 if (expression_expensive_p (arg, cache, op_cost))
3510 return true;
3511 *cache.get (expr) += op_cost;
3512 cost += op_cost + 1;
3513 return false;
3516 if (code == COND_EXPR)
3518 if (expression_expensive_p (TREE_OPERAND (expr, 0), cache, op_cost)
3519 || (EXPR_P (TREE_OPERAND (expr, 1))
3520 && EXPR_P (TREE_OPERAND (expr, 2)))
3521 /* If either branch has side effects or could trap. */
3522 || TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1))
3523 || generic_expr_could_trap_p (TREE_OPERAND (expr, 1))
3524 || TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 0))
3525 || generic_expr_could_trap_p (TREE_OPERAND (expr, 0))
3526 || expression_expensive_p (TREE_OPERAND (expr, 1),
3527 cache, op_cost)
3528 || expression_expensive_p (TREE_OPERAND (expr, 2),
3529 cache, op_cost))
3530 return true;
3531 *cache.get (expr) += op_cost;
3532 cost += op_cost + 1;
3533 return false;
3536 switch (TREE_CODE_CLASS (code))
3538 case tcc_binary:
3539 case tcc_comparison:
3540 if (expression_expensive_p (TREE_OPERAND (expr, 1), cache, op_cost))
3541 return true;
3543 /* Fallthru. */
3544 case tcc_unary:
3545 if (expression_expensive_p (TREE_OPERAND (expr, 0), cache, op_cost))
3546 return true;
3547 *cache.get (expr) += op_cost;
3548 cost += op_cost + 1;
3549 return false;
3551 default:
3552 return true;
3556 bool
3557 expression_expensive_p (tree expr)
3559 hash_map<tree, uint64_t> cache;
3560 uint64_t expanded_size = 0;
3561 return (expression_expensive_p (expr, cache, expanded_size)
3562 || expanded_size > cache.elements ());
3565 /* Do final value replacement for LOOP, return true if we did anything. */
3567 bool
3568 final_value_replacement_loop (class loop *loop)
3570 /* If we do not know exact number of iterations of the loop, we cannot
3571 replace the final value. */
3572 edge exit = single_exit (loop);
3573 if (!exit)
3574 return false;
3576 tree niter = number_of_latch_executions (loop);
3577 if (niter == chrec_dont_know)
3578 return false;
3580 /* Ensure that it is possible to insert new statements somewhere. */
3581 if (!single_pred_p (exit->dest))
3582 split_loop_exit_edge (exit);
3584 /* Set stmt insertion pointer. All stmts are inserted before this point. */
3585 gimple_stmt_iterator gsi = gsi_after_labels (exit->dest);
3587 class loop *ex_loop
3588 = superloop_at_depth (loop,
3589 loop_depth (exit->dest->loop_father) + 1);
3591 bool any = false;
3592 gphi_iterator psi;
3593 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); )
3595 gphi *phi = psi.phi ();
3596 tree rslt = PHI_RESULT (phi);
3597 tree def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
3598 if (virtual_operand_p (def))
3600 gsi_next (&psi);
3601 continue;
3604 if (!POINTER_TYPE_P (TREE_TYPE (def))
3605 && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
3607 gsi_next (&psi);
3608 continue;
3611 bool folded_casts;
3612 def = analyze_scalar_evolution_in_loop (ex_loop, loop, def,
3613 &folded_casts);
3614 def = compute_overall_effect_of_inner_loop (ex_loop, def);
3615 if (!tree_does_not_contain_chrecs (def)
3616 || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
3617 /* Moving the computation from the loop may prolong life range
3618 of some ssa names, which may cause problems if they appear
3619 on abnormal edges. */
3620 || contains_abnormal_ssa_name_p (def)
3621 /* Do not emit expensive expressions. The rationale is that
3622 when someone writes a code like
3624 while (n > 45) n -= 45;
3626 he probably knows that n is not large, and does not want it
3627 to be turned into n %= 45. */
3628 || expression_expensive_p (def))
3630 if (dump_file && (dump_flags & TDF_DETAILS))
3632 fprintf (dump_file, "not replacing:\n ");
3633 print_gimple_stmt (dump_file, phi, 0);
3634 fprintf (dump_file, "\n");
3636 gsi_next (&psi);
3637 continue;
3640 /* Eliminate the PHI node and replace it by a computation outside
3641 the loop. */
3642 if (dump_file)
3644 fprintf (dump_file, "\nfinal value replacement:\n ");
3645 print_gimple_stmt (dump_file, phi, 0);
3646 fprintf (dump_file, " with expr: ");
3647 print_generic_expr (dump_file, def);
3649 any = true;
3650 def = unshare_expr (def);
3651 remove_phi_node (&psi, false);
3653 /* If def's type has undefined overflow and there were folded
3654 casts, rewrite all stmts added for def into arithmetics
3655 with defined overflow behavior. */
3656 if (folded_casts && ANY_INTEGRAL_TYPE_P (TREE_TYPE (def))
3657 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (def)))
3659 gimple_seq stmts;
3660 gimple_stmt_iterator gsi2;
3661 def = force_gimple_operand (def, &stmts, true, NULL_TREE);
3662 gsi2 = gsi_start (stmts);
3663 while (!gsi_end_p (gsi2))
3665 gimple *stmt = gsi_stmt (gsi2);
3666 gimple_stmt_iterator gsi3 = gsi2;
3667 gsi_next (&gsi2);
3668 gsi_remove (&gsi3, false);
3669 if (is_gimple_assign (stmt)
3670 && arith_code_with_undefined_signed_overflow
3671 (gimple_assign_rhs_code (stmt)))
3672 gsi_insert_seq_before (&gsi,
3673 rewrite_to_defined_overflow (stmt),
3674 GSI_SAME_STMT);
3675 else
3676 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
3679 else
3680 def = force_gimple_operand_gsi (&gsi, def, false, NULL_TREE,
3681 true, GSI_SAME_STMT);
3683 gassign *ass = gimple_build_assign (rslt, def);
3684 gimple_set_location (ass,
3685 gimple_phi_arg_location (phi, exit->dest_idx));
3686 gsi_insert_before (&gsi, ass, GSI_SAME_STMT);
3687 if (dump_file)
3689 fprintf (dump_file, "\n final stmt:\n ");
3690 print_gimple_stmt (dump_file, ass, 0);
3691 fprintf (dump_file, "\n");
3695 return any;
3698 #include "gt-tree-scalar-evolution.h"