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