OSDN Git Service

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