OSDN Git Service

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