Collections.java (UnmodifiableMap.toArray): Imported changes from Classpath.
[gcc.git] / gcc / tree-scalar-evolution.c
1 /* Scalar evolution detector.
2 Copyright (C) 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
3 Contributed by Sebastian Pop <s.pop@laposte.net>
4
5 This file is part of GCC.
6
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 2, or (at your option) any later
10 version.
11
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.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING. If not, write to the Free
19 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
20 02110-1301, USA. */
21
22 /*
23 Description:
24
25 This pass analyzes the evolution of scalar variables in loop
26 structures. The algorithm is based on the SSA representation,
27 and on the loop hierarchy tree. This algorithm is not based on
28 the notion of versions of a variable, as it was the case for the
29 previous implementations of the scalar evolution algorithm, but
30 it assumes that each defined name is unique.
31
32 The notation used in this file is called "chains of recurrences",
33 and has been proposed by Eugene Zima, Robert Van Engelen, and
34 others for describing induction variables in programs. For example
35 "b -> {0, +, 2}_1" means that the scalar variable "b" is equal to 0
36 when entering in the loop_1 and has a step 2 in this loop, in other
37 words "for (b = 0; b < N; b+=2);". Note that the coefficients of
38 this chain of recurrence (or chrec [shrek]) can contain the name of
39 other variables, in which case they are called parametric chrecs.
40 For example, "b -> {a, +, 2}_1" means that the initial value of "b"
41 is the value of "a". In most of the cases these parametric chrecs
42 are fully instantiated before their use because symbolic names can
43 hide some difficult cases such as self-references described later
44 (see the Fibonacci example).
45
46 A short sketch of the algorithm is:
47
48 Given a scalar variable to be analyzed, follow the SSA edge to
49 its definition:
50
51 - When the definition is a GIMPLE_MODIFY_STMT: if the right hand side
52 (RHS) of the definition cannot be statically analyzed, the answer
53 of the analyzer is: "don't know".
54 Otherwise, for all the variables that are not yet analyzed in the
55 RHS, try to determine their evolution, and finally try to
56 evaluate the operation of the RHS that gives the evolution
57 function of the analyzed variable.
58
59 - When the definition is a condition-phi-node: determine the
60 evolution function for all the branches of the phi node, and
61 finally merge these evolutions (see chrec_merge).
62
63 - When the definition is a loop-phi-node: determine its initial
64 condition, that is the SSA edge defined in an outer loop, and
65 keep it symbolic. Then determine the SSA edges that are defined
66 in the body of the loop. Follow the inner edges until ending on
67 another loop-phi-node of the same analyzed loop. If the reached
68 loop-phi-node is not the starting loop-phi-node, then we keep
69 this definition under a symbolic form. If the reached
70 loop-phi-node is the same as the starting one, then we compute a
71 symbolic stride on the return path. The result is then the
72 symbolic chrec {initial_condition, +, symbolic_stride}_loop.
73
74 Examples:
75
76 Example 1: Illustration of the basic algorithm.
77
78 | a = 3
79 | loop_1
80 | b = phi (a, c)
81 | c = b + 1
82 | if (c > 10) exit_loop
83 | endloop
84
85 Suppose that we want to know the number of iterations of the
86 loop_1. The exit_loop is controlled by a COND_EXPR (c > 10). We
87 ask the scalar evolution analyzer two questions: what's the
88 scalar evolution (scev) of "c", and what's the scev of "10". For
89 "10" the answer is "10" since it is a scalar constant. For the
90 scalar variable "c", it follows the SSA edge to its definition,
91 "c = b + 1", and then asks again what's the scev of "b".
92 Following the SSA edge, we end on a loop-phi-node "b = phi (a,
93 c)", where the initial condition is "a", and the inner loop edge
94 is "c". The initial condition is kept under a symbolic form (it
95 may be the case that the copy constant propagation has done its
96 work and we end with the constant "3" as one of the edges of the
97 loop-phi-node). The update edge is followed to the end of the
98 loop, and until reaching again the starting loop-phi-node: b -> c
99 -> b. At this point we have drawn a path from "b" to "b" from
100 which we compute the stride in the loop: in this example it is
101 "+1". The resulting scev for "b" is "b -> {a, +, 1}_1". Now
102 that the scev for "b" is known, it is possible to compute the
103 scev for "c", that is "c -> {a + 1, +, 1}_1". In order to
104 determine the number of iterations in the loop_1, we have to
105 instantiate_parameters ({a + 1, +, 1}_1), that gives after some
106 more analysis the scev {4, +, 1}_1, or in other words, this is
107 the function "f (x) = x + 4", where x is the iteration count of
108 the loop_1. Now we have to solve the inequality "x + 4 > 10",
109 and take the smallest iteration number for which the loop is
110 exited: x = 7. This loop runs from x = 0 to x = 7, and in total
111 there are 8 iterations. In terms of loop normalization, we have
112 created a variable that is implicitly defined, "x" or just "_1",
113 and all the other analyzed scalars of the loop are defined in
114 function of this variable:
115
116 a -> 3
117 b -> {3, +, 1}_1
118 c -> {4, +, 1}_1
119
120 or in terms of a C program:
121
122 | a = 3
123 | for (x = 0; x <= 7; x++)
124 | {
125 | b = x + 3
126 | c = x + 4
127 | }
128
129 Example 2: Illustration of the algorithm on nested loops.
130
131 | loop_1
132 | a = phi (1, b)
133 | c = a + 2
134 | loop_2 10 times
135 | b = phi (c, d)
136 | d = b + 3
137 | endloop
138 | endloop
139
140 For analyzing the scalar evolution of "a", the algorithm follows
141 the SSA edge into the loop's body: "a -> b". "b" is an inner
142 loop-phi-node, and its analysis as in Example 1, gives:
143
144 b -> {c, +, 3}_2
145 d -> {c + 3, +, 3}_2
146
147 Following the SSA edge for the initial condition, we end on "c = a
148 + 2", and then on the starting loop-phi-node "a". From this point,
149 the loop stride is computed: back on "c = a + 2" we get a "+2" in
150 the loop_1, then on the loop-phi-node "b" we compute the overall
151 effect of the inner loop that is "b = c + 30", and we get a "+30"
152 in the loop_1. That means that the overall stride in loop_1 is
153 equal to "+32", and the result is:
154
155 a -> {1, +, 32}_1
156 c -> {3, +, 32}_1
157
158 Example 3: Higher degree polynomials.
159
160 | loop_1
161 | a = phi (2, b)
162 | c = phi (5, d)
163 | b = a + 1
164 | d = c + a
165 | endloop
166
167 a -> {2, +, 1}_1
168 b -> {3, +, 1}_1
169 c -> {5, +, a}_1
170 d -> {5 + a, +, a}_1
171
172 instantiate_parameters ({5, +, a}_1) -> {5, +, 2, +, 1}_1
173 instantiate_parameters ({5 + a, +, a}_1) -> {7, +, 3, +, 1}_1
174
175 Example 4: Lucas, Fibonacci, or mixers in general.
176
177 | loop_1
178 | a = phi (1, b)
179 | c = phi (3, d)
180 | b = c
181 | d = c + a
182 | endloop
183
184 a -> (1, c)_1
185 c -> {3, +, a}_1
186
187 The syntax "(1, c)_1" stands for a PEELED_CHREC that has the
188 following semantics: during the first iteration of the loop_1, the
189 variable contains the value 1, and then it contains the value "c".
190 Note that this syntax is close to the syntax of the loop-phi-node:
191 "a -> (1, c)_1" vs. "a = phi (1, c)".
192
193 The symbolic chrec representation contains all the semantics of the
194 original code. What is more difficult is to use this information.
195
196 Example 5: Flip-flops, or exchangers.
197
198 | loop_1
199 | a = phi (1, b)
200 | c = phi (3, d)
201 | b = c
202 | d = a
203 | endloop
204
205 a -> (1, c)_1
206 c -> (3, a)_1
207
208 Based on these symbolic chrecs, it is possible to refine this
209 information into the more precise PERIODIC_CHRECs:
210
211 a -> |1, 3|_1
212 c -> |3, 1|_1
213
214 This transformation is not yet implemented.
215
216 Further readings:
217
218 You can find a more detailed description of the algorithm in:
219 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.pdf
220 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.ps.gz. But note that
221 this is a preliminary report and some of the details of the
222 algorithm have changed. I'm working on a research report that
223 updates the description of the algorithms to reflect the design
224 choices used in this implementation.
225
226 A set of slides show a high level overview of the algorithm and run
227 an example through the scalar evolution analyzer:
228 http://cri.ensmp.fr/~pop/gcc/mar04/slides.pdf
229
230 The slides that I have presented at the GCC Summit'04 are available
231 at: http://cri.ensmp.fr/~pop/gcc/20040604/gccsummit-lno-spop.pdf
232 */
233
234 #include "config.h"
235 #include "system.h"
236 #include "coretypes.h"
237 #include "tm.h"
238 #include "ggc.h"
239 #include "tree.h"
240 #include "real.h"
241
242 /* These RTL headers are needed for basic-block.h. */
243 #include "rtl.h"
244 #include "basic-block.h"
245 #include "diagnostic.h"
246 #include "tree-flow.h"
247 #include "tree-dump.h"
248 #include "timevar.h"
249 #include "cfgloop.h"
250 #include "tree-chrec.h"
251 #include "tree-scalar-evolution.h"
252 #include "tree-pass.h"
253 #include "flags.h"
254 #include "params.h"
255
256 static tree analyze_scalar_evolution_1 (struct loop *, tree, tree);
257 static tree resolve_mixers (struct loop *, tree);
258
259 /* The cached information about a ssa name VAR, claiming that inside LOOP,
260 the value of VAR can be expressed as CHREC. */
261
262 struct scev_info_str
263 {
264 tree var;
265 tree chrec;
266 };
267
268 /* Counters for the scev database. */
269 static unsigned nb_set_scev = 0;
270 static unsigned nb_get_scev = 0;
271
272 /* The following trees are unique elements. Thus the comparison of
273 another element to these elements should be done on the pointer to
274 these trees, and not on their value. */
275
276 /* The SSA_NAMEs that are not yet analyzed are qualified with NULL_TREE. */
277 tree chrec_not_analyzed_yet;
278
279 /* Reserved to the cases where the analyzer has detected an
280 undecidable property at compile time. */
281 tree chrec_dont_know;
282
283 /* When the analyzer has detected that a property will never
284 happen, then it qualifies it with chrec_known. */
285 tree chrec_known;
286
287 static bitmap already_instantiated;
288
289 static htab_t scalar_evolution_info;
290
291 \f
292 /* Constructs a new SCEV_INFO_STR structure. */
293
294 static inline struct scev_info_str *
295 new_scev_info_str (tree var)
296 {
297 struct scev_info_str *res;
298
299 res = XNEW (struct scev_info_str);
300 res->var = var;
301 res->chrec = chrec_not_analyzed_yet;
302
303 return res;
304 }
305
306 /* Computes a hash function for database element ELT. */
307
308 static hashval_t
309 hash_scev_info (const void *elt)
310 {
311 return SSA_NAME_VERSION (((struct scev_info_str *) elt)->var);
312 }
313
314 /* Compares database elements E1 and E2. */
315
316 static int
317 eq_scev_info (const void *e1, const void *e2)
318 {
319 const struct scev_info_str *elt1 = (const struct scev_info_str *) e1;
320 const struct scev_info_str *elt2 = (const struct scev_info_str *) e2;
321
322 return elt1->var == elt2->var;
323 }
324
325 /* Deletes database element E. */
326
327 static void
328 del_scev_info (void *e)
329 {
330 free (e);
331 }
332
333 /* Get the index corresponding to VAR in the current LOOP. If
334 it's the first time we ask for this VAR, then we return
335 chrec_not_analyzed_yet for this VAR and return its index. */
336
337 static tree *
338 find_var_scev_info (tree var)
339 {
340 struct scev_info_str *res;
341 struct scev_info_str tmp;
342 PTR *slot;
343
344 tmp.var = var;
345 slot = htab_find_slot (scalar_evolution_info, &tmp, INSERT);
346
347 if (!*slot)
348 *slot = new_scev_info_str (var);
349 res = (struct scev_info_str *) *slot;
350
351 return &res->chrec;
352 }
353
354 /* Return true when CHREC contains symbolic names defined in
355 LOOP_NB. */
356
357 bool
358 chrec_contains_symbols_defined_in_loop (tree chrec, unsigned loop_nb)
359 {
360 if (chrec == NULL_TREE)
361 return false;
362
363 if (TREE_INVARIANT (chrec))
364 return false;
365
366 if (TREE_CODE (chrec) == VAR_DECL
367 || TREE_CODE (chrec) == PARM_DECL
368 || TREE_CODE (chrec) == FUNCTION_DECL
369 || TREE_CODE (chrec) == LABEL_DECL
370 || TREE_CODE (chrec) == RESULT_DECL
371 || TREE_CODE (chrec) == FIELD_DECL)
372 return true;
373
374 if (TREE_CODE (chrec) == SSA_NAME)
375 {
376 tree def = SSA_NAME_DEF_STMT (chrec);
377 struct loop *def_loop = loop_containing_stmt (def);
378 struct loop *loop = get_loop (loop_nb);
379
380 if (def_loop == NULL)
381 return false;
382
383 if (loop == def_loop || flow_loop_nested_p (loop, def_loop))
384 return true;
385
386 return false;
387 }
388
389 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
390 {
391 case 3:
392 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, 2),
393 loop_nb))
394 return true;
395
396 case 2:
397 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, 1),
398 loop_nb))
399 return true;
400
401 case 1:
402 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, 0),
403 loop_nb))
404 return true;
405
406 default:
407 return false;
408 }
409 }
410
411 /* Return true when PHI is a loop-phi-node. */
412
413 static bool
414 loop_phi_node_p (tree phi)
415 {
416 /* The implementation of this function is based on the following
417 property: "all the loop-phi-nodes of a loop are contained in the
418 loop's header basic block". */
419
420 return loop_containing_stmt (phi)->header == bb_for_stmt (phi);
421 }
422
423 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
424 In general, in the case of multivariate evolutions we want to get
425 the evolution in different loops. LOOP specifies the level for
426 which to get the evolution.
427
428 Example:
429
430 | for (j = 0; j < 100; j++)
431 | {
432 | for (k = 0; k < 100; k++)
433 | {
434 | i = k + j; - Here the value of i is a function of j, k.
435 | }
436 | ... = i - Here the value of i is a function of j.
437 | }
438 | ... = i - Here the value of i is a scalar.
439
440 Example:
441
442 | i_0 = ...
443 | loop_1 10 times
444 | i_1 = phi (i_0, i_2)
445 | i_2 = i_1 + 2
446 | endloop
447
448 This loop has the same effect as:
449 LOOP_1 has the same effect as:
450
451 | i_1 = i_0 + 20
452
453 The overall effect of the loop, "i_0 + 20" in the previous example,
454 is obtained by passing in the parameters: LOOP = 1,
455 EVOLUTION_FN = {i_0, +, 2}_1.
456 */
457
458 static tree
459 compute_overall_effect_of_inner_loop (struct loop *loop, tree evolution_fn)
460 {
461 bool val = false;
462
463 if (evolution_fn == chrec_dont_know)
464 return chrec_dont_know;
465
466 else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
467 {
468 struct loop *inner_loop = get_chrec_loop (evolution_fn);
469
470 if (inner_loop == loop
471 || flow_loop_nested_p (loop, inner_loop))
472 {
473 tree nb_iter = number_of_latch_executions (inner_loop);
474
475 if (nb_iter == chrec_dont_know)
476 return chrec_dont_know;
477 else
478 {
479 tree res;
480
481 /* evolution_fn is the evolution function in LOOP. Get
482 its value in the nb_iter-th iteration. */
483 res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
484
485 /* Continue the computation until ending on a parent of LOOP. */
486 return compute_overall_effect_of_inner_loop (loop, res);
487 }
488 }
489 else
490 return evolution_fn;
491 }
492
493 /* If the evolution function is an invariant, there is nothing to do. */
494 else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
495 return evolution_fn;
496
497 else
498 return chrec_dont_know;
499 }
500
501 /* Determine whether the CHREC is always positive/negative. If the expression
502 cannot be statically analyzed, return false, otherwise set the answer into
503 VALUE. */
504
505 bool
506 chrec_is_positive (tree chrec, bool *value)
507 {
508 bool value0, value1, value2;
509 tree end_value, nb_iter;
510
511 switch (TREE_CODE (chrec))
512 {
513 case POLYNOMIAL_CHREC:
514 if (!chrec_is_positive (CHREC_LEFT (chrec), &value0)
515 || !chrec_is_positive (CHREC_RIGHT (chrec), &value1))
516 return false;
517
518 /* FIXME -- overflows. */
519 if (value0 == value1)
520 {
521 *value = value0;
522 return true;
523 }
524
525 /* Otherwise the chrec is under the form: "{-197, +, 2}_1",
526 and the proof consists in showing that the sign never
527 changes during the execution of the loop, from 0 to
528 loop->nb_iterations. */
529 if (!evolution_function_is_affine_p (chrec))
530 return false;
531
532 nb_iter = number_of_latch_executions (get_chrec_loop (chrec));
533 if (chrec_contains_undetermined (nb_iter))
534 return false;
535
536 #if 0
537 /* TODO -- If the test is after the exit, we may decrease the number of
538 iterations by one. */
539 if (after_exit)
540 nb_iter = chrec_fold_minus (type, nb_iter, build_int_cst (type, 1));
541 #endif
542
543 end_value = chrec_apply (CHREC_VARIABLE (chrec), chrec, nb_iter);
544
545 if (!chrec_is_positive (end_value, &value2))
546 return false;
547
548 *value = value0;
549 return value0 == value1;
550
551 case INTEGER_CST:
552 *value = (tree_int_cst_sgn (chrec) == 1);
553 return true;
554
555 default:
556 return false;
557 }
558 }
559
560 /* Associate CHREC to SCALAR. */
561
562 static void
563 set_scalar_evolution (tree scalar, tree chrec)
564 {
565 tree *scalar_info;
566
567 if (TREE_CODE (scalar) != SSA_NAME)
568 return;
569
570 scalar_info = find_var_scev_info (scalar);
571
572 if (dump_file)
573 {
574 if (dump_flags & TDF_DETAILS)
575 {
576 fprintf (dump_file, "(set_scalar_evolution \n");
577 fprintf (dump_file, " (scalar = ");
578 print_generic_expr (dump_file, scalar, 0);
579 fprintf (dump_file, ")\n (scalar_evolution = ");
580 print_generic_expr (dump_file, chrec, 0);
581 fprintf (dump_file, "))\n");
582 }
583 if (dump_flags & TDF_STATS)
584 nb_set_scev++;
585 }
586
587 *scalar_info = chrec;
588 }
589
590 /* Retrieve the chrec associated to SCALAR in the LOOP. */
591
592 static tree
593 get_scalar_evolution (tree scalar)
594 {
595 tree res;
596
597 if (dump_file)
598 {
599 if (dump_flags & TDF_DETAILS)
600 {
601 fprintf (dump_file, "(get_scalar_evolution \n");
602 fprintf (dump_file, " (scalar = ");
603 print_generic_expr (dump_file, scalar, 0);
604 fprintf (dump_file, ")\n");
605 }
606 if (dump_flags & TDF_STATS)
607 nb_get_scev++;
608 }
609
610 switch (TREE_CODE (scalar))
611 {
612 case SSA_NAME:
613 res = *find_var_scev_info (scalar);
614 break;
615
616 case REAL_CST:
617 case INTEGER_CST:
618 res = scalar;
619 break;
620
621 default:
622 res = chrec_not_analyzed_yet;
623 break;
624 }
625
626 if (dump_file && (dump_flags & TDF_DETAILS))
627 {
628 fprintf (dump_file, " (scalar_evolution = ");
629 print_generic_expr (dump_file, res, 0);
630 fprintf (dump_file, "))\n");
631 }
632
633 return res;
634 }
635
636 /* Helper function for add_to_evolution. Returns the evolution
637 function for an assignment of the form "a = b + c", where "a" and
638 "b" are on the strongly connected component. CHREC_BEFORE is the
639 information that we already have collected up to this point.
640 TO_ADD is the evolution of "c".
641
642 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
643 evolution the expression TO_ADD, otherwise construct an evolution
644 part for this loop. */
645
646 static tree
647 add_to_evolution_1 (unsigned loop_nb, tree chrec_before, tree to_add,
648 tree at_stmt)
649 {
650 tree type, left, right;
651 struct loop *loop = get_loop (loop_nb), *chloop;
652
653 switch (TREE_CODE (chrec_before))
654 {
655 case POLYNOMIAL_CHREC:
656 chloop = get_chrec_loop (chrec_before);
657 if (chloop == loop
658 || flow_loop_nested_p (chloop, loop))
659 {
660 unsigned var;
661
662 type = chrec_type (chrec_before);
663
664 /* When there is no evolution part in this loop, build it. */
665 if (chloop != loop)
666 {
667 var = loop_nb;
668 left = chrec_before;
669 right = SCALAR_FLOAT_TYPE_P (type)
670 ? build_real (type, dconst0)
671 : build_int_cst (type, 0);
672 }
673 else
674 {
675 var = CHREC_VARIABLE (chrec_before);
676 left = CHREC_LEFT (chrec_before);
677 right = CHREC_RIGHT (chrec_before);
678 }
679
680 to_add = chrec_convert (type, to_add, at_stmt);
681 right = chrec_convert (type, right, at_stmt);
682 right = chrec_fold_plus (type, right, to_add);
683 return build_polynomial_chrec (var, left, right);
684 }
685 else
686 {
687 gcc_assert (flow_loop_nested_p (loop, chloop));
688
689 /* Search the evolution in LOOP_NB. */
690 left = add_to_evolution_1 (loop_nb, CHREC_LEFT (chrec_before),
691 to_add, at_stmt);
692 right = CHREC_RIGHT (chrec_before);
693 right = chrec_convert (chrec_type (left), right, at_stmt);
694 return build_polynomial_chrec (CHREC_VARIABLE (chrec_before),
695 left, right);
696 }
697
698 default:
699 /* These nodes do not depend on a loop. */
700 if (chrec_before == chrec_dont_know)
701 return chrec_dont_know;
702
703 left = chrec_before;
704 right = chrec_convert (chrec_type (left), to_add, at_stmt);
705 return build_polynomial_chrec (loop_nb, left, right);
706 }
707 }
708
709 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
710 of LOOP_NB.
711
712 Description (provided for completeness, for those who read code in
713 a plane, and for my poor 62 bytes brain that would have forgotten
714 all this in the next two or three months):
715
716 The algorithm of translation of programs from the SSA representation
717 into the chrecs syntax is based on a pattern matching. After having
718 reconstructed the overall tree expression for a loop, there are only
719 two cases that can arise:
720
721 1. a = loop-phi (init, a + expr)
722 2. a = loop-phi (init, expr)
723
724 where EXPR is either a scalar constant with respect to the analyzed
725 loop (this is a degree 0 polynomial), or an expression containing
726 other loop-phi definitions (these are higher degree polynomials).
727
728 Examples:
729
730 1.
731 | init = ...
732 | loop_1
733 | a = phi (init, a + 5)
734 | endloop
735
736 2.
737 | inita = ...
738 | initb = ...
739 | loop_1
740 | a = phi (inita, 2 * b + 3)
741 | b = phi (initb, b + 1)
742 | endloop
743
744 For the first case, the semantics of the SSA representation is:
745
746 | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
747
748 that is, there is a loop index "x" that determines the scalar value
749 of the variable during the loop execution. During the first
750 iteration, the value is that of the initial condition INIT, while
751 during the subsequent iterations, it is the sum of the initial
752 condition with the sum of all the values of EXPR from the initial
753 iteration to the before last considered iteration.
754
755 For the second case, the semantics of the SSA program is:
756
757 | a (x) = init, if x = 0;
758 | expr (x - 1), otherwise.
759
760 The second case corresponds to the PEELED_CHREC, whose syntax is
761 close to the syntax of a loop-phi-node:
762
763 | phi (init, expr) vs. (init, expr)_x
764
765 The proof of the translation algorithm for the first case is a
766 proof by structural induction based on the degree of EXPR.
767
768 Degree 0:
769 When EXPR is a constant with respect to the analyzed loop, or in
770 other words when EXPR is a polynomial of degree 0, the evolution of
771 the variable A in the loop is an affine function with an initial
772 condition INIT, and a step EXPR. In order to show this, we start
773 from the semantics of the SSA representation:
774
775 f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
776
777 and since "expr (j)" is a constant with respect to "j",
778
779 f (x) = init + x * expr
780
781 Finally, based on the semantics of the pure sum chrecs, by
782 identification we get the corresponding chrecs syntax:
783
784 f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
785 f (x) -> {init, +, expr}_x
786
787 Higher degree:
788 Suppose that EXPR is a polynomial of degree N with respect to the
789 analyzed loop_x for which we have already determined that it is
790 written under the chrecs syntax:
791
792 | expr (x) -> {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
793
794 We start from the semantics of the SSA program:
795
796 | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
797 |
798 | f (x) = init + \sum_{j = 0}^{x - 1}
799 | (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
800 |
801 | f (x) = init + \sum_{j = 0}^{x - 1}
802 | \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
803 |
804 | f (x) = init + \sum_{k = 0}^{n - 1}
805 | (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
806 |
807 | f (x) = init + \sum_{k = 0}^{n - 1}
808 | (b_k * \binom{x}{k + 1})
809 |
810 | f (x) = init + b_0 * \binom{x}{1} + ...
811 | + b_{n-1} * \binom{x}{n}
812 |
813 | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
814 | + b_{n-1} * \binom{x}{n}
815 |
816
817 And finally from the definition of the chrecs syntax, we identify:
818 | f (x) -> {init, +, b_0, +, ..., +, b_{n-1}}_x
819
820 This shows the mechanism that stands behind the add_to_evolution
821 function. An important point is that the use of symbolic
822 parameters avoids the need of an analysis schedule.
823
824 Example:
825
826 | inita = ...
827 | initb = ...
828 | loop_1
829 | a = phi (inita, a + 2 + b)
830 | b = phi (initb, b + 1)
831 | endloop
832
833 When analyzing "a", the algorithm keeps "b" symbolically:
834
835 | a -> {inita, +, 2 + b}_1
836
837 Then, after instantiation, the analyzer ends on the evolution:
838
839 | a -> {inita, +, 2 + initb, +, 1}_1
840
841 */
842
843 static tree
844 add_to_evolution (unsigned loop_nb, tree chrec_before, enum tree_code code,
845 tree to_add, tree at_stmt)
846 {
847 tree type = chrec_type (to_add);
848 tree res = NULL_TREE;
849
850 if (to_add == NULL_TREE)
851 return chrec_before;
852
853 /* TO_ADD is either a scalar, or a parameter. TO_ADD is not
854 instantiated at this point. */
855 if (TREE_CODE (to_add) == POLYNOMIAL_CHREC)
856 /* This should not happen. */
857 return chrec_dont_know;
858
859 if (dump_file && (dump_flags & TDF_DETAILS))
860 {
861 fprintf (dump_file, "(add_to_evolution \n");
862 fprintf (dump_file, " (loop_nb = %d)\n", loop_nb);
863 fprintf (dump_file, " (chrec_before = ");
864 print_generic_expr (dump_file, chrec_before, 0);
865 fprintf (dump_file, ")\n (to_add = ");
866 print_generic_expr (dump_file, to_add, 0);
867 fprintf (dump_file, ")\n");
868 }
869
870 if (code == MINUS_EXPR)
871 to_add = chrec_fold_multiply (type, to_add, SCALAR_FLOAT_TYPE_P (type)
872 ? build_real (type, dconstm1)
873 : build_int_cst_type (type, -1));
874
875 res = add_to_evolution_1 (loop_nb, chrec_before, to_add, at_stmt);
876
877 if (dump_file && (dump_flags & TDF_DETAILS))
878 {
879 fprintf (dump_file, " (res = ");
880 print_generic_expr (dump_file, res, 0);
881 fprintf (dump_file, "))\n");
882 }
883
884 return res;
885 }
886
887 /* Helper function. */
888
889 static inline tree
890 set_nb_iterations_in_loop (struct loop *loop,
891 tree res)
892 {
893 if (dump_file && (dump_flags & TDF_DETAILS))
894 {
895 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
896 print_generic_expr (dump_file, res, 0);
897 fprintf (dump_file, "))\n");
898 }
899
900 loop->nb_iterations = res;
901 return res;
902 }
903
904 \f
905
906 /* This section selects the loops that will be good candidates for the
907 scalar evolution analysis. For the moment, greedily select all the
908 loop nests we could analyze. */
909
910 /* Return true when it is possible to analyze the condition expression
911 EXPR. */
912
913 static bool
914 analyzable_condition (tree expr)
915 {
916 tree condition;
917
918 if (TREE_CODE (expr) != COND_EXPR)
919 return false;
920
921 condition = TREE_OPERAND (expr, 0);
922
923 switch (TREE_CODE (condition))
924 {
925 case SSA_NAME:
926 return true;
927
928 case LT_EXPR:
929 case LE_EXPR:
930 case GT_EXPR:
931 case GE_EXPR:
932 case EQ_EXPR:
933 case NE_EXPR:
934 return true;
935
936 default:
937 return false;
938 }
939
940 return false;
941 }
942
943 /* For a loop with a single exit edge, return the COND_EXPR that
944 guards the exit edge. If the expression is too difficult to
945 analyze, then give up. */
946
947 tree
948 get_loop_exit_condition (struct loop *loop)
949 {
950 tree res = NULL_TREE;
951 edge exit_edge = single_exit (loop);
952
953 if (dump_file && (dump_flags & TDF_DETAILS))
954 fprintf (dump_file, "(get_loop_exit_condition \n ");
955
956 if (exit_edge)
957 {
958 tree expr;
959
960 expr = last_stmt (exit_edge->src);
961 if (analyzable_condition (expr))
962 res = expr;
963 }
964
965 if (dump_file && (dump_flags & TDF_DETAILS))
966 {
967 print_generic_expr (dump_file, res, 0);
968 fprintf (dump_file, ")\n");
969 }
970
971 return res;
972 }
973
974 /* Recursively determine and enqueue the exit conditions for a loop. */
975
976 static void
977 get_exit_conditions_rec (struct loop *loop,
978 VEC(tree,heap) **exit_conditions)
979 {
980 if (!loop)
981 return;
982
983 /* Recurse on the inner loops, then on the next (sibling) loops. */
984 get_exit_conditions_rec (loop->inner, exit_conditions);
985 get_exit_conditions_rec (loop->next, exit_conditions);
986
987 if (single_exit (loop))
988 {
989 tree loop_condition = get_loop_exit_condition (loop);
990
991 if (loop_condition)
992 VEC_safe_push (tree, heap, *exit_conditions, loop_condition);
993 }
994 }
995
996 /* Select the candidate loop nests for the analysis. This function
997 initializes the EXIT_CONDITIONS array. */
998
999 static void
1000 select_loops_exit_conditions (VEC(tree,heap) **exit_conditions)
1001 {
1002 struct loop *function_body = current_loops->tree_root;
1003
1004 get_exit_conditions_rec (function_body->inner, exit_conditions);
1005 }
1006
1007 \f
1008 /* Depth first search algorithm. */
1009
1010 typedef enum t_bool {
1011 t_false,
1012 t_true,
1013 t_dont_know
1014 } t_bool;
1015
1016
1017 static t_bool follow_ssa_edge (struct loop *loop, tree, tree, tree *, int);
1018
1019 /* Follow the ssa edge into the right hand side RHS of an assignment.
1020 Return true if the strongly connected component has been found. */
1021
1022 static t_bool
1023 follow_ssa_edge_in_rhs (struct loop *loop, tree at_stmt, tree rhs,
1024 tree halting_phi, tree *evolution_of_loop, int limit)
1025 {
1026 t_bool res = t_false;
1027 tree rhs0, rhs1;
1028 tree type_rhs = TREE_TYPE (rhs);
1029 tree evol;
1030
1031 /* The RHS is one of the following cases:
1032 - an SSA_NAME,
1033 - an INTEGER_CST,
1034 - a PLUS_EXPR,
1035 - a MINUS_EXPR,
1036 - an ASSERT_EXPR,
1037 - other cases are not yet handled. */
1038 switch (TREE_CODE (rhs))
1039 {
1040 case NOP_EXPR:
1041 /* This assignment is under the form "a_1 = (cast) rhs. */
1042 res = follow_ssa_edge_in_rhs (loop, at_stmt, TREE_OPERAND (rhs, 0),
1043 halting_phi, evolution_of_loop, limit);
1044 *evolution_of_loop = chrec_convert (TREE_TYPE (rhs),
1045 *evolution_of_loop, at_stmt);
1046 break;
1047
1048 case INTEGER_CST:
1049 /* This assignment is under the form "a_1 = 7". */
1050 res = t_false;
1051 break;
1052
1053 case SSA_NAME:
1054 /* This assignment is under the form: "a_1 = b_2". */
1055 res = follow_ssa_edge
1056 (loop, SSA_NAME_DEF_STMT (rhs), halting_phi, evolution_of_loop, limit);
1057 break;
1058
1059 case PLUS_EXPR:
1060 /* This case is under the form "rhs0 + rhs1". */
1061 rhs0 = TREE_OPERAND (rhs, 0);
1062 rhs1 = TREE_OPERAND (rhs, 1);
1063 STRIP_TYPE_NOPS (rhs0);
1064 STRIP_TYPE_NOPS (rhs1);
1065
1066 if (TREE_CODE (rhs0) == SSA_NAME)
1067 {
1068 if (TREE_CODE (rhs1) == SSA_NAME)
1069 {
1070 /* Match an assignment under the form:
1071 "a = b + c". */
1072 evol = *evolution_of_loop;
1073 res = follow_ssa_edge
1074 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1075 &evol, limit);
1076
1077 if (res == t_true)
1078 *evolution_of_loop = add_to_evolution
1079 (loop->num,
1080 chrec_convert (type_rhs, evol, at_stmt),
1081 PLUS_EXPR, rhs1, at_stmt);
1082
1083 else if (res == t_false)
1084 {
1085 res = follow_ssa_edge
1086 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1087 evolution_of_loop, limit);
1088
1089 if (res == t_true)
1090 *evolution_of_loop = add_to_evolution
1091 (loop->num,
1092 chrec_convert (type_rhs, *evolution_of_loop, at_stmt),
1093 PLUS_EXPR, rhs0, at_stmt);
1094
1095 else if (res == t_dont_know)
1096 *evolution_of_loop = chrec_dont_know;
1097 }
1098
1099 else if (res == t_dont_know)
1100 *evolution_of_loop = chrec_dont_know;
1101 }
1102
1103 else
1104 {
1105 /* Match an assignment under the form:
1106 "a = b + ...". */
1107 res = follow_ssa_edge
1108 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1109 evolution_of_loop, limit);
1110 if (res == t_true)
1111 *evolution_of_loop = add_to_evolution
1112 (loop->num, chrec_convert (type_rhs, *evolution_of_loop,
1113 at_stmt),
1114 PLUS_EXPR, rhs1, at_stmt);
1115
1116 else if (res == t_dont_know)
1117 *evolution_of_loop = chrec_dont_know;
1118 }
1119 }
1120
1121 else if (TREE_CODE (rhs1) == SSA_NAME)
1122 {
1123 /* Match an assignment under the form:
1124 "a = ... + c". */
1125 res = follow_ssa_edge
1126 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1127 evolution_of_loop, limit);
1128 if (res == t_true)
1129 *evolution_of_loop = add_to_evolution
1130 (loop->num, chrec_convert (type_rhs, *evolution_of_loop,
1131 at_stmt),
1132 PLUS_EXPR, rhs0, at_stmt);
1133
1134 else if (res == t_dont_know)
1135 *evolution_of_loop = chrec_dont_know;
1136 }
1137
1138 else
1139 /* Otherwise, match an assignment under the form:
1140 "a = ... + ...". */
1141 /* And there is nothing to do. */
1142 res = t_false;
1143
1144 break;
1145
1146 case MINUS_EXPR:
1147 /* This case is under the form "opnd0 = rhs0 - rhs1". */
1148 rhs0 = TREE_OPERAND (rhs, 0);
1149 rhs1 = TREE_OPERAND (rhs, 1);
1150 STRIP_TYPE_NOPS (rhs0);
1151 STRIP_TYPE_NOPS (rhs1);
1152
1153 if (TREE_CODE (rhs0) == SSA_NAME)
1154 {
1155 /* Match an assignment under the form:
1156 "a = b - ...". */
1157 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1158 evolution_of_loop, limit);
1159 if (res == t_true)
1160 *evolution_of_loop = add_to_evolution
1161 (loop->num, chrec_convert (type_rhs, *evolution_of_loop, at_stmt),
1162 MINUS_EXPR, rhs1, at_stmt);
1163
1164 else if (res == t_dont_know)
1165 *evolution_of_loop = chrec_dont_know;
1166 }
1167 else
1168 /* Otherwise, match an assignment under the form:
1169 "a = ... - ...". */
1170 /* And there is nothing to do. */
1171 res = t_false;
1172
1173 break;
1174
1175 case ASSERT_EXPR:
1176 {
1177 /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1178 It must be handled as a copy assignment of the form a_1 = a_2. */
1179 tree op0 = ASSERT_EXPR_VAR (rhs);
1180 if (TREE_CODE (op0) == SSA_NAME)
1181 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (op0),
1182 halting_phi, evolution_of_loop, limit);
1183 else
1184 res = t_false;
1185 break;
1186 }
1187
1188
1189 default:
1190 res = t_false;
1191 break;
1192 }
1193
1194 return res;
1195 }
1196
1197 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1198
1199 static bool
1200 backedge_phi_arg_p (tree phi, int i)
1201 {
1202 edge e = PHI_ARG_EDGE (phi, i);
1203
1204 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1205 about updating it anywhere, and this should work as well most of the
1206 time. */
1207 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1208 return true;
1209
1210 return false;
1211 }
1212
1213 /* Helper function for one branch of the condition-phi-node. Return
1214 true if the strongly connected component has been found following
1215 this path. */
1216
1217 static inline t_bool
1218 follow_ssa_edge_in_condition_phi_branch (int i,
1219 struct loop *loop,
1220 tree condition_phi,
1221 tree halting_phi,
1222 tree *evolution_of_branch,
1223 tree init_cond, int limit)
1224 {
1225 tree branch = PHI_ARG_DEF (condition_phi, i);
1226 *evolution_of_branch = chrec_dont_know;
1227
1228 /* Do not follow back edges (they must belong to an irreducible loop, which
1229 we really do not want to worry about). */
1230 if (backedge_phi_arg_p (condition_phi, i))
1231 return t_false;
1232
1233 if (TREE_CODE (branch) == SSA_NAME)
1234 {
1235 *evolution_of_branch = init_cond;
1236 return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1237 evolution_of_branch, limit);
1238 }
1239
1240 /* This case occurs when one of the condition branches sets
1241 the variable to a constant: i.e. a phi-node like
1242 "a_2 = PHI <a_7(5), 2(6)>;".
1243
1244 FIXME: This case have to be refined correctly:
1245 in some cases it is possible to say something better than
1246 chrec_dont_know, for example using a wrap-around notation. */
1247 return t_false;
1248 }
1249
1250 /* This function merges the branches of a condition-phi-node in a
1251 loop. */
1252
1253 static t_bool
1254 follow_ssa_edge_in_condition_phi (struct loop *loop,
1255 tree condition_phi,
1256 tree halting_phi,
1257 tree *evolution_of_loop, int limit)
1258 {
1259 int i;
1260 tree init = *evolution_of_loop;
1261 tree evolution_of_branch;
1262 t_bool res = follow_ssa_edge_in_condition_phi_branch (0, loop, condition_phi,
1263 halting_phi,
1264 &evolution_of_branch,
1265 init, limit);
1266 if (res == t_false || res == t_dont_know)
1267 return res;
1268
1269 *evolution_of_loop = evolution_of_branch;
1270
1271 for (i = 1; i < PHI_NUM_ARGS (condition_phi); i++)
1272 {
1273 /* Quickly give up when the evolution of one of the branches is
1274 not known. */
1275 if (*evolution_of_loop == chrec_dont_know)
1276 return t_true;
1277
1278 res = follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1279 halting_phi,
1280 &evolution_of_branch,
1281 init, limit);
1282 if (res == t_false || res == t_dont_know)
1283 return res;
1284
1285 *evolution_of_loop = chrec_merge (*evolution_of_loop,
1286 evolution_of_branch);
1287 }
1288
1289 return t_true;
1290 }
1291
1292 /* Follow an SSA edge in an inner loop. It computes the overall
1293 effect of the loop, and following the symbolic initial conditions,
1294 it follows the edges in the parent loop. The inner loop is
1295 considered as a single statement. */
1296
1297 static t_bool
1298 follow_ssa_edge_inner_loop_phi (struct loop *outer_loop,
1299 tree loop_phi_node,
1300 tree halting_phi,
1301 tree *evolution_of_loop, int limit)
1302 {
1303 struct loop *loop = loop_containing_stmt (loop_phi_node);
1304 tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1305
1306 /* Sometimes, the inner loop is too difficult to analyze, and the
1307 result of the analysis is a symbolic parameter. */
1308 if (ev == PHI_RESULT (loop_phi_node))
1309 {
1310 t_bool res = t_false;
1311 int i;
1312
1313 for (i = 0; i < PHI_NUM_ARGS (loop_phi_node); i++)
1314 {
1315 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1316 basic_block bb;
1317
1318 /* Follow the edges that exit the inner loop. */
1319 bb = PHI_ARG_EDGE (loop_phi_node, i)->src;
1320 if (!flow_bb_inside_loop_p (loop, bb))
1321 res = follow_ssa_edge_in_rhs (outer_loop, loop_phi_node,
1322 arg, halting_phi,
1323 evolution_of_loop, limit);
1324 if (res == t_true)
1325 break;
1326 }
1327
1328 /* If the path crosses this loop-phi, give up. */
1329 if (res == t_true)
1330 *evolution_of_loop = chrec_dont_know;
1331
1332 return res;
1333 }
1334
1335 /* Otherwise, compute the overall effect of the inner loop. */
1336 ev = compute_overall_effect_of_inner_loop (loop, ev);
1337 return follow_ssa_edge_in_rhs (outer_loop, loop_phi_node, ev, halting_phi,
1338 evolution_of_loop, limit);
1339 }
1340
1341 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1342 path that is analyzed on the return walk. */
1343
1344 static t_bool
1345 follow_ssa_edge (struct loop *loop, tree def, tree halting_phi,
1346 tree *evolution_of_loop, int limit)
1347 {
1348 struct loop *def_loop;
1349
1350 if (TREE_CODE (def) == NOP_EXPR)
1351 return t_false;
1352
1353 /* Give up if the path is longer than the MAX that we allow. */
1354 if (limit++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
1355 return t_dont_know;
1356
1357 def_loop = loop_containing_stmt (def);
1358
1359 switch (TREE_CODE (def))
1360 {
1361 case PHI_NODE:
1362 if (!loop_phi_node_p (def))
1363 /* DEF is a condition-phi-node. Follow the branches, and
1364 record their evolutions. Finally, merge the collected
1365 information and set the approximation to the main
1366 variable. */
1367 return follow_ssa_edge_in_condition_phi
1368 (loop, def, halting_phi, evolution_of_loop, limit);
1369
1370 /* When the analyzed phi is the halting_phi, the
1371 depth-first search is over: we have found a path from
1372 the halting_phi to itself in the loop. */
1373 if (def == halting_phi)
1374 return t_true;
1375
1376 /* Otherwise, the evolution of the HALTING_PHI depends
1377 on the evolution of another loop-phi-node, i.e. the
1378 evolution function is a higher degree polynomial. */
1379 if (def_loop == loop)
1380 return t_false;
1381
1382 /* Inner loop. */
1383 if (flow_loop_nested_p (loop, def_loop))
1384 return follow_ssa_edge_inner_loop_phi
1385 (loop, def, halting_phi, evolution_of_loop, limit);
1386
1387 /* Outer loop. */
1388 return t_false;
1389
1390 case GIMPLE_MODIFY_STMT:
1391 return follow_ssa_edge_in_rhs (loop, def,
1392 GIMPLE_STMT_OPERAND (def, 1),
1393 halting_phi,
1394 evolution_of_loop, limit);
1395
1396 default:
1397 /* At this level of abstraction, the program is just a set
1398 of GIMPLE_MODIFY_STMTs and PHI_NODEs. In principle there is no
1399 other node to be handled. */
1400 return t_false;
1401 }
1402 }
1403
1404 \f
1405
1406 /* Given a LOOP_PHI_NODE, this function determines the evolution
1407 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1408
1409 static tree
1410 analyze_evolution_in_loop (tree loop_phi_node,
1411 tree init_cond)
1412 {
1413 int i;
1414 tree evolution_function = chrec_not_analyzed_yet;
1415 struct loop *loop = loop_containing_stmt (loop_phi_node);
1416 basic_block bb;
1417
1418 if (dump_file && (dump_flags & TDF_DETAILS))
1419 {
1420 fprintf (dump_file, "(analyze_evolution_in_loop \n");
1421 fprintf (dump_file, " (loop_phi_node = ");
1422 print_generic_expr (dump_file, loop_phi_node, 0);
1423 fprintf (dump_file, ")\n");
1424 }
1425
1426 for (i = 0; i < PHI_NUM_ARGS (loop_phi_node); i++)
1427 {
1428 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1429 tree ssa_chain, ev_fn;
1430 t_bool res;
1431
1432 /* Select the edges that enter the loop body. */
1433 bb = PHI_ARG_EDGE (loop_phi_node, i)->src;
1434 if (!flow_bb_inside_loop_p (loop, bb))
1435 continue;
1436
1437 if (TREE_CODE (arg) == SSA_NAME)
1438 {
1439 ssa_chain = SSA_NAME_DEF_STMT (arg);
1440
1441 /* Pass in the initial condition to the follow edge function. */
1442 ev_fn = init_cond;
1443 res = follow_ssa_edge (loop, ssa_chain, loop_phi_node, &ev_fn, 0);
1444 }
1445 else
1446 res = t_false;
1447
1448 /* When it is impossible to go back on the same
1449 loop_phi_node by following the ssa edges, the
1450 evolution is represented by a peeled chrec, i.e. the
1451 first iteration, EV_FN has the value INIT_COND, then
1452 all the other iterations it has the value of ARG.
1453 For the moment, PEELED_CHREC nodes are not built. */
1454 if (res != t_true)
1455 ev_fn = chrec_dont_know;
1456
1457 /* When there are multiple back edges of the loop (which in fact never
1458 happens currently, but nevertheless), merge their evolutions. */
1459 evolution_function = chrec_merge (evolution_function, ev_fn);
1460 }
1461
1462 if (dump_file && (dump_flags & TDF_DETAILS))
1463 {
1464 fprintf (dump_file, " (evolution_function = ");
1465 print_generic_expr (dump_file, evolution_function, 0);
1466 fprintf (dump_file, "))\n");
1467 }
1468
1469 return evolution_function;
1470 }
1471
1472 /* Given a loop-phi-node, return the initial conditions of the
1473 variable on entry of the loop. When the CCP has propagated
1474 constants into the loop-phi-node, the initial condition is
1475 instantiated, otherwise the initial condition is kept symbolic.
1476 This analyzer does not analyze the evolution outside the current
1477 loop, and leaves this task to the on-demand tree reconstructor. */
1478
1479 static tree
1480 analyze_initial_condition (tree loop_phi_node)
1481 {
1482 int i;
1483 tree init_cond = chrec_not_analyzed_yet;
1484 struct loop *loop = bb_for_stmt (loop_phi_node)->loop_father;
1485
1486 if (dump_file && (dump_flags & TDF_DETAILS))
1487 {
1488 fprintf (dump_file, "(analyze_initial_condition \n");
1489 fprintf (dump_file, " (loop_phi_node = \n");
1490 print_generic_expr (dump_file, loop_phi_node, 0);
1491 fprintf (dump_file, ")\n");
1492 }
1493
1494 for (i = 0; i < PHI_NUM_ARGS (loop_phi_node); i++)
1495 {
1496 tree branch = PHI_ARG_DEF (loop_phi_node, i);
1497 basic_block bb = PHI_ARG_EDGE (loop_phi_node, i)->src;
1498
1499 /* When the branch is oriented to the loop's body, it does
1500 not contribute to the initial condition. */
1501 if (flow_bb_inside_loop_p (loop, bb))
1502 continue;
1503
1504 if (init_cond == chrec_not_analyzed_yet)
1505 {
1506 init_cond = branch;
1507 continue;
1508 }
1509
1510 if (TREE_CODE (branch) == SSA_NAME)
1511 {
1512 init_cond = chrec_dont_know;
1513 break;
1514 }
1515
1516 init_cond = chrec_merge (init_cond, branch);
1517 }
1518
1519 /* Ooops -- a loop without an entry??? */
1520 if (init_cond == chrec_not_analyzed_yet)
1521 init_cond = chrec_dont_know;
1522
1523 if (dump_file && (dump_flags & TDF_DETAILS))
1524 {
1525 fprintf (dump_file, " (init_cond = ");
1526 print_generic_expr (dump_file, init_cond, 0);
1527 fprintf (dump_file, "))\n");
1528 }
1529
1530 return init_cond;
1531 }
1532
1533 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1534
1535 static tree
1536 interpret_loop_phi (struct loop *loop, tree loop_phi_node)
1537 {
1538 tree res;
1539 struct loop *phi_loop = loop_containing_stmt (loop_phi_node);
1540 tree init_cond;
1541
1542 if (phi_loop != loop)
1543 {
1544 struct loop *subloop;
1545 tree evolution_fn = analyze_scalar_evolution
1546 (phi_loop, PHI_RESULT (loop_phi_node));
1547
1548 /* Dive one level deeper. */
1549 subloop = superloop_at_depth (phi_loop, loop->depth + 1);
1550
1551 /* Interpret the subloop. */
1552 res = compute_overall_effect_of_inner_loop (subloop, evolution_fn);
1553 return res;
1554 }
1555
1556 /* Otherwise really interpret the loop phi. */
1557 init_cond = analyze_initial_condition (loop_phi_node);
1558 res = analyze_evolution_in_loop (loop_phi_node, init_cond);
1559
1560 return res;
1561 }
1562
1563 /* This function merges the branches of a condition-phi-node,
1564 contained in the outermost loop, and whose arguments are already
1565 analyzed. */
1566
1567 static tree
1568 interpret_condition_phi (struct loop *loop, tree condition_phi)
1569 {
1570 int i;
1571 tree res = chrec_not_analyzed_yet;
1572
1573 for (i = 0; i < PHI_NUM_ARGS (condition_phi); i++)
1574 {
1575 tree branch_chrec;
1576
1577 if (backedge_phi_arg_p (condition_phi, i))
1578 {
1579 res = chrec_dont_know;
1580 break;
1581 }
1582
1583 branch_chrec = analyze_scalar_evolution
1584 (loop, PHI_ARG_DEF (condition_phi, i));
1585
1586 res = chrec_merge (res, branch_chrec);
1587 }
1588
1589 return res;
1590 }
1591
1592 /* Interpret the right hand side of a GIMPLE_MODIFY_STMT OPND1. If we didn't
1593 analyze this node before, follow the definitions until ending
1594 either on an analyzed GIMPLE_MODIFY_STMT, or on a loop-phi-node. On the
1595 return path, this function propagates evolutions (ala constant copy
1596 propagation). OPND1 is not a GIMPLE expression because we could
1597 analyze the effect of an inner loop: see interpret_loop_phi. */
1598
1599 static tree
1600 interpret_rhs_modify_stmt (struct loop *loop, tree at_stmt,
1601 tree opnd1, tree type)
1602 {
1603 tree res, opnd10, opnd11, chrec10, chrec11;
1604
1605 if (is_gimple_min_invariant (opnd1))
1606 return chrec_convert (type, opnd1, at_stmt);
1607
1608 switch (TREE_CODE (opnd1))
1609 {
1610 case PLUS_EXPR:
1611 opnd10 = TREE_OPERAND (opnd1, 0);
1612 opnd11 = TREE_OPERAND (opnd1, 1);
1613 chrec10 = analyze_scalar_evolution (loop, opnd10);
1614 chrec11 = analyze_scalar_evolution (loop, opnd11);
1615 chrec10 = chrec_convert (type, chrec10, at_stmt);
1616 chrec11 = chrec_convert (type, chrec11, at_stmt);
1617 res = chrec_fold_plus (type, chrec10, chrec11);
1618 break;
1619
1620 case MINUS_EXPR:
1621 opnd10 = TREE_OPERAND (opnd1, 0);
1622 opnd11 = TREE_OPERAND (opnd1, 1);
1623 chrec10 = analyze_scalar_evolution (loop, opnd10);
1624 chrec11 = analyze_scalar_evolution (loop, opnd11);
1625 chrec10 = chrec_convert (type, chrec10, at_stmt);
1626 chrec11 = chrec_convert (type, chrec11, at_stmt);
1627 res = chrec_fold_minus (type, chrec10, chrec11);
1628 break;
1629
1630 case NEGATE_EXPR:
1631 opnd10 = TREE_OPERAND (opnd1, 0);
1632 chrec10 = analyze_scalar_evolution (loop, opnd10);
1633 chrec10 = chrec_convert (type, chrec10, at_stmt);
1634 /* TYPE may be integer, real or complex, so use fold_convert. */
1635 res = chrec_fold_multiply (type, chrec10,
1636 fold_convert (type, integer_minus_one_node));
1637 break;
1638
1639 case MULT_EXPR:
1640 opnd10 = TREE_OPERAND (opnd1, 0);
1641 opnd11 = TREE_OPERAND (opnd1, 1);
1642 chrec10 = analyze_scalar_evolution (loop, opnd10);
1643 chrec11 = analyze_scalar_evolution (loop, opnd11);
1644 chrec10 = chrec_convert (type, chrec10, at_stmt);
1645 chrec11 = chrec_convert (type, chrec11, at_stmt);
1646 res = chrec_fold_multiply (type, chrec10, chrec11);
1647 break;
1648
1649 case SSA_NAME:
1650 res = chrec_convert (type, analyze_scalar_evolution (loop, opnd1),
1651 at_stmt);
1652 break;
1653
1654 case ASSERT_EXPR:
1655 opnd10 = ASSERT_EXPR_VAR (opnd1);
1656 res = chrec_convert (type, analyze_scalar_evolution (loop, opnd10),
1657 at_stmt);
1658 break;
1659
1660 case NOP_EXPR:
1661 case CONVERT_EXPR:
1662 opnd10 = TREE_OPERAND (opnd1, 0);
1663 chrec10 = analyze_scalar_evolution (loop, opnd10);
1664 res = chrec_convert (type, chrec10, at_stmt);
1665 break;
1666
1667 default:
1668 res = chrec_dont_know;
1669 break;
1670 }
1671
1672 return res;
1673 }
1674
1675 \f
1676
1677 /* This section contains all the entry points:
1678 - number_of_iterations_in_loop,
1679 - analyze_scalar_evolution,
1680 - instantiate_parameters.
1681 */
1682
1683 /* Compute and return the evolution function in WRTO_LOOP, the nearest
1684 common ancestor of DEF_LOOP and USE_LOOP. */
1685
1686 static tree
1687 compute_scalar_evolution_in_loop (struct loop *wrto_loop,
1688 struct loop *def_loop,
1689 tree ev)
1690 {
1691 tree res;
1692 if (def_loop == wrto_loop)
1693 return ev;
1694
1695 def_loop = superloop_at_depth (def_loop, wrto_loop->depth + 1);
1696 res = compute_overall_effect_of_inner_loop (def_loop, ev);
1697
1698 return analyze_scalar_evolution_1 (wrto_loop, res, chrec_not_analyzed_yet);
1699 }
1700
1701 /* Folds EXPR, if it is a cast to pointer, assuming that the created
1702 polynomial_chrec does not wrap. */
1703
1704 static tree
1705 fold_used_pointer_cast (tree expr)
1706 {
1707 tree op;
1708 tree type, inner_type;
1709
1710 if (TREE_CODE (expr) != NOP_EXPR && TREE_CODE (expr) != CONVERT_EXPR)
1711 return expr;
1712
1713 op = TREE_OPERAND (expr, 0);
1714 if (TREE_CODE (op) != POLYNOMIAL_CHREC)
1715 return expr;
1716
1717 type = TREE_TYPE (expr);
1718 inner_type = TREE_TYPE (op);
1719
1720 if (!INTEGRAL_TYPE_P (inner_type)
1721 || TYPE_PRECISION (inner_type) != TYPE_PRECISION (type))
1722 return expr;
1723
1724 return build_polynomial_chrec (CHREC_VARIABLE (op),
1725 chrec_convert (type, CHREC_LEFT (op), NULL_TREE),
1726 chrec_convert (type, CHREC_RIGHT (op), NULL_TREE));
1727 }
1728
1729 /* Returns true if EXPR is an expression corresponding to offset of pointer
1730 in p + offset. */
1731
1732 static bool
1733 pointer_offset_p (tree expr)
1734 {
1735 if (TREE_CODE (expr) == INTEGER_CST)
1736 return true;
1737
1738 if ((TREE_CODE (expr) == NOP_EXPR || TREE_CODE (expr) == CONVERT_EXPR)
1739 && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
1740 return true;
1741
1742 return false;
1743 }
1744
1745 /* EXPR is a scalar evolution of a pointer that is dereferenced or used in
1746 comparison. This means that it must point to a part of some object in
1747 memory, which enables us to argue about overflows and possibly simplify
1748 the EXPR. AT_STMT is the statement in which this conversion has to be
1749 performed. Returns the simplified value.
1750
1751 Currently, for
1752
1753 int i, n;
1754 int *p;
1755
1756 for (i = -n; i < n; i++)
1757 *(p + i) = ...;
1758
1759 We generate the following code (assuming that size of int and size_t is
1760 4 bytes):
1761
1762 for (i = -n; i < n; i++)
1763 {
1764 size_t tmp1, tmp2;
1765 int *tmp3, *tmp4;
1766
1767 tmp1 = (size_t) i; (1)
1768 tmp2 = 4 * tmp1; (2)
1769 tmp3 = (int *) tmp2; (3)
1770 tmp4 = p + tmp3; (4)
1771
1772 *tmp4 = ...;
1773 }
1774
1775 We in general assume that pointer arithmetics does not overflow (since its
1776 behavior is undefined in that case). One of the problems is that our
1777 translation does not capture this property very well -- (int *) is
1778 considered unsigned, hence the computation in (4) does overflow if i is
1779 negative.
1780
1781 This impreciseness creates complications in scev analysis. The scalar
1782 evolution of i is [-n, +, 1]. Since int and size_t have the same precision
1783 (in this example), and size_t is unsigned (so we do not care about
1784 overflows), we succeed to derive that scev of tmp1 is [(size_t) -n, +, 1]
1785 and scev of tmp2 is [4 * (size_t) -n, +, 4]. With tmp3, we run into
1786 problem -- [(int *) (4 * (size_t) -n), +, 4] wraps, and since we on several
1787 places assume that this is not the case for scevs with pointer type, we
1788 cannot use this scev for tmp3; hence, its scev is
1789 (int *) [(4 * (size_t) -n), +, 4], and scev of tmp4 is
1790 p + (int *) [(4 * (size_t) -n), +, 4]. Most of the optimizers are unable to
1791 work with scevs of this shape.
1792
1793 However, since tmp4 is dereferenced, all its values must belong to a single
1794 object, and taking into account that the precision of int * and size_t is
1795 the same, it is impossible for its scev to wrap. Hence, we can derive that
1796 its evolution is [p + (int *) (4 * (size_t) -n), +, 4], which the optimizers
1797 can work with.
1798
1799 ??? Maybe we should use different representation for pointer arithmetics,
1800 however that is a long-term project with a lot of potential for creating
1801 bugs. */
1802
1803 static tree
1804 fold_used_pointer (tree expr, tree at_stmt)
1805 {
1806 tree op0, op1, new0, new1;
1807 enum tree_code code = TREE_CODE (expr);
1808
1809 if (code == PLUS_EXPR
1810 || code == MINUS_EXPR)
1811 {
1812 op0 = TREE_OPERAND (expr, 0);
1813 op1 = TREE_OPERAND (expr, 1);
1814
1815 if (pointer_offset_p (op1))
1816 {
1817 new0 = fold_used_pointer (op0, at_stmt);
1818 new1 = fold_used_pointer_cast (op1);
1819 }
1820 else if (code == PLUS_EXPR && pointer_offset_p (op0))
1821 {
1822 new0 = fold_used_pointer_cast (op0);
1823 new1 = fold_used_pointer (op1, at_stmt);
1824 }
1825 else
1826 return expr;
1827
1828 if (new0 == op0 && new1 == op1)
1829 return expr;
1830
1831 new0 = chrec_convert (TREE_TYPE (expr), new0, at_stmt);
1832 new1 = chrec_convert (TREE_TYPE (expr), new1, at_stmt);
1833
1834 if (code == PLUS_EXPR)
1835 expr = chrec_fold_plus (TREE_TYPE (expr), new0, new1);
1836 else
1837 expr = chrec_fold_minus (TREE_TYPE (expr), new0, new1);
1838
1839 return expr;
1840 }
1841 else
1842 return fold_used_pointer_cast (expr);
1843 }
1844
1845 /* Returns true if PTR is dereferenced, or used in comparison. */
1846
1847 static bool
1848 pointer_used_p (tree ptr)
1849 {
1850 use_operand_p use_p;
1851 imm_use_iterator imm_iter;
1852 tree stmt, rhs;
1853 struct ptr_info_def *pi = get_ptr_info (ptr);
1854
1855 /* Check whether the pointer has a memory tag; if it does, it is
1856 (or at least used to be) dereferenced. */
1857 if ((pi != NULL && pi->name_mem_tag != NULL)
1858 || symbol_mem_tag (SSA_NAME_VAR (ptr)))
1859 return true;
1860
1861 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, ptr)
1862 {
1863 stmt = USE_STMT (use_p);
1864 if (TREE_CODE (stmt) == COND_EXPR)
1865 return true;
1866
1867 if (TREE_CODE (stmt) != GIMPLE_MODIFY_STMT)
1868 continue;
1869
1870 rhs = GIMPLE_STMT_OPERAND (stmt, 1);
1871 if (!COMPARISON_CLASS_P (rhs))
1872 continue;
1873
1874 if (GIMPLE_STMT_OPERAND (stmt, 0) == ptr
1875 || GIMPLE_STMT_OPERAND (stmt, 1) == ptr)
1876 return true;
1877 }
1878
1879 return false;
1880 }
1881
1882 /* Helper recursive function. */
1883
1884 static tree
1885 analyze_scalar_evolution_1 (struct loop *loop, tree var, tree res)
1886 {
1887 tree def, type = TREE_TYPE (var);
1888 basic_block bb;
1889 struct loop *def_loop;
1890
1891 if (loop == NULL || TREE_CODE (type) == VECTOR_TYPE)
1892 return chrec_dont_know;
1893
1894 if (TREE_CODE (var) != SSA_NAME)
1895 return interpret_rhs_modify_stmt (loop, NULL_TREE, var, type);
1896
1897 def = SSA_NAME_DEF_STMT (var);
1898 bb = bb_for_stmt (def);
1899 def_loop = bb ? bb->loop_father : NULL;
1900
1901 if (bb == NULL
1902 || !flow_bb_inside_loop_p (loop, bb))
1903 {
1904 /* Keep the symbolic form. */
1905 res = var;
1906 goto set_and_end;
1907 }
1908
1909 if (res != chrec_not_analyzed_yet)
1910 {
1911 if (loop != bb->loop_father)
1912 res = compute_scalar_evolution_in_loop
1913 (find_common_loop (loop, bb->loop_father), bb->loop_father, res);
1914
1915 goto set_and_end;
1916 }
1917
1918 if (loop != def_loop)
1919 {
1920 res = analyze_scalar_evolution_1 (def_loop, var, chrec_not_analyzed_yet);
1921 res = compute_scalar_evolution_in_loop (loop, def_loop, res);
1922
1923 goto set_and_end;
1924 }
1925
1926 switch (TREE_CODE (def))
1927 {
1928 case GIMPLE_MODIFY_STMT:
1929 res = interpret_rhs_modify_stmt (loop, def,
1930 GIMPLE_STMT_OPERAND (def, 1), type);
1931
1932 if (POINTER_TYPE_P (type)
1933 && !automatically_generated_chrec_p (res)
1934 && pointer_used_p (var))
1935 res = fold_used_pointer (res, def);
1936 break;
1937
1938 case PHI_NODE:
1939 if (loop_phi_node_p (def))
1940 res = interpret_loop_phi (loop, def);
1941 else
1942 res = interpret_condition_phi (loop, def);
1943 break;
1944
1945 default:
1946 res = chrec_dont_know;
1947 break;
1948 }
1949
1950 set_and_end:
1951
1952 /* Keep the symbolic form. */
1953 if (res == chrec_dont_know)
1954 res = var;
1955
1956 if (loop == def_loop)
1957 set_scalar_evolution (var, res);
1958
1959 return res;
1960 }
1961
1962 /* Entry point for the scalar evolution analyzer.
1963 Analyzes and returns the scalar evolution of the ssa_name VAR.
1964 LOOP_NB is the identifier number of the loop in which the variable
1965 is used.
1966
1967 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
1968 pointer to the statement that uses this variable, in order to
1969 determine the evolution function of the variable, use the following
1970 calls:
1971
1972 unsigned loop_nb = loop_containing_stmt (stmt)->num;
1973 tree chrec_with_symbols = analyze_scalar_evolution (loop_nb, var);
1974 tree chrec_instantiated = instantiate_parameters
1975 (loop_nb, chrec_with_symbols);
1976 */
1977
1978 tree
1979 analyze_scalar_evolution (struct loop *loop, tree var)
1980 {
1981 tree res;
1982
1983 if (dump_file && (dump_flags & TDF_DETAILS))
1984 {
1985 fprintf (dump_file, "(analyze_scalar_evolution \n");
1986 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
1987 fprintf (dump_file, " (scalar = ");
1988 print_generic_expr (dump_file, var, 0);
1989 fprintf (dump_file, ")\n");
1990 }
1991
1992 res = analyze_scalar_evolution_1 (loop, var, get_scalar_evolution (var));
1993
1994 if (TREE_CODE (var) == SSA_NAME && res == chrec_dont_know)
1995 res = var;
1996
1997 if (dump_file && (dump_flags & TDF_DETAILS))
1998 fprintf (dump_file, ")\n");
1999
2000 return res;
2001 }
2002
2003 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
2004 WRTO_LOOP (which should be a superloop of both USE_LOOP and definition
2005 of VERSION).
2006
2007 FOLDED_CASTS is set to true if resolve_mixers used
2008 chrec_convert_aggressive (TODO -- not really, we are way too conservative
2009 at the moment in order to keep things simple). */
2010
2011 static tree
2012 analyze_scalar_evolution_in_loop (struct loop *wrto_loop, struct loop *use_loop,
2013 tree version, bool *folded_casts)
2014 {
2015 bool val = false;
2016 tree ev = version, tmp;
2017
2018 if (folded_casts)
2019 *folded_casts = false;
2020 while (1)
2021 {
2022 tmp = analyze_scalar_evolution (use_loop, ev);
2023 ev = resolve_mixers (use_loop, tmp);
2024
2025 if (folded_casts && tmp != ev)
2026 *folded_casts = true;
2027
2028 if (use_loop == wrto_loop)
2029 return ev;
2030
2031 /* If the value of the use changes in the inner loop, we cannot express
2032 its value in the outer loop (we might try to return interval chrec,
2033 but we do not have a user for it anyway) */
2034 if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
2035 || !val)
2036 return chrec_dont_know;
2037
2038 use_loop = use_loop->outer;
2039 }
2040 }
2041
2042 /* Returns instantiated value for VERSION in CACHE. */
2043
2044 static tree
2045 get_instantiated_value (htab_t cache, tree version)
2046 {
2047 struct scev_info_str *info, pattern;
2048
2049 pattern.var = version;
2050 info = (struct scev_info_str *) htab_find (cache, &pattern);
2051
2052 if (info)
2053 return info->chrec;
2054 else
2055 return NULL_TREE;
2056 }
2057
2058 /* Sets instantiated value for VERSION to VAL in CACHE. */
2059
2060 static void
2061 set_instantiated_value (htab_t cache, tree version, tree val)
2062 {
2063 struct scev_info_str *info, pattern;
2064 PTR *slot;
2065
2066 pattern.var = version;
2067 slot = htab_find_slot (cache, &pattern, INSERT);
2068
2069 if (!*slot)
2070 *slot = new_scev_info_str (version);
2071 info = (struct scev_info_str *) *slot;
2072 info->chrec = val;
2073 }
2074
2075 /* Return the closed_loop_phi node for VAR. If there is none, return
2076 NULL_TREE. */
2077
2078 static tree
2079 loop_closed_phi_def (tree var)
2080 {
2081 struct loop *loop;
2082 edge exit;
2083 tree phi;
2084
2085 if (var == NULL_TREE
2086 || TREE_CODE (var) != SSA_NAME)
2087 return NULL_TREE;
2088
2089 loop = loop_containing_stmt (SSA_NAME_DEF_STMT (var));
2090 exit = single_exit (loop);
2091 if (!exit)
2092 return NULL_TREE;
2093
2094 for (phi = phi_nodes (exit->dest); phi; phi = PHI_CHAIN (phi))
2095 if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == var)
2096 return PHI_RESULT (phi);
2097
2098 return NULL_TREE;
2099 }
2100
2101 /* Analyze all the parameters of the chrec that were left under a symbolic form,
2102 with respect to LOOP. CHREC is the chrec to instantiate. CACHE is the cache
2103 of already instantiated values. FLAGS modify the way chrecs are
2104 instantiated. SIZE_EXPR is used for computing the size of the expression to
2105 be instantiated, and to stop if it exceeds some limit. */
2106
2107 /* Values for FLAGS. */
2108 enum
2109 {
2110 INSERT_SUPERLOOP_CHRECS = 1, /* Loop invariants are replaced with chrecs
2111 in outer loops. */
2112 FOLD_CONVERSIONS = 2 /* The conversions that may wrap in
2113 signed/pointer type are folded, as long as the
2114 value of the chrec is preserved. */
2115 };
2116
2117 static tree
2118 instantiate_parameters_1 (struct loop *loop, tree chrec, int flags, htab_t cache,
2119 int size_expr)
2120 {
2121 tree res, op0, op1, op2;
2122 basic_block def_bb;
2123 struct loop *def_loop;
2124 tree type = chrec_type (chrec);
2125
2126 /* Give up if the expression is larger than the MAX that we allow. */
2127 if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
2128 return chrec_dont_know;
2129
2130 if (automatically_generated_chrec_p (chrec)
2131 || is_gimple_min_invariant (chrec))
2132 return chrec;
2133
2134 switch (TREE_CODE (chrec))
2135 {
2136 case SSA_NAME:
2137 def_bb = bb_for_stmt (SSA_NAME_DEF_STMT (chrec));
2138
2139 /* A parameter (or loop invariant and we do not want to include
2140 evolutions in outer loops), nothing to do. */
2141 if (!def_bb
2142 || (!(flags & INSERT_SUPERLOOP_CHRECS)
2143 && !flow_bb_inside_loop_p (loop, def_bb)))
2144 return chrec;
2145
2146 /* We cache the value of instantiated variable to avoid exponential
2147 time complexity due to reevaluations. We also store the convenient
2148 value in the cache in order to prevent infinite recursion -- we do
2149 not want to instantiate the SSA_NAME if it is in a mixer
2150 structure. This is used for avoiding the instantiation of
2151 recursively defined functions, such as:
2152
2153 | a_2 -> {0, +, 1, +, a_2}_1 */
2154
2155 res = get_instantiated_value (cache, chrec);
2156 if (res)
2157 return res;
2158
2159 /* Store the convenient value for chrec in the structure. If it
2160 is defined outside of the loop, we may just leave it in symbolic
2161 form, otherwise we need to admit that we do not know its behavior
2162 inside the loop. */
2163 res = !flow_bb_inside_loop_p (loop, def_bb) ? chrec : chrec_dont_know;
2164 set_instantiated_value (cache, chrec, res);
2165
2166 /* To make things even more complicated, instantiate_parameters_1
2167 calls analyze_scalar_evolution that may call # of iterations
2168 analysis that may in turn call instantiate_parameters_1 again.
2169 To prevent the infinite recursion, keep also the bitmap of
2170 ssa names that are being instantiated globally. */
2171 if (bitmap_bit_p (already_instantiated, SSA_NAME_VERSION (chrec)))
2172 return res;
2173
2174 def_loop = find_common_loop (loop, def_bb->loop_father);
2175
2176 /* If the analysis yields a parametric chrec, instantiate the
2177 result again. */
2178 bitmap_set_bit (already_instantiated, SSA_NAME_VERSION (chrec));
2179 res = analyze_scalar_evolution (def_loop, chrec);
2180
2181 /* Don't instantiate loop-closed-ssa phi nodes. */
2182 if (TREE_CODE (res) == SSA_NAME
2183 && (loop_containing_stmt (SSA_NAME_DEF_STMT (res)) == NULL
2184 || (loop_containing_stmt (SSA_NAME_DEF_STMT (res))->depth
2185 > def_loop->depth)))
2186 {
2187 if (res == chrec)
2188 res = loop_closed_phi_def (chrec);
2189 else
2190 res = chrec;
2191
2192 if (res == NULL_TREE)
2193 res = chrec_dont_know;
2194 }
2195
2196 else if (res != chrec_dont_know)
2197 res = instantiate_parameters_1 (loop, res, flags, cache, size_expr);
2198
2199 bitmap_clear_bit (already_instantiated, SSA_NAME_VERSION (chrec));
2200
2201 /* Store the correct value to the cache. */
2202 set_instantiated_value (cache, chrec, res);
2203 return res;
2204
2205 case POLYNOMIAL_CHREC:
2206 op0 = instantiate_parameters_1 (loop, CHREC_LEFT (chrec),
2207 flags, cache, size_expr);
2208 if (op0 == chrec_dont_know)
2209 return chrec_dont_know;
2210
2211 op1 = instantiate_parameters_1 (loop, CHREC_RIGHT (chrec),
2212 flags, cache, size_expr);
2213 if (op1 == chrec_dont_know)
2214 return chrec_dont_know;
2215
2216 if (CHREC_LEFT (chrec) != op0
2217 || CHREC_RIGHT (chrec) != op1)
2218 {
2219 op1 = chrec_convert (chrec_type (op0), op1, NULL_TREE);
2220 chrec = build_polynomial_chrec (CHREC_VARIABLE (chrec), op0, op1);
2221 }
2222 return chrec;
2223
2224 case PLUS_EXPR:
2225 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2226 flags, cache, size_expr);
2227 if (op0 == chrec_dont_know)
2228 return chrec_dont_know;
2229
2230 op1 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 1),
2231 flags, cache, size_expr);
2232 if (op1 == chrec_dont_know)
2233 return chrec_dont_know;
2234
2235 if (TREE_OPERAND (chrec, 0) != op0
2236 || TREE_OPERAND (chrec, 1) != op1)
2237 {
2238 op0 = chrec_convert (type, op0, NULL_TREE);
2239 op1 = chrec_convert (type, op1, NULL_TREE);
2240 chrec = chrec_fold_plus (type, op0, op1);
2241 }
2242 return chrec;
2243
2244 case MINUS_EXPR:
2245 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2246 flags, cache, size_expr);
2247 if (op0 == chrec_dont_know)
2248 return chrec_dont_know;
2249
2250 op1 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 1),
2251 flags, cache, size_expr);
2252 if (op1 == chrec_dont_know)
2253 return chrec_dont_know;
2254
2255 if (TREE_OPERAND (chrec, 0) != op0
2256 || TREE_OPERAND (chrec, 1) != op1)
2257 {
2258 op0 = chrec_convert (type, op0, NULL_TREE);
2259 op1 = chrec_convert (type, op1, NULL_TREE);
2260 chrec = chrec_fold_minus (type, op0, op1);
2261 }
2262 return chrec;
2263
2264 case MULT_EXPR:
2265 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2266 flags, cache, size_expr);
2267 if (op0 == chrec_dont_know)
2268 return chrec_dont_know;
2269
2270 op1 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 1),
2271 flags, cache, size_expr);
2272 if (op1 == chrec_dont_know)
2273 return chrec_dont_know;
2274
2275 if (TREE_OPERAND (chrec, 0) != op0
2276 || TREE_OPERAND (chrec, 1) != op1)
2277 {
2278 op0 = chrec_convert (type, op0, NULL_TREE);
2279 op1 = chrec_convert (type, op1, NULL_TREE);
2280 chrec = chrec_fold_multiply (type, op0, op1);
2281 }
2282 return chrec;
2283
2284 case NOP_EXPR:
2285 case CONVERT_EXPR:
2286 case NON_LVALUE_EXPR:
2287 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2288 flags, cache, size_expr);
2289 if (op0 == chrec_dont_know)
2290 return chrec_dont_know;
2291
2292 if (flags & FOLD_CONVERSIONS)
2293 {
2294 tree tmp = chrec_convert_aggressive (TREE_TYPE (chrec), op0);
2295 if (tmp)
2296 return tmp;
2297 }
2298
2299 if (op0 == TREE_OPERAND (chrec, 0))
2300 return chrec;
2301
2302 /* If we used chrec_convert_aggressive, we can no longer assume that
2303 signed chrecs do not overflow, as chrec_convert does, so avoid
2304 calling it in that case. */
2305 if (flags & FOLD_CONVERSIONS)
2306 return fold_convert (TREE_TYPE (chrec), op0);
2307
2308 return chrec_convert (TREE_TYPE (chrec), op0, NULL_TREE);
2309
2310 case SCEV_NOT_KNOWN:
2311 return chrec_dont_know;
2312
2313 case SCEV_KNOWN:
2314 return chrec_known;
2315
2316 default:
2317 break;
2318 }
2319
2320 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
2321 {
2322 case 3:
2323 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2324 flags, cache, size_expr);
2325 if (op0 == chrec_dont_know)
2326 return chrec_dont_know;
2327
2328 op1 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 1),
2329 flags, cache, size_expr);
2330 if (op1 == chrec_dont_know)
2331 return chrec_dont_know;
2332
2333 op2 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 2),
2334 flags, cache, size_expr);
2335 if (op2 == chrec_dont_know)
2336 return chrec_dont_know;
2337
2338 if (op0 == TREE_OPERAND (chrec, 0)
2339 && op1 == TREE_OPERAND (chrec, 1)
2340 && op2 == TREE_OPERAND (chrec, 2))
2341 return chrec;
2342
2343 return fold_build3 (TREE_CODE (chrec),
2344 TREE_TYPE (chrec), op0, op1, op2);
2345
2346 case 2:
2347 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2348 flags, cache, size_expr);
2349 if (op0 == chrec_dont_know)
2350 return chrec_dont_know;
2351
2352 op1 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 1),
2353 flags, cache, size_expr);
2354 if (op1 == chrec_dont_know)
2355 return chrec_dont_know;
2356
2357 if (op0 == TREE_OPERAND (chrec, 0)
2358 && op1 == TREE_OPERAND (chrec, 1))
2359 return chrec;
2360 return fold_build2 (TREE_CODE (chrec), TREE_TYPE (chrec), op0, op1);
2361
2362 case 1:
2363 op0 = instantiate_parameters_1 (loop, TREE_OPERAND (chrec, 0),
2364 flags, cache, size_expr);
2365 if (op0 == chrec_dont_know)
2366 return chrec_dont_know;
2367 if (op0 == TREE_OPERAND (chrec, 0))
2368 return chrec;
2369 return fold_build1 (TREE_CODE (chrec), TREE_TYPE (chrec), op0);
2370
2371 case 0:
2372 return chrec;
2373
2374 default:
2375 break;
2376 }
2377
2378 /* Too complicated to handle. */
2379 return chrec_dont_know;
2380 }
2381
2382 /* Analyze all the parameters of the chrec that were left under a
2383 symbolic form. LOOP is the loop in which symbolic names have to
2384 be analyzed and instantiated. */
2385
2386 tree
2387 instantiate_parameters (struct loop *loop,
2388 tree chrec)
2389 {
2390 tree res;
2391 htab_t cache = htab_create (10, hash_scev_info, eq_scev_info, del_scev_info);
2392
2393 if (dump_file && (dump_flags & TDF_DETAILS))
2394 {
2395 fprintf (dump_file, "(instantiate_parameters \n");
2396 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
2397 fprintf (dump_file, " (chrec = ");
2398 print_generic_expr (dump_file, chrec, 0);
2399 fprintf (dump_file, ")\n");
2400 }
2401
2402 res = instantiate_parameters_1 (loop, chrec, INSERT_SUPERLOOP_CHRECS, cache,
2403 0);
2404
2405 if (dump_file && (dump_flags & TDF_DETAILS))
2406 {
2407 fprintf (dump_file, " (res = ");
2408 print_generic_expr (dump_file, res, 0);
2409 fprintf (dump_file, "))\n");
2410 }
2411
2412 htab_delete (cache);
2413
2414 return res;
2415 }
2416
2417 /* Similar to instantiate_parameters, but does not introduce the
2418 evolutions in outer loops for LOOP invariants in CHREC, and does not
2419 care about causing overflows, as long as they do not affect value
2420 of an expression. */
2421
2422 static tree
2423 resolve_mixers (struct loop *loop, tree chrec)
2424 {
2425 htab_t cache = htab_create (10, hash_scev_info, eq_scev_info, del_scev_info);
2426 tree ret = instantiate_parameters_1 (loop, chrec, FOLD_CONVERSIONS, cache, 0);
2427 htab_delete (cache);
2428 return ret;
2429 }
2430
2431 /* Entry point for the analysis of the number of iterations pass.
2432 This function tries to safely approximate the number of iterations
2433 the loop will run. When this property is not decidable at compile
2434 time, the result is chrec_dont_know. Otherwise the result is
2435 a scalar or a symbolic parameter.
2436
2437 Example of analysis: suppose that the loop has an exit condition:
2438
2439 "if (b > 49) goto end_loop;"
2440
2441 and that in a previous analysis we have determined that the
2442 variable 'b' has an evolution function:
2443
2444 "EF = {23, +, 5}_2".
2445
2446 When we evaluate the function at the point 5, i.e. the value of the
2447 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2448 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2449 the loop body has been executed 6 times. */
2450
2451 tree
2452 number_of_latch_executions (struct loop *loop)
2453 {
2454 tree res, type;
2455 edge exit;
2456 struct tree_niter_desc niter_desc;
2457
2458 /* Determine whether the number_of_iterations_in_loop has already
2459 been computed. */
2460 res = loop->nb_iterations;
2461 if (res)
2462 return res;
2463 res = chrec_dont_know;
2464
2465 if (dump_file && (dump_flags & TDF_DETAILS))
2466 fprintf (dump_file, "(number_of_iterations_in_loop\n");
2467
2468 exit = single_exit (loop);
2469 if (!exit)
2470 goto end;
2471
2472 if (!number_of_iterations_exit (loop, exit, &niter_desc, false))
2473 goto end;
2474
2475 type = TREE_TYPE (niter_desc.niter);
2476 if (integer_nonzerop (niter_desc.may_be_zero))
2477 res = build_int_cst (type, 0);
2478 else if (integer_zerop (niter_desc.may_be_zero))
2479 res = niter_desc.niter;
2480 else
2481 res = chrec_dont_know;
2482
2483 end:
2484 return set_nb_iterations_in_loop (loop, res);
2485 }
2486
2487 /* Returns the number of executions of the exit condition of LOOP,
2488 i.e., the number by one higher than number_of_latch_executions.
2489 Note that unline number_of_latch_executions, this number does
2490 not necessarily fit in the unsigned variant of the type of
2491 the control variable -- if the number of iterations is a constant,
2492 we return chrec_dont_know if adding one to number_of_latch_executions
2493 overflows; however, in case the number of iterations is symbolic
2494 expression, the caller is responsible for dealing with this
2495 the possible overflow. */
2496
2497 tree
2498 number_of_exit_cond_executions (struct loop *loop)
2499 {
2500 tree ret = number_of_latch_executions (loop);
2501 tree type = chrec_type (ret);
2502
2503 if (chrec_contains_undetermined (ret))
2504 return ret;
2505
2506 ret = chrec_fold_plus (type, ret, build_int_cst (type, 1));
2507 if (TREE_CODE (ret) == INTEGER_CST
2508 && TREE_OVERFLOW (ret))
2509 return chrec_dont_know;
2510
2511 return ret;
2512 }
2513
2514 /* One of the drivers for testing the scalar evolutions analysis.
2515 This function computes the number of iterations for all the loops
2516 from the EXIT_CONDITIONS array. */
2517
2518 static void
2519 number_of_iterations_for_all_loops (VEC(tree,heap) **exit_conditions)
2520 {
2521 unsigned int i;
2522 unsigned nb_chrec_dont_know_loops = 0;
2523 unsigned nb_static_loops = 0;
2524 tree cond;
2525
2526 for (i = 0; VEC_iterate (tree, *exit_conditions, i, cond); i++)
2527 {
2528 tree res = number_of_latch_executions (loop_containing_stmt (cond));
2529 if (chrec_contains_undetermined (res))
2530 nb_chrec_dont_know_loops++;
2531 else
2532 nb_static_loops++;
2533 }
2534
2535 if (dump_file)
2536 {
2537 fprintf (dump_file, "\n(\n");
2538 fprintf (dump_file, "-----------------------------------------\n");
2539 fprintf (dump_file, "%d\tnb_chrec_dont_know_loops\n", nb_chrec_dont_know_loops);
2540 fprintf (dump_file, "%d\tnb_static_loops\n", nb_static_loops);
2541 fprintf (dump_file, "%d\tnb_total_loops\n", number_of_loops ());
2542 fprintf (dump_file, "-----------------------------------------\n");
2543 fprintf (dump_file, ")\n\n");
2544
2545 print_loop_ir (dump_file);
2546 }
2547 }
2548
2549 \f
2550
2551 /* Counters for the stats. */
2552
2553 struct chrec_stats
2554 {
2555 unsigned nb_chrecs;
2556 unsigned nb_affine;
2557 unsigned nb_affine_multivar;
2558 unsigned nb_higher_poly;
2559 unsigned nb_chrec_dont_know;
2560 unsigned nb_undetermined;
2561 };
2562
2563 /* Reset the counters. */
2564
2565 static inline void
2566 reset_chrecs_counters (struct chrec_stats *stats)
2567 {
2568 stats->nb_chrecs = 0;
2569 stats->nb_affine = 0;
2570 stats->nb_affine_multivar = 0;
2571 stats->nb_higher_poly = 0;
2572 stats->nb_chrec_dont_know = 0;
2573 stats->nb_undetermined = 0;
2574 }
2575
2576 /* Dump the contents of a CHREC_STATS structure. */
2577
2578 static void
2579 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
2580 {
2581 fprintf (file, "\n(\n");
2582 fprintf (file, "-----------------------------------------\n");
2583 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
2584 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
2585 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
2586 stats->nb_higher_poly);
2587 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
2588 fprintf (file, "-----------------------------------------\n");
2589 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
2590 fprintf (file, "%d\twith undetermined coefficients\n",
2591 stats->nb_undetermined);
2592 fprintf (file, "-----------------------------------------\n");
2593 fprintf (file, "%d\tchrecs in the scev database\n",
2594 (int) htab_elements (scalar_evolution_info));
2595 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
2596 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
2597 fprintf (file, "-----------------------------------------\n");
2598 fprintf (file, ")\n\n");
2599 }
2600
2601 /* Gather statistics about CHREC. */
2602
2603 static void
2604 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
2605 {
2606 if (dump_file && (dump_flags & TDF_STATS))
2607 {
2608 fprintf (dump_file, "(classify_chrec ");
2609 print_generic_expr (dump_file, chrec, 0);
2610 fprintf (dump_file, "\n");
2611 }
2612
2613 stats->nb_chrecs++;
2614
2615 if (chrec == NULL_TREE)
2616 {
2617 stats->nb_undetermined++;
2618 return;
2619 }
2620
2621 switch (TREE_CODE (chrec))
2622 {
2623 case POLYNOMIAL_CHREC:
2624 if (evolution_function_is_affine_p (chrec))
2625 {
2626 if (dump_file && (dump_flags & TDF_STATS))
2627 fprintf (dump_file, " affine_univariate\n");
2628 stats->nb_affine++;
2629 }
2630 else if (evolution_function_is_affine_multivariate_p (chrec))
2631 {
2632 if (dump_file && (dump_flags & TDF_STATS))
2633 fprintf (dump_file, " affine_multivariate\n");
2634 stats->nb_affine_multivar++;
2635 }
2636 else
2637 {
2638 if (dump_file && (dump_flags & TDF_STATS))
2639 fprintf (dump_file, " higher_degree_polynomial\n");
2640 stats->nb_higher_poly++;
2641 }
2642
2643 break;
2644
2645 default:
2646 break;
2647 }
2648
2649 if (chrec_contains_undetermined (chrec))
2650 {
2651 if (dump_file && (dump_flags & TDF_STATS))
2652 fprintf (dump_file, " undetermined\n");
2653 stats->nb_undetermined++;
2654 }
2655
2656 if (dump_file && (dump_flags & TDF_STATS))
2657 fprintf (dump_file, ")\n");
2658 }
2659
2660 /* One of the drivers for testing the scalar evolutions analysis.
2661 This function analyzes the scalar evolution of all the scalars
2662 defined as loop phi nodes in one of the loops from the
2663 EXIT_CONDITIONS array.
2664
2665 TODO Optimization: A loop is in canonical form if it contains only
2666 a single scalar loop phi node. All the other scalars that have an
2667 evolution in the loop are rewritten in function of this single
2668 index. This allows the parallelization of the loop. */
2669
2670 static void
2671 analyze_scalar_evolution_for_all_loop_phi_nodes (VEC(tree,heap) **exit_conditions)
2672 {
2673 unsigned int i;
2674 struct chrec_stats stats;
2675 tree cond;
2676
2677 reset_chrecs_counters (&stats);
2678
2679 for (i = 0; VEC_iterate (tree, *exit_conditions, i, cond); i++)
2680 {
2681 struct loop *loop;
2682 basic_block bb;
2683 tree phi, chrec;
2684
2685 loop = loop_containing_stmt (cond);
2686 bb = loop->header;
2687
2688 for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2689 if (is_gimple_reg (PHI_RESULT (phi)))
2690 {
2691 chrec = instantiate_parameters
2692 (loop,
2693 analyze_scalar_evolution (loop, PHI_RESULT (phi)));
2694
2695 if (dump_file && (dump_flags & TDF_STATS))
2696 gather_chrec_stats (chrec, &stats);
2697 }
2698 }
2699
2700 if (dump_file && (dump_flags & TDF_STATS))
2701 dump_chrecs_stats (dump_file, &stats);
2702 }
2703
2704 /* Callback for htab_traverse, gathers information on chrecs in the
2705 hashtable. */
2706
2707 static int
2708 gather_stats_on_scev_database_1 (void **slot, void *stats)
2709 {
2710 struct scev_info_str *entry = (struct scev_info_str *) *slot;
2711
2712 gather_chrec_stats (entry->chrec, (struct chrec_stats *) stats);
2713
2714 return 1;
2715 }
2716
2717 /* Classify the chrecs of the whole database. */
2718
2719 void
2720 gather_stats_on_scev_database (void)
2721 {
2722 struct chrec_stats stats;
2723
2724 if (!dump_file)
2725 return;
2726
2727 reset_chrecs_counters (&stats);
2728
2729 htab_traverse (scalar_evolution_info, gather_stats_on_scev_database_1,
2730 &stats);
2731
2732 dump_chrecs_stats (dump_file, &stats);
2733 }
2734
2735 \f
2736
2737 /* Initializer. */
2738
2739 static void
2740 initialize_scalar_evolutions_analyzer (void)
2741 {
2742 /* The elements below are unique. */
2743 if (chrec_dont_know == NULL_TREE)
2744 {
2745 chrec_not_analyzed_yet = NULL_TREE;
2746 chrec_dont_know = make_node (SCEV_NOT_KNOWN);
2747 chrec_known = make_node (SCEV_KNOWN);
2748 TREE_TYPE (chrec_dont_know) = void_type_node;
2749 TREE_TYPE (chrec_known) = void_type_node;
2750 }
2751 }
2752
2753 /* Initialize the analysis of scalar evolutions for LOOPS. */
2754
2755 void
2756 scev_initialize (void)
2757 {
2758 loop_iterator li;
2759 struct loop *loop;
2760
2761 scalar_evolution_info = htab_create (100, hash_scev_info,
2762 eq_scev_info, del_scev_info);
2763 already_instantiated = BITMAP_ALLOC (NULL);
2764
2765 initialize_scalar_evolutions_analyzer ();
2766
2767 FOR_EACH_LOOP (li, loop, 0)
2768 {
2769 loop->nb_iterations = NULL_TREE;
2770 }
2771 }
2772
2773 /* Cleans up the information cached by the scalar evolutions analysis. */
2774
2775 void
2776 scev_reset (void)
2777 {
2778 loop_iterator li;
2779 struct loop *loop;
2780
2781 if (!scalar_evolution_info || !current_loops)
2782 return;
2783
2784 htab_empty (scalar_evolution_info);
2785 FOR_EACH_LOOP (li, loop, 0)
2786 {
2787 loop->nb_iterations = NULL_TREE;
2788 }
2789 }
2790
2791 /* Checks whether OP behaves as a simple affine iv of LOOP in STMT and returns
2792 its base and step in IV if possible. If ALLOW_NONCONSTANT_STEP is true, we
2793 want step to be invariant in LOOP. Otherwise we require it to be an
2794 integer constant. IV->no_overflow is set to true if we are sure the iv cannot
2795 overflow (e.g. because it is computed in signed arithmetics). */
2796
2797 bool
2798 simple_iv (struct loop *loop, tree stmt, tree op, affine_iv *iv,
2799 bool allow_nonconstant_step)
2800 {
2801 basic_block bb = bb_for_stmt (stmt);
2802 tree type, ev;
2803 bool folded_casts;
2804
2805 iv->base = NULL_TREE;
2806 iv->step = NULL_TREE;
2807 iv->no_overflow = false;
2808
2809 type = TREE_TYPE (op);
2810 if (TREE_CODE (type) != INTEGER_TYPE
2811 && TREE_CODE (type) != POINTER_TYPE)
2812 return false;
2813
2814 ev = analyze_scalar_evolution_in_loop (loop, bb->loop_father, op,
2815 &folded_casts);
2816 if (chrec_contains_undetermined (ev))
2817 return false;
2818
2819 if (tree_does_not_contain_chrecs (ev)
2820 && !chrec_contains_symbols_defined_in_loop (ev, loop->num))
2821 {
2822 iv->base = ev;
2823 iv->step = build_int_cst (TREE_TYPE (ev), 0);
2824 iv->no_overflow = true;
2825 return true;
2826 }
2827
2828 if (TREE_CODE (ev) != POLYNOMIAL_CHREC
2829 || CHREC_VARIABLE (ev) != (unsigned) loop->num)
2830 return false;
2831
2832 iv->step = CHREC_RIGHT (ev);
2833 if (allow_nonconstant_step)
2834 {
2835 if (tree_contains_chrecs (iv->step, NULL)
2836 || chrec_contains_symbols_defined_in_loop (iv->step, loop->num))
2837 return false;
2838 }
2839 else if (TREE_CODE (iv->step) != INTEGER_CST)
2840 return false;
2841
2842 iv->base = CHREC_LEFT (ev);
2843 if (tree_contains_chrecs (iv->base, NULL)
2844 || chrec_contains_symbols_defined_in_loop (iv->base, loop->num))
2845 return false;
2846
2847 iv->no_overflow = !folded_casts && TYPE_OVERFLOW_UNDEFINED (type);
2848
2849 return true;
2850 }
2851
2852 /* Runs the analysis of scalar evolutions. */
2853
2854 void
2855 scev_analysis (void)
2856 {
2857 VEC(tree,heap) *exit_conditions;
2858
2859 exit_conditions = VEC_alloc (tree, heap, 37);
2860 select_loops_exit_conditions (&exit_conditions);
2861
2862 if (dump_file && (dump_flags & TDF_STATS))
2863 analyze_scalar_evolution_for_all_loop_phi_nodes (&exit_conditions);
2864
2865 number_of_iterations_for_all_loops (&exit_conditions);
2866 VEC_free (tree, heap, exit_conditions);
2867 }
2868
2869 /* Finalize the scalar evolution analysis. */
2870
2871 void
2872 scev_finalize (void)
2873 {
2874 htab_delete (scalar_evolution_info);
2875 BITMAP_FREE (already_instantiated);
2876 }
2877
2878 /* Returns true if EXPR looks expensive. */
2879
2880 static bool
2881 expression_expensive_p (tree expr)
2882 {
2883 return force_expr_to_var_cost (expr) >= target_spill_cost;
2884 }
2885
2886 /* Replace ssa names for that scev can prove they are constant by the
2887 appropriate constants. Also perform final value replacement in loops,
2888 in case the replacement expressions are cheap.
2889
2890 We only consider SSA names defined by phi nodes; rest is left to the
2891 ordinary constant propagation pass. */
2892
2893 unsigned int
2894 scev_const_prop (void)
2895 {
2896 basic_block bb;
2897 tree name, phi, next_phi, type, ev;
2898 struct loop *loop, *ex_loop;
2899 bitmap ssa_names_to_remove = NULL;
2900 unsigned i;
2901 loop_iterator li;
2902
2903 if (!current_loops)
2904 return 0;
2905
2906 FOR_EACH_BB (bb)
2907 {
2908 loop = bb->loop_father;
2909
2910 for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2911 {
2912 name = PHI_RESULT (phi);
2913
2914 if (!is_gimple_reg (name))
2915 continue;
2916
2917 type = TREE_TYPE (name);
2918
2919 if (!POINTER_TYPE_P (type)
2920 && !INTEGRAL_TYPE_P (type))
2921 continue;
2922
2923 ev = resolve_mixers (loop, analyze_scalar_evolution (loop, name));
2924 if (!is_gimple_min_invariant (ev)
2925 || !may_propagate_copy (name, ev))
2926 continue;
2927
2928 /* Replace the uses of the name. */
2929 if (name != ev)
2930 replace_uses_by (name, ev);
2931
2932 if (!ssa_names_to_remove)
2933 ssa_names_to_remove = BITMAP_ALLOC (NULL);
2934 bitmap_set_bit (ssa_names_to_remove, SSA_NAME_VERSION (name));
2935 }
2936 }
2937
2938 /* Remove the ssa names that were replaced by constants. We do not
2939 remove them directly in the previous cycle, since this
2940 invalidates scev cache. */
2941 if (ssa_names_to_remove)
2942 {
2943 bitmap_iterator bi;
2944
2945 EXECUTE_IF_SET_IN_BITMAP (ssa_names_to_remove, 0, i, bi)
2946 {
2947 name = ssa_name (i);
2948 phi = SSA_NAME_DEF_STMT (name);
2949
2950 gcc_assert (TREE_CODE (phi) == PHI_NODE);
2951 remove_phi_node (phi, NULL, true);
2952 }
2953
2954 BITMAP_FREE (ssa_names_to_remove);
2955 scev_reset ();
2956 }
2957
2958 /* Now the regular final value replacement. */
2959 FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
2960 {
2961 edge exit;
2962 tree def, rslt, ass, niter;
2963 block_stmt_iterator bsi;
2964
2965 /* If we do not know exact number of iterations of the loop, we cannot
2966 replace the final value. */
2967 exit = single_exit (loop);
2968 if (!exit)
2969 continue;
2970
2971 niter = number_of_latch_executions (loop);
2972 if (niter == chrec_dont_know
2973 /* If computing the number of iterations is expensive, it may be
2974 better not to introduce computations involving it. */
2975 || expression_expensive_p (niter))
2976 continue;
2977
2978 /* Ensure that it is possible to insert new statements somewhere. */
2979 if (!single_pred_p (exit->dest))
2980 split_loop_exit_edge (exit);
2981 tree_block_label (exit->dest);
2982 bsi = bsi_after_labels (exit->dest);
2983
2984 ex_loop = superloop_at_depth (loop, exit->dest->loop_father->depth + 1);
2985
2986 for (phi = phi_nodes (exit->dest); phi; phi = next_phi)
2987 {
2988 next_phi = PHI_CHAIN (phi);
2989 rslt = PHI_RESULT (phi);
2990 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
2991 if (!is_gimple_reg (def))
2992 continue;
2993
2994 if (!POINTER_TYPE_P (TREE_TYPE (def))
2995 && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
2996 continue;
2997
2998 def = analyze_scalar_evolution_in_loop (ex_loop, loop, def, NULL);
2999 def = compute_overall_effect_of_inner_loop (ex_loop, def);
3000 if (!tree_does_not_contain_chrecs (def)
3001 || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
3002 /* Moving the computation from the loop may prolong life range
3003 of some ssa names, which may cause problems if they appear
3004 on abnormal edges. */
3005 || contains_abnormal_ssa_name_p (def))
3006 continue;
3007
3008 /* Eliminate the PHI node and replace it by a computation outside
3009 the loop. */
3010 def = unshare_expr (def);
3011 remove_phi_node (phi, NULL_TREE, false);
3012
3013 ass = build2 (GIMPLE_MODIFY_STMT, void_type_node, rslt, NULL_TREE);
3014 SSA_NAME_DEF_STMT (rslt) = ass;
3015 {
3016 block_stmt_iterator dest = bsi;
3017 bsi_insert_before (&dest, ass, BSI_NEW_STMT);
3018 def = force_gimple_operand_bsi (&dest, def, false, NULL_TREE);
3019 }
3020 GIMPLE_STMT_OPERAND (ass, 1) = def;
3021 update_stmt (ass);
3022 }
3023 }
3024 return 0;
3025 }