OSDN Git Service

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