OSDN Git Service

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