xref: /netbsd-src/external/gpl3/gcc.old/dist/gcc/tree-scalar-evolution.c (revision cef8759bd76c1b621f8eab8faa6f208faabc2e15)
1 /* Scalar evolution detector.
2    Copyright (C) 2003-2017 Free Software Foundation, Inc.
3    Contributed by Sebastian Pop <s.pop@laposte.net>
4 
5 This file is part of GCC.
6 
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
11 
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16 
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20 
21 /*
22    Description:
23 
24    This pass analyzes the evolution of scalar variables in loop
25    structures.  The algorithm is based on the SSA representation,
26    and on the loop hierarchy tree.  This algorithm is not based on
27    the notion of versions of a variable, as it was the case for the
28    previous implementations of the scalar evolution algorithm, but
29    it assumes that each defined name is unique.
30 
31    The notation used in this file is called "chains of recurrences",
32    and has been proposed by Eugene Zima, Robert Van Engelen, and
33    others for describing induction variables in programs.  For example
34    "b -> {0, +, 2}_1" means that the scalar variable "b" is equal to 0
35    when entering in the loop_1 and has a step 2 in this loop, in other
36    words "for (b = 0; b < N; b+=2);".  Note that the coefficients of
37    this chain of recurrence (or chrec [shrek]) can contain the name of
38    other variables, in which case they are called parametric chrecs.
39    For example, "b -> {a, +, 2}_1" means that the initial value of "b"
40    is the value of "a".  In most of the cases these parametric chrecs
41    are fully instantiated before their use because symbolic names can
42    hide some difficult cases such as self-references described later
43    (see the Fibonacci example).
44 
45    A short sketch of the algorithm is:
46 
47    Given a scalar variable to be analyzed, follow the SSA edge to
48    its definition:
49 
50    - When the definition is a GIMPLE_ASSIGN: if the right hand side
51    (RHS) of the definition cannot be statically analyzed, the answer
52    of the analyzer is: "don't know".
53    Otherwise, for all the variables that are not yet analyzed in the
54    RHS, try to determine their evolution, and finally try to
55    evaluate the operation of the RHS that gives the evolution
56    function of the analyzed variable.
57 
58    - When the definition is a condition-phi-node: determine the
59    evolution function for all the branches of the phi node, and
60    finally merge these evolutions (see chrec_merge).
61 
62    - When the definition is a loop-phi-node: determine its initial
63    condition, that is the SSA edge defined in an outer loop, and
64    keep it symbolic.  Then determine the SSA edges that are defined
65    in the body of the loop.  Follow the inner edges until ending on
66    another loop-phi-node of the same analyzed loop.  If the reached
67    loop-phi-node is not the starting loop-phi-node, then we keep
68    this definition under a symbolic form.  If the reached
69    loop-phi-node is the same as the starting one, then we compute a
70    symbolic stride on the return path.  The result is then the
71    symbolic chrec {initial_condition, +, symbolic_stride}_loop.
72 
73    Examples:
74 
75    Example 1: Illustration of the basic algorithm.
76 
77    | a = 3
78    | loop_1
79    |   b = phi (a, c)
80    |   c = b + 1
81    |   if (c > 10) exit_loop
82    | endloop
83 
84    Suppose that we want to know the number of iterations of the
85    loop_1.  The exit_loop is controlled by a COND_EXPR (c > 10).  We
86    ask the scalar evolution analyzer two questions: what's the
87    scalar evolution (scev) of "c", and what's the scev of "10".  For
88    "10" the answer is "10" since it is a scalar constant.  For the
89    scalar variable "c", it follows the SSA edge to its definition,
90    "c = b + 1", and then asks again what's the scev of "b".
91    Following the SSA edge, we end on a loop-phi-node "b = phi (a,
92    c)", where the initial condition is "a", and the inner loop edge
93    is "c".  The initial condition is kept under a symbolic form (it
94    may be the case that the copy constant propagation has done its
95    work and we end with the constant "3" as one of the edges of the
96    loop-phi-node).  The update edge is followed to the end of the
97    loop, and until reaching again the starting loop-phi-node: b -> c
98    -> b.  At this point we have drawn a path from "b" to "b" from
99    which we compute the stride in the loop: in this example it is
100    "+1".  The resulting scev for "b" is "b -> {a, +, 1}_1".  Now
101    that the scev for "b" is known, it is possible to compute the
102    scev for "c", that is "c -> {a + 1, +, 1}_1".  In order to
103    determine the number of iterations in the loop_1, we have to
104    instantiate_parameters (loop_1, {a + 1, +, 1}_1), that gives after some
105    more analysis the scev {4, +, 1}_1, or in other words, this is
106    the function "f (x) = x + 4", where x is the iteration count of
107    the loop_1.  Now we have to solve the inequality "x + 4 > 10",
108    and take the smallest iteration number for which the loop is
109    exited: x = 7.  This loop runs from x = 0 to x = 7, and in total
110    there are 8 iterations.  In terms of loop normalization, we have
111    created a variable that is implicitly defined, "x" or just "_1",
112    and all the other analyzed scalars of the loop are defined in
113    function of this variable:
114 
115    a -> 3
116    b -> {3, +, 1}_1
117    c -> {4, +, 1}_1
118 
119    or in terms of a C program:
120 
121    | a = 3
122    | for (x = 0; x <= 7; x++)
123    |   {
124    |     b = x + 3
125    |     c = x + 4
126    |   }
127 
128    Example 2a: Illustration of the algorithm on nested loops.
129 
130    | loop_1
131    |   a = phi (1, b)
132    |   c = a + 2
133    |   loop_2  10 times
134    |     b = phi (c, d)
135    |     d = b + 3
136    |   endloop
137    | endloop
138 
139    For analyzing the scalar evolution of "a", the algorithm follows
140    the SSA edge into the loop's body: "a -> b".  "b" is an inner
141    loop-phi-node, and its analysis as in Example 1, gives:
142 
143    b -> {c, +, 3}_2
144    d -> {c + 3, +, 3}_2
145 
146    Following the SSA edge for the initial condition, we end on "c = a
147    + 2", and then on the starting loop-phi-node "a".  From this point,
148    the loop stride is computed: back on "c = a + 2" we get a "+2" in
149    the loop_1, then on the loop-phi-node "b" we compute the overall
150    effect of the inner loop that is "b = c + 30", and we get a "+30"
151    in the loop_1.  That means that the overall stride in loop_1 is
152    equal to "+32", and the result is:
153 
154    a -> {1, +, 32}_1
155    c -> {3, +, 32}_1
156 
157    Example 2b: Multivariate chains of recurrences.
158 
159    | loop_1
160    |   k = phi (0, k + 1)
161    |   loop_2  4 times
162    |     j = phi (0, j + 1)
163    |     loop_3 4 times
164    |       i = phi (0, i + 1)
165    |       A[j + k] = ...
166    |     endloop
167    |   endloop
168    | endloop
169 
170    Analyzing the access function of array A with
171    instantiate_parameters (loop_1, "j + k"), we obtain the
172    instantiation and the analysis of the scalar variables "j" and "k"
173    in loop_1.  This leads to the scalar evolution {4, +, 1}_1: the end
174    value of loop_2 for "j" is 4, and the evolution of "k" in loop_1 is
175    {0, +, 1}_1.  To obtain the evolution function in loop_3 and
176    instantiate the scalar variables up to loop_1, one has to use:
177    instantiate_scev (block_before_loop (loop_1), loop_3, "j + k").
178    The result of this call is {{0, +, 1}_1, +, 1}_2.
179 
180    Example 3: Higher degree polynomials.
181 
182    | loop_1
183    |   a = phi (2, b)
184    |   c = phi (5, d)
185    |   b = a + 1
186    |   d = c + a
187    | endloop
188 
189    a -> {2, +, 1}_1
190    b -> {3, +, 1}_1
191    c -> {5, +, a}_1
192    d -> {5 + a, +, a}_1
193 
194    instantiate_parameters (loop_1, {5, +, a}_1) -> {5, +, 2, +, 1}_1
195    instantiate_parameters (loop_1, {5 + a, +, a}_1) -> {7, +, 3, +, 1}_1
196 
197    Example 4: Lucas, Fibonacci, or mixers in general.
198 
199    | loop_1
200    |   a = phi (1, b)
201    |   c = phi (3, d)
202    |   b = c
203    |   d = c + a
204    | endloop
205 
206    a -> (1, c)_1
207    c -> {3, +, a}_1
208 
209    The syntax "(1, c)_1" stands for a PEELED_CHREC that has the
210    following semantics: during the first iteration of the loop_1, the
211    variable contains the value 1, and then it contains the value "c".
212    Note that this syntax is close to the syntax of the loop-phi-node:
213    "a -> (1, c)_1" vs. "a = phi (1, c)".
214 
215    The symbolic chrec representation contains all the semantics of the
216    original code.  What is more difficult is to use this information.
217 
218    Example 5: Flip-flops, or exchangers.
219 
220    | loop_1
221    |   a = phi (1, b)
222    |   c = phi (3, d)
223    |   b = c
224    |   d = a
225    | endloop
226 
227    a -> (1, c)_1
228    c -> (3, a)_1
229 
230    Based on these symbolic chrecs, it is possible to refine this
231    information into the more precise PERIODIC_CHRECs:
232 
233    a -> |1, 3|_1
234    c -> |3, 1|_1
235 
236    This transformation is not yet implemented.
237 
238    Further readings:
239 
240    You can find a more detailed description of the algorithm in:
241    http://icps.u-strasbg.fr/~pop/DEA_03_Pop.pdf
242    http://icps.u-strasbg.fr/~pop/DEA_03_Pop.ps.gz.  But note that
243    this is a preliminary report and some of the details of the
244    algorithm have changed.  I'm working on a research report that
245    updates the description of the algorithms to reflect the design
246    choices used in this implementation.
247 
248    A set of slides show a high level overview of the algorithm and run
249    an example through the scalar evolution analyzer:
250    http://cri.ensmp.fr/~pop/gcc/mar04/slides.pdf
251 
252    The slides that I have presented at the GCC Summit'04 are available
253    at: http://cri.ensmp.fr/~pop/gcc/20040604/gccsummit-lno-spop.pdf
254 */
255 
256 #include "config.h"
257 #include "system.h"
258 #include "coretypes.h"
259 #include "backend.h"
260 #include "rtl.h"
261 #include "tree.h"
262 #include "gimple.h"
263 #include "ssa.h"
264 #include "gimple-pretty-print.h"
265 #include "fold-const.h"
266 #include "gimplify.h"
267 #include "gimple-iterator.h"
268 #include "gimplify-me.h"
269 #include "tree-cfg.h"
270 #include "tree-ssa-loop-ivopts.h"
271 #include "tree-ssa-loop-manip.h"
272 #include "tree-ssa-loop-niter.h"
273 #include "tree-ssa-loop.h"
274 #include "tree-ssa.h"
275 #include "cfgloop.h"
276 #include "tree-chrec.h"
277 #include "tree-affine.h"
278 #include "tree-scalar-evolution.h"
279 #include "dumpfile.h"
280 #include "params.h"
281 #include "tree-ssa-propagate.h"
282 #include "gimple-fold.h"
283 #include "tree-into-ssa.h"
284 
285 static tree analyze_scalar_evolution_1 (struct loop *, tree, tree);
286 static tree analyze_scalar_evolution_for_address_of (struct loop *loop,
287 						     tree var);
288 
289 /* The cached information about an SSA name with version NAME_VERSION,
290    claiming that below basic block with index INSTANTIATED_BELOW, the
291    value of the SSA name can be expressed as CHREC.  */
292 
293 struct GTY((for_user)) scev_info_str {
294   unsigned int name_version;
295   int instantiated_below;
296   tree chrec;
297 };
298 
299 /* Counters for the scev database.  */
300 static unsigned nb_set_scev = 0;
301 static unsigned nb_get_scev = 0;
302 
303 /* The following trees are unique elements.  Thus the comparison of
304    another element to these elements should be done on the pointer to
305    these trees, and not on their value.  */
306 
307 /* The SSA_NAMEs that are not yet analyzed are qualified with NULL_TREE.  */
308 tree chrec_not_analyzed_yet;
309 
310 /* Reserved to the cases where the analyzer has detected an
311    undecidable property at compile time.  */
312 tree chrec_dont_know;
313 
314 /* When the analyzer has detected that a property will never
315    happen, then it qualifies it with chrec_known.  */
316 tree chrec_known;
317 
318 struct scev_info_hasher : ggc_ptr_hash<scev_info_str>
319 {
320   static hashval_t hash (scev_info_str *i);
321   static bool equal (const scev_info_str *a, const scev_info_str *b);
322 };
323 
324 static GTY (()) hash_table<scev_info_hasher> *scalar_evolution_info;
325 
326 
327 /* Constructs a new SCEV_INFO_STR structure for VAR and INSTANTIATED_BELOW.  */
328 
329 static inline struct scev_info_str *
330 new_scev_info_str (basic_block instantiated_below, tree var)
331 {
332   struct scev_info_str *res;
333 
334   res = ggc_alloc<scev_info_str> ();
335   res->name_version = SSA_NAME_VERSION (var);
336   res->chrec = chrec_not_analyzed_yet;
337   res->instantiated_below = instantiated_below->index;
338 
339   return res;
340 }
341 
342 /* Computes a hash function for database element ELT.  */
343 
344 hashval_t
345 scev_info_hasher::hash (scev_info_str *elt)
346 {
347   return elt->name_version ^ elt->instantiated_below;
348 }
349 
350 /* Compares database elements E1 and E2.  */
351 
352 bool
353 scev_info_hasher::equal (const scev_info_str *elt1, const scev_info_str *elt2)
354 {
355   return (elt1->name_version == elt2->name_version
356 	  && elt1->instantiated_below == elt2->instantiated_below);
357 }
358 
359 /* Get the scalar evolution of VAR for INSTANTIATED_BELOW basic block.
360    A first query on VAR returns chrec_not_analyzed_yet.  */
361 
362 static tree *
363 find_var_scev_info (basic_block instantiated_below, tree var)
364 {
365   struct scev_info_str *res;
366   struct scev_info_str tmp;
367 
368   tmp.name_version = SSA_NAME_VERSION (var);
369   tmp.instantiated_below = instantiated_below->index;
370   scev_info_str **slot = scalar_evolution_info->find_slot (&tmp, INSERT);
371 
372   if (!*slot)
373     *slot = new_scev_info_str (instantiated_below, var);
374   res = *slot;
375 
376   return &res->chrec;
377 }
378 
379 /* Return true when CHREC contains symbolic names defined in
380    LOOP_NB.  */
381 
382 bool
383 chrec_contains_symbols_defined_in_loop (const_tree chrec, unsigned loop_nb)
384 {
385   int i, n;
386 
387   if (chrec == NULL_TREE)
388     return false;
389 
390   if (is_gimple_min_invariant (chrec))
391     return false;
392 
393   if (TREE_CODE (chrec) == SSA_NAME)
394     {
395       gimple *def;
396       loop_p def_loop, loop;
397 
398       if (SSA_NAME_IS_DEFAULT_DEF (chrec))
399 	return false;
400 
401       def = SSA_NAME_DEF_STMT (chrec);
402       def_loop = loop_containing_stmt (def);
403       loop = get_loop (cfun, loop_nb);
404 
405       if (def_loop == NULL)
406 	return false;
407 
408       if (loop == def_loop || flow_loop_nested_p (loop, def_loop))
409 	return true;
410 
411       return false;
412     }
413 
414   n = TREE_OPERAND_LENGTH (chrec);
415   for (i = 0; i < n; i++)
416     if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, i),
417 						loop_nb))
418       return true;
419   return false;
420 }
421 
422 /* Return true when PHI is a loop-phi-node.  */
423 
424 static bool
425 loop_phi_node_p (gimple *phi)
426 {
427   /* The implementation of this function is based on the following
428      property: "all the loop-phi-nodes of a loop are contained in the
429      loop's header basic block".  */
430 
431   return loop_containing_stmt (phi)->header == gimple_bb (phi);
432 }
433 
434 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
435    In general, in the case of multivariate evolutions we want to get
436    the evolution in different loops.  LOOP specifies the level for
437    which to get the evolution.
438 
439    Example:
440 
441    | for (j = 0; j < 100; j++)
442    |   {
443    |     for (k = 0; k < 100; k++)
444    |       {
445    |         i = k + j;   - Here the value of i is a function of j, k.
446    |       }
447    |      ... = i         - Here the value of i is a function of j.
448    |   }
449    | ... = i              - Here the value of i is a scalar.
450 
451    Example:
452 
453    | i_0 = ...
454    | loop_1 10 times
455    |   i_1 = phi (i_0, i_2)
456    |   i_2 = i_1 + 2
457    | endloop
458 
459    This loop has the same effect as:
460    LOOP_1 has the same effect as:
461 
462    | i_1 = i_0 + 20
463 
464    The overall effect of the loop, "i_0 + 20" in the previous example,
465    is obtained by passing in the parameters: LOOP = 1,
466    EVOLUTION_FN = {i_0, +, 2}_1.
467 */
468 
469 tree
470 compute_overall_effect_of_inner_loop (struct loop *loop, tree evolution_fn)
471 {
472   bool val = false;
473 
474   if (evolution_fn == chrec_dont_know)
475     return chrec_dont_know;
476 
477   else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
478     {
479       struct loop *inner_loop = get_chrec_loop (evolution_fn);
480 
481       if (inner_loop == loop
482 	  || flow_loop_nested_p (loop, inner_loop))
483 	{
484 	  tree nb_iter = number_of_latch_executions (inner_loop);
485 
486 	  if (nb_iter == chrec_dont_know)
487 	    return chrec_dont_know;
488 	  else
489 	    {
490 	      tree res;
491 
492 	      /* evolution_fn is the evolution function in LOOP.  Get
493 		 its value in the nb_iter-th iteration.  */
494 	      res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
495 
496 	      if (chrec_contains_symbols_defined_in_loop (res, loop->num))
497 		res = instantiate_parameters (loop, res);
498 
499 	      /* Continue the computation until ending on a parent of LOOP.  */
500 	      return compute_overall_effect_of_inner_loop (loop, res);
501 	    }
502 	}
503       else
504 	return evolution_fn;
505      }
506 
507   /* If the evolution function is an invariant, there is nothing to do.  */
508   else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
509     return evolution_fn;
510 
511   else
512     return chrec_dont_know;
513 }
514 
515 /* Associate CHREC to SCALAR.  */
516 
517 static void
518 set_scalar_evolution (basic_block instantiated_below, tree scalar, tree chrec)
519 {
520   tree *scalar_info;
521 
522   if (TREE_CODE (scalar) != SSA_NAME)
523     return;
524 
525   scalar_info = find_var_scev_info (instantiated_below, scalar);
526 
527   if (dump_file)
528     {
529       if (dump_flags & TDF_SCEV)
530 	{
531 	  fprintf (dump_file, "(set_scalar_evolution \n");
532 	  fprintf (dump_file, "  instantiated_below = %d \n",
533 		   instantiated_below->index);
534 	  fprintf (dump_file, "  (scalar = ");
535 	  print_generic_expr (dump_file, scalar, 0);
536 	  fprintf (dump_file, ")\n  (scalar_evolution = ");
537 	  print_generic_expr (dump_file, chrec, 0);
538 	  fprintf (dump_file, "))\n");
539 	}
540       if (dump_flags & TDF_STATS)
541 	nb_set_scev++;
542     }
543 
544   *scalar_info = chrec;
545 }
546 
547 /* Retrieve the chrec associated to SCALAR instantiated below
548    INSTANTIATED_BELOW block.  */
549 
550 static tree
551 get_scalar_evolution (basic_block instantiated_below, tree scalar)
552 {
553   tree res;
554 
555   if (dump_file)
556     {
557       if (dump_flags & TDF_SCEV)
558 	{
559 	  fprintf (dump_file, "(get_scalar_evolution \n");
560 	  fprintf (dump_file, "  (scalar = ");
561 	  print_generic_expr (dump_file, scalar, 0);
562 	  fprintf (dump_file, ")\n");
563 	}
564       if (dump_flags & TDF_STATS)
565 	nb_get_scev++;
566     }
567 
568   switch (TREE_CODE (scalar))
569     {
570     case SSA_NAME:
571       res = *find_var_scev_info (instantiated_below, scalar);
572       break;
573 
574     case REAL_CST:
575     case FIXED_CST:
576     case INTEGER_CST:
577       res = scalar;
578       break;
579 
580     default:
581       res = chrec_not_analyzed_yet;
582       break;
583     }
584 
585   if (dump_file && (dump_flags & TDF_SCEV))
586     {
587       fprintf (dump_file, "  (scalar_evolution = ");
588       print_generic_expr (dump_file, res, 0);
589       fprintf (dump_file, "))\n");
590     }
591 
592   return res;
593 }
594 
595 /* Helper function for add_to_evolution.  Returns the evolution
596    function for an assignment of the form "a = b + c", where "a" and
597    "b" are on the strongly connected component.  CHREC_BEFORE is the
598    information that we already have collected up to this point.
599    TO_ADD is the evolution of "c".
600 
601    When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
602    evolution the expression TO_ADD, otherwise construct an evolution
603    part for this loop.  */
604 
605 static tree
606 add_to_evolution_1 (unsigned loop_nb, tree chrec_before, tree to_add,
607 		    gimple *at_stmt)
608 {
609   tree type, left, right;
610   struct loop *loop = get_loop (cfun, loop_nb), *chloop;
611 
612   switch (TREE_CODE (chrec_before))
613     {
614     case POLYNOMIAL_CHREC:
615       chloop = get_chrec_loop (chrec_before);
616       if (chloop == loop
617 	  || flow_loop_nested_p (chloop, loop))
618 	{
619 	  unsigned var;
620 
621 	  type = chrec_type (chrec_before);
622 
623 	  /* When there is no evolution part in this loop, build it.  */
624 	  if (chloop != loop)
625 	    {
626 	      var = loop_nb;
627 	      left = chrec_before;
628 	      right = SCALAR_FLOAT_TYPE_P (type)
629 		? build_real (type, dconst0)
630 		: build_int_cst (type, 0);
631 	    }
632 	  else
633 	    {
634 	      var = CHREC_VARIABLE (chrec_before);
635 	      left = CHREC_LEFT (chrec_before);
636 	      right = CHREC_RIGHT (chrec_before);
637 	    }
638 
639 	  to_add = chrec_convert (type, to_add, at_stmt);
640 	  right = chrec_convert_rhs (type, right, at_stmt);
641 	  right = chrec_fold_plus (chrec_type (right), right, to_add);
642 	  return build_polynomial_chrec (var, left, right);
643 	}
644       else
645 	{
646 	  gcc_assert (flow_loop_nested_p (loop, chloop));
647 
648 	  /* Search the evolution in LOOP_NB.  */
649 	  left = add_to_evolution_1 (loop_nb, CHREC_LEFT (chrec_before),
650 				     to_add, at_stmt);
651 	  right = CHREC_RIGHT (chrec_before);
652 	  right = chrec_convert_rhs (chrec_type (left), right, at_stmt);
653 	  return build_polynomial_chrec (CHREC_VARIABLE (chrec_before),
654 					 left, right);
655 	}
656 
657     default:
658       /* These nodes do not depend on a loop.  */
659       if (chrec_before == chrec_dont_know)
660 	return chrec_dont_know;
661 
662       left = chrec_before;
663       right = chrec_convert_rhs (chrec_type (left), to_add, at_stmt);
664       return build_polynomial_chrec (loop_nb, left, right);
665     }
666 }
667 
668 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
669    of LOOP_NB.
670 
671    Description (provided for completeness, for those who read code in
672    a plane, and for my poor 62 bytes brain that would have forgotten
673    all this in the next two or three months):
674 
675    The algorithm of translation of programs from the SSA representation
676    into the chrecs syntax is based on a pattern matching.  After having
677    reconstructed the overall tree expression for a loop, there are only
678    two cases that can arise:
679 
680    1. a = loop-phi (init, a + expr)
681    2. a = loop-phi (init, expr)
682 
683    where EXPR is either a scalar constant with respect to the analyzed
684    loop (this is a degree 0 polynomial), or an expression containing
685    other loop-phi definitions (these are higher degree polynomials).
686 
687    Examples:
688 
689    1.
690    | init = ...
691    | loop_1
692    |   a = phi (init, a + 5)
693    | endloop
694 
695    2.
696    | inita = ...
697    | initb = ...
698    | loop_1
699    |   a = phi (inita, 2 * b + 3)
700    |   b = phi (initb, b + 1)
701    | endloop
702 
703    For the first case, the semantics of the SSA representation is:
704 
705    | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
706 
707    that is, there is a loop index "x" that determines the scalar value
708    of the variable during the loop execution.  During the first
709    iteration, the value is that of the initial condition INIT, while
710    during the subsequent iterations, it is the sum of the initial
711    condition with the sum of all the values of EXPR from the initial
712    iteration to the before last considered iteration.
713 
714    For the second case, the semantics of the SSA program is:
715 
716    | a (x) = init, if x = 0;
717    |         expr (x - 1), otherwise.
718 
719    The second case corresponds to the PEELED_CHREC, whose syntax is
720    close to the syntax of a loop-phi-node:
721 
722    | phi (init, expr)  vs.  (init, expr)_x
723 
724    The proof of the translation algorithm for the first case is a
725    proof by structural induction based on the degree of EXPR.
726 
727    Degree 0:
728    When EXPR is a constant with respect to the analyzed loop, or in
729    other words when EXPR is a polynomial of degree 0, the evolution of
730    the variable A in the loop is an affine function with an initial
731    condition INIT, and a step EXPR.  In order to show this, we start
732    from the semantics of the SSA representation:
733 
734    f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
735 
736    and since "expr (j)" is a constant with respect to "j",
737 
738    f (x) = init + x * expr
739 
740    Finally, based on the semantics of the pure sum chrecs, by
741    identification we get the corresponding chrecs syntax:
742 
743    f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
744    f (x) -> {init, +, expr}_x
745 
746    Higher degree:
747    Suppose that EXPR is a polynomial of degree N with respect to the
748    analyzed loop_x for which we have already determined that it is
749    written under the chrecs syntax:
750 
751    | expr (x)  ->  {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
752 
753    We start from the semantics of the SSA program:
754 
755    | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
756    |
757    | f (x) = init + \sum_{j = 0}^{x - 1}
758    |                (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
759    |
760    | f (x) = init + \sum_{j = 0}^{x - 1}
761    |                \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
762    |
763    | f (x) = init + \sum_{k = 0}^{n - 1}
764    |                (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
765    |
766    | f (x) = init + \sum_{k = 0}^{n - 1}
767    |                (b_k * \binom{x}{k + 1})
768    |
769    | f (x) = init + b_0 * \binom{x}{1} + ...
770    |              + b_{n-1} * \binom{x}{n}
771    |
772    | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
773    |                             + b_{n-1} * \binom{x}{n}
774    |
775 
776    And finally from the definition of the chrecs syntax, we identify:
777    | f (x)  ->  {init, +, b_0, +, ..., +, b_{n-1}}_x
778 
779    This shows the mechanism that stands behind the add_to_evolution
780    function.  An important point is that the use of symbolic
781    parameters avoids the need of an analysis schedule.
782 
783    Example:
784 
785    | inita = ...
786    | initb = ...
787    | loop_1
788    |   a = phi (inita, a + 2 + b)
789    |   b = phi (initb, b + 1)
790    | endloop
791 
792    When analyzing "a", the algorithm keeps "b" symbolically:
793 
794    | a  ->  {inita, +, 2 + b}_1
795 
796    Then, after instantiation, the analyzer ends on the evolution:
797 
798    | a  ->  {inita, +, 2 + initb, +, 1}_1
799 
800 */
801 
802 static tree
803 add_to_evolution (unsigned loop_nb, tree chrec_before, enum tree_code code,
804 		  tree to_add, gimple *at_stmt)
805 {
806   tree type = chrec_type (to_add);
807   tree res = NULL_TREE;
808 
809   if (to_add == NULL_TREE)
810     return chrec_before;
811 
812   /* TO_ADD is either a scalar, or a parameter.  TO_ADD is not
813      instantiated at this point.  */
814   if (TREE_CODE (to_add) == POLYNOMIAL_CHREC)
815     /* This should not happen.  */
816     return chrec_dont_know;
817 
818   if (dump_file && (dump_flags & TDF_SCEV))
819     {
820       fprintf (dump_file, "(add_to_evolution \n");
821       fprintf (dump_file, "  (loop_nb = %d)\n", loop_nb);
822       fprintf (dump_file, "  (chrec_before = ");
823       print_generic_expr (dump_file, chrec_before, 0);
824       fprintf (dump_file, ")\n  (to_add = ");
825       print_generic_expr (dump_file, to_add, 0);
826       fprintf (dump_file, ")\n");
827     }
828 
829   if (code == MINUS_EXPR)
830     to_add = chrec_fold_multiply (type, to_add, SCALAR_FLOAT_TYPE_P (type)
831 				  ? build_real (type, dconstm1)
832 				  : build_int_cst_type (type, -1));
833 
834   res = add_to_evolution_1 (loop_nb, chrec_before, to_add, at_stmt);
835 
836   if (dump_file && (dump_flags & TDF_SCEV))
837     {
838       fprintf (dump_file, "  (res = ");
839       print_generic_expr (dump_file, res, 0);
840       fprintf (dump_file, "))\n");
841     }
842 
843   return res;
844 }
845 
846 
847 
848 /* This section selects the loops that will be good candidates for the
849    scalar evolution analysis.  For the moment, greedily select all the
850    loop nests we could analyze.  */
851 
852 /* For a loop with a single exit edge, return the COND_EXPR that
853    guards the exit edge.  If the expression is too difficult to
854    analyze, then give up.  */
855 
856 gcond *
857 get_loop_exit_condition (const struct loop *loop)
858 {
859   gcond *res = NULL;
860   edge exit_edge = single_exit (loop);
861 
862   if (dump_file && (dump_flags & TDF_SCEV))
863     fprintf (dump_file, "(get_loop_exit_condition \n  ");
864 
865   if (exit_edge)
866     {
867       gimple *stmt;
868 
869       stmt = last_stmt (exit_edge->src);
870       if (gcond *cond_stmt = safe_dyn_cast <gcond *> (stmt))
871 	res = cond_stmt;
872     }
873 
874   if (dump_file && (dump_flags & TDF_SCEV))
875     {
876       print_gimple_stmt (dump_file, res, 0, 0);
877       fprintf (dump_file, ")\n");
878     }
879 
880   return res;
881 }
882 
883 
884 /* Depth first search algorithm.  */
885 
886 enum t_bool {
887   t_false,
888   t_true,
889   t_dont_know
890 };
891 
892 
893 static t_bool follow_ssa_edge (struct loop *loop, gimple *, gphi *,
894 			       tree *, int);
895 
896 /* Follow the ssa edge into the binary expression RHS0 CODE RHS1.
897    Return true if the strongly connected component has been found.  */
898 
899 static t_bool
900 follow_ssa_edge_binary (struct loop *loop, gimple *at_stmt,
901 			tree type, tree rhs0, enum tree_code code, tree rhs1,
902 			gphi *halting_phi, tree *evolution_of_loop,
903 			int limit)
904 {
905   t_bool res = t_false;
906   tree evol;
907 
908   switch (code)
909     {
910     case POINTER_PLUS_EXPR:
911     case PLUS_EXPR:
912       if (TREE_CODE (rhs0) == SSA_NAME)
913 	{
914 	  if (TREE_CODE (rhs1) == SSA_NAME)
915 	    {
916 	      /* Match an assignment under the form:
917 		 "a = b + c".  */
918 
919 	      /* We want only assignments of form "name + name" contribute to
920 		 LIMIT, as the other cases do not necessarily contribute to
921 		 the complexity of the expression.  */
922 	      limit++;
923 
924 	      evol = *evolution_of_loop;
925 	      evol = add_to_evolution
926 		  (loop->num,
927 		   chrec_convert (type, evol, at_stmt),
928 		   code, rhs1, at_stmt);
929 	      res = follow_ssa_edge
930 		(loop, SSA_NAME_DEF_STMT (rhs0), halting_phi, &evol, limit);
931 	      if (res == t_true)
932 		*evolution_of_loop = evol;
933 	      else if (res == t_false)
934 		{
935 		  *evolution_of_loop = add_to_evolution
936 		      (loop->num,
937 		       chrec_convert (type, *evolution_of_loop, at_stmt),
938 		       code, rhs0, at_stmt);
939 		  res = follow_ssa_edge
940 		    (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
941 		     evolution_of_loop, limit);
942 		  if (res == t_true)
943 		    ;
944 		  else if (res == t_dont_know)
945 		    *evolution_of_loop = chrec_dont_know;
946 		}
947 
948 	      else if (res == t_dont_know)
949 		*evolution_of_loop = chrec_dont_know;
950 	    }
951 
952 	  else
953 	    {
954 	      /* Match an assignment under the form:
955 		 "a = b + ...".  */
956 	      *evolution_of_loop = add_to_evolution
957 		  (loop->num, chrec_convert (type, *evolution_of_loop,
958 					     at_stmt),
959 		   code, rhs1, at_stmt);
960 	      res = follow_ssa_edge
961 		(loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
962 		 evolution_of_loop, limit);
963 	      if (res == t_true)
964 		;
965 	      else if (res == t_dont_know)
966 		*evolution_of_loop = chrec_dont_know;
967 	    }
968 	}
969 
970       else if (TREE_CODE (rhs1) == SSA_NAME)
971 	{
972 	  /* Match an assignment under the form:
973 	     "a = ... + c".  */
974 	  *evolution_of_loop = add_to_evolution
975 	      (loop->num, chrec_convert (type, *evolution_of_loop,
976 					 at_stmt),
977 	       code, rhs0, at_stmt);
978 	  res = follow_ssa_edge
979 	    (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
980 	     evolution_of_loop, limit);
981 	  if (res == t_true)
982 	    ;
983 	  else if (res == t_dont_know)
984 	    *evolution_of_loop = chrec_dont_know;
985 	}
986 
987       else
988 	/* Otherwise, match an assignment under the form:
989 	   "a = ... + ...".  */
990 	/* And there is nothing to do.  */
991 	res = t_false;
992       break;
993 
994     case MINUS_EXPR:
995       /* This case is under the form "opnd0 = rhs0 - rhs1".  */
996       if (TREE_CODE (rhs0) == SSA_NAME)
997 	{
998 	  /* Match an assignment under the form:
999 	     "a = b - ...".  */
1000 
1001 	  /* We want only assignments of form "name - name" contribute to
1002 	     LIMIT, as the other cases do not necessarily contribute to
1003 	     the complexity of the expression.  */
1004 	  if (TREE_CODE (rhs1) == SSA_NAME)
1005 	    limit++;
1006 
1007 	  *evolution_of_loop = add_to_evolution
1008 	      (loop->num, chrec_convert (type, *evolution_of_loop, at_stmt),
1009 	       MINUS_EXPR, rhs1, at_stmt);
1010 	  res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1011 				 evolution_of_loop, limit);
1012 	  if (res == t_true)
1013 	    ;
1014 	  else if (res == t_dont_know)
1015 	    *evolution_of_loop = chrec_dont_know;
1016 	}
1017       else
1018 	/* Otherwise, match an assignment under the form:
1019 	   "a = ... - ...".  */
1020 	/* And there is nothing to do.  */
1021 	res = t_false;
1022       break;
1023 
1024     default:
1025       res = t_false;
1026     }
1027 
1028   return res;
1029 }
1030 
1031 /* Follow the ssa edge into the expression EXPR.
1032    Return true if the strongly connected component has been found.  */
1033 
1034 static t_bool
1035 follow_ssa_edge_expr (struct loop *loop, gimple *at_stmt, tree expr,
1036 		      gphi *halting_phi, tree *evolution_of_loop,
1037 		      int limit)
1038 {
1039   enum tree_code code = TREE_CODE (expr);
1040   tree type = TREE_TYPE (expr), rhs0, rhs1;
1041   t_bool res;
1042 
1043   /* The EXPR is one of the following cases:
1044      - an SSA_NAME,
1045      - an INTEGER_CST,
1046      - a PLUS_EXPR,
1047      - a POINTER_PLUS_EXPR,
1048      - a MINUS_EXPR,
1049      - an ASSERT_EXPR,
1050      - other cases are not yet handled.  */
1051 
1052   switch (code)
1053     {
1054     CASE_CONVERT:
1055       /* This assignment is under the form "a_1 = (cast) rhs.  */
1056       res = follow_ssa_edge_expr (loop, at_stmt, TREE_OPERAND (expr, 0),
1057 				  halting_phi, evolution_of_loop, limit);
1058       *evolution_of_loop = chrec_convert (type, *evolution_of_loop, at_stmt);
1059       break;
1060 
1061     case INTEGER_CST:
1062       /* This assignment is under the form "a_1 = 7".  */
1063       res = t_false;
1064       break;
1065 
1066     case SSA_NAME:
1067       /* This assignment is under the form: "a_1 = b_2".  */
1068       res = follow_ssa_edge
1069 	(loop, SSA_NAME_DEF_STMT (expr), halting_phi, evolution_of_loop, limit);
1070       break;
1071 
1072     case POINTER_PLUS_EXPR:
1073     case PLUS_EXPR:
1074     case MINUS_EXPR:
1075       /* This case is under the form "rhs0 +- rhs1".  */
1076       rhs0 = TREE_OPERAND (expr, 0);
1077       rhs1 = TREE_OPERAND (expr, 1);
1078       type = TREE_TYPE (rhs0);
1079       STRIP_USELESS_TYPE_CONVERSION (rhs0);
1080       STRIP_USELESS_TYPE_CONVERSION (rhs1);
1081       res = follow_ssa_edge_binary (loop, at_stmt, type, rhs0, code, rhs1,
1082 				    halting_phi, evolution_of_loop, limit);
1083       break;
1084 
1085     case ADDR_EXPR:
1086       /* Handle &MEM[ptr + CST] which is equivalent to POINTER_PLUS_EXPR.  */
1087       if (TREE_CODE (TREE_OPERAND (expr, 0)) == MEM_REF)
1088 	{
1089 	  expr = TREE_OPERAND (expr, 0);
1090 	  rhs0 = TREE_OPERAND (expr, 0);
1091 	  rhs1 = TREE_OPERAND (expr, 1);
1092 	  type = TREE_TYPE (rhs0);
1093 	  STRIP_USELESS_TYPE_CONVERSION (rhs0);
1094 	  STRIP_USELESS_TYPE_CONVERSION (rhs1);
1095 	  res = follow_ssa_edge_binary (loop, at_stmt, type,
1096 					rhs0, POINTER_PLUS_EXPR, rhs1,
1097 					halting_phi, evolution_of_loop, limit);
1098 	}
1099       else
1100 	res = t_false;
1101       break;
1102 
1103     case ASSERT_EXPR:
1104       /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1105 	 It must be handled as a copy assignment of the form a_1 = a_2.  */
1106       rhs0 = ASSERT_EXPR_VAR (expr);
1107       if (TREE_CODE (rhs0) == SSA_NAME)
1108 	res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0),
1109 			       halting_phi, evolution_of_loop, limit);
1110       else
1111 	res = t_false;
1112       break;
1113 
1114     default:
1115       res = t_false;
1116       break;
1117     }
1118 
1119   return res;
1120 }
1121 
1122 /* Follow the ssa edge into the right hand side of an assignment STMT.
1123    Return true if the strongly connected component has been found.  */
1124 
1125 static t_bool
1126 follow_ssa_edge_in_rhs (struct loop *loop, gimple *stmt,
1127 			gphi *halting_phi, tree *evolution_of_loop,
1128 			int limit)
1129 {
1130   enum tree_code code = gimple_assign_rhs_code (stmt);
1131   tree type = gimple_expr_type (stmt), rhs1, rhs2;
1132   t_bool res;
1133 
1134   switch (code)
1135     {
1136     CASE_CONVERT:
1137       /* This assignment is under the form "a_1 = (cast) rhs.  */
1138       res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1139 				  halting_phi, evolution_of_loop, limit);
1140       *evolution_of_loop = chrec_convert (type, *evolution_of_loop, stmt);
1141       break;
1142 
1143     case POINTER_PLUS_EXPR:
1144     case PLUS_EXPR:
1145     case MINUS_EXPR:
1146       rhs1 = gimple_assign_rhs1 (stmt);
1147       rhs2 = gimple_assign_rhs2 (stmt);
1148       type = TREE_TYPE (rhs1);
1149       res = follow_ssa_edge_binary (loop, stmt, type, rhs1, code, rhs2,
1150 				    halting_phi, evolution_of_loop, limit);
1151       break;
1152 
1153     default:
1154       if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1155 	res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1156 				    halting_phi, evolution_of_loop, limit);
1157       else
1158 	res = t_false;
1159       break;
1160     }
1161 
1162   return res;
1163 }
1164 
1165 /* Checks whether the I-th argument of a PHI comes from a backedge.  */
1166 
1167 static bool
1168 backedge_phi_arg_p (gphi *phi, int i)
1169 {
1170   const_edge e = gimple_phi_arg_edge (phi, i);
1171 
1172   /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1173      about updating it anywhere, and this should work as well most of the
1174      time.  */
1175   if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1176     return true;
1177 
1178   return false;
1179 }
1180 
1181 /* Helper function for one branch of the condition-phi-node.  Return
1182    true if the strongly connected component has been found following
1183    this path.  */
1184 
1185 static inline t_bool
1186 follow_ssa_edge_in_condition_phi_branch (int i,
1187 					 struct loop *loop,
1188 					 gphi *condition_phi,
1189 					 gphi *halting_phi,
1190 					 tree *evolution_of_branch,
1191 					 tree init_cond, int limit)
1192 {
1193   tree branch = PHI_ARG_DEF (condition_phi, i);
1194   *evolution_of_branch = chrec_dont_know;
1195 
1196   /* Do not follow back edges (they must belong to an irreducible loop, which
1197      we really do not want to worry about).  */
1198   if (backedge_phi_arg_p (condition_phi, i))
1199     return t_false;
1200 
1201   if (TREE_CODE (branch) == SSA_NAME)
1202     {
1203       *evolution_of_branch = init_cond;
1204       return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1205 			      evolution_of_branch, limit);
1206     }
1207 
1208   /* This case occurs when one of the condition branches sets
1209      the variable to a constant: i.e. a phi-node like
1210      "a_2 = PHI <a_7(5), 2(6)>;".
1211 
1212      FIXME:  This case have to be refined correctly:
1213      in some cases it is possible to say something better than
1214      chrec_dont_know, for example using a wrap-around notation.  */
1215   return t_false;
1216 }
1217 
1218 /* This function merges the branches of a condition-phi-node in a
1219    loop.  */
1220 
1221 static t_bool
1222 follow_ssa_edge_in_condition_phi (struct loop *loop,
1223 				  gphi *condition_phi,
1224 				  gphi *halting_phi,
1225 				  tree *evolution_of_loop, int limit)
1226 {
1227   int i, n;
1228   tree init = *evolution_of_loop;
1229   tree evolution_of_branch;
1230   t_bool res = follow_ssa_edge_in_condition_phi_branch (0, loop, condition_phi,
1231 							halting_phi,
1232 							&evolution_of_branch,
1233 							init, limit);
1234   if (res == t_false || res == t_dont_know)
1235     return res;
1236 
1237   *evolution_of_loop = evolution_of_branch;
1238 
1239   n = gimple_phi_num_args (condition_phi);
1240   for (i = 1; i < n; i++)
1241     {
1242       /* Quickly give up when the evolution of one of the branches is
1243 	 not known.  */
1244       if (*evolution_of_loop == chrec_dont_know)
1245 	return t_true;
1246 
1247       /* Increase the limit by the PHI argument number to avoid exponential
1248 	 time and memory complexity.  */
1249       res = follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1250 						     halting_phi,
1251 						     &evolution_of_branch,
1252 						     init, limit + i);
1253       if (res == t_false || res == t_dont_know)
1254 	return res;
1255 
1256       *evolution_of_loop = chrec_merge (*evolution_of_loop,
1257 					evolution_of_branch);
1258     }
1259 
1260   return t_true;
1261 }
1262 
1263 /* Follow an SSA edge in an inner loop.  It computes the overall
1264    effect of the loop, and following the symbolic initial conditions,
1265    it follows the edges in the parent loop.  The inner loop is
1266    considered as a single statement.  */
1267 
1268 static t_bool
1269 follow_ssa_edge_inner_loop_phi (struct loop *outer_loop,
1270 				gphi *loop_phi_node,
1271 				gphi *halting_phi,
1272 				tree *evolution_of_loop, int limit)
1273 {
1274   struct loop *loop = loop_containing_stmt (loop_phi_node);
1275   tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1276 
1277   /* Sometimes, the inner loop is too difficult to analyze, and the
1278      result of the analysis is a symbolic parameter.  */
1279   if (ev == PHI_RESULT (loop_phi_node))
1280     {
1281       t_bool res = t_false;
1282       int i, n = gimple_phi_num_args (loop_phi_node);
1283 
1284       for (i = 0; i < n; i++)
1285 	{
1286 	  tree arg = PHI_ARG_DEF (loop_phi_node, i);
1287 	  basic_block bb;
1288 
1289 	  /* Follow the edges that exit the inner loop.  */
1290 	  bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1291 	  if (!flow_bb_inside_loop_p (loop, bb))
1292 	    res = follow_ssa_edge_expr (outer_loop, loop_phi_node,
1293 					arg, halting_phi,
1294 					evolution_of_loop, limit);
1295 	  if (res == t_true)
1296 	    break;
1297 	}
1298 
1299       /* If the path crosses this loop-phi, give up.  */
1300       if (res == t_true)
1301 	*evolution_of_loop = chrec_dont_know;
1302 
1303       return res;
1304     }
1305 
1306   /* Otherwise, compute the overall effect of the inner loop.  */
1307   ev = compute_overall_effect_of_inner_loop (loop, ev);
1308   return follow_ssa_edge_expr (outer_loop, loop_phi_node, ev, halting_phi,
1309 			       evolution_of_loop, limit);
1310 }
1311 
1312 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1313    path that is analyzed on the return walk.  */
1314 
1315 static t_bool
1316 follow_ssa_edge (struct loop *loop, gimple *def, gphi *halting_phi,
1317 		 tree *evolution_of_loop, int limit)
1318 {
1319   struct loop *def_loop;
1320 
1321   if (gimple_nop_p (def))
1322     return t_false;
1323 
1324   /* Give up if the path is longer than the MAX that we allow.  */
1325   if (limit > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_COMPLEXITY))
1326     return t_dont_know;
1327 
1328   def_loop = loop_containing_stmt (def);
1329 
1330   switch (gimple_code (def))
1331     {
1332     case GIMPLE_PHI:
1333       if (!loop_phi_node_p (def))
1334 	/* DEF is a condition-phi-node.  Follow the branches, and
1335 	   record their evolutions.  Finally, merge the collected
1336 	   information and set the approximation to the main
1337 	   variable.  */
1338 	return follow_ssa_edge_in_condition_phi
1339 	  (loop, as_a <gphi *> (def), halting_phi, evolution_of_loop,
1340 	   limit);
1341 
1342       /* When the analyzed phi is the halting_phi, the
1343 	 depth-first search is over: we have found a path from
1344 	 the halting_phi to itself in the loop.  */
1345       if (def == halting_phi)
1346 	return t_true;
1347 
1348       /* Otherwise, the evolution of the HALTING_PHI depends
1349 	 on the evolution of another loop-phi-node, i.e. the
1350 	 evolution function is a higher degree polynomial.  */
1351       if (def_loop == loop)
1352 	return t_false;
1353 
1354       /* Inner loop.  */
1355       if (flow_loop_nested_p (loop, def_loop))
1356 	return follow_ssa_edge_inner_loop_phi
1357 	  (loop, as_a <gphi *> (def), halting_phi, evolution_of_loop,
1358 	   limit + 1);
1359 
1360       /* Outer loop.  */
1361       return t_false;
1362 
1363     case GIMPLE_ASSIGN:
1364       return follow_ssa_edge_in_rhs (loop, def, halting_phi,
1365 				     evolution_of_loop, limit);
1366 
1367     default:
1368       /* At this level of abstraction, the program is just a set
1369 	 of GIMPLE_ASSIGNs and PHI_NODEs.  In principle there is no
1370 	 other node to be handled.  */
1371       return t_false;
1372     }
1373 }
1374 
1375 
1376 /* Simplify PEELED_CHREC represented by (init_cond, arg) in LOOP.
1377    Handle below case and return the corresponding POLYNOMIAL_CHREC:
1378 
1379    # i_17 = PHI <i_13(5), 0(3)>
1380    # _20 = PHI <_5(5), start_4(D)(3)>
1381    ...
1382    i_13 = i_17 + 1;
1383    _5 = start_4(D) + i_13;
1384 
1385    Though variable _20 appears as a PEELED_CHREC in the form of
1386    (start_4, _5)_LOOP, it's a POLYNOMIAL_CHREC like {start_4, 1}_LOOP.
1387 
1388    See PR41488.  */
1389 
1390 static tree
1391 simplify_peeled_chrec (struct loop *loop, tree arg, tree init_cond)
1392 {
1393   aff_tree aff1, aff2;
1394   tree ev, left, right, type, step_val;
1395   hash_map<tree, name_expansion *> *peeled_chrec_map = NULL;
1396 
1397   ev = instantiate_parameters (loop, analyze_scalar_evolution (loop, arg));
1398   if (ev == NULL_TREE || TREE_CODE (ev) != POLYNOMIAL_CHREC)
1399     return chrec_dont_know;
1400 
1401   left = CHREC_LEFT (ev);
1402   right = CHREC_RIGHT (ev);
1403   type = TREE_TYPE (left);
1404   step_val = chrec_fold_plus (type, init_cond, right);
1405 
1406   /* Transform (init, {left, right}_LOOP)_LOOP to {init, right}_LOOP
1407      if "left" equals to "init + right".  */
1408   if (operand_equal_p (left, step_val, 0))
1409     {
1410       if (dump_file && (dump_flags & TDF_SCEV))
1411 	fprintf (dump_file, "Simplify PEELED_CHREC into POLYNOMIAL_CHREC.\n");
1412 
1413       return build_polynomial_chrec (loop->num, init_cond, right);
1414     }
1415 
1416   /* The affine code only deals with pointer and integer types.  */
1417   if (!POINTER_TYPE_P (type)
1418       && !INTEGRAL_TYPE_P (type))
1419     return chrec_dont_know;
1420 
1421   /* Try harder to check if they are equal.  */
1422   tree_to_aff_combination_expand (left, type, &aff1, &peeled_chrec_map);
1423   tree_to_aff_combination_expand (step_val, type, &aff2, &peeled_chrec_map);
1424   free_affine_expand_cache (&peeled_chrec_map);
1425   aff_combination_scale (&aff2, -1);
1426   aff_combination_add (&aff1, &aff2);
1427 
1428   /* Transform (init, {left, right}_LOOP)_LOOP to {init, right}_LOOP
1429      if "left" equals to "init + right".  */
1430   if (aff_combination_zero_p (&aff1))
1431     {
1432       if (dump_file && (dump_flags & TDF_SCEV))
1433 	fprintf (dump_file, "Simplify PEELED_CHREC into POLYNOMIAL_CHREC.\n");
1434 
1435       return build_polynomial_chrec (loop->num, init_cond, right);
1436     }
1437   return chrec_dont_know;
1438 }
1439 
1440 /* Given a LOOP_PHI_NODE, this function determines the evolution
1441    function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop.  */
1442 
1443 static tree
1444 analyze_evolution_in_loop (gphi *loop_phi_node,
1445 			   tree init_cond)
1446 {
1447   int i, n = gimple_phi_num_args (loop_phi_node);
1448   tree evolution_function = chrec_not_analyzed_yet;
1449   struct loop *loop = loop_containing_stmt (loop_phi_node);
1450   basic_block bb;
1451   static bool simplify_peeled_chrec_p = true;
1452 
1453   if (dump_file && (dump_flags & TDF_SCEV))
1454     {
1455       fprintf (dump_file, "(analyze_evolution_in_loop \n");
1456       fprintf (dump_file, "  (loop_phi_node = ");
1457       print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1458       fprintf (dump_file, ")\n");
1459     }
1460 
1461   for (i = 0; i < n; i++)
1462     {
1463       tree arg = PHI_ARG_DEF (loop_phi_node, i);
1464       gimple *ssa_chain;
1465       tree ev_fn;
1466       t_bool res;
1467 
1468       /* Select the edges that enter the loop body.  */
1469       bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1470       if (!flow_bb_inside_loop_p (loop, bb))
1471 	continue;
1472 
1473       if (TREE_CODE (arg) == SSA_NAME)
1474 	{
1475 	  bool val = false;
1476 
1477 	  ssa_chain = SSA_NAME_DEF_STMT (arg);
1478 
1479 	  /* Pass in the initial condition to the follow edge function.  */
1480 	  ev_fn = init_cond;
1481 	  res = follow_ssa_edge (loop, ssa_chain, loop_phi_node, &ev_fn, 0);
1482 
1483 	  /* If ev_fn has no evolution in the inner loop, and the
1484 	     init_cond is not equal to ev_fn, then we have an
1485 	     ambiguity between two possible values, as we cannot know
1486 	     the number of iterations at this point.  */
1487 	  if (TREE_CODE (ev_fn) != POLYNOMIAL_CHREC
1488 	      && no_evolution_in_loop_p (ev_fn, loop->num, &val) && val
1489 	      && !operand_equal_p (init_cond, ev_fn, 0))
1490 	    ev_fn = chrec_dont_know;
1491 	}
1492       else
1493 	res = t_false;
1494 
1495       /* When it is impossible to go back on the same
1496 	 loop_phi_node by following the ssa edges, the
1497 	 evolution is represented by a peeled chrec, i.e. the
1498 	 first iteration, EV_FN has the value INIT_COND, then
1499 	 all the other iterations it has the value of ARG.
1500 	 For the moment, PEELED_CHREC nodes are not built.  */
1501       if (res != t_true)
1502 	{
1503 	  ev_fn = chrec_dont_know;
1504 	  /* Try to recognize POLYNOMIAL_CHREC which appears in
1505 	     the form of PEELED_CHREC, but guard the process with
1506 	     a bool variable to keep the analyzer from infinite
1507 	     recurrence for real PEELED_RECs.  */
1508 	  if (simplify_peeled_chrec_p && TREE_CODE (arg) == SSA_NAME)
1509 	    {
1510 	      simplify_peeled_chrec_p = false;
1511 	      ev_fn = simplify_peeled_chrec (loop, arg, init_cond);
1512 	      simplify_peeled_chrec_p = true;
1513 	    }
1514 	}
1515 
1516       /* When there are multiple back edges of the loop (which in fact never
1517 	 happens currently, but nevertheless), merge their evolutions.  */
1518       evolution_function = chrec_merge (evolution_function, ev_fn);
1519 
1520       if (evolution_function == chrec_dont_know)
1521 	break;
1522     }
1523 
1524   if (dump_file && (dump_flags & TDF_SCEV))
1525     {
1526       fprintf (dump_file, "  (evolution_function = ");
1527       print_generic_expr (dump_file, evolution_function, 0);
1528       fprintf (dump_file, "))\n");
1529     }
1530 
1531   return evolution_function;
1532 }
1533 
1534 /* Looks to see if VAR is a copy of a constant (via straightforward assignments
1535    or degenerate phi's).  If so, returns the constant; else, returns VAR.  */
1536 
1537 static tree
1538 follow_copies_to_constant (tree var)
1539 {
1540   tree res = var;
1541   while (TREE_CODE (res) == SSA_NAME
1542 	 /* We face not updated SSA form in multiple places and this walk
1543 	    may end up in sibling loops so we have to guard it.  */
1544 	 && !name_registered_for_update_p (res))
1545     {
1546       gimple *def = SSA_NAME_DEF_STMT (res);
1547       if (gphi *phi = dyn_cast <gphi *> (def))
1548 	{
1549 	  if (tree rhs = degenerate_phi_result (phi))
1550 	    res = rhs;
1551 	  else
1552 	    break;
1553 	}
1554       else if (gimple_assign_single_p (def))
1555 	/* Will exit loop if not an SSA_NAME.  */
1556 	res = gimple_assign_rhs1 (def);
1557       else
1558 	break;
1559     }
1560   if (CONSTANT_CLASS_P (res))
1561     return res;
1562   return var;
1563 }
1564 
1565 /* Given a loop-phi-node, return the initial conditions of the
1566    variable on entry of the loop.  When the CCP has propagated
1567    constants into the loop-phi-node, the initial condition is
1568    instantiated, otherwise the initial condition is kept symbolic.
1569    This analyzer does not analyze the evolution outside the current
1570    loop, and leaves this task to the on-demand tree reconstructor.  */
1571 
1572 static tree
1573 analyze_initial_condition (gphi *loop_phi_node)
1574 {
1575   int i, n;
1576   tree init_cond = chrec_not_analyzed_yet;
1577   struct loop *loop = loop_containing_stmt (loop_phi_node);
1578 
1579   if (dump_file && (dump_flags & TDF_SCEV))
1580     {
1581       fprintf (dump_file, "(analyze_initial_condition \n");
1582       fprintf (dump_file, "  (loop_phi_node = \n");
1583       print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1584       fprintf (dump_file, ")\n");
1585     }
1586 
1587   n = gimple_phi_num_args (loop_phi_node);
1588   for (i = 0; i < n; i++)
1589     {
1590       tree branch = PHI_ARG_DEF (loop_phi_node, i);
1591       basic_block bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1592 
1593       /* When the branch is oriented to the loop's body, it does
1594      	 not contribute to the initial condition.  */
1595       if (flow_bb_inside_loop_p (loop, bb))
1596        	continue;
1597 
1598       if (init_cond == chrec_not_analyzed_yet)
1599 	{
1600 	  init_cond = branch;
1601 	  continue;
1602 	}
1603 
1604       if (TREE_CODE (branch) == SSA_NAME)
1605 	{
1606 	  init_cond = chrec_dont_know;
1607       	  break;
1608 	}
1609 
1610       init_cond = chrec_merge (init_cond, branch);
1611     }
1612 
1613   /* Ooops -- a loop without an entry???  */
1614   if (init_cond == chrec_not_analyzed_yet)
1615     init_cond = chrec_dont_know;
1616 
1617   /* We may not have fully constant propagated IL.  Handle degenerate PHIs here
1618      to not miss important early loop unrollings.  */
1619   init_cond = follow_copies_to_constant (init_cond);
1620 
1621   if (dump_file && (dump_flags & TDF_SCEV))
1622     {
1623       fprintf (dump_file, "  (init_cond = ");
1624       print_generic_expr (dump_file, init_cond, 0);
1625       fprintf (dump_file, "))\n");
1626     }
1627 
1628   return init_cond;
1629 }
1630 
1631 /* Analyze the scalar evolution for LOOP_PHI_NODE.  */
1632 
1633 static tree
1634 interpret_loop_phi (struct loop *loop, gphi *loop_phi_node)
1635 {
1636   tree res;
1637   struct loop *phi_loop = loop_containing_stmt (loop_phi_node);
1638   tree init_cond;
1639 
1640   if (phi_loop != loop)
1641     {
1642       struct loop *subloop;
1643       tree evolution_fn = analyze_scalar_evolution
1644 	(phi_loop, PHI_RESULT (loop_phi_node));
1645 
1646       /* Dive one level deeper.  */
1647       subloop = superloop_at_depth (phi_loop, loop_depth (loop) + 1);
1648 
1649       /* Interpret the subloop.  */
1650       res = compute_overall_effect_of_inner_loop (subloop, evolution_fn);
1651       return res;
1652     }
1653 
1654   /* Otherwise really interpret the loop phi.  */
1655   init_cond = analyze_initial_condition (loop_phi_node);
1656   res = analyze_evolution_in_loop (loop_phi_node, init_cond);
1657 
1658   /* Verify we maintained the correct initial condition throughout
1659      possible conversions in the SSA chain.  */
1660   if (res != chrec_dont_know)
1661     {
1662       tree new_init = res;
1663       if (CONVERT_EXPR_P (res)
1664 	  && TREE_CODE (TREE_OPERAND (res, 0)) == POLYNOMIAL_CHREC)
1665 	new_init = fold_convert (TREE_TYPE (res),
1666 				 CHREC_LEFT (TREE_OPERAND (res, 0)));
1667       else if (TREE_CODE (res) == POLYNOMIAL_CHREC)
1668 	new_init = CHREC_LEFT (res);
1669       STRIP_USELESS_TYPE_CONVERSION (new_init);
1670       if (TREE_CODE (new_init) == POLYNOMIAL_CHREC
1671 	  || !operand_equal_p (init_cond, new_init, 0))
1672 	return chrec_dont_know;
1673     }
1674 
1675   return res;
1676 }
1677 
1678 /* This function merges the branches of a condition-phi-node,
1679    contained in the outermost loop, and whose arguments are already
1680    analyzed.  */
1681 
1682 static tree
1683 interpret_condition_phi (struct loop *loop, gphi *condition_phi)
1684 {
1685   int i, n = gimple_phi_num_args (condition_phi);
1686   tree res = chrec_not_analyzed_yet;
1687 
1688   for (i = 0; i < n; i++)
1689     {
1690       tree branch_chrec;
1691 
1692       if (backedge_phi_arg_p (condition_phi, i))
1693 	{
1694 	  res = chrec_dont_know;
1695 	  break;
1696 	}
1697 
1698       branch_chrec = analyze_scalar_evolution
1699 	(loop, PHI_ARG_DEF (condition_phi, i));
1700 
1701       res = chrec_merge (res, branch_chrec);
1702       if (res == chrec_dont_know)
1703 	break;
1704     }
1705 
1706   return res;
1707 }
1708 
1709 /* Interpret the operation RHS1 OP RHS2.  If we didn't
1710    analyze this node before, follow the definitions until ending
1711    either on an analyzed GIMPLE_ASSIGN, or on a loop-phi-node.  On the
1712    return path, this function propagates evolutions (ala constant copy
1713    propagation).  OPND1 is not a GIMPLE expression because we could
1714    analyze the effect of an inner loop: see interpret_loop_phi.  */
1715 
1716 static tree
1717 interpret_rhs_expr (struct loop *loop, gimple *at_stmt,
1718 		    tree type, tree rhs1, enum tree_code code, tree rhs2)
1719 {
1720   tree res, chrec1, chrec2, ctype;
1721   gimple *def;
1722 
1723   if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1724     {
1725       if (is_gimple_min_invariant (rhs1))
1726 	return chrec_convert (type, rhs1, at_stmt);
1727 
1728       if (code == SSA_NAME)
1729 	return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1730 			      at_stmt);
1731 
1732       if (code == ASSERT_EXPR)
1733 	{
1734 	  rhs1 = ASSERT_EXPR_VAR (rhs1);
1735 	  return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1736 				at_stmt);
1737 	}
1738     }
1739 
1740   switch (code)
1741     {
1742     case ADDR_EXPR:
1743       if (TREE_CODE (TREE_OPERAND (rhs1, 0)) == MEM_REF
1744 	  || handled_component_p (TREE_OPERAND (rhs1, 0)))
1745         {
1746 	  machine_mode mode;
1747 	  HOST_WIDE_INT bitsize, bitpos;
1748 	  int unsignedp, reversep;
1749 	  int volatilep = 0;
1750 	  tree base, offset;
1751 	  tree chrec3;
1752 	  tree unitpos;
1753 
1754 	  base = get_inner_reference (TREE_OPERAND (rhs1, 0),
1755 				      &bitsize, &bitpos, &offset, &mode,
1756 				      &unsignedp, &reversep, &volatilep);
1757 
1758 	  if (TREE_CODE (base) == MEM_REF)
1759 	    {
1760 	      rhs2 = TREE_OPERAND (base, 1);
1761 	      rhs1 = TREE_OPERAND (base, 0);
1762 
1763 	      chrec1 = analyze_scalar_evolution (loop, rhs1);
1764 	      chrec2 = analyze_scalar_evolution (loop, rhs2);
1765 	      chrec1 = chrec_convert (type, chrec1, at_stmt);
1766 	      chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1767 	      chrec1 = instantiate_parameters (loop, chrec1);
1768 	      chrec2 = instantiate_parameters (loop, chrec2);
1769 	      res = chrec_fold_plus (type, chrec1, chrec2);
1770 	    }
1771 	  else
1772 	    {
1773 	      chrec1 = analyze_scalar_evolution_for_address_of (loop, base);
1774 	      chrec1 = chrec_convert (type, chrec1, at_stmt);
1775 	      res = chrec1;
1776 	    }
1777 
1778 	  if (offset != NULL_TREE)
1779 	    {
1780 	      chrec2 = analyze_scalar_evolution (loop, offset);
1781 	      chrec2 = chrec_convert (TREE_TYPE (offset), chrec2, at_stmt);
1782 	      chrec2 = instantiate_parameters (loop, chrec2);
1783 	      res = chrec_fold_plus (type, res, chrec2);
1784 	    }
1785 
1786 	  if (bitpos != 0)
1787 	    {
1788 	      gcc_assert ((bitpos % BITS_PER_UNIT) == 0);
1789 
1790 	      unitpos = size_int (bitpos / BITS_PER_UNIT);
1791 	      chrec3 = analyze_scalar_evolution (loop, unitpos);
1792 	      chrec3 = chrec_convert (TREE_TYPE (unitpos), chrec3, at_stmt);
1793 	      chrec3 = instantiate_parameters (loop, chrec3);
1794 	      res = chrec_fold_plus (type, res, chrec3);
1795 	    }
1796         }
1797       else
1798 	res = chrec_dont_know;
1799       break;
1800 
1801     case POINTER_PLUS_EXPR:
1802       chrec1 = analyze_scalar_evolution (loop, rhs1);
1803       chrec2 = analyze_scalar_evolution (loop, rhs2);
1804       chrec1 = chrec_convert (type, chrec1, at_stmt);
1805       chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1806       chrec1 = instantiate_parameters (loop, chrec1);
1807       chrec2 = instantiate_parameters (loop, chrec2);
1808       res = chrec_fold_plus (type, chrec1, chrec2);
1809       break;
1810 
1811     case PLUS_EXPR:
1812       chrec1 = analyze_scalar_evolution (loop, rhs1);
1813       chrec2 = analyze_scalar_evolution (loop, rhs2);
1814       ctype = type;
1815       /* When the stmt is conditionally executed re-write the CHREC
1816          into a form that has well-defined behavior on overflow.  */
1817       if (at_stmt
1818 	  && INTEGRAL_TYPE_P (type)
1819 	  && ! TYPE_OVERFLOW_WRAPS (type)
1820 	  && ! dominated_by_p (CDI_DOMINATORS, loop->latch,
1821 			       gimple_bb (at_stmt)))
1822 	ctype = unsigned_type_for (type);
1823       chrec1 = chrec_convert (ctype, chrec1, at_stmt);
1824       chrec2 = chrec_convert (ctype, chrec2, at_stmt);
1825       chrec1 = instantiate_parameters (loop, chrec1);
1826       chrec2 = instantiate_parameters (loop, chrec2);
1827       res = chrec_fold_plus (ctype, chrec1, chrec2);
1828       if (type != ctype)
1829 	res = chrec_convert (type, res, at_stmt);
1830       break;
1831 
1832     case MINUS_EXPR:
1833       chrec1 = analyze_scalar_evolution (loop, rhs1);
1834       chrec2 = analyze_scalar_evolution (loop, rhs2);
1835       ctype = type;
1836       /* When the stmt is conditionally executed re-write the CHREC
1837          into a form that has well-defined behavior on overflow.  */
1838       if (at_stmt
1839 	  && INTEGRAL_TYPE_P (type)
1840 	  && ! TYPE_OVERFLOW_WRAPS (type)
1841 	  && ! dominated_by_p (CDI_DOMINATORS,
1842 			       loop->latch, gimple_bb (at_stmt)))
1843 	ctype = unsigned_type_for (type);
1844       chrec1 = chrec_convert (ctype, chrec1, at_stmt);
1845       chrec2 = chrec_convert (ctype, chrec2, at_stmt);
1846       chrec1 = instantiate_parameters (loop, chrec1);
1847       chrec2 = instantiate_parameters (loop, chrec2);
1848       res = chrec_fold_minus (ctype, chrec1, chrec2);
1849       if (type != ctype)
1850 	res = chrec_convert (type, res, at_stmt);
1851       break;
1852 
1853     case NEGATE_EXPR:
1854       chrec1 = analyze_scalar_evolution (loop, rhs1);
1855       ctype = type;
1856       /* When the stmt is conditionally executed re-write the CHREC
1857          into a form that has well-defined behavior on overflow.  */
1858       if (at_stmt
1859 	  && INTEGRAL_TYPE_P (type)
1860 	  && ! TYPE_OVERFLOW_WRAPS (type)
1861 	  && ! dominated_by_p (CDI_DOMINATORS,
1862 			       loop->latch, gimple_bb (at_stmt)))
1863 	ctype = unsigned_type_for (type);
1864       chrec1 = chrec_convert (ctype, chrec1, at_stmt);
1865       /* TYPE may be integer, real or complex, so use fold_convert.  */
1866       chrec1 = instantiate_parameters (loop, chrec1);
1867       res = chrec_fold_multiply (ctype, chrec1,
1868 				 fold_convert (ctype, integer_minus_one_node));
1869       if (type != ctype)
1870 	res = chrec_convert (type, res, at_stmt);
1871       break;
1872 
1873     case BIT_NOT_EXPR:
1874       /* Handle ~X as -1 - X.  */
1875       chrec1 = analyze_scalar_evolution (loop, rhs1);
1876       chrec1 = chrec_convert (type, chrec1, at_stmt);
1877       chrec1 = instantiate_parameters (loop, chrec1);
1878       res = chrec_fold_minus (type,
1879 			      fold_convert (type, integer_minus_one_node),
1880 			      chrec1);
1881       break;
1882 
1883     case MULT_EXPR:
1884       chrec1 = analyze_scalar_evolution (loop, rhs1);
1885       chrec2 = analyze_scalar_evolution (loop, rhs2);
1886       ctype = type;
1887       /* When the stmt is conditionally executed re-write the CHREC
1888          into a form that has well-defined behavior on overflow.  */
1889       if (at_stmt
1890 	  && INTEGRAL_TYPE_P (type)
1891 	  && ! TYPE_OVERFLOW_WRAPS (type)
1892 	  && ! dominated_by_p (CDI_DOMINATORS,
1893 			       loop->latch, gimple_bb (at_stmt)))
1894 	ctype = unsigned_type_for (type);
1895       chrec1 = chrec_convert (ctype, chrec1, at_stmt);
1896       chrec2 = chrec_convert (ctype, chrec2, at_stmt);
1897       chrec1 = instantiate_parameters (loop, chrec1);
1898       chrec2 = instantiate_parameters (loop, chrec2);
1899       res = chrec_fold_multiply (ctype, chrec1, chrec2);
1900       if (type != ctype)
1901 	res = chrec_convert (type, res, at_stmt);
1902       break;
1903 
1904     case LSHIFT_EXPR:
1905       {
1906 	/* Handle A<<B as A * (1<<B).  */
1907 	tree uns = unsigned_type_for (type);
1908 	chrec1 = analyze_scalar_evolution (loop, rhs1);
1909 	chrec2 = analyze_scalar_evolution (loop, rhs2);
1910 	chrec1 = chrec_convert (uns, chrec1, at_stmt);
1911 	chrec1 = instantiate_parameters (loop, chrec1);
1912 	chrec2 = instantiate_parameters (loop, chrec2);
1913 
1914 	tree one = build_int_cst (uns, 1);
1915 	chrec2 = fold_build2 (LSHIFT_EXPR, uns, one, chrec2);
1916 	res = chrec_fold_multiply (uns, chrec1, chrec2);
1917 	res = chrec_convert (type, res, at_stmt);
1918       }
1919       break;
1920 
1921     CASE_CONVERT:
1922       /* In case we have a truncation of a widened operation that in
1923          the truncated type has undefined overflow behavior analyze
1924 	 the operation done in an unsigned type of the same precision
1925 	 as the final truncation.  We cannot derive a scalar evolution
1926 	 for the widened operation but for the truncated result.  */
1927       if (TREE_CODE (type) == INTEGER_TYPE
1928 	  && TREE_CODE (TREE_TYPE (rhs1)) == INTEGER_TYPE
1929 	  && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (rhs1))
1930 	  && TYPE_OVERFLOW_UNDEFINED (type)
1931 	  && TREE_CODE (rhs1) == SSA_NAME
1932 	  && (def = SSA_NAME_DEF_STMT (rhs1))
1933 	  && is_gimple_assign (def)
1934 	  && TREE_CODE_CLASS (gimple_assign_rhs_code (def)) == tcc_binary
1935 	  && TREE_CODE (gimple_assign_rhs2 (def)) == INTEGER_CST)
1936 	{
1937 	  tree utype = unsigned_type_for (type);
1938 	  chrec1 = interpret_rhs_expr (loop, at_stmt, utype,
1939 				       gimple_assign_rhs1 (def),
1940 				       gimple_assign_rhs_code (def),
1941 				       gimple_assign_rhs2 (def));
1942 	}
1943       else
1944 	chrec1 = analyze_scalar_evolution (loop, rhs1);
1945       res = chrec_convert (type, chrec1, at_stmt, true, rhs1);
1946       break;
1947 
1948     case BIT_AND_EXPR:
1949       /* Given int variable A, handle A&0xffff as (int)(unsigned short)A.
1950 	 If A is SCEV and its value is in the range of representable set
1951 	 of type unsigned short, the result expression is a (no-overflow)
1952 	 SCEV.  */
1953       res = chrec_dont_know;
1954       if (tree_fits_uhwi_p (rhs2))
1955 	{
1956 	  int precision;
1957 	  unsigned HOST_WIDE_INT val = tree_to_uhwi (rhs2);
1958 
1959 	  val ++;
1960 	  /* Skip if value of rhs2 wraps in unsigned HOST_WIDE_INT or
1961 	     it's not the maximum value of a smaller type than rhs1.  */
1962 	  if (val != 0
1963 	      && (precision = exact_log2 (val)) > 0
1964 	      && (unsigned) precision < TYPE_PRECISION (TREE_TYPE (rhs1)))
1965 	    {
1966 	      tree utype = build_nonstandard_integer_type (precision, 1);
1967 
1968 	      if (TYPE_PRECISION (utype) < TYPE_PRECISION (TREE_TYPE (rhs1)))
1969 		{
1970 		  chrec1 = analyze_scalar_evolution (loop, rhs1);
1971 		  chrec1 = chrec_convert (utype, chrec1, at_stmt);
1972 		  res = chrec_convert (TREE_TYPE (rhs1), chrec1, at_stmt);
1973 		}
1974 	    }
1975 	}
1976       break;
1977 
1978     default:
1979       res = chrec_dont_know;
1980       break;
1981     }
1982 
1983   return res;
1984 }
1985 
1986 /* Interpret the expression EXPR.  */
1987 
1988 static tree
1989 interpret_expr (struct loop *loop, gimple *at_stmt, tree expr)
1990 {
1991   enum tree_code code;
1992   tree type = TREE_TYPE (expr), op0, op1;
1993 
1994   if (automatically_generated_chrec_p (expr))
1995     return expr;
1996 
1997   if (TREE_CODE (expr) == POLYNOMIAL_CHREC
1998       || get_gimple_rhs_class (TREE_CODE (expr)) == GIMPLE_TERNARY_RHS)
1999     return chrec_dont_know;
2000 
2001   extract_ops_from_tree (expr, &code, &op0, &op1);
2002 
2003   return interpret_rhs_expr (loop, at_stmt, type,
2004 			     op0, code, op1);
2005 }
2006 
2007 /* Interpret the rhs of the assignment STMT.  */
2008 
2009 static tree
2010 interpret_gimple_assign (struct loop *loop, gimple *stmt)
2011 {
2012   tree type = TREE_TYPE (gimple_assign_lhs (stmt));
2013   enum tree_code code = gimple_assign_rhs_code (stmt);
2014 
2015   return interpret_rhs_expr (loop, stmt, type,
2016 			     gimple_assign_rhs1 (stmt), code,
2017 			     gimple_assign_rhs2 (stmt));
2018 }
2019 
2020 
2021 
2022 /* This section contains all the entry points:
2023    - number_of_iterations_in_loop,
2024    - analyze_scalar_evolution,
2025    - instantiate_parameters.
2026 */
2027 
2028 /* Compute and return the evolution function in WRTO_LOOP, the nearest
2029    common ancestor of DEF_LOOP and USE_LOOP.  */
2030 
2031 static tree
2032 compute_scalar_evolution_in_loop (struct loop *wrto_loop,
2033 				  struct loop *def_loop,
2034 				  tree ev)
2035 {
2036   bool val;
2037   tree res;
2038 
2039   if (def_loop == wrto_loop)
2040     return ev;
2041 
2042   def_loop = superloop_at_depth (def_loop, loop_depth (wrto_loop) + 1);
2043   res = compute_overall_effect_of_inner_loop (def_loop, ev);
2044 
2045   if (no_evolution_in_loop_p (res, wrto_loop->num, &val) && val)
2046     return res;
2047 
2048   return analyze_scalar_evolution_1 (wrto_loop, res, chrec_not_analyzed_yet);
2049 }
2050 
2051 /* Helper recursive function.  */
2052 
2053 static tree
2054 analyze_scalar_evolution_1 (struct loop *loop, tree var, tree res)
2055 {
2056   tree type = TREE_TYPE (var);
2057   gimple *def;
2058   basic_block bb;
2059   struct loop *def_loop;
2060 
2061   if (loop == NULL || TREE_CODE (type) == VECTOR_TYPE)
2062     return chrec_dont_know;
2063 
2064   if (TREE_CODE (var) != SSA_NAME)
2065     return interpret_expr (loop, NULL, var);
2066 
2067   def = SSA_NAME_DEF_STMT (var);
2068   bb = gimple_bb (def);
2069   def_loop = bb ? bb->loop_father : NULL;
2070 
2071   if (bb == NULL
2072       || !flow_bb_inside_loop_p (loop, bb))
2073     {
2074       /* Keep symbolic form, but look through obvious copies for constants.  */
2075       res = follow_copies_to_constant (var);
2076       goto set_and_end;
2077     }
2078 
2079   if (res != chrec_not_analyzed_yet)
2080     {
2081       if (loop != bb->loop_father)
2082 	res = compute_scalar_evolution_in_loop
2083 	    (find_common_loop (loop, bb->loop_father), bb->loop_father, res);
2084 
2085       goto set_and_end;
2086     }
2087 
2088   if (loop != def_loop)
2089     {
2090       res = analyze_scalar_evolution_1 (def_loop, var, chrec_not_analyzed_yet);
2091       res = compute_scalar_evolution_in_loop (loop, def_loop, res);
2092 
2093       goto set_and_end;
2094     }
2095 
2096   switch (gimple_code (def))
2097     {
2098     case GIMPLE_ASSIGN:
2099       res = interpret_gimple_assign (loop, def);
2100       break;
2101 
2102     case GIMPLE_PHI:
2103       if (loop_phi_node_p (def))
2104 	res = interpret_loop_phi (loop, as_a <gphi *> (def));
2105       else
2106 	res = interpret_condition_phi (loop, as_a <gphi *> (def));
2107       break;
2108 
2109     default:
2110       res = chrec_dont_know;
2111       break;
2112     }
2113 
2114  set_and_end:
2115 
2116   /* Keep the symbolic form.  */
2117   if (res == chrec_dont_know)
2118     res = var;
2119 
2120   if (loop == def_loop)
2121     set_scalar_evolution (block_before_loop (loop), var, res);
2122 
2123   return res;
2124 }
2125 
2126 /* Analyzes and returns the scalar evolution of the ssa_name VAR in
2127    LOOP.  LOOP is the loop in which the variable is used.
2128 
2129    Example of use: having a pointer VAR to a SSA_NAME node, STMT a
2130    pointer to the statement that uses this variable, in order to
2131    determine the evolution function of the variable, use the following
2132    calls:
2133 
2134    loop_p loop = loop_containing_stmt (stmt);
2135    tree chrec_with_symbols = analyze_scalar_evolution (loop, var);
2136    tree chrec_instantiated = instantiate_parameters (loop, chrec_with_symbols);
2137 */
2138 
2139 tree
2140 analyze_scalar_evolution (struct loop *loop, tree var)
2141 {
2142   tree res;
2143 
2144   if (dump_file && (dump_flags & TDF_SCEV))
2145     {
2146       fprintf (dump_file, "(analyze_scalar_evolution \n");
2147       fprintf (dump_file, "  (loop_nb = %d)\n", loop->num);
2148       fprintf (dump_file, "  (scalar = ");
2149       print_generic_expr (dump_file, var, 0);
2150       fprintf (dump_file, ")\n");
2151     }
2152 
2153   res = get_scalar_evolution (block_before_loop (loop), var);
2154   res = analyze_scalar_evolution_1 (loop, var, res);
2155 
2156   if (dump_file && (dump_flags & TDF_SCEV))
2157     fprintf (dump_file, ")\n");
2158 
2159   return res;
2160 }
2161 
2162 /* Analyzes and returns the scalar evolution of VAR address in LOOP.  */
2163 
2164 static tree
2165 analyze_scalar_evolution_for_address_of (struct loop *loop, tree var)
2166 {
2167   return analyze_scalar_evolution (loop, build_fold_addr_expr (var));
2168 }
2169 
2170 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
2171    WRTO_LOOP (which should be a superloop of USE_LOOP)
2172 
2173    FOLDED_CASTS is set to true if resolve_mixers used
2174    chrec_convert_aggressive (TODO -- not really, we are way too conservative
2175    at the moment in order to keep things simple).
2176 
2177    To illustrate the meaning of USE_LOOP and WRTO_LOOP, consider the following
2178    example:
2179 
2180    for (i = 0; i < 100; i++)			-- loop 1
2181      {
2182        for (j = 0; j < 100; j++)		-- loop 2
2183          {
2184 	   k1 = i;
2185 	   k2 = j;
2186 
2187 	   use2 (k1, k2);
2188 
2189 	   for (t = 0; t < 100; t++)		-- loop 3
2190 	     use3 (k1, k2);
2191 
2192 	 }
2193        use1 (k1, k2);
2194      }
2195 
2196    Both k1 and k2 are invariants in loop3, thus
2197      analyze_scalar_evolution_in_loop (loop3, loop3, k1) = k1
2198      analyze_scalar_evolution_in_loop (loop3, loop3, k2) = k2
2199 
2200    As they are invariant, it does not matter whether we consider their
2201    usage in loop 3 or loop 2, hence
2202      analyze_scalar_evolution_in_loop (loop2, loop3, k1) =
2203        analyze_scalar_evolution_in_loop (loop2, loop2, k1) = i
2204      analyze_scalar_evolution_in_loop (loop2, loop3, k2) =
2205        analyze_scalar_evolution_in_loop (loop2, loop2, k2) = [0,+,1]_2
2206 
2207    Similarly for their evolutions with respect to loop 1.  The values of K2
2208    in the use in loop 2 vary independently on loop 1, thus we cannot express
2209    the evolution with respect to loop 1:
2210      analyze_scalar_evolution_in_loop (loop1, loop3, k1) =
2211        analyze_scalar_evolution_in_loop (loop1, loop2, k1) = [0,+,1]_1
2212      analyze_scalar_evolution_in_loop (loop1, loop3, k2) =
2213        analyze_scalar_evolution_in_loop (loop1, loop2, k2) = dont_know
2214 
2215    The value of k2 in the use in loop 1 is known, though:
2216      analyze_scalar_evolution_in_loop (loop1, loop1, k1) = [0,+,1]_1
2217      analyze_scalar_evolution_in_loop (loop1, loop1, k2) = 100
2218    */
2219 
2220 static tree
2221 analyze_scalar_evolution_in_loop (struct loop *wrto_loop, struct loop *use_loop,
2222 				  tree version, bool *folded_casts)
2223 {
2224   bool val = false;
2225   tree ev = version, tmp;
2226 
2227   /* We cannot just do
2228 
2229      tmp = analyze_scalar_evolution (use_loop, version);
2230      ev = resolve_mixers (wrto_loop, tmp, folded_casts);
2231 
2232      as resolve_mixers would query the scalar evolution with respect to
2233      wrto_loop.  For example, in the situation described in the function
2234      comment, suppose that wrto_loop = loop1, use_loop = loop3 and
2235      version = k2.  Then
2236 
2237      analyze_scalar_evolution (use_loop, version) = k2
2238 
2239      and resolve_mixers (loop1, k2, folded_casts) finds that the value of
2240      k2 in loop 1 is 100, which is a wrong result, since we are interested
2241      in the value in loop 3.
2242 
2243      Instead, we need to proceed from use_loop to wrto_loop loop by loop,
2244      each time checking that there is no evolution in the inner loop.  */
2245 
2246   if (folded_casts)
2247     *folded_casts = false;
2248   while (1)
2249     {
2250       tmp = analyze_scalar_evolution (use_loop, ev);
2251       ev = resolve_mixers (use_loop, tmp, folded_casts);
2252 
2253       if (use_loop == wrto_loop)
2254 	return ev;
2255 
2256       /* If the value of the use changes in the inner loop, we cannot express
2257 	 its value in the outer loop (we might try to return interval chrec,
2258 	 but we do not have a user for it anyway)  */
2259       if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
2260 	  || !val)
2261 	return chrec_dont_know;
2262 
2263       use_loop = loop_outer (use_loop);
2264     }
2265 }
2266 
2267 
2268 /* Hashtable helpers for a temporary hash-table used when
2269    instantiating a CHREC or resolving mixers.  For this use
2270    instantiated_below is always the same.  */
2271 
2272 struct instantiate_cache_type
2273 {
2274   htab_t map;
2275   vec<scev_info_str> entries;
2276 
2277   instantiate_cache_type () : map (NULL), entries (vNULL) {}
2278   ~instantiate_cache_type ();
2279   tree get (unsigned slot) { return entries[slot].chrec; }
2280   void set (unsigned slot, tree chrec) { entries[slot].chrec = chrec; }
2281 };
2282 
2283 instantiate_cache_type::~instantiate_cache_type ()
2284 {
2285   if (map != NULL)
2286     {
2287       htab_delete (map);
2288       entries.release ();
2289     }
2290 }
2291 
2292 /* Cache to avoid infinite recursion when instantiating an SSA name.
2293    Live during the outermost instantiate_scev or resolve_mixers call.  */
2294 static instantiate_cache_type *global_cache;
2295 
2296 /* Computes a hash function for database element ELT.  */
2297 
2298 static inline hashval_t
2299 hash_idx_scev_info (const void *elt_)
2300 {
2301   unsigned idx = ((size_t) elt_) - 2;
2302   return scev_info_hasher::hash (&global_cache->entries[idx]);
2303 }
2304 
2305 /* Compares database elements E1 and E2.  */
2306 
2307 static inline int
2308 eq_idx_scev_info (const void *e1, const void *e2)
2309 {
2310   unsigned idx1 = ((size_t) e1) - 2;
2311   return scev_info_hasher::equal (&global_cache->entries[idx1],
2312 				  (const scev_info_str *) e2);
2313 }
2314 
2315 /* Returns from CACHE the slot number of the cached chrec for NAME.  */
2316 
2317 static unsigned
2318 get_instantiated_value_entry (instantiate_cache_type &cache,
2319 			      tree name, basic_block instantiate_below)
2320 {
2321   if (!cache.map)
2322     {
2323       cache.map = htab_create (10, hash_idx_scev_info, eq_idx_scev_info, NULL);
2324       cache.entries.create (10);
2325     }
2326 
2327   scev_info_str e;
2328   e.name_version = SSA_NAME_VERSION (name);
2329   e.instantiated_below = instantiate_below->index;
2330   void **slot = htab_find_slot_with_hash (cache.map, &e,
2331 					  scev_info_hasher::hash (&e), INSERT);
2332   if (!*slot)
2333     {
2334       e.chrec = chrec_not_analyzed_yet;
2335       *slot = (void *)(size_t)(cache.entries.length () + 2);
2336       cache.entries.safe_push (e);
2337     }
2338 
2339   return ((size_t)*slot) - 2;
2340 }
2341 
2342 
2343 /* Return the closed_loop_phi node for VAR.  If there is none, return
2344    NULL_TREE.  */
2345 
2346 static tree
2347 loop_closed_phi_def (tree var)
2348 {
2349   struct loop *loop;
2350   edge exit;
2351   gphi *phi;
2352   gphi_iterator psi;
2353 
2354   if (var == NULL_TREE
2355       || TREE_CODE (var) != SSA_NAME)
2356     return NULL_TREE;
2357 
2358   loop = loop_containing_stmt (SSA_NAME_DEF_STMT (var));
2359   exit = single_exit (loop);
2360   if (!exit)
2361     return NULL_TREE;
2362 
2363   for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
2364     {
2365       phi = psi.phi ();
2366       if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == var)
2367 	return PHI_RESULT (phi);
2368     }
2369 
2370   return NULL_TREE;
2371 }
2372 
2373 static tree instantiate_scev_r (basic_block, struct loop *, struct loop *,
2374 				tree, bool *, int);
2375 
2376 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2377    and EVOLUTION_LOOP, that were left under a symbolic form.
2378 
2379    CHREC is an SSA_NAME to be instantiated.
2380 
2381    CACHE is the cache of already instantiated values.
2382 
2383    Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2384    conversions that may wrap in signed/pointer type are folded, as long
2385    as the value of the chrec is preserved.  If FOLD_CONVERSIONS is NULL
2386    then we don't do such fold.
2387 
2388    SIZE_EXPR is used for computing the size of the expression to be
2389    instantiated, and to stop if it exceeds some limit.  */
2390 
2391 static tree
2392 instantiate_scev_name (basic_block instantiate_below,
2393 		       struct loop *evolution_loop, struct loop *inner_loop,
2394 		       tree chrec,
2395 		       bool *fold_conversions,
2396 		       int size_expr)
2397 {
2398   tree res;
2399   struct loop *def_loop;
2400   basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (chrec));
2401 
2402   /* A parameter (or loop invariant and we do not want to include
2403      evolutions in outer loops), nothing to do.  */
2404   if (!def_bb
2405       || loop_depth (def_bb->loop_father) == 0
2406       || dominated_by_p (CDI_DOMINATORS, instantiate_below, def_bb))
2407     return chrec;
2408 
2409   /* We cache the value of instantiated variable to avoid exponential
2410      time complexity due to reevaluations.  We also store the convenient
2411      value in the cache in order to prevent infinite recursion -- we do
2412      not want to instantiate the SSA_NAME if it is in a mixer
2413      structure.  This is used for avoiding the instantiation of
2414      recursively defined functions, such as:
2415 
2416      | a_2 -> {0, +, 1, +, a_2}_1  */
2417 
2418   unsigned si = get_instantiated_value_entry (*global_cache,
2419 					      chrec, instantiate_below);
2420   if (global_cache->get (si) != chrec_not_analyzed_yet)
2421     return global_cache->get (si);
2422 
2423   /* On recursion return chrec_dont_know.  */
2424   global_cache->set (si, chrec_dont_know);
2425 
2426   def_loop = find_common_loop (evolution_loop, def_bb->loop_father);
2427 
2428   /* If the analysis yields a parametric chrec, instantiate the
2429      result again.  */
2430   res = analyze_scalar_evolution (def_loop, chrec);
2431 
2432   /* Don't instantiate default definitions.  */
2433   if (TREE_CODE (res) == SSA_NAME
2434       && SSA_NAME_IS_DEFAULT_DEF (res))
2435     ;
2436 
2437   /* Don't instantiate loop-closed-ssa phi nodes.  */
2438   else if (TREE_CODE (res) == SSA_NAME
2439 	   && loop_depth (loop_containing_stmt (SSA_NAME_DEF_STMT (res)))
2440 	   > loop_depth (def_loop))
2441     {
2442       if (res == chrec)
2443 	res = loop_closed_phi_def (chrec);
2444       else
2445 	res = chrec;
2446 
2447       /* When there is no loop_closed_phi_def, it means that the
2448 	 variable is not used after the loop: try to still compute the
2449 	 value of the variable when exiting the loop.  */
2450       if (res == NULL_TREE)
2451 	{
2452 	  loop_p loop = loop_containing_stmt (SSA_NAME_DEF_STMT (chrec));
2453 	  res = analyze_scalar_evolution (loop, chrec);
2454 	  res = compute_overall_effect_of_inner_loop (loop, res);
2455 	  res = instantiate_scev_r (instantiate_below, evolution_loop,
2456 				    inner_loop, res,
2457 				    fold_conversions, size_expr);
2458 	}
2459       else if (!dominated_by_p (CDI_DOMINATORS, instantiate_below,
2460 				gimple_bb (SSA_NAME_DEF_STMT (res))))
2461 	res = chrec_dont_know;
2462     }
2463 
2464   else if (res != chrec_dont_know)
2465     {
2466       if (inner_loop
2467 	  && def_bb->loop_father != inner_loop
2468 	  && !flow_loop_nested_p (def_bb->loop_father, inner_loop))
2469 	/* ???  We could try to compute the overall effect of the loop here.  */
2470 	res = chrec_dont_know;
2471       else
2472 	res = instantiate_scev_r (instantiate_below, evolution_loop,
2473 				  inner_loop, res,
2474 				  fold_conversions, size_expr);
2475     }
2476 
2477   /* Store the correct value to the cache.  */
2478   global_cache->set (si, res);
2479   return res;
2480 }
2481 
2482 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2483    and EVOLUTION_LOOP, that were left under a symbolic form.
2484 
2485    CHREC is a polynomial chain of recurrence to be instantiated.
2486 
2487    CACHE is the cache of already instantiated values.
2488 
2489    Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2490    conversions that may wrap in signed/pointer type are folded, as long
2491    as the value of the chrec is preserved.  If FOLD_CONVERSIONS is NULL
2492    then we don't do such fold.
2493 
2494    SIZE_EXPR is used for computing the size of the expression to be
2495    instantiated, and to stop if it exceeds some limit.  */
2496 
2497 static tree
2498 instantiate_scev_poly (basic_block instantiate_below,
2499 		       struct loop *evolution_loop, struct loop *,
2500 		       tree chrec, bool *fold_conversions, int size_expr)
2501 {
2502   tree op1;
2503   tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2504 				 get_chrec_loop (chrec),
2505 				 CHREC_LEFT (chrec), fold_conversions,
2506 				 size_expr);
2507   if (op0 == chrec_dont_know)
2508     return chrec_dont_know;
2509 
2510   op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2511 			    get_chrec_loop (chrec),
2512 			    CHREC_RIGHT (chrec), fold_conversions,
2513 			    size_expr);
2514   if (op1 == chrec_dont_know)
2515     return chrec_dont_know;
2516 
2517   if (CHREC_LEFT (chrec) != op0
2518       || CHREC_RIGHT (chrec) != op1)
2519     {
2520       op1 = chrec_convert_rhs (chrec_type (op0), op1, NULL);
2521       chrec = build_polynomial_chrec (CHREC_VARIABLE (chrec), op0, op1);
2522     }
2523 
2524   return chrec;
2525 }
2526 
2527 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2528    and EVOLUTION_LOOP, that were left under a symbolic form.
2529 
2530    "C0 CODE C1" is a binary expression of type TYPE to be instantiated.
2531 
2532    CACHE is the cache of already instantiated values.
2533 
2534    Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2535    conversions that may wrap in signed/pointer type are folded, as long
2536    as the value of the chrec is preserved.  If FOLD_CONVERSIONS is NULL
2537    then we don't do such fold.
2538 
2539    SIZE_EXPR is used for computing the size of the expression to be
2540    instantiated, and to stop if it exceeds some limit.  */
2541 
2542 static tree
2543 instantiate_scev_binary (basic_block instantiate_below,
2544 			 struct loop *evolution_loop, struct loop *inner_loop,
2545 			 tree chrec, enum tree_code code,
2546 			 tree type, tree c0, tree c1,
2547 			 bool *fold_conversions, int size_expr)
2548 {
2549   tree op1;
2550   tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2551 				 c0, fold_conversions, size_expr);
2552   if (op0 == chrec_dont_know)
2553     return chrec_dont_know;
2554 
2555   op1 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2556 			    c1, fold_conversions, size_expr);
2557   if (op1 == chrec_dont_know)
2558     return chrec_dont_know;
2559 
2560   if (c0 != op0
2561       || c1 != op1)
2562     {
2563       op0 = chrec_convert (type, op0, NULL);
2564       op1 = chrec_convert_rhs (type, op1, NULL);
2565 
2566       switch (code)
2567 	{
2568 	case POINTER_PLUS_EXPR:
2569 	case PLUS_EXPR:
2570 	  return chrec_fold_plus (type, op0, op1);
2571 
2572 	case MINUS_EXPR:
2573 	  return chrec_fold_minus (type, op0, op1);
2574 
2575 	case MULT_EXPR:
2576 	  return chrec_fold_multiply (type, op0, op1);
2577 
2578 	default:
2579 	  gcc_unreachable ();
2580 	}
2581     }
2582 
2583   return chrec ? chrec : fold_build2 (code, type, c0, c1);
2584 }
2585 
2586 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2587    and EVOLUTION_LOOP, that were left under a symbolic form.
2588 
2589    "CHREC" is an array reference to be instantiated.
2590 
2591    CACHE is the cache of already instantiated values.
2592 
2593    Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2594    conversions that may wrap in signed/pointer type are folded, as long
2595    as the value of the chrec is preserved.  If FOLD_CONVERSIONS is NULL
2596    then we don't do such fold.
2597 
2598    SIZE_EXPR is used for computing the size of the expression to be
2599    instantiated, and to stop if it exceeds some limit.  */
2600 
2601 static tree
2602 instantiate_array_ref (basic_block instantiate_below,
2603 		       struct loop *evolution_loop, struct loop *inner_loop,
2604 		       tree chrec, bool *fold_conversions, int size_expr)
2605 {
2606   tree res;
2607   tree index = TREE_OPERAND (chrec, 1);
2608   tree op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2609 				 inner_loop, index,
2610 				 fold_conversions, size_expr);
2611 
2612   if (op1 == chrec_dont_know)
2613     return chrec_dont_know;
2614 
2615   if (chrec && op1 == index)
2616     return chrec;
2617 
2618   res = unshare_expr (chrec);
2619   TREE_OPERAND (res, 1) = op1;
2620   return res;
2621 }
2622 
2623 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2624    and EVOLUTION_LOOP, that were left under a symbolic form.
2625 
2626    "CHREC" that stands for a convert expression "(TYPE) OP" is to be
2627    instantiated.
2628 
2629    CACHE is the cache of already instantiated values.
2630 
2631    Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2632    conversions that may wrap in signed/pointer type are folded, as long
2633    as the value of the chrec is preserved.  If FOLD_CONVERSIONS is NULL
2634    then we don't do such fold.
2635 
2636    SIZE_EXPR is used for computing the size of the expression to be
2637    instantiated, and to stop if it exceeds some limit.  */
2638 
2639 static tree
2640 instantiate_scev_convert (basic_block instantiate_below,
2641 			  struct loop *evolution_loop, struct loop *inner_loop,
2642 			  tree chrec, tree type, tree op,
2643 			  bool *fold_conversions, int size_expr)
2644 {
2645   tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2646 				 inner_loop, op,
2647 				 fold_conversions, size_expr);
2648 
2649   if (op0 == chrec_dont_know)
2650     return chrec_dont_know;
2651 
2652   if (fold_conversions)
2653     {
2654       tree tmp = chrec_convert_aggressive (type, op0, fold_conversions);
2655       if (tmp)
2656 	return tmp;
2657 
2658       /* If we used chrec_convert_aggressive, we can no longer assume that
2659 	 signed chrecs do not overflow, as chrec_convert does, so avoid
2660 	 calling it in that case.  */
2661       if (*fold_conversions)
2662 	{
2663 	  if (chrec && op0 == op)
2664 	    return chrec;
2665 
2666 	  return fold_convert (type, op0);
2667 	}
2668     }
2669 
2670   return chrec_convert (type, op0, NULL);
2671 }
2672 
2673 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2674    and EVOLUTION_LOOP, that were left under a symbolic form.
2675 
2676    CHREC is a BIT_NOT_EXPR or a NEGATE_EXPR expression to be instantiated.
2677    Handle ~X as -1 - X.
2678    Handle -X as -1 * X.
2679 
2680    CACHE is the cache of already instantiated values.
2681 
2682    Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2683    conversions that may wrap in signed/pointer type are folded, as long
2684    as the value of the chrec is preserved.  If FOLD_CONVERSIONS is NULL
2685    then we don't do such fold.
2686 
2687    SIZE_EXPR is used for computing the size of the expression to be
2688    instantiated, and to stop if it exceeds some limit.  */
2689 
2690 static tree
2691 instantiate_scev_not (basic_block instantiate_below,
2692 		      struct loop *evolution_loop, struct loop *inner_loop,
2693 		      tree chrec,
2694 		      enum tree_code code, tree type, tree op,
2695 		      bool *fold_conversions, int size_expr)
2696 {
2697   tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2698 				 inner_loop, op,
2699 				 fold_conversions, size_expr);
2700 
2701   if (op0 == chrec_dont_know)
2702     return chrec_dont_know;
2703 
2704   if (op != op0)
2705     {
2706       op0 = chrec_convert (type, op0, NULL);
2707 
2708       switch (code)
2709 	{
2710 	case BIT_NOT_EXPR:
2711 	  return chrec_fold_minus
2712 	    (type, fold_convert (type, integer_minus_one_node), op0);
2713 
2714 	case NEGATE_EXPR:
2715 	  return chrec_fold_multiply
2716 	    (type, fold_convert (type, integer_minus_one_node), op0);
2717 
2718 	default:
2719 	  gcc_unreachable ();
2720 	}
2721     }
2722 
2723   return chrec ? chrec : fold_build1 (code, type, op0);
2724 }
2725 
2726 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2727    and EVOLUTION_LOOP, that were left under a symbolic form.
2728 
2729    CHREC is an expression with 3 operands to be instantiated.
2730 
2731    CACHE is the cache of already instantiated values.
2732 
2733    Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2734    conversions that may wrap in signed/pointer type are folded, as long
2735    as the value of the chrec is preserved.  If FOLD_CONVERSIONS is NULL
2736    then we don't do such fold.
2737 
2738    SIZE_EXPR is used for computing the size of the expression to be
2739    instantiated, and to stop if it exceeds some limit.  */
2740 
2741 static tree
2742 instantiate_scev_3 (basic_block instantiate_below,
2743 		    struct loop *evolution_loop, struct loop *inner_loop,
2744 		    tree chrec,
2745 		    bool *fold_conversions, int size_expr)
2746 {
2747   tree op1, op2;
2748   tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2749 				 inner_loop, TREE_OPERAND (chrec, 0),
2750 				 fold_conversions, size_expr);
2751   if (op0 == chrec_dont_know)
2752     return chrec_dont_know;
2753 
2754   op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2755 			    inner_loop, TREE_OPERAND (chrec, 1),
2756 			    fold_conversions, size_expr);
2757   if (op1 == chrec_dont_know)
2758     return chrec_dont_know;
2759 
2760   op2 = instantiate_scev_r (instantiate_below, evolution_loop,
2761 			    inner_loop, TREE_OPERAND (chrec, 2),
2762 			    fold_conversions, size_expr);
2763   if (op2 == chrec_dont_know)
2764     return chrec_dont_know;
2765 
2766   if (op0 == TREE_OPERAND (chrec, 0)
2767       && op1 == TREE_OPERAND (chrec, 1)
2768       && op2 == TREE_OPERAND (chrec, 2))
2769     return chrec;
2770 
2771   return fold_build3 (TREE_CODE (chrec),
2772 		      TREE_TYPE (chrec), op0, op1, op2);
2773 }
2774 
2775 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2776    and EVOLUTION_LOOP, that were left under a symbolic form.
2777 
2778    CHREC is an expression with 2 operands to be instantiated.
2779 
2780    CACHE is the cache of already instantiated values.
2781 
2782    Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2783    conversions that may wrap in signed/pointer type are folded, as long
2784    as the value of the chrec is preserved.  If FOLD_CONVERSIONS is NULL
2785    then we don't do such fold.
2786 
2787    SIZE_EXPR is used for computing the size of the expression to be
2788    instantiated, and to stop if it exceeds some limit.  */
2789 
2790 static tree
2791 instantiate_scev_2 (basic_block instantiate_below,
2792 		    struct loop *evolution_loop, struct loop *inner_loop,
2793 		    tree chrec,
2794 		    bool *fold_conversions, int size_expr)
2795 {
2796   tree op1;
2797   tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2798 				 inner_loop, TREE_OPERAND (chrec, 0),
2799 				 fold_conversions, size_expr);
2800   if (op0 == chrec_dont_know)
2801     return chrec_dont_know;
2802 
2803   op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2804 			    inner_loop, TREE_OPERAND (chrec, 1),
2805 			    fold_conversions, size_expr);
2806   if (op1 == chrec_dont_know)
2807     return chrec_dont_know;
2808 
2809   if (op0 == TREE_OPERAND (chrec, 0)
2810       && op1 == TREE_OPERAND (chrec, 1))
2811     return chrec;
2812 
2813   return fold_build2 (TREE_CODE (chrec), TREE_TYPE (chrec), op0, op1);
2814 }
2815 
2816 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2817    and EVOLUTION_LOOP, that were left under a symbolic form.
2818 
2819    CHREC is an expression with 2 operands to be instantiated.
2820 
2821    CACHE is the cache of already instantiated values.
2822 
2823    Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2824    conversions that may wrap in signed/pointer type are folded, as long
2825    as the value of the chrec is preserved.  If FOLD_CONVERSIONS is NULL
2826    then we don't do such fold.
2827 
2828    SIZE_EXPR is used for computing the size of the expression to be
2829    instantiated, and to stop if it exceeds some limit.  */
2830 
2831 static tree
2832 instantiate_scev_1 (basic_block instantiate_below,
2833 		    struct loop *evolution_loop, struct loop *inner_loop,
2834 		    tree chrec,
2835 		    bool *fold_conversions, int size_expr)
2836 {
2837   tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2838 				 inner_loop, TREE_OPERAND (chrec, 0),
2839 				 fold_conversions, size_expr);
2840 
2841   if (op0 == chrec_dont_know)
2842     return chrec_dont_know;
2843 
2844   if (op0 == TREE_OPERAND (chrec, 0))
2845     return chrec;
2846 
2847   return fold_build1 (TREE_CODE (chrec), TREE_TYPE (chrec), op0);
2848 }
2849 
2850 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2851    and EVOLUTION_LOOP, that were left under a symbolic form.
2852 
2853    CHREC is the scalar evolution to instantiate.
2854 
2855    CACHE is the cache of already instantiated values.
2856 
2857    Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2858    conversions that may wrap in signed/pointer type are folded, as long
2859    as the value of the chrec is preserved.  If FOLD_CONVERSIONS is NULL
2860    then we don't do such fold.
2861 
2862    SIZE_EXPR is used for computing the size of the expression to be
2863    instantiated, and to stop if it exceeds some limit.  */
2864 
2865 static tree
2866 instantiate_scev_r (basic_block instantiate_below,
2867 		    struct loop *evolution_loop, struct loop *inner_loop,
2868 		    tree chrec,
2869 		    bool *fold_conversions, int size_expr)
2870 {
2871   /* Give up if the expression is larger than the MAX that we allow.  */
2872   if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
2873     return chrec_dont_know;
2874 
2875   if (chrec == NULL_TREE
2876       || automatically_generated_chrec_p (chrec)
2877       || is_gimple_min_invariant (chrec))
2878     return chrec;
2879 
2880   switch (TREE_CODE (chrec))
2881     {
2882     case SSA_NAME:
2883       return instantiate_scev_name (instantiate_below, evolution_loop,
2884 				    inner_loop, chrec,
2885 				    fold_conversions, size_expr);
2886 
2887     case POLYNOMIAL_CHREC:
2888       return instantiate_scev_poly (instantiate_below, evolution_loop,
2889 				    inner_loop, chrec,
2890 				    fold_conversions, size_expr);
2891 
2892     case POINTER_PLUS_EXPR:
2893     case PLUS_EXPR:
2894     case MINUS_EXPR:
2895     case MULT_EXPR:
2896       return instantiate_scev_binary (instantiate_below, evolution_loop,
2897 				      inner_loop, chrec,
2898 				      TREE_CODE (chrec), chrec_type (chrec),
2899 				      TREE_OPERAND (chrec, 0),
2900 				      TREE_OPERAND (chrec, 1),
2901 				      fold_conversions, size_expr);
2902 
2903     CASE_CONVERT:
2904       return instantiate_scev_convert (instantiate_below, evolution_loop,
2905 				       inner_loop, chrec,
2906 				       TREE_TYPE (chrec), TREE_OPERAND (chrec, 0),
2907 				       fold_conversions, size_expr);
2908 
2909     case NEGATE_EXPR:
2910     case BIT_NOT_EXPR:
2911       return instantiate_scev_not (instantiate_below, evolution_loop,
2912 				   inner_loop, chrec,
2913 				   TREE_CODE (chrec), TREE_TYPE (chrec),
2914 				   TREE_OPERAND (chrec, 0),
2915 				   fold_conversions, size_expr);
2916 
2917     case ADDR_EXPR:
2918     case SCEV_NOT_KNOWN:
2919       return chrec_dont_know;
2920 
2921     case SCEV_KNOWN:
2922       return chrec_known;
2923 
2924     case ARRAY_REF:
2925       return instantiate_array_ref (instantiate_below, evolution_loop,
2926 				    inner_loop, chrec,
2927 				    fold_conversions, size_expr);
2928 
2929     default:
2930       break;
2931     }
2932 
2933   if (VL_EXP_CLASS_P (chrec))
2934     return chrec_dont_know;
2935 
2936   switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
2937     {
2938     case 3:
2939       return instantiate_scev_3 (instantiate_below, evolution_loop,
2940 				 inner_loop, chrec,
2941 				 fold_conversions, size_expr);
2942 
2943     case 2:
2944       return instantiate_scev_2 (instantiate_below, evolution_loop,
2945 				 inner_loop, chrec,
2946 				 fold_conversions, size_expr);
2947 
2948     case 1:
2949       return instantiate_scev_1 (instantiate_below, evolution_loop,
2950 				 inner_loop, chrec,
2951 				 fold_conversions, size_expr);
2952 
2953     case 0:
2954       return chrec;
2955 
2956     default:
2957       break;
2958     }
2959 
2960   /* Too complicated to handle.  */
2961   return chrec_dont_know;
2962 }
2963 
2964 /* Analyze all the parameters of the chrec that were left under a
2965    symbolic form.  INSTANTIATE_BELOW is the basic block that stops the
2966    recursive instantiation of parameters: a parameter is a variable
2967    that is defined in a basic block that dominates INSTANTIATE_BELOW or
2968    a function parameter.  */
2969 
2970 tree
2971 instantiate_scev (basic_block instantiate_below, struct loop *evolution_loop,
2972 		  tree chrec)
2973 {
2974   tree res;
2975 
2976   if (dump_file && (dump_flags & TDF_SCEV))
2977     {
2978       fprintf (dump_file, "(instantiate_scev \n");
2979       fprintf (dump_file, "  (instantiate_below = %d)\n", instantiate_below->index);
2980       fprintf (dump_file, "  (evolution_loop = %d)\n", evolution_loop->num);
2981       fprintf (dump_file, "  (chrec = ");
2982       print_generic_expr (dump_file, chrec, 0);
2983       fprintf (dump_file, ")\n");
2984     }
2985 
2986   bool destr = false;
2987   if (!global_cache)
2988     {
2989       global_cache = new instantiate_cache_type;
2990       destr = true;
2991     }
2992 
2993   res = instantiate_scev_r (instantiate_below, evolution_loop,
2994 			    NULL, chrec, NULL, 0);
2995 
2996   if (destr)
2997     {
2998       delete global_cache;
2999       global_cache = NULL;
3000     }
3001 
3002   if (dump_file && (dump_flags & TDF_SCEV))
3003     {
3004       fprintf (dump_file, "  (res = ");
3005       print_generic_expr (dump_file, res, 0);
3006       fprintf (dump_file, "))\n");
3007     }
3008 
3009   return res;
3010 }
3011 
3012 /* Similar to instantiate_parameters, but does not introduce the
3013    evolutions in outer loops for LOOP invariants in CHREC, and does not
3014    care about causing overflows, as long as they do not affect value
3015    of an expression.  */
3016 
3017 tree
3018 resolve_mixers (struct loop *loop, tree chrec, bool *folded_casts)
3019 {
3020   bool destr = false;
3021   bool fold_conversions = false;
3022   if (!global_cache)
3023     {
3024       global_cache = new instantiate_cache_type;
3025       destr = true;
3026     }
3027 
3028   tree ret = instantiate_scev_r (block_before_loop (loop), loop, NULL,
3029 				 chrec, &fold_conversions, 0);
3030 
3031   if (folded_casts && !*folded_casts)
3032     *folded_casts = fold_conversions;
3033 
3034   if (destr)
3035     {
3036       delete global_cache;
3037       global_cache = NULL;
3038     }
3039 
3040   return ret;
3041 }
3042 
3043 /* Entry point for the analysis of the number of iterations pass.
3044    This function tries to safely approximate the number of iterations
3045    the loop will run.  When this property is not decidable at compile
3046    time, the result is chrec_dont_know.  Otherwise the result is a
3047    scalar or a symbolic parameter.  When the number of iterations may
3048    be equal to zero and the property cannot be determined at compile
3049    time, the result is a COND_EXPR that represents in a symbolic form
3050    the conditions under which the number of iterations is not zero.
3051 
3052    Example of analysis: suppose that the loop has an exit condition:
3053 
3054    "if (b > 49) goto end_loop;"
3055 
3056    and that in a previous analysis we have determined that the
3057    variable 'b' has an evolution function:
3058 
3059    "EF = {23, +, 5}_2".
3060 
3061    When we evaluate the function at the point 5, i.e. the value of the
3062    variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
3063    and EF (6) = 53.  In this case the value of 'b' on exit is '53' and
3064    the loop body has been executed 6 times.  */
3065 
3066 tree
3067 number_of_latch_executions (struct loop *loop)
3068 {
3069   edge exit;
3070   struct tree_niter_desc niter_desc;
3071   tree may_be_zero;
3072   tree res;
3073 
3074   /* Determine whether the number of iterations in loop has already
3075      been computed.  */
3076   res = loop->nb_iterations;
3077   if (res)
3078     return res;
3079 
3080   may_be_zero = NULL_TREE;
3081 
3082   if (dump_file && (dump_flags & TDF_SCEV))
3083     fprintf (dump_file, "(number_of_iterations_in_loop = \n");
3084 
3085   res = chrec_dont_know;
3086   exit = single_exit (loop);
3087 
3088   if (exit && number_of_iterations_exit (loop, exit, &niter_desc, false))
3089     {
3090       may_be_zero = niter_desc.may_be_zero;
3091       res = niter_desc.niter;
3092     }
3093 
3094   if (res == chrec_dont_know
3095       || !may_be_zero
3096       || integer_zerop (may_be_zero))
3097     ;
3098   else if (integer_nonzerop (may_be_zero))
3099     res = build_int_cst (TREE_TYPE (res), 0);
3100 
3101   else if (COMPARISON_CLASS_P (may_be_zero))
3102     res = fold_build3 (COND_EXPR, TREE_TYPE (res), may_be_zero,
3103 		       build_int_cst (TREE_TYPE (res), 0), res);
3104   else
3105     res = chrec_dont_know;
3106 
3107   if (dump_file && (dump_flags & TDF_SCEV))
3108     {
3109       fprintf (dump_file, "  (set_nb_iterations_in_loop = ");
3110       print_generic_expr (dump_file, res, 0);
3111       fprintf (dump_file, "))\n");
3112     }
3113 
3114   loop->nb_iterations = res;
3115   return res;
3116 }
3117 
3118 
3119 /* Counters for the stats.  */
3120 
3121 struct chrec_stats
3122 {
3123   unsigned nb_chrecs;
3124   unsigned nb_affine;
3125   unsigned nb_affine_multivar;
3126   unsigned nb_higher_poly;
3127   unsigned nb_chrec_dont_know;
3128   unsigned nb_undetermined;
3129 };
3130 
3131 /* Reset the counters.  */
3132 
3133 static inline void
3134 reset_chrecs_counters (struct chrec_stats *stats)
3135 {
3136   stats->nb_chrecs = 0;
3137   stats->nb_affine = 0;
3138   stats->nb_affine_multivar = 0;
3139   stats->nb_higher_poly = 0;
3140   stats->nb_chrec_dont_know = 0;
3141   stats->nb_undetermined = 0;
3142 }
3143 
3144 /* Dump the contents of a CHREC_STATS structure.  */
3145 
3146 static void
3147 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
3148 {
3149   fprintf (file, "\n(\n");
3150   fprintf (file, "-----------------------------------------\n");
3151   fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
3152   fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
3153   fprintf (file, "%d\tdegree greater than 2 polynomials\n",
3154 	   stats->nb_higher_poly);
3155   fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
3156   fprintf (file, "-----------------------------------------\n");
3157   fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
3158   fprintf (file, "%d\twith undetermined coefficients\n",
3159 	   stats->nb_undetermined);
3160   fprintf (file, "-----------------------------------------\n");
3161   fprintf (file, "%d\tchrecs in the scev database\n",
3162 	   (int) scalar_evolution_info->elements ());
3163   fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
3164   fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
3165   fprintf (file, "-----------------------------------------\n");
3166   fprintf (file, ")\n\n");
3167 }
3168 
3169 /* Gather statistics about CHREC.  */
3170 
3171 static void
3172 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
3173 {
3174   if (dump_file && (dump_flags & TDF_STATS))
3175     {
3176       fprintf (dump_file, "(classify_chrec ");
3177       print_generic_expr (dump_file, chrec, 0);
3178       fprintf (dump_file, "\n");
3179     }
3180 
3181   stats->nb_chrecs++;
3182 
3183   if (chrec == NULL_TREE)
3184     {
3185       stats->nb_undetermined++;
3186       return;
3187     }
3188 
3189   switch (TREE_CODE (chrec))
3190     {
3191     case POLYNOMIAL_CHREC:
3192       if (evolution_function_is_affine_p (chrec))
3193 	{
3194 	  if (dump_file && (dump_flags & TDF_STATS))
3195 	    fprintf (dump_file, "  affine_univariate\n");
3196 	  stats->nb_affine++;
3197 	}
3198       else if (evolution_function_is_affine_multivariate_p (chrec, 0))
3199 	{
3200 	  if (dump_file && (dump_flags & TDF_STATS))
3201 	    fprintf (dump_file, "  affine_multivariate\n");
3202 	  stats->nb_affine_multivar++;
3203 	}
3204       else
3205 	{
3206 	  if (dump_file && (dump_flags & TDF_STATS))
3207 	    fprintf (dump_file, "  higher_degree_polynomial\n");
3208 	  stats->nb_higher_poly++;
3209 	}
3210 
3211       break;
3212 
3213     default:
3214       break;
3215     }
3216 
3217   if (chrec_contains_undetermined (chrec))
3218     {
3219       if (dump_file && (dump_flags & TDF_STATS))
3220 	fprintf (dump_file, "  undetermined\n");
3221       stats->nb_undetermined++;
3222     }
3223 
3224   if (dump_file && (dump_flags & TDF_STATS))
3225     fprintf (dump_file, ")\n");
3226 }
3227 
3228 /* Classify the chrecs of the whole database.  */
3229 
3230 void
3231 gather_stats_on_scev_database (void)
3232 {
3233   struct chrec_stats stats;
3234 
3235   if (!dump_file)
3236     return;
3237 
3238   reset_chrecs_counters (&stats);
3239 
3240   hash_table<scev_info_hasher>::iterator iter;
3241   scev_info_str *elt;
3242   FOR_EACH_HASH_TABLE_ELEMENT (*scalar_evolution_info, elt, scev_info_str *,
3243 			       iter)
3244     gather_chrec_stats (elt->chrec, &stats);
3245 
3246   dump_chrecs_stats (dump_file, &stats);
3247 }
3248 
3249 
3250 
3251 /* Initializer.  */
3252 
3253 static void
3254 initialize_scalar_evolutions_analyzer (void)
3255 {
3256   /* The elements below are unique.  */
3257   if (chrec_dont_know == NULL_TREE)
3258     {
3259       chrec_not_analyzed_yet = NULL_TREE;
3260       chrec_dont_know = make_node (SCEV_NOT_KNOWN);
3261       chrec_known = make_node (SCEV_KNOWN);
3262       TREE_TYPE (chrec_dont_know) = void_type_node;
3263       TREE_TYPE (chrec_known) = void_type_node;
3264     }
3265 }
3266 
3267 /* Initialize the analysis of scalar evolutions for LOOPS.  */
3268 
3269 void
3270 scev_initialize (void)
3271 {
3272   struct loop *loop;
3273 
3274   scalar_evolution_info = hash_table<scev_info_hasher>::create_ggc (100);
3275 
3276   initialize_scalar_evolutions_analyzer ();
3277 
3278   FOR_EACH_LOOP (loop, 0)
3279     {
3280       loop->nb_iterations = NULL_TREE;
3281     }
3282 }
3283 
3284 /* Return true if SCEV is initialized.  */
3285 
3286 bool
3287 scev_initialized_p (void)
3288 {
3289   return scalar_evolution_info != NULL;
3290 }
3291 
3292 /* Cleans up the information cached by the scalar evolutions analysis
3293    in the hash table.  */
3294 
3295 void
3296 scev_reset_htab (void)
3297 {
3298   if (!scalar_evolution_info)
3299     return;
3300 
3301   scalar_evolution_info->empty ();
3302 }
3303 
3304 /* Cleans up the information cached by the scalar evolutions analysis
3305    in the hash table and in the loop->nb_iterations.  */
3306 
3307 void
3308 scev_reset (void)
3309 {
3310   struct loop *loop;
3311 
3312   scev_reset_htab ();
3313 
3314   FOR_EACH_LOOP (loop, 0)
3315     {
3316       loop->nb_iterations = NULL_TREE;
3317     }
3318 }
3319 
3320 /* Return true if the IV calculation in TYPE can overflow based on the knowledge
3321    of the upper bound on the number of iterations of LOOP, the BASE and STEP
3322    of IV.
3323 
3324    We do not use information whether TYPE can overflow so it is safe to
3325    use this test even for derived IVs not computed every iteration or
3326    hypotetical IVs to be inserted into code.  */
3327 
3328 bool
3329 iv_can_overflow_p (struct loop *loop, tree type, tree base, tree step)
3330 {
3331   widest_int nit;
3332   wide_int base_min, base_max, step_min, step_max, type_min, type_max;
3333   signop sgn = TYPE_SIGN (type);
3334 
3335   if (integer_zerop (step))
3336     return false;
3337 
3338   if (TREE_CODE (base) == INTEGER_CST)
3339     base_min = base_max = base;
3340   else if (TREE_CODE (base) == SSA_NAME
3341 	   && INTEGRAL_TYPE_P (TREE_TYPE (base))
3342 	   && get_range_info (base, &base_min, &base_max) == VR_RANGE)
3343     ;
3344   else
3345     return true;
3346 
3347   if (TREE_CODE (step) == INTEGER_CST)
3348     step_min = step_max = step;
3349   else if (TREE_CODE (step) == SSA_NAME
3350 	   && INTEGRAL_TYPE_P (TREE_TYPE (step))
3351 	   && get_range_info (step, &step_min, &step_max) == VR_RANGE)
3352     ;
3353   else
3354     return true;
3355 
3356   if (!get_max_loop_iterations (loop, &nit))
3357     return true;
3358 
3359   type_min = wi::min_value (type);
3360   type_max = wi::max_value (type);
3361 
3362   /* Just sanity check that we don't see values out of the range of the type.
3363      In this case the arithmetics bellow would overflow.  */
3364   gcc_checking_assert (wi::ge_p (base_min, type_min, sgn)
3365 		       && wi::le_p (base_max, type_max, sgn));
3366 
3367   /* Account the possible increment in the last ieration.  */
3368   bool overflow = false;
3369   nit = wi::add (nit, 1, SIGNED, &overflow);
3370   if (overflow)
3371     return true;
3372 
3373   /* NIT is typeless and can exceed the precision of the type.  In this case
3374      overflow is always possible, because we know STEP is non-zero.  */
3375   if (wi::min_precision (nit, UNSIGNED) > TYPE_PRECISION (type))
3376     return true;
3377   wide_int nit2 = wide_int::from (nit, TYPE_PRECISION (type), UNSIGNED);
3378 
3379   /* If step can be positive, check that nit*step <= type_max-base.
3380      This can be done by unsigned arithmetic and we only need to watch overflow
3381      in the multiplication. The right hand side can always be represented in
3382      the type.  */
3383   if (sgn == UNSIGNED || !wi::neg_p (step_max))
3384     {
3385       bool overflow = false;
3386       if (wi::gtu_p (wi::mul (step_max, nit2, UNSIGNED, &overflow),
3387 		     type_max - base_max)
3388 	  || overflow)
3389 	return true;
3390     }
3391   /* If step can be negative, check that nit*(-step) <= base_min-type_min.  */
3392   if (sgn == SIGNED && wi::neg_p (step_min))
3393     {
3394       bool overflow = false, overflow2 = false;
3395       if (wi::gtu_p (wi::mul (wi::neg (step_min, &overflow2),
3396 		     nit2, UNSIGNED, &overflow),
3397 		     base_min - type_min)
3398 	  || overflow || overflow2)
3399         return true;
3400     }
3401 
3402   return false;
3403 }
3404 
3405 /* Given EV with form of "(type) {inner_base, inner_step}_loop", this
3406    function tries to derive condition under which it can be simplified
3407    into "{(type)inner_base, (type)inner_step}_loop".  The condition is
3408    the maximum number that inner iv can iterate.  */
3409 
3410 static tree
3411 derive_simple_iv_with_niters (tree ev, tree *niters)
3412 {
3413   if (!CONVERT_EXPR_P (ev))
3414     return ev;
3415 
3416   tree inner_ev = TREE_OPERAND (ev, 0);
3417   if (TREE_CODE (inner_ev) != POLYNOMIAL_CHREC)
3418     return ev;
3419 
3420   tree init = CHREC_LEFT (inner_ev);
3421   tree step = CHREC_RIGHT (inner_ev);
3422   if (TREE_CODE (init) != INTEGER_CST
3423       || TREE_CODE (step) != INTEGER_CST || integer_zerop (step))
3424     return ev;
3425 
3426   tree type = TREE_TYPE (ev);
3427   tree inner_type = TREE_TYPE (inner_ev);
3428   if (TYPE_PRECISION (inner_type) >= TYPE_PRECISION (type))
3429     return ev;
3430 
3431   /* Type conversion in "(type) {inner_base, inner_step}_loop" can be
3432      folded only if inner iv won't overflow.  We compute the maximum
3433      number the inner iv can iterate before overflowing and return the
3434      simplified affine iv.  */
3435   tree delta;
3436   init = fold_convert (type, init);
3437   step = fold_convert (type, step);
3438   ev = build_polynomial_chrec (CHREC_VARIABLE (inner_ev), init, step);
3439   if (tree_int_cst_sign_bit (step))
3440     {
3441       tree bound = lower_bound_in_type (inner_type, inner_type);
3442       delta = fold_build2 (MINUS_EXPR, type, init, fold_convert (type, bound));
3443       step = fold_build1 (NEGATE_EXPR, type, step);
3444     }
3445   else
3446     {
3447       tree bound = upper_bound_in_type (inner_type, inner_type);
3448       delta = fold_build2 (MINUS_EXPR, type, fold_convert (type, bound), init);
3449     }
3450   *niters = fold_build2 (FLOOR_DIV_EXPR, type, delta, step);
3451   return ev;
3452 }
3453 
3454 /* Checks whether use of OP in USE_LOOP behaves as a simple affine iv with
3455    respect to WRTO_LOOP and returns its base and step in IV if possible
3456    (see analyze_scalar_evolution_in_loop for more details on USE_LOOP
3457    and WRTO_LOOP).  If ALLOW_NONCONSTANT_STEP is true, we want step to be
3458    invariant in LOOP.  Otherwise we require it to be an integer constant.
3459 
3460    IV->no_overflow is set to true if we are sure the iv cannot overflow (e.g.
3461    because it is computed in signed arithmetics).  Consequently, adding an
3462    induction variable
3463 
3464    for (i = IV->base; ; i += IV->step)
3465 
3466    is only safe if IV->no_overflow is false, or TYPE_OVERFLOW_UNDEFINED is
3467    false for the type of the induction variable, or you can prove that i does
3468    not wrap by some other argument.  Otherwise, this might introduce undefined
3469    behavior, and
3470 
3471    i = iv->base;
3472    for (; ; i = (type) ((unsigned type) i + (unsigned type) iv->step))
3473 
3474    must be used instead.
3475 
3476    When IV_NITERS is not NULL, this function also checks case in which OP
3477    is a conversion of an inner simple iv of below form:
3478 
3479      (outer_type){inner_base, inner_step}_loop.
3480 
3481    If type of inner iv has smaller precision than outer_type, it can't be
3482    folded into {(outer_type)inner_base, (outer_type)inner_step}_loop because
3483    the inner iv could overflow/wrap.  In this case, we derive a condition
3484    under which the inner iv won't overflow/wrap and do the simplification.
3485    The derived condition normally is the maximum number the inner iv can
3486    iterate, and will be stored in IV_NITERS.  This is useful in loop niter
3487    analysis, to derive break conditions when a loop must terminate, when is
3488    infinite.  */
3489 
3490 bool
3491 simple_iv_with_niters (struct loop *wrto_loop, struct loop *use_loop,
3492 		       tree op, affine_iv *iv, tree *iv_niters,
3493 		       bool allow_nonconstant_step)
3494 {
3495   enum tree_code code;
3496   tree type, ev, base, e;
3497   wide_int extreme;
3498   bool folded_casts, overflow;
3499 
3500   iv->base = NULL_TREE;
3501   iv->step = NULL_TREE;
3502   iv->no_overflow = false;
3503 
3504   type = TREE_TYPE (op);
3505   if (!POINTER_TYPE_P (type)
3506       && !INTEGRAL_TYPE_P (type))
3507     return false;
3508 
3509   ev = analyze_scalar_evolution_in_loop (wrto_loop, use_loop, op,
3510 					 &folded_casts);
3511   if (chrec_contains_undetermined (ev)
3512       || chrec_contains_symbols_defined_in_loop (ev, wrto_loop->num))
3513     return false;
3514 
3515   if (tree_does_not_contain_chrecs (ev))
3516     {
3517       iv->base = ev;
3518       iv->step = build_int_cst (TREE_TYPE (ev), 0);
3519       iv->no_overflow = true;
3520       return true;
3521     }
3522 
3523   /* If we can derive valid scalar evolution with assumptions.  */
3524   if (iv_niters && TREE_CODE (ev) != POLYNOMIAL_CHREC)
3525     ev = derive_simple_iv_with_niters (ev, iv_niters);
3526 
3527   if (TREE_CODE (ev) != POLYNOMIAL_CHREC)
3528     return false;
3529 
3530   if (CHREC_VARIABLE (ev) != (unsigned) wrto_loop->num)
3531     return false;
3532 
3533   iv->step = CHREC_RIGHT (ev);
3534   if ((!allow_nonconstant_step && TREE_CODE (iv->step) != INTEGER_CST)
3535       || tree_contains_chrecs (iv->step, NULL))
3536     return false;
3537 
3538   iv->base = CHREC_LEFT (ev);
3539   if (tree_contains_chrecs (iv->base, NULL))
3540     return false;
3541 
3542   iv->no_overflow = !folded_casts && nowrap_type_p (type);
3543 
3544   if (!iv->no_overflow
3545       && !iv_can_overflow_p (wrto_loop, type, iv->base, iv->step))
3546     iv->no_overflow = true;
3547 
3548   /* Try to simplify iv base:
3549 
3550        (signed T) ((unsigned T)base + step) ;; TREE_TYPE (base) == signed T
3551 	 == (signed T)(unsigned T)base + step
3552 	 == base + step
3553 
3554      If we can prove operation (base + step) doesn't overflow or underflow.
3555      Specifically, we try to prove below conditions are satisfied:
3556 
3557 	     base <= UPPER_BOUND (type) - step  ;;step > 0
3558 	     base >= LOWER_BOUND (type) - step  ;;step < 0
3559 
3560      This is done by proving the reverse conditions are false using loop's
3561      initial conditions.
3562 
3563      The is necessary to make loop niter, or iv overflow analysis easier
3564      for below example:
3565 
3566        int foo (int *a, signed char s, signed char l)
3567 	 {
3568 	   signed char i;
3569 	   for (i = s; i < l; i++)
3570 	     a[i] = 0;
3571 	   return 0;
3572 	  }
3573 
3574      Note variable I is firstly converted to type unsigned char, incremented,
3575      then converted back to type signed char.  */
3576 
3577   if (wrto_loop->num != use_loop->num)
3578     return true;
3579 
3580   if (!CONVERT_EXPR_P (iv->base) || TREE_CODE (iv->step) != INTEGER_CST)
3581     return true;
3582 
3583   type = TREE_TYPE (iv->base);
3584   e = TREE_OPERAND (iv->base, 0);
3585   if (TREE_CODE (e) != PLUS_EXPR
3586       || TREE_CODE (TREE_OPERAND (e, 1)) != INTEGER_CST
3587       || !tree_int_cst_equal (iv->step,
3588 			      fold_convert (type, TREE_OPERAND (e, 1))))
3589     return true;
3590   e = TREE_OPERAND (e, 0);
3591   if (!CONVERT_EXPR_P (e))
3592     return true;
3593   base = TREE_OPERAND (e, 0);
3594   if (!useless_type_conversion_p (type, TREE_TYPE (base)))
3595     return true;
3596 
3597   if (tree_int_cst_sign_bit (iv->step))
3598     {
3599       code = LT_EXPR;
3600       extreme = wi::min_value (type);
3601     }
3602   else
3603     {
3604       code = GT_EXPR;
3605       extreme = wi::max_value (type);
3606     }
3607   overflow = false;
3608   extreme = wi::sub (extreme, iv->step, TYPE_SIGN (type), &overflow);
3609   if (overflow)
3610     return true;
3611   e = fold_build2 (code, boolean_type_node, base,
3612 		   wide_int_to_tree (type, extreme));
3613   e = simplify_using_initial_conditions (use_loop, e);
3614   if (!integer_zerop (e))
3615     return true;
3616 
3617   if (POINTER_TYPE_P (TREE_TYPE (base)))
3618     code = POINTER_PLUS_EXPR;
3619   else
3620     code = PLUS_EXPR;
3621 
3622   iv->base = fold_build2 (code, TREE_TYPE (base), base, iv->step);
3623   return true;
3624 }
3625 
3626 /* Like simple_iv_with_niters, but return TRUE when OP behaves as a simple
3627    affine iv unconditionally.  */
3628 
3629 bool
3630 simple_iv (struct loop *wrto_loop, struct loop *use_loop, tree op,
3631 	   affine_iv *iv, bool allow_nonconstant_step)
3632 {
3633   return simple_iv_with_niters (wrto_loop, use_loop, op, iv,
3634 				NULL, allow_nonconstant_step);
3635 }
3636 
3637 /* Finalize the scalar evolution analysis.  */
3638 
3639 void
3640 scev_finalize (void)
3641 {
3642   if (!scalar_evolution_info)
3643     return;
3644   scalar_evolution_info->empty ();
3645   scalar_evolution_info = NULL;
3646 }
3647 
3648 /* Returns true if the expression EXPR is considered to be too expensive
3649    for scev_const_prop.  */
3650 
3651 bool
3652 expression_expensive_p (tree expr)
3653 {
3654   enum tree_code code;
3655 
3656   if (is_gimple_val (expr))
3657     return false;
3658 
3659   code = TREE_CODE (expr);
3660   if (code == TRUNC_DIV_EXPR
3661       || code == CEIL_DIV_EXPR
3662       || code == FLOOR_DIV_EXPR
3663       || code == ROUND_DIV_EXPR
3664       || code == TRUNC_MOD_EXPR
3665       || code == CEIL_MOD_EXPR
3666       || code == FLOOR_MOD_EXPR
3667       || code == ROUND_MOD_EXPR
3668       || code == EXACT_DIV_EXPR)
3669     {
3670       /* Division by power of two is usually cheap, so we allow it.
3671 	 Forbid anything else.  */
3672       if (!integer_pow2p (TREE_OPERAND (expr, 1)))
3673 	return true;
3674     }
3675 
3676   switch (TREE_CODE_CLASS (code))
3677     {
3678     case tcc_binary:
3679     case tcc_comparison:
3680       if (expression_expensive_p (TREE_OPERAND (expr, 1)))
3681 	return true;
3682 
3683       /* Fallthru.  */
3684     case tcc_unary:
3685       return expression_expensive_p (TREE_OPERAND (expr, 0));
3686 
3687     default:
3688       return true;
3689     }
3690 }
3691 
3692 /* Do final value replacement for LOOP.  */
3693 
3694 void
3695 final_value_replacement_loop (struct loop *loop)
3696 {
3697   /* If we do not know exact number of iterations of the loop, we cannot
3698      replace the final value.  */
3699   edge exit = single_exit (loop);
3700   if (!exit)
3701     return;
3702 
3703   tree niter = number_of_latch_executions (loop);
3704   if (niter == chrec_dont_know)
3705     return;
3706 
3707   /* Ensure that it is possible to insert new statements somewhere.  */
3708   if (!single_pred_p (exit->dest))
3709     split_loop_exit_edge (exit);
3710 
3711   /* Set stmt insertion pointer.  All stmts are inserted before this point.  */
3712   gimple_stmt_iterator gsi = gsi_after_labels (exit->dest);
3713 
3714   struct loop *ex_loop
3715     = superloop_at_depth (loop,
3716 			  loop_depth (exit->dest->loop_father) + 1);
3717 
3718   gphi_iterator psi;
3719   for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); )
3720     {
3721       gphi *phi = psi.phi ();
3722       tree rslt = PHI_RESULT (phi);
3723       tree def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
3724       if (virtual_operand_p (def))
3725 	{
3726 	  gsi_next (&psi);
3727 	  continue;
3728 	}
3729 
3730       if (!POINTER_TYPE_P (TREE_TYPE (def))
3731 	  && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
3732 	{
3733 	  gsi_next (&psi);
3734 	  continue;
3735 	}
3736 
3737       bool folded_casts;
3738       def = analyze_scalar_evolution_in_loop (ex_loop, loop, def,
3739 					      &folded_casts);
3740       def = compute_overall_effect_of_inner_loop (ex_loop, def);
3741       if (!tree_does_not_contain_chrecs (def)
3742 	  || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
3743 	  /* Moving the computation from the loop may prolong life range
3744 	     of some ssa names, which may cause problems if they appear
3745 	     on abnormal edges.  */
3746 	  || contains_abnormal_ssa_name_p (def)
3747 	  /* Do not emit expensive expressions.  The rationale is that
3748 	     when someone writes a code like
3749 
3750 	     while (n > 45) n -= 45;
3751 
3752 	     he probably knows that n is not large, and does not want it
3753 	     to be turned into n %= 45.  */
3754 	  || expression_expensive_p (def))
3755 	{
3756 	  if (dump_file && (dump_flags & TDF_DETAILS))
3757 	    {
3758 	      fprintf (dump_file, "not replacing:\n  ");
3759 	      print_gimple_stmt (dump_file, phi, 0, 0);
3760 	      fprintf (dump_file, "\n");
3761 	    }
3762 	  gsi_next (&psi);
3763 	  continue;
3764 	}
3765 
3766       /* Eliminate the PHI node and replace it by a computation outside
3767 	 the loop.  */
3768       if (dump_file)
3769 	{
3770 	  fprintf (dump_file, "\nfinal value replacement:\n  ");
3771 	  print_gimple_stmt (dump_file, phi, 0, 0);
3772 	  fprintf (dump_file, "  with\n  ");
3773 	}
3774       def = unshare_expr (def);
3775       remove_phi_node (&psi, false);
3776 
3777       /* If def's type has undefined overflow and there were folded
3778 	 casts, rewrite all stmts added for def into arithmetics
3779 	 with defined overflow behavior.  */
3780       if (folded_casts && ANY_INTEGRAL_TYPE_P (TREE_TYPE (def))
3781 	  && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (def)))
3782 	{
3783 	  gimple_seq stmts;
3784 	  gimple_stmt_iterator gsi2;
3785 	  def = force_gimple_operand (def, &stmts, true, NULL_TREE);
3786 	  gsi2 = gsi_start (stmts);
3787 	  while (!gsi_end_p (gsi2))
3788 	    {
3789 	      gimple *stmt = gsi_stmt (gsi2);
3790 	      gimple_stmt_iterator gsi3 = gsi2;
3791 	      gsi_next (&gsi2);
3792 	      gsi_remove (&gsi3, false);
3793 	      if (is_gimple_assign (stmt)
3794 		  && arith_code_with_undefined_signed_overflow
3795 		  (gimple_assign_rhs_code (stmt)))
3796 		gsi_insert_seq_before (&gsi,
3797 				       rewrite_to_defined_overflow (stmt),
3798 				       GSI_SAME_STMT);
3799 	      else
3800 		gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
3801 	    }
3802 	}
3803       else
3804 	def = force_gimple_operand_gsi (&gsi, def, false, NULL_TREE,
3805 					true, GSI_SAME_STMT);
3806 
3807       gassign *ass = gimple_build_assign (rslt, def);
3808       gsi_insert_before (&gsi, ass, GSI_SAME_STMT);
3809       if (dump_file)
3810 	{
3811 	  print_gimple_stmt (dump_file, ass, 0, 0);
3812 	  fprintf (dump_file, "\n");
3813 	}
3814     }
3815 }
3816 
3817 /* Replace ssa names for that scev can prove they are constant by the
3818    appropriate constants.  Also perform final value replacement in loops,
3819    in case the replacement expressions are cheap.
3820 
3821    We only consider SSA names defined by phi nodes; rest is left to the
3822    ordinary constant propagation pass.  */
3823 
3824 unsigned int
3825 scev_const_prop (void)
3826 {
3827   basic_block bb;
3828   tree name, type, ev;
3829   gphi *phi;
3830   struct loop *loop;
3831   bitmap ssa_names_to_remove = NULL;
3832   unsigned i;
3833   gphi_iterator psi;
3834 
3835   if (number_of_loops (cfun) <= 1)
3836     return 0;
3837 
3838   FOR_EACH_BB_FN (bb, cfun)
3839     {
3840       loop = bb->loop_father;
3841 
3842       for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
3843 	{
3844 	  phi = psi.phi ();
3845 	  name = PHI_RESULT (phi);
3846 
3847 	  if (virtual_operand_p (name))
3848 	    continue;
3849 
3850 	  type = TREE_TYPE (name);
3851 
3852 	  if (!POINTER_TYPE_P (type)
3853 	      && !INTEGRAL_TYPE_P (type))
3854 	    continue;
3855 
3856 	  ev = resolve_mixers (loop, analyze_scalar_evolution (loop, name),
3857 			       NULL);
3858 	  if (!is_gimple_min_invariant (ev)
3859 	      || !may_propagate_copy (name, ev))
3860 	    continue;
3861 
3862 	  /* Replace the uses of the name.  */
3863 	  if (name != ev)
3864 	    {
3865 	      if (dump_file && (dump_flags & TDF_DETAILS))
3866 		{
3867 		  fprintf (dump_file, "Replacing uses of: ");
3868 		  print_generic_expr (dump_file, name, 0);
3869 		  fprintf (dump_file, " with: ");
3870 		  print_generic_expr (dump_file, ev, 0);
3871 		  fprintf (dump_file, "\n");
3872 		}
3873 	      replace_uses_by (name, ev);
3874 	    }
3875 
3876 	  if (!ssa_names_to_remove)
3877 	    ssa_names_to_remove = BITMAP_ALLOC (NULL);
3878 	  bitmap_set_bit (ssa_names_to_remove, SSA_NAME_VERSION (name));
3879 	}
3880     }
3881 
3882   /* Remove the ssa names that were replaced by constants.  We do not
3883      remove them directly in the previous cycle, since this
3884      invalidates scev cache.  */
3885   if (ssa_names_to_remove)
3886     {
3887       bitmap_iterator bi;
3888 
3889       EXECUTE_IF_SET_IN_BITMAP (ssa_names_to_remove, 0, i, bi)
3890 	{
3891 	  gimple_stmt_iterator psi;
3892 	  name = ssa_name (i);
3893 	  phi = as_a <gphi *> (SSA_NAME_DEF_STMT (name));
3894 
3895 	  gcc_assert (gimple_code (phi) == GIMPLE_PHI);
3896 	  psi = gsi_for_stmt (phi);
3897 	  remove_phi_node (&psi, true);
3898 	}
3899 
3900       BITMAP_FREE (ssa_names_to_remove);
3901       scev_reset ();
3902     }
3903 
3904   /* Now the regular final value replacement.  */
3905   FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
3906     final_value_replacement_loop (loop);
3907 
3908   return 0;
3909 }
3910 
3911 #include "gt-tree-scalar-evolution.h"
3912