OSDN Git Service

* fold-const.c (fold): Fold difference of addresses.
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-loop-ivopts.c
1 /* Induction variable optimizations.
2    Copyright (C) 2003 Free Software Foundation, Inc.
3    
4 This file is part of GCC.
5    
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
9 later version.
10    
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15    
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING.  If not, write to the Free
18 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA.  */
20
21 /* This pass tries to find the optimal set of induction variables for the loop.
22    It optimizes just the basic linear induction variables (although adding
23    support for other types should not be too hard).  It includes the
24    optimizations commonly known as strength reduction, induction variable
25    coalescing and induction variable elimination.  It does it in the
26    following steps:
27
28    1) The interesting uses of induction variables are found.  This includes
29
30       -- uses of induction variables in non-linear expressions
31       -- addresses of arrays
32       -- comparisons of induction variables
33
34    2) Candidates for the induction variables are found.  This includes
35
36       -- old induction variables
37       -- the variables defined by expressions derived from the "interesting
38          uses" above
39
40    3) The optimal (w.r. to a cost function) set of variables is chosen.  The
41       cost function assigns a cost to sets of induction variables and consists
42       of three parts:
43
44       -- The use costs.  Each of the interesting uses chooses the best induction
45          variable in the set and adds its cost to the sum.  The cost reflects
46          the time spent on modifying the induction variables value to be usable
47          for the given purpose (adding base and offset for arrays, etc.).
48       -- The variable costs.  Each of the variables has a cost assigned that
49          reflects the costs associated with incrementing the value of the
50          variable.  The original variables are somewhat preferred.
51       -- The set cost.  Depending on the size of the set, extra cost may be
52          added to reflect register pressure.
53
54       All the costs are defined in a machine-specific way, using the target
55       hooks and machine descriptions to determine them.
56
57    4) The trees are transformed to use the new variables, the dead code is
58       removed.
59    
60    All of this is done loop by loop.  Doing it globally is theoretically
61    possible, it might give a better performance and it might enable us
62    to decide costs more precisely, but getting all the interactions right
63    would be complicated.  */
64
65 #include "config.h"
66 #include "system.h"
67 #include "coretypes.h"
68 #include "tm.h"
69 #include "tree.h"
70 #include "rtl.h"
71 #include "tm_p.h"
72 #include "hard-reg-set.h"
73 #include "basic-block.h"
74 #include "output.h"
75 #include "diagnostic.h"
76 #include "tree-flow.h"
77 #include "tree-dump.h"
78 #include "timevar.h"
79 #include "cfgloop.h"
80 #include "varray.h"
81 #include "expr.h"
82 #include "tree-pass.h"
83 #include "ggc.h"
84 #include "insn-config.h"
85 #include "recog.h"
86 #include "hashtab.h"
87 #include "tree-chrec.h"
88 #include "tree-scalar-evolution.h"
89 #include "cfgloop.h"
90 #include "params.h"
91
92 /* The infinite cost.  */
93 #define INFTY 10000000
94
95 /* The expected number of loop iterations.  TODO -- use profiling instead of
96    this.  */
97 #define AVG_LOOP_NITER(LOOP) 5
98
99 /* Just to shorten the ugly names.  */
100 #define EXEC_BINARY nondestructive_fold_binary_to_constant
101 #define EXEC_UNARY nondestructive_fold_unary_to_constant
102
103 /* Representation of the induction variable.  */
104 struct iv
105 {
106   tree base;            /* Initial value of the iv.  */
107   tree step;            /* Step of the iv (constant only).  */
108   tree ssa_name;        /* The ssa name with the value.  */
109   bool biv_p;           /* Is it a biv?  */
110   bool have_use_for;    /* Do we already have a use for it?  */
111   unsigned use_id;      /* The identifier in the use if it is the case.  */
112 };
113
114 /* Per-ssa version information (induction variable descriptions, etc.).  */
115 struct version_info
116 {
117   tree name;            /* The ssa name.  */
118   struct iv *iv;        /* Induction variable description.  */
119   bool has_nonlin_use;  /* For a loop-level invariant, whether it is used in
120                            an expression that is not an induction variable.  */
121   unsigned inv_id;      /* Id of an invariant.  */
122   bool preserve_biv;    /* For the original biv, whether to preserve it.  */
123 };
124
125 /* Information attached to loop.  */
126 struct loop_data
127 {
128   struct tree_niter_desc niter;
129                         /* Number of iterations.  */
130
131   unsigned regs_used;   /* Number of registers used.  */
132 };
133
134 /* Types of uses.  */
135 enum use_type
136 {
137   USE_NONLINEAR_EXPR,   /* Use in a nonlinear expression.  */
138   USE_OUTER,            /* The induction variable is used outside the loop.  */
139   USE_ADDRESS,          /* Use in an address.  */
140   USE_COMPARE           /* Use is a compare.  */
141 };
142
143 /* The candidate - cost pair.  */
144 struct cost_pair
145 {
146   struct iv_cand *cand; /* The candidate.  */
147   unsigned cost;        /* The cost.  */
148   bitmap depends_on;    /* The list of invariants that have to be
149                            preserved.  */
150 };
151
152 /* Use.  */
153 struct iv_use
154 {
155   unsigned id;          /* The id of the use.  */
156   enum use_type type;   /* Type of the use.  */
157   struct iv *iv;        /* The induction variable it is based on.  */
158   tree stmt;            /* Statement in that it occurs.  */
159   tree *op_p;           /* The place where it occurs.  */
160   bitmap related_cands; /* The set of "related" iv candidates.  */
161
162   unsigned n_map_members; /* Number of candidates in the cost_map list.  */
163   struct cost_pair *cost_map;
164                         /* The costs wrto the iv candidates.  */
165
166   struct iv_cand *selected;
167                         /* The selected candidate.  */
168 };
169
170 /* The position where the iv is computed.  */
171 enum iv_position
172 {
173   IP_NORMAL,            /* At the end, just before the exit condition.  */
174   IP_END,               /* At the end of the latch block.  */
175   IP_ORIGINAL           /* The original biv.  */
176 };
177
178 /* The induction variable candidate.  */
179 struct iv_cand
180 {
181   unsigned id;          /* The number of the candidate.  */
182   bool important;       /* Whether this is an "important" candidate, i.e. such
183                            that it should be considered by all uses.  */
184   enum iv_position pos; /* Where it is computed.  */
185   tree incremented_at;  /* For original biv, the statement where it is
186                            incremented.  */
187   tree var_before;      /* The variable used for it before increment.  */
188   tree var_after;       /* The variable used for it after increment.  */
189   struct iv *iv;        /* The value of the candidate.  NULL for
190                            "pseudocandidate" used to indicate the possibility
191                            to replace the final value of an iv by direct
192                            computation of the value.  */
193   unsigned cost;        /* Cost of the candidate.  */
194 };
195
196 /* The data used by the induction variable optimizations.  */
197
198 struct ivopts_data
199 {
200   /* The currently optimized loop.  */
201   struct loop *current_loop;
202
203   /* The size of version_info array allocated.  */
204   unsigned version_info_size;
205
206   /* The array of information for the ssa names.  */
207   struct version_info *version_info;
208
209   /* The bitmap of indices in version_info whose value was changed.  */
210   bitmap relevant;
211
212   /* The maximum invariant id.  */
213   unsigned max_inv_id;
214
215   /* The uses of induction variables.  */
216   varray_type iv_uses;
217
218   /* The candidates.  */
219   varray_type iv_candidates;
220
221   /* Whether to consider just related and important candidates when replacing a
222      use.  */
223   bool consider_all_candidates;
224 };
225
226 /* Bound on number of candidates below that all candidates are considered.  */
227
228 #define CONSIDER_ALL_CANDIDATES_BOUND \
229   ((unsigned) PARAM_VALUE (PARAM_IV_CONSIDER_ALL_CANDIDATES_BOUND))
230
231 /* If there are more iv occurrences, we just give up (it is quite unlikely that
232    optimizing such a loop would help, and it would take ages).  */
233
234 #define MAX_CONSIDERED_USES \
235   ((unsigned) PARAM_VALUE (PARAM_IV_MAX_CONSIDERED_USES))
236
237 /* The list of trees for that the decl_rtl field must be reset is stored
238    here.  */
239
240 static varray_type decl_rtl_to_reset;
241
242 /* Number of uses recorded in DATA.  */
243
244 static inline unsigned
245 n_iv_uses (struct ivopts_data *data)
246 {
247   return VARRAY_ACTIVE_SIZE (data->iv_uses);
248 }
249
250 /* Ith use recorded in DATA.  */
251
252 static inline struct iv_use *
253 iv_use (struct ivopts_data *data, unsigned i)
254 {
255   return VARRAY_GENERIC_PTR_NOGC (data->iv_uses, i);
256 }
257
258 /* Number of candidates recorded in DATA.  */
259
260 static inline unsigned
261 n_iv_cands (struct ivopts_data *data)
262 {
263   return VARRAY_ACTIVE_SIZE (data->iv_candidates);
264 }
265
266 /* Ith candidate recorded in DATA.  */
267
268 static inline struct iv_cand *
269 iv_cand (struct ivopts_data *data, unsigned i)
270 {
271   return VARRAY_GENERIC_PTR_NOGC (data->iv_candidates, i);
272 }
273
274 /* The data for LOOP.  */
275
276 static inline struct loop_data *
277 loop_data (struct loop *loop)
278 {
279   return loop->aux;
280 }
281
282 /* The single loop exit if it dominates the latch, NULL otherwise.  */
283
284 static edge
285 single_dom_exit (struct loop *loop)
286 {
287   edge exit = loop->single_exit;
288
289   if (!exit)
290     return NULL;
291
292   if (!just_once_each_iteration_p (loop, exit->src))
293     return NULL;
294
295   return exit;
296 }
297
298 /* Dumps information about the induction variable IV to FILE.  */
299
300 extern void dump_iv (FILE *, struct iv *);
301 void
302 dump_iv (FILE *file, struct iv *iv)
303 {
304   fprintf (file, "ssa name ");
305   print_generic_expr (file, iv->ssa_name, TDF_SLIM);
306   fprintf (file, "\n");
307
308   fprintf (file, "  type ");
309   print_generic_expr (file, TREE_TYPE (iv->base), TDF_SLIM);
310   fprintf (file, "\n");
311
312   if (iv->step)
313     {
314       fprintf (file, "  base ");
315       print_generic_expr (file, iv->base, TDF_SLIM);
316       fprintf (file, "\n");
317
318       fprintf (file, "  step ");
319       print_generic_expr (file, iv->step, TDF_SLIM);
320       fprintf (file, "\n");
321     }
322   else
323     {
324       fprintf (file, "  invariant ");
325       print_generic_expr (file, iv->base, TDF_SLIM);
326       fprintf (file, "\n");
327     }
328
329   if (iv->biv_p)
330     fprintf (file, "  is a biv\n");
331 }
332
333 /* Dumps information about the USE to FILE.  */
334
335 extern void dump_use (FILE *, struct iv_use *);
336 void
337 dump_use (FILE *file, struct iv_use *use)
338 {
339   struct iv *iv = use->iv;
340
341   fprintf (file, "use %d\n", use->id);
342
343   switch (use->type)
344     {
345     case USE_NONLINEAR_EXPR:
346       fprintf (file, "  generic\n");
347       break;
348
349     case USE_OUTER:
350       fprintf (file, "  outside\n");
351       break;
352
353     case USE_ADDRESS:
354       fprintf (file, "  address\n");
355       break;
356
357     case USE_COMPARE:
358       fprintf (file, "  compare\n");
359       break;
360
361     default:
362       gcc_unreachable ();
363     }
364
365   fprintf (file, "  in statement ");
366   print_generic_expr (file, use->stmt, TDF_SLIM);
367   fprintf (file, "\n");
368
369   fprintf (file, "  at position ");
370   if (use->op_p)
371     print_generic_expr (file, *use->op_p, TDF_SLIM);
372   fprintf (file, "\n");
373
374   fprintf (file, "  type ");
375   print_generic_expr (file, TREE_TYPE (iv->base), TDF_SLIM);
376   fprintf (file, "\n");
377
378   if (iv->step)
379     {
380       fprintf (file, "  base ");
381       print_generic_expr (file, iv->base, TDF_SLIM);
382       fprintf (file, "\n");
383
384       fprintf (file, "  step ");
385       print_generic_expr (file, iv->step, TDF_SLIM);
386       fprintf (file, "\n");
387     }
388   else
389     {
390       fprintf (file, "  invariant ");
391       print_generic_expr (file, iv->base, TDF_SLIM);
392       fprintf (file, "\n");
393     }
394
395   fprintf (file, "  related candidates ");
396   dump_bitmap (file, use->related_cands);
397 }
398
399 /* Dumps information about the uses to FILE.  */
400
401 extern void dump_uses (FILE *, struct ivopts_data *);
402 void
403 dump_uses (FILE *file, struct ivopts_data *data)
404 {
405   unsigned i;
406   struct iv_use *use;
407
408   for (i = 0; i < n_iv_uses (data); i++)
409     {
410       use = iv_use (data, i);
411
412       dump_use (file, use);
413       fprintf (file, "\n");
414     }
415 }
416
417 /* Dumps information about induction variable candidate CAND to FILE.  */
418
419 extern void dump_cand (FILE *, struct iv_cand *);
420 void
421 dump_cand (FILE *file, struct iv_cand *cand)
422 {
423   struct iv *iv = cand->iv;
424
425   fprintf (file, "candidate %d%s\n",
426            cand->id, cand->important ? " (important)" : "");
427
428   if (!iv)
429     {
430       fprintf (file, "  final value replacement\n");
431       return;
432     }
433
434   switch (cand->pos)
435     {
436     case IP_NORMAL:
437       fprintf (file, "  incremented before exit test\n");
438       break;
439
440     case IP_END:
441       fprintf (file, "  incremented at end\n");
442       break;
443
444     case IP_ORIGINAL:
445       fprintf (file, "  original biv\n");
446       break;
447     }
448
449   fprintf (file, "  type ");
450   print_generic_expr (file, TREE_TYPE (iv->base), TDF_SLIM);
451   fprintf (file, "\n");
452
453   if (iv->step)
454     {
455       fprintf (file, "  base ");
456       print_generic_expr (file, iv->base, TDF_SLIM);
457       fprintf (file, "\n");
458
459       fprintf (file, "  step ");
460       print_generic_expr (file, iv->step, TDF_SLIM);
461       fprintf (file, "\n");
462     }
463   else
464     {
465       fprintf (file, "  invariant ");
466       print_generic_expr (file, iv->base, TDF_SLIM);
467       fprintf (file, "\n");
468     }
469 }
470
471 /* Returns the info for ssa version VER.  */
472
473 static inline struct version_info *
474 ver_info (struct ivopts_data *data, unsigned ver)
475 {
476   return data->version_info + ver;
477 }
478
479 /* Returns the info for ssa name NAME.  */
480
481 static inline struct version_info *
482 name_info (struct ivopts_data *data, tree name)
483 {
484   return ver_info (data, SSA_NAME_VERSION (name));
485 }
486
487 /* Checks whether there exists number X such that X * B = A, counting modulo
488    2^BITS.  */
489
490 static bool
491 divide (unsigned bits, unsigned HOST_WIDE_INT a, unsigned HOST_WIDE_INT b,
492         HOST_WIDE_INT *x)
493 {
494   unsigned HOST_WIDE_INT mask = ~(~(unsigned HOST_WIDE_INT) 0 << (bits - 1) << 1);
495   unsigned HOST_WIDE_INT inv, ex, val;
496   unsigned i;
497
498   a &= mask;
499   b &= mask;
500
501   /* First divide the whole equation by 2 as long as possible.  */
502   while (!(a & 1) && !(b & 1))
503     {
504       a >>= 1;
505       b >>= 1;
506       bits--;
507       mask >>= 1;
508     }
509
510   if (!(b & 1))
511     {
512       /* If b is still even, a is odd and there is no such x.  */
513       return false;
514     }
515
516   /* Find the inverse of b.  We compute it as
517      b^(2^(bits - 1) - 1) (mod 2^bits).  */
518   inv = 1;
519   ex = b;
520   for (i = 0; i < bits - 1; i++)
521     {
522       inv = (inv * ex) & mask;
523       ex = (ex * ex) & mask;
524     }
525
526   val = (a * inv) & mask;
527
528   gcc_assert (((val * b) & mask) == a);
529
530   if ((val >> (bits - 1)) & 1)
531     val |= ~mask;
532
533   *x = val;
534
535   return true;
536 }
537
538 /* Returns true if STMT is after the place where the IP_NORMAL ivs will be
539    emitted in LOOP.  */
540
541 static bool
542 stmt_after_ip_normal_pos (struct loop *loop, tree stmt)
543 {
544   basic_block bb = ip_normal_pos (loop), sbb = bb_for_stmt (stmt);
545
546   gcc_assert (bb);
547
548   if (sbb == loop->latch)
549     return true;
550
551   if (sbb != bb)
552     return false;
553
554   return stmt == last_stmt (bb);
555 }
556
557 /* Returns true if STMT if after the place where the original induction
558    variable CAND is incremented.  */
559
560 static bool
561 stmt_after_ip_original_pos (struct iv_cand *cand, tree stmt)
562 {
563   basic_block cand_bb = bb_for_stmt (cand->incremented_at);
564   basic_block stmt_bb = bb_for_stmt (stmt);
565   block_stmt_iterator bsi;
566
567   if (!dominated_by_p (CDI_DOMINATORS, stmt_bb, cand_bb))
568     return false;
569
570   if (stmt_bb != cand_bb)
571     return true;
572
573   /* Scan the block from the end, since the original ivs are usually
574      incremented at the end of the loop body.  */
575   for (bsi = bsi_last (stmt_bb); ; bsi_prev (&bsi))
576     {
577       if (bsi_stmt (bsi) == cand->incremented_at)
578         return false;
579       if (bsi_stmt (bsi) == stmt)
580         return true;
581     }
582 }
583
584 /* Returns true if STMT if after the place where the induction variable
585    CAND is incremented in LOOP.  */
586
587 static bool
588 stmt_after_increment (struct loop *loop, struct iv_cand *cand, tree stmt)
589 {
590   switch (cand->pos)
591     {
592     case IP_END:
593       return false;
594
595     case IP_NORMAL:
596       return stmt_after_ip_normal_pos (loop, stmt);
597
598     case IP_ORIGINAL:
599       return stmt_after_ip_original_pos (cand, stmt);
600
601     default:
602       gcc_unreachable ();
603     }
604 }
605
606 /* Initializes data structures used by the iv optimization pass, stored
607    in DATA.  LOOPS is the loop tree.  */
608
609 static void
610 tree_ssa_iv_optimize_init (struct loops *loops, struct ivopts_data *data)
611 {
612   unsigned i;
613
614   data->version_info_size = 2 * num_ssa_names;
615   data->version_info = xcalloc (data->version_info_size,
616                                 sizeof (struct version_info));
617   data->relevant = BITMAP_XMALLOC ();
618   data->max_inv_id = 0;
619
620   for (i = 1; i < loops->num; i++)
621     if (loops->parray[i])
622       loops->parray[i]->aux = xcalloc (1, sizeof (struct loop_data));
623
624   VARRAY_GENERIC_PTR_NOGC_INIT (data->iv_uses, 20, "iv_uses");
625   VARRAY_GENERIC_PTR_NOGC_INIT (data->iv_candidates, 20, "iv_candidates");
626   VARRAY_GENERIC_PTR_NOGC_INIT (decl_rtl_to_reset, 20, "decl_rtl_to_reset");
627 }
628
629 /* Allocates an induction variable with given initial value BASE and step STEP
630    for loop LOOP.  */
631
632 static struct iv *
633 alloc_iv (tree base, tree step)
634 {
635   struct iv *iv = xcalloc (1, sizeof (struct iv));
636
637   if (step && integer_zerop (step))
638     step = NULL_TREE;
639
640   iv->base = base;
641   iv->step = step;
642   iv->biv_p = false;
643   iv->have_use_for = false;
644   iv->use_id = 0;
645   iv->ssa_name = NULL_TREE;
646
647   return iv;
648 }
649
650 /* Sets STEP and BASE for induction variable IV.  */
651
652 static void
653 set_iv (struct ivopts_data *data, tree iv, tree base, tree step)
654 {
655   struct version_info *info = name_info (data, iv);
656
657   gcc_assert (!info->iv);
658
659   bitmap_set_bit (data->relevant, SSA_NAME_VERSION (iv));
660   info->iv = alloc_iv (base, step);
661   info->iv->ssa_name = iv;
662 }
663
664 /* Finds induction variable declaration for VAR.  */
665
666 static struct iv *
667 get_iv (struct ivopts_data *data, tree var)
668 {
669   basic_block bb;
670   
671   if (!name_info (data, var)->iv)
672     {
673       bb = bb_for_stmt (SSA_NAME_DEF_STMT (var));
674
675       if (!bb
676           || !flow_bb_inside_loop_p (data->current_loop, bb))
677         set_iv (data, var, var, NULL_TREE);
678     }
679
680   return name_info (data, var)->iv;
681 }
682
683 /* Determines the step of a biv defined in PHI.  */
684
685 static tree
686 determine_biv_step (tree phi)
687 {
688   struct loop *loop = bb_for_stmt (phi)->loop_father;
689   tree name = PHI_RESULT (phi), base, step;
690   tree type = TREE_TYPE (name);
691
692   if (!is_gimple_reg (name))
693     return NULL_TREE;
694
695   if (!simple_iv (loop, phi, name, &base, &step))
696     return NULL_TREE;
697
698   if (!step)
699     return build_int_cst (type, 0);
700
701   return step;
702 }
703
704 /* Returns false if INDEX is a ssa name that occurs in an
705    abnormal phi node.  Callback for for_each_index.  */
706
707 static bool
708 idx_contains_abnormal_ssa_name_p (tree base ATTRIBUTE_UNUSED, tree *index,
709                                   void *data ATTRIBUTE_UNUSED)
710 {
711   if (TREE_CODE (*index) != SSA_NAME)
712     return true;
713
714   return SSA_NAME_OCCURS_IN_ABNORMAL_PHI (*index) == 0;
715 }
716
717 /* Returns true if EXPR contains a ssa name that occurs in an
718    abnormal phi node.  */
719
720 static bool
721 contains_abnormal_ssa_name_p (tree expr)
722 {
723   enum tree_code code = TREE_CODE (expr);
724   char class = TREE_CODE_CLASS (code);
725     
726   if (code == SSA_NAME)
727     return SSA_NAME_OCCURS_IN_ABNORMAL_PHI (expr) != 0;
728
729   if (code == INTEGER_CST
730       || is_gimple_min_invariant (expr))
731     return false;
732
733   if (code == ADDR_EXPR)
734     return !for_each_index (&TREE_OPERAND (expr, 1),
735                             idx_contains_abnormal_ssa_name_p,
736                             NULL);
737
738   switch (class)
739     {
740     case '2':
741     case '<':
742       if (contains_abnormal_ssa_name_p (TREE_OPERAND (expr, 1)))
743         return true;
744
745       /* Fallthru.  */
746     case '1':
747       if (contains_abnormal_ssa_name_p (TREE_OPERAND (expr, 0)))
748         return true;
749
750       break;
751
752     default:
753       gcc_unreachable ();
754     }
755
756   return false;
757 }
758
759 /* Finds basic ivs.  */
760
761 static bool
762 find_bivs (struct ivopts_data *data)
763 {
764   tree phi, step, type, base;
765   bool found = false;
766   struct loop *loop = data->current_loop;
767
768   for (phi = phi_nodes (loop->header); phi; phi = TREE_CHAIN (phi))
769     {
770       if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (PHI_RESULT (phi)))
771         continue;
772
773       step = determine_biv_step (phi);
774
775       if (!step)
776         continue;
777       if (cst_and_fits_in_hwi (step)
778           && int_cst_value (step) == 0)
779         continue;
780
781       base = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
782       if (contains_abnormal_ssa_name_p (base))
783         continue;
784
785       type = TREE_TYPE (PHI_RESULT (phi));
786       base = fold_convert (type, base);
787       step = fold_convert (type, step);
788
789       /* FIXME: We do not handle induction variables whose step does
790          not satisfy cst_and_fits_in_hwi.  */
791       if (!cst_and_fits_in_hwi (step))
792         continue;
793
794       set_iv (data, PHI_RESULT (phi), base, step);
795       found = true;
796     }
797
798   return found;
799 }
800
801 /* Marks basic ivs.  */
802
803 static void
804 mark_bivs (struct ivopts_data *data)
805 {
806   tree phi, var;
807   struct iv *iv, *incr_iv;
808   struct loop *loop = data->current_loop;
809   basic_block incr_bb;
810
811   for (phi = phi_nodes (loop->header); phi; phi = TREE_CHAIN (phi))
812     {
813       iv = get_iv (data, PHI_RESULT (phi));
814       if (!iv)
815         continue;
816
817       var = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
818       incr_iv = get_iv (data, var);
819       if (!incr_iv)
820         continue;
821
822       /* If the increment is in the subloop, ignore it.  */
823       incr_bb = bb_for_stmt (SSA_NAME_DEF_STMT (var));
824       if (incr_bb->loop_father != data->current_loop
825           || (incr_bb->flags & BB_IRREDUCIBLE_LOOP))
826         continue;
827
828       iv->biv_p = true;
829       incr_iv->biv_p = true;
830     }
831 }
832
833 /* Checks whether STMT defines a linear induction variable and stores its
834    parameters to BASE and STEP.  */
835
836 static bool
837 find_givs_in_stmt_scev (struct ivopts_data *data, tree stmt,
838                         tree *base, tree *step)
839 {
840   tree lhs;
841   struct loop *loop = data->current_loop;
842
843   *base = NULL_TREE;
844   *step = NULL_TREE;
845
846   if (TREE_CODE (stmt) != MODIFY_EXPR)
847     return false;
848
849   lhs = TREE_OPERAND (stmt, 0);
850   if (TREE_CODE (lhs) != SSA_NAME)
851     return false;
852
853   if (!simple_iv (loop, stmt, TREE_OPERAND (stmt, 1), base, step))
854     return false;
855
856   /* FIXME: We do not handle induction variables whose step does
857      not satisfy cst_and_fits_in_hwi.  */
858   if (!zero_p (*step)
859       && !cst_and_fits_in_hwi (*step))
860     return false;
861
862   if (contains_abnormal_ssa_name_p (*base))
863     return false;
864
865   return true;
866 }
867
868 /* Finds general ivs in statement STMT.  */
869
870 static void
871 find_givs_in_stmt (struct ivopts_data *data, tree stmt)
872 {
873   tree base, step;
874
875   if (!find_givs_in_stmt_scev (data, stmt, &base, &step))
876     return;
877
878   set_iv (data, TREE_OPERAND (stmt, 0), base, step);
879 }
880
881 /* Finds general ivs in basic block BB.  */
882
883 static void
884 find_givs_in_bb (struct ivopts_data *data, basic_block bb)
885 {
886   block_stmt_iterator bsi;
887
888   for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
889     find_givs_in_stmt (data, bsi_stmt (bsi));
890 }
891
892 /* Finds general ivs.  */
893
894 static void
895 find_givs (struct ivopts_data *data)
896 {
897   struct loop *loop = data->current_loop;
898   basic_block *body = get_loop_body_in_dom_order (loop);
899   unsigned i;
900
901   for (i = 0; i < loop->num_nodes; i++)
902     find_givs_in_bb (data, body[i]);
903   free (body);
904 }
905
906 /* Determine the number of iterations of the current loop.  */
907
908 static void
909 determine_number_of_iterations (struct ivopts_data *data)
910 {
911   struct loop *loop = data->current_loop;
912   edge exit = single_dom_exit (loop);
913
914   if (!exit)
915     return;
916
917   number_of_iterations_exit (loop, exit, &loop_data (loop)->niter);
918 }
919
920 /* For each ssa name defined in LOOP determines whether it is an induction
921    variable and if so, its initial value and step.  */
922
923 static bool
924 find_induction_variables (struct ivopts_data *data)
925 {
926   unsigned i;
927   struct loop *loop = data->current_loop;
928
929   if (!find_bivs (data))
930     return false;
931
932   find_givs (data);
933   mark_bivs (data);
934   determine_number_of_iterations (data);
935
936   if (dump_file && (dump_flags & TDF_DETAILS))
937     {
938       if (loop_data (loop)->niter.niter)
939         {
940           fprintf (dump_file, "  number of iterations ");
941           print_generic_expr (dump_file, loop_data (loop)->niter.niter,
942                               TDF_SLIM);
943           fprintf (dump_file, "\n");
944
945           fprintf (dump_file, "  may be zero if ");
946           print_generic_expr (dump_file, loop_data (loop)->niter.may_be_zero,
947                               TDF_SLIM);
948           fprintf (dump_file, "\n");
949
950           fprintf (dump_file, "  bogus unless ");
951           print_generic_expr (dump_file, loop_data (loop)->niter.assumptions,
952                               TDF_SLIM);
953           fprintf (dump_file, "\n");
954           fprintf (dump_file, "\n");
955         };
956  
957       fprintf (dump_file, "Induction variables:\n\n");
958
959       EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i,
960         {
961           if (ver_info (data, i)->iv)
962             dump_iv (dump_file, ver_info (data, i)->iv);
963         });
964     }
965
966   return true;
967 }
968
969 /* Records a use of type USE_TYPE at *USE_P in STMT whose value is IV.  */
970
971 static struct iv_use *
972 record_use (struct ivopts_data *data, tree *use_p, struct iv *iv,
973             tree stmt, enum use_type use_type)
974 {
975   struct iv_use *use = xcalloc (1, sizeof (struct iv_use));
976
977   use->id = n_iv_uses (data);
978   use->type = use_type;
979   use->iv = iv;
980   use->stmt = stmt;
981   use->op_p = use_p;
982   use->related_cands = BITMAP_XMALLOC ();
983
984   if (dump_file && (dump_flags & TDF_DETAILS))
985     dump_use (dump_file, use);
986
987   VARRAY_PUSH_GENERIC_PTR_NOGC (data->iv_uses, use);
988
989   return use;
990 }
991
992 /* Checks whether OP is a loop-level invariant and if so, records it.
993    NONLINEAR_USE is true if the invariant is used in a way we do not
994    handle specially.  */
995
996 static void
997 record_invariant (struct ivopts_data *data, tree op, bool nonlinear_use)
998 {
999   basic_block bb;
1000   struct version_info *info;
1001
1002   if (TREE_CODE (op) != SSA_NAME
1003       || !is_gimple_reg (op))
1004     return;
1005
1006   bb = bb_for_stmt (SSA_NAME_DEF_STMT (op));
1007   if (bb
1008       && flow_bb_inside_loop_p (data->current_loop, bb))
1009     return;
1010
1011   info = name_info (data, op);
1012   info->name = op;
1013   info->has_nonlin_use |= nonlinear_use;
1014   if (!info->inv_id)
1015     info->inv_id = ++data->max_inv_id;
1016   bitmap_set_bit (data->relevant, SSA_NAME_VERSION (op));
1017 }
1018
1019 /* Checks whether the use OP is interesting and if so, records it
1020    as TYPE.  */
1021
1022 static struct iv_use *
1023 find_interesting_uses_outer_or_nonlin (struct ivopts_data *data, tree op,
1024                                        enum use_type type)
1025 {
1026   struct iv *iv;
1027   struct iv *civ;
1028   tree stmt;
1029   struct iv_use *use;
1030
1031   if (TREE_CODE (op) != SSA_NAME)
1032     return NULL;
1033
1034   iv = get_iv (data, op);
1035   if (!iv)
1036     return NULL;
1037   
1038   if (iv->have_use_for)
1039     {
1040       use = iv_use (data, iv->use_id);
1041
1042       gcc_assert (use->type == USE_NONLINEAR_EXPR
1043                   || use->type == USE_OUTER);
1044
1045       if (type == USE_NONLINEAR_EXPR)
1046         use->type = USE_NONLINEAR_EXPR;
1047       return use;
1048     }
1049
1050   if (zero_p (iv->step))
1051     {
1052       record_invariant (data, op, true);
1053       return NULL;
1054     }
1055   iv->have_use_for = true;
1056
1057   civ = xmalloc (sizeof (struct iv));
1058   *civ = *iv;
1059
1060   stmt = SSA_NAME_DEF_STMT (op);
1061   gcc_assert (TREE_CODE (stmt) == PHI_NODE
1062               || TREE_CODE (stmt) == MODIFY_EXPR);
1063
1064   use = record_use (data, NULL, civ, stmt, type);
1065   iv->use_id = use->id;
1066
1067   return use;
1068 }
1069
1070 /* Checks whether the use OP is interesting and if so, records it.  */
1071
1072 static struct iv_use *
1073 find_interesting_uses_op (struct ivopts_data *data, tree op)
1074 {
1075   return find_interesting_uses_outer_or_nonlin (data, op, USE_NONLINEAR_EXPR);
1076 }
1077
1078 /* Records a definition of induction variable OP that is used outside of the
1079    loop.  */
1080
1081 static struct iv_use *
1082 find_interesting_uses_outer (struct ivopts_data *data, tree op)
1083 {
1084   return find_interesting_uses_outer_or_nonlin (data, op, USE_OUTER);
1085 }
1086
1087 /* Checks whether the condition *COND_P in STMT is interesting
1088    and if so, records it.  */
1089
1090 static void
1091 find_interesting_uses_cond (struct ivopts_data *data, tree stmt, tree *cond_p)
1092 {
1093   tree *op0_p;
1094   tree *op1_p;
1095   struct iv *iv0 = NULL, *iv1 = NULL, *civ;
1096   struct iv const_iv;
1097   tree zero = integer_zero_node;
1098
1099   const_iv.step = NULL_TREE;
1100
1101   if (integer_zerop (*cond_p)
1102       || integer_nonzerop (*cond_p))
1103     return;
1104
1105   if (TREE_CODE (*cond_p) == SSA_NAME)
1106     {
1107       op0_p = cond_p;
1108       op1_p = &zero;
1109     }
1110   else
1111     {
1112       op0_p = &TREE_OPERAND (*cond_p, 0);
1113       op1_p = &TREE_OPERAND (*cond_p, 1);
1114     }
1115
1116   if (TREE_CODE (*op0_p) == SSA_NAME)
1117     iv0 = get_iv (data, *op0_p);
1118   else
1119     iv0 = &const_iv;
1120
1121   if (TREE_CODE (*op1_p) == SSA_NAME)
1122     iv1 = get_iv (data, *op1_p);
1123   else
1124     iv1 = &const_iv;
1125
1126   if (/* When comparing with non-invariant value, we may not do any senseful
1127          induction variable elimination.  */
1128       (!iv0 || !iv1)
1129       /* Eliminating condition based on two ivs would be nontrivial.
1130          ??? TODO -- it is not really important to handle this case.  */
1131       || (!zero_p (iv0->step) && !zero_p (iv1->step)))
1132     {
1133       find_interesting_uses_op (data, *op0_p);
1134       find_interesting_uses_op (data, *op1_p);
1135       return;
1136     }
1137
1138   if (zero_p (iv0->step) && zero_p (iv1->step))
1139     {
1140       /* If both are invariants, this is a work for unswitching.  */
1141       return;
1142     }
1143
1144   civ = xmalloc (sizeof (struct iv));
1145   *civ = zero_p (iv0->step) ? *iv1: *iv0;
1146   record_use (data, cond_p, civ, stmt, USE_COMPARE);
1147 }
1148
1149 /* Cumulates the steps of indices into DATA and replaces their values with the
1150    initial ones.  Returns false when the value of the index cannot be determined.
1151    Callback for for_each_index.  */
1152
1153 struct ifs_ivopts_data
1154 {
1155   struct ivopts_data *ivopts_data;
1156   tree stmt;
1157   tree *step_p;
1158 };
1159
1160 static bool
1161 idx_find_step (tree base, tree *idx, void *data)
1162 {
1163   struct ifs_ivopts_data *dta = data;
1164   struct iv *iv;
1165   tree step, type, iv_type, iv_step, lbound;
1166   basic_block def_bb;
1167   struct loop *loop = dta->ivopts_data->current_loop;
1168   
1169   if (TREE_CODE (*idx) != SSA_NAME)
1170     return true;
1171
1172   iv = get_iv (dta->ivopts_data, *idx);
1173   if (!iv)
1174     return false;
1175
1176   *idx = iv->base;
1177
1178   if (!iv->step)
1179     return true;
1180
1181   iv_type = TREE_TYPE (iv->base);
1182   type = build_pointer_type (TREE_TYPE (base));
1183   if (TREE_CODE (base) == ARRAY_REF)
1184     {
1185       step = array_ref_element_size (base);
1186       lbound = array_ref_low_bound (base);
1187
1188       /* We only handle addresses whose step is an integer constant.  */
1189       if (TREE_CODE (step) != INTEGER_CST)
1190         return false;
1191
1192       /* We need the lower bound to be invariant in loop, since otherwise
1193          we are unable to initialize a new induction variable created
1194          in strength reduction -- we need to take the address of the
1195          reference in front of the loop.  */
1196       if (is_gimple_min_invariant (lbound))
1197         ; /* Nothing to do.  */
1198       else if (TREE_CODE (lbound) != SSA_NAME)
1199         return false;
1200       else
1201         {
1202           def_bb = bb_for_stmt (SSA_NAME_DEF_STMT (lbound));
1203           if (def_bb
1204               && flow_bb_inside_loop_p (loop, def_bb))
1205             return false;
1206         }
1207     }
1208   else
1209     /* The step for pointer arithmetics already is 1 byte.  */
1210     step = build_int_cst (type, 1);
1211
1212   if (TYPE_PRECISION (iv_type) < TYPE_PRECISION (type))
1213     iv_step = can_count_iv_in_wider_type (dta->ivopts_data->current_loop,
1214                                           type, iv->base, iv->step, dta->stmt);
1215   else
1216     iv_step = fold_convert (iv_type, iv->step);
1217
1218   if (!iv_step)
1219     {
1220       /* The index might wrap.  */
1221       return false;
1222     }
1223
1224   step = EXEC_BINARY (MULT_EXPR, type, step, iv_step);
1225
1226   if (!*dta->step_p)
1227     *dta->step_p = step;
1228   else
1229     *dta->step_p = EXEC_BINARY (PLUS_EXPR, type, *dta->step_p, step);
1230
1231   return true;
1232 }
1233
1234 /* Records use in index IDX.  Callback for for_each_index.  Ivopts data
1235    object is passed to it in DATA.  */
1236
1237 static bool
1238 idx_record_use (tree base, tree *idx,
1239                 void *data)
1240 {
1241   find_interesting_uses_op (data, *idx);
1242   if (TREE_CODE (base) == ARRAY_REF)
1243     {
1244       find_interesting_uses_op (data, array_ref_element_size (base));
1245       find_interesting_uses_op (data, array_ref_low_bound (base));
1246     }
1247   return true;
1248 }
1249
1250 /* Finds addresses in *OP_P inside STMT.  */
1251
1252 static void
1253 find_interesting_uses_address (struct ivopts_data *data, tree stmt, tree *op_p)
1254 {
1255   tree base = unshare_expr (*op_p), step = NULL;
1256   struct iv *civ;
1257   struct ifs_ivopts_data ifs_ivopts_data;
1258
1259   /* Ignore bitfields for now.  Not really something terribly complicated
1260      to handle.  TODO.  */
1261   if (TREE_CODE (base) == COMPONENT_REF
1262       && DECL_NONADDRESSABLE_P (TREE_OPERAND (base, 1)))
1263     goto fail;
1264
1265   ifs_ivopts_data.ivopts_data = data;
1266   ifs_ivopts_data.stmt = stmt;
1267   ifs_ivopts_data.step_p = &step;
1268   if (!for_each_index (&base, idx_find_step, &ifs_ivopts_data)
1269       || zero_p (step))
1270     goto fail;
1271
1272   if (TREE_CODE (base) == INDIRECT_REF)
1273     base = TREE_OPERAND (base, 0);
1274   else
1275     base = build_addr (base);
1276
1277   civ = alloc_iv (base, step);
1278   record_use (data, op_p, civ, stmt, USE_ADDRESS);
1279   return;
1280
1281 fail:
1282   for_each_index (op_p, idx_record_use, data);
1283 }
1284
1285 /* Finds and records invariants used in STMT.  */
1286
1287 static void
1288 find_invariants_stmt (struct ivopts_data *data, tree stmt)
1289 {
1290   use_optype uses = NULL;
1291   unsigned i, n;
1292   tree op;
1293
1294   if (TREE_CODE (stmt) == PHI_NODE)
1295     n = PHI_NUM_ARGS (stmt);
1296   else
1297     {
1298       get_stmt_operands (stmt);
1299       uses = STMT_USE_OPS (stmt);
1300       n = NUM_USES (uses);
1301     }
1302
1303   for (i = 0; i < n; i++)
1304     {
1305       if (TREE_CODE (stmt) == PHI_NODE)
1306         op = PHI_ARG_DEF (stmt, i);
1307       else
1308         op = USE_OP (uses, i);
1309
1310       record_invariant (data, op, false);
1311     }
1312 }
1313
1314 /* Finds interesting uses of induction variables in the statement STMT.  */
1315
1316 static void
1317 find_interesting_uses_stmt (struct ivopts_data *data, tree stmt)
1318 {
1319   struct iv *iv;
1320   tree op, lhs, rhs;
1321   use_optype uses = NULL;
1322   unsigned i, n;
1323
1324   find_invariants_stmt (data, stmt);
1325
1326   if (TREE_CODE (stmt) == COND_EXPR)
1327     {
1328       find_interesting_uses_cond (data, stmt, &COND_EXPR_COND (stmt));
1329       return;
1330     }
1331
1332   if (TREE_CODE (stmt) == MODIFY_EXPR)
1333     {
1334       lhs = TREE_OPERAND (stmt, 0);
1335       rhs = TREE_OPERAND (stmt, 1);
1336
1337       if (TREE_CODE (lhs) == SSA_NAME)
1338         {
1339           /* If the statement defines an induction variable, the uses are not
1340              interesting by themselves.  */
1341
1342           iv = get_iv (data, lhs);
1343
1344           if (iv && !zero_p (iv->step))
1345             return;
1346         }
1347
1348       switch (TREE_CODE_CLASS (TREE_CODE (rhs)))
1349         {
1350         case '<':
1351           find_interesting_uses_cond (data, stmt, &TREE_OPERAND (stmt, 1));
1352           return;
1353
1354         case 'r':
1355           find_interesting_uses_address (data, stmt, &TREE_OPERAND (stmt, 1));
1356           if (TREE_CODE_CLASS (TREE_CODE (lhs)) == 'r')
1357             find_interesting_uses_address (data, stmt, &TREE_OPERAND (stmt, 0));
1358           return;
1359
1360         default: ;
1361         }
1362
1363       /* Handle memory = gimple_val.  */
1364       if (TREE_CODE_CLASS (TREE_CODE (lhs)) == 'r'
1365           && is_gimple_val (rhs))
1366         {
1367           find_interesting_uses_address (data, stmt, &TREE_OPERAND (stmt, 0));
1368           find_interesting_uses_op (data, rhs);
1369           return;
1370         }
1371
1372       /* TODO -- we should also handle address uses of type
1373
1374          memory = call (whatever);
1375
1376          and
1377
1378          call (memory).  */
1379     }
1380
1381   if (TREE_CODE (stmt) == PHI_NODE
1382       && bb_for_stmt (stmt) == data->current_loop->header)
1383     {
1384       lhs = PHI_RESULT (stmt);
1385       iv = get_iv (data, lhs);
1386
1387       if (iv && !zero_p (iv->step))
1388         return;
1389     }
1390
1391   if (TREE_CODE (stmt) == PHI_NODE)
1392     n = PHI_NUM_ARGS (stmt);
1393   else
1394     {
1395       uses = STMT_USE_OPS (stmt);
1396       n = NUM_USES (uses);
1397     }
1398
1399   for (i = 0; i < n; i++)
1400     {
1401       if (TREE_CODE (stmt) == PHI_NODE)
1402         op = PHI_ARG_DEF (stmt, i);
1403       else
1404         op = USE_OP (uses, i);
1405
1406       if (TREE_CODE (op) != SSA_NAME)
1407         continue;
1408
1409       iv = get_iv (data, op);
1410       if (!iv)
1411         continue;
1412
1413       find_interesting_uses_op (data, op);
1414     }
1415 }
1416
1417 /* Finds interesting uses of induction variables outside of loops
1418    on loop exit edge EXIT.  */
1419
1420 static void
1421 find_interesting_uses_outside (struct ivopts_data *data, edge exit)
1422 {
1423   tree phi, def;
1424
1425   for (phi = phi_nodes (exit->dest); phi; phi = TREE_CHAIN (phi))
1426     {
1427       def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
1428       find_interesting_uses_outer (data, def);
1429     }
1430 }
1431
1432 /* Finds uses of the induction variables that are interesting.  */
1433
1434 static void
1435 find_interesting_uses (struct ivopts_data *data)
1436 {
1437   basic_block bb;
1438   block_stmt_iterator bsi;
1439   tree phi;
1440   basic_block *body = get_loop_body (data->current_loop);
1441   unsigned i;
1442   struct version_info *info;
1443   edge e;
1444
1445   if (dump_file && (dump_flags & TDF_DETAILS))
1446     fprintf (dump_file, "Uses:\n\n");
1447
1448   for (i = 0; i < data->current_loop->num_nodes; i++)
1449     {
1450       bb = body[i];
1451
1452       for (e = bb->succ; e; e = e->succ_next)
1453         if (e->dest != EXIT_BLOCK_PTR
1454             && !flow_bb_inside_loop_p (data->current_loop, e->dest))
1455           find_interesting_uses_outside (data, e);
1456
1457       for (phi = phi_nodes (bb); phi; phi = TREE_CHAIN (phi))
1458         find_interesting_uses_stmt (data, phi);
1459       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1460         find_interesting_uses_stmt (data, bsi_stmt (bsi));
1461     }
1462
1463   if (dump_file && (dump_flags & TDF_DETAILS))
1464     {
1465       fprintf (dump_file, "\n");
1466
1467       EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i,
1468         {
1469           info = ver_info (data, i);
1470           if (info->inv_id)
1471             {
1472               fprintf (dump_file, "  ");
1473               print_generic_expr (dump_file, info->name, TDF_SLIM);
1474               fprintf (dump_file, " is invariant (%d)%s\n",
1475                        info->inv_id, info->has_nonlin_use ? "" : ", eliminable");
1476             }
1477         });
1478
1479       fprintf (dump_file, "\n");
1480     }
1481
1482   free (body);
1483 }
1484
1485 /* Adds a candidate BASE + STEP * i.  Important field is set to IMPORTANT and
1486    position to POS.  If USE is not NULL, the candidate is set as related to
1487    it.  If both BASE and STEP are NULL, we add a pseudocandidate for the
1488    replacement of the final value of the iv by a direct computation.  */
1489
1490 static struct iv_cand *
1491 add_candidate_1 (struct ivopts_data *data,
1492                  tree base, tree step, bool important, enum iv_position pos,
1493                  struct iv_use *use, tree incremented_at)
1494 {
1495   unsigned i;
1496   struct iv_cand *cand = NULL;
1497   tree type;
1498   
1499   if (base)
1500     {
1501       type = TREE_TYPE (base);
1502       if (!TYPE_UNSIGNED (type))
1503         {
1504           type = unsigned_type_for (type);
1505           base = fold_convert (type, base);
1506           if (step)
1507             step = fold_convert (type, step);
1508         }
1509     }
1510
1511   for (i = 0; i < n_iv_cands (data); i++)
1512     {
1513       cand = iv_cand (data, i);
1514
1515       if (cand->pos != pos)
1516         continue;
1517
1518       if (cand->incremented_at != incremented_at)
1519         continue;
1520
1521       if (!cand->iv)
1522         {
1523           if (!base && !step)
1524             break;
1525
1526           continue;
1527         }
1528
1529       if (!base && !step)
1530         continue;
1531
1532       if (!operand_equal_p (base, cand->iv->base, 0))
1533         continue;
1534
1535       if (zero_p (cand->iv->step))
1536         {
1537           if (zero_p (step))
1538             break;
1539         }
1540       else
1541         {
1542           if (step && operand_equal_p (step, cand->iv->step, 0))
1543             break;
1544         }
1545     }
1546
1547   if (i == n_iv_cands (data))
1548     {
1549       cand = xcalloc (1, sizeof (struct iv_cand));
1550       cand->id = i;
1551
1552       if (!base && !step)
1553         cand->iv = NULL;
1554       else
1555         cand->iv = alloc_iv (base, step);
1556
1557       cand->pos = pos;
1558       if (pos != IP_ORIGINAL && cand->iv)
1559         {
1560           cand->var_before = create_tmp_var_raw (TREE_TYPE (base), "ivtmp");
1561           cand->var_after = cand->var_before;
1562         }
1563       cand->important = important;
1564       cand->incremented_at = incremented_at;
1565       VARRAY_PUSH_GENERIC_PTR_NOGC (data->iv_candidates, cand);
1566
1567       if (dump_file && (dump_flags & TDF_DETAILS))
1568         dump_cand (dump_file, cand);
1569     }
1570
1571   if (important && !cand->important)
1572     {
1573       cand->important = true;
1574       if (dump_file && (dump_flags & TDF_DETAILS))
1575         fprintf (dump_file, "Candidate %d is important\n", cand->id);
1576     }
1577
1578   if (use)
1579     {
1580       bitmap_set_bit (use->related_cands, i);
1581       if (dump_file && (dump_flags & TDF_DETAILS))
1582         fprintf (dump_file, "Candidate %d is related to use %d\n",
1583                  cand->id, use->id);
1584     }
1585
1586   return cand;
1587 }
1588
1589 /* Adds a candidate BASE + STEP * i.  Important field is set to IMPORTANT and
1590    position to POS.  If USE is not NULL, the candidate is set as related to
1591    it.  The candidate computation is scheduled on all available positions.  */
1592
1593 static void
1594 add_candidate (struct ivopts_data *data, 
1595                tree base, tree step, bool important, struct iv_use *use)
1596 {
1597   if (ip_normal_pos (data->current_loop))
1598     add_candidate_1 (data, base, step, important, IP_NORMAL, use, NULL_TREE);
1599   if (ip_end_pos (data->current_loop))
1600     add_candidate_1 (data, base, step, important, IP_END, use, NULL_TREE);
1601 }
1602
1603 /* Adds standard iv candidates.  */
1604
1605 static void
1606 add_standard_iv_candidates (struct ivopts_data *data)
1607 {
1608   /* Add 0 + 1 * iteration candidate.  */
1609   add_candidate (data,
1610                  build_int_cst (unsigned_intSI_type_node, 0),
1611                  build_int_cst (unsigned_intSI_type_node, 1),
1612                  true, NULL);
1613
1614   /* The same for a long type if it is still fast enough.  */
1615   if (BITS_PER_WORD > 32)
1616     add_candidate (data,
1617                    build_int_cst (unsigned_intDI_type_node, 0),
1618                    build_int_cst (unsigned_intDI_type_node, 1),
1619                    true, NULL);
1620 }
1621
1622
1623 /* Adds candidates bases on the old induction variable IV.  */
1624
1625 static void
1626 add_old_iv_candidates (struct ivopts_data *data, struct iv *iv)
1627 {
1628   tree phi, def;
1629   struct iv_cand *cand;
1630
1631   add_candidate (data, iv->base, iv->step, true, NULL);
1632
1633   /* The same, but with initial value zero.  */
1634   add_candidate (data,
1635                  build_int_cst (TREE_TYPE (iv->base), 0),
1636                  iv->step, true, NULL);
1637
1638   phi = SSA_NAME_DEF_STMT (iv->ssa_name);
1639   if (TREE_CODE (phi) == PHI_NODE)
1640     {
1641       /* Additionally record the possibility of leaving the original iv
1642          untouched.  */
1643       def = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (data->current_loop));
1644       cand = add_candidate_1 (data,
1645                               iv->base, iv->step, true, IP_ORIGINAL, NULL,
1646                               SSA_NAME_DEF_STMT (def));
1647       cand->var_before = iv->ssa_name;
1648       cand->var_after = def;
1649     }
1650 }
1651
1652 /* Adds candidates based on the old induction variables.  */
1653
1654 static void
1655 add_old_ivs_candidates (struct ivopts_data *data)
1656 {
1657   unsigned i;
1658   struct iv *iv;
1659
1660   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i,
1661     {
1662       iv = ver_info (data, i)->iv;
1663       if (iv && iv->biv_p && !zero_p (iv->step))
1664         add_old_iv_candidates (data, iv);
1665     });
1666 }
1667
1668 /* Adds candidates based on the value of the induction variable IV and USE.  */
1669
1670 static void
1671 add_iv_value_candidates (struct ivopts_data *data,
1672                          struct iv *iv, struct iv_use *use)
1673 {
1674   add_candidate (data, iv->base, iv->step, false, use);
1675
1676   /* The same, but with initial value zero.  */
1677   add_candidate (data, build_int_cst (TREE_TYPE (iv->base), 0),
1678                  iv->step, false, use);
1679 }
1680
1681 /* Adds candidates based on the address IV and USE.  */
1682
1683 static void
1684 add_address_candidates (struct ivopts_data *data,
1685                         struct iv *iv, struct iv_use *use)
1686 {
1687   tree base, abase, tmp, *act;
1688
1689   /* First, the trivial choices.  */
1690   add_iv_value_candidates (data, iv, use);
1691
1692   /* Second, try removing the COMPONENT_REFs.  */
1693   if (TREE_CODE (iv->base) == ADDR_EXPR)
1694     {
1695       base = TREE_OPERAND (iv->base, 0);
1696       while (TREE_CODE (base) == COMPONENT_REF
1697              || (TREE_CODE (base) == ARRAY_REF
1698                  && TREE_CODE (TREE_OPERAND (base, 1)) == INTEGER_CST))
1699         base = TREE_OPERAND (base, 0);
1700
1701       if (base != TREE_OPERAND (iv->base, 0))
1702         { 
1703           if (TREE_CODE (base) == INDIRECT_REF)
1704             base = TREE_OPERAND (base, 0);
1705           else
1706             base = build_addr (base);
1707           add_candidate (data, base, iv->step, false, use);
1708         }
1709     }
1710
1711   /* Third, try removing the constant offset.  */
1712   abase = iv->base;
1713   while (TREE_CODE (abase) == PLUS_EXPR
1714          && TREE_CODE (TREE_OPERAND (abase, 1)) != INTEGER_CST)
1715     abase = TREE_OPERAND (abase, 0);
1716   /* We found the offset, so make the copy of the non-shared part and
1717      remove it.  */
1718   if (TREE_CODE (abase) == PLUS_EXPR)
1719     {
1720       tmp = iv->base;
1721       act = &base;
1722
1723       for (tmp = iv->base; tmp != abase; tmp = TREE_OPERAND (tmp, 0))
1724         {
1725           *act = build2 (PLUS_EXPR, TREE_TYPE (tmp),
1726                          NULL_TREE, TREE_OPERAND (tmp, 1));
1727           act = &TREE_OPERAND (*act, 0);
1728         }
1729       *act = TREE_OPERAND (tmp, 0);
1730
1731       add_candidate (data, base, iv->step, false, use);
1732     }
1733 }
1734
1735 /* Possibly adds pseudocandidate for replacing the final value of USE by
1736    a direct computation.  */
1737
1738 static void
1739 add_iv_outer_candidates (struct ivopts_data *data, struct iv_use *use)
1740 {
1741   struct tree_niter_desc *niter;
1742   struct loop *loop = data->current_loop;
1743
1744   /* We must know where we exit the loop and how many times does it roll.  */
1745   if (!single_dom_exit (loop))
1746     return;
1747
1748   niter = &loop_data (loop)->niter;
1749   if (!niter->niter
1750       || !operand_equal_p (niter->assumptions, boolean_true_node, 0)
1751       || !operand_equal_p (niter->may_be_zero, boolean_false_node, 0))
1752     return;
1753
1754   add_candidate_1 (data, NULL, NULL, false, IP_NORMAL, use, NULL_TREE);
1755 }
1756
1757 /* Adds candidates based on the uses.  */
1758
1759 static void
1760 add_derived_ivs_candidates (struct ivopts_data *data)
1761 {
1762   unsigned i;
1763
1764   for (i = 0; i < n_iv_uses (data); i++)
1765     {
1766       struct iv_use *use = iv_use (data, i);
1767
1768       if (!use)
1769         continue;
1770
1771       switch (use->type)
1772         {
1773         case USE_NONLINEAR_EXPR:
1774         case USE_COMPARE:
1775           /* Just add the ivs based on the value of the iv used here.  */
1776           add_iv_value_candidates (data, use->iv, use);
1777           break;
1778
1779         case USE_OUTER:
1780           add_iv_value_candidates (data, use->iv, use);
1781
1782           /* Additionally, add the pseudocandidate for the possibility to
1783              replace the final value by a direct computation.  */
1784           add_iv_outer_candidates (data, use);
1785           break;
1786
1787         case USE_ADDRESS:
1788           add_address_candidates (data, use->iv, use);
1789           break;
1790
1791         default:
1792           gcc_unreachable ();
1793         }
1794     }
1795 }
1796
1797 /* Finds the candidates for the induction variables.  */
1798
1799 static void
1800 find_iv_candidates (struct ivopts_data *data)
1801 {
1802   /* Add commonly used ivs.  */
1803   add_standard_iv_candidates (data);
1804
1805   /* Add old induction variables.  */
1806   add_old_ivs_candidates (data);
1807
1808   /* Add induction variables derived from uses.  */
1809   add_derived_ivs_candidates (data);
1810 }
1811
1812 /* Allocates the data structure mapping the (use, candidate) pairs to costs.
1813    If consider_all_candidates is true, we use a two-dimensional array, otherwise
1814    we allocate a simple list to every use.  */
1815
1816 static void
1817 alloc_use_cost_map (struct ivopts_data *data)
1818 {
1819   unsigned i, n_imp = 0, size, j;
1820
1821   if (!data->consider_all_candidates)
1822     {
1823       for (i = 0; i < n_iv_cands (data); i++)
1824         {
1825           struct iv_cand *cand = iv_cand (data, i);
1826           if (cand->important)
1827             n_imp++;
1828         }
1829     }
1830
1831   for (i = 0; i < n_iv_uses (data); i++)
1832     {
1833       struct iv_use *use = iv_use (data, i);
1834
1835       if (data->consider_all_candidates)
1836         {
1837           size = n_iv_cands (data);
1838           use->n_map_members = size;
1839         }
1840       else
1841         {
1842           size = n_imp;
1843           EXECUTE_IF_SET_IN_BITMAP (use->related_cands, 0, j, size++);
1844           use->n_map_members = 0;
1845         }
1846
1847       use->cost_map = xcalloc (size, sizeof (struct cost_pair));
1848     }
1849 }
1850
1851 /* Sets cost of (USE, CANDIDATE) pair to COST and record that it depends
1852    on invariants DEPENDS_ON.  */
1853
1854 static void
1855 set_use_iv_cost (struct ivopts_data *data,
1856                  struct iv_use *use, struct iv_cand *cand, unsigned cost,
1857                  bitmap depends_on)
1858 {
1859   if (cost == INFTY
1860       && depends_on)
1861     {
1862       BITMAP_XFREE (depends_on);
1863       depends_on = NULL;
1864     }
1865
1866   if (data->consider_all_candidates)
1867     {
1868       use->cost_map[cand->id].cand = cand;
1869       use->cost_map[cand->id].cost = cost;
1870       use->cost_map[cand->id].depends_on = depends_on;
1871       return;
1872     }
1873
1874   if (cost == INFTY)
1875     return;
1876
1877   use->cost_map[use->n_map_members].cand = cand;
1878   use->cost_map[use->n_map_members].cost = cost;
1879   use->cost_map[use->n_map_members].depends_on = depends_on;
1880   use->n_map_members++;
1881 }
1882
1883 /* Gets cost of (USE, CANDIDATE) pair.  Stores the bitmap of dependencies to
1884    DEPENDS_ON.  */
1885
1886 static unsigned
1887 get_use_iv_cost (struct ivopts_data *data,
1888                  struct iv_use *use, struct iv_cand *cand, bitmap *depends_on)
1889 {
1890   unsigned i;
1891
1892   if (!cand)
1893     return INFTY;
1894
1895   if (data->consider_all_candidates)
1896     i = cand->id;
1897   else
1898     {
1899       for (i = 0; i < use->n_map_members; i++)
1900         if (use->cost_map[i].cand == cand)
1901           break;
1902
1903       if (i == use->n_map_members)
1904         return INFTY;
1905     }
1906
1907   if (depends_on)
1908     *depends_on = use->cost_map[i].depends_on;
1909   return use->cost_map[i].cost;
1910 }
1911
1912 /* Returns estimate on cost of computing SEQ.  */
1913
1914 static unsigned
1915 seq_cost (rtx seq)
1916 {
1917   unsigned cost = 0;
1918   rtx set;
1919
1920   for (; seq; seq = NEXT_INSN (seq))
1921     {
1922       set = single_set (seq);
1923       if (set)
1924         cost += rtx_cost (set, SET);
1925       else
1926         cost++;
1927     }
1928
1929   return cost;
1930 }
1931
1932 /* Produce DECL_RTL for object obj so it looks like it is stored in memory.  */
1933 static rtx
1934 produce_memory_decl_rtl (tree obj, int *regno)
1935 {
1936   rtx x;
1937   if (!obj)
1938     abort ();
1939   if (TREE_STATIC (obj) || DECL_EXTERNAL (obj))
1940     {
1941       const char *name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (obj));
1942       x = gen_rtx_SYMBOL_REF (Pmode, name);
1943     }
1944   else
1945     x = gen_raw_REG (Pmode, (*regno)++);
1946
1947   return gen_rtx_MEM (DECL_MODE (obj), x);
1948 }
1949
1950 /* Prepares decl_rtl for variables referred in *EXPR_P.  Callback for
1951    walk_tree.  DATA contains the actual fake register number.  */
1952
1953 static tree
1954 prepare_decl_rtl (tree *expr_p, int *ws, void *data)
1955 {
1956   tree obj = NULL_TREE;
1957   rtx x = NULL_RTX;
1958   int *regno = data;
1959
1960   switch (TREE_CODE (*expr_p))
1961     {
1962     case ADDR_EXPR:
1963       for (expr_p = &TREE_OPERAND (*expr_p, 0);
1964            (handled_component_p (*expr_p)
1965             || TREE_CODE (*expr_p) == REALPART_EXPR
1966             || TREE_CODE (*expr_p) == IMAGPART_EXPR);
1967            expr_p = &TREE_OPERAND (*expr_p, 0));
1968       obj = *expr_p;
1969       if (DECL_P (obj))
1970         x = produce_memory_decl_rtl (obj, regno);
1971       break;
1972
1973     case SSA_NAME:
1974       *ws = 0;
1975       obj = SSA_NAME_VAR (*expr_p);
1976       if (!DECL_RTL_SET_P (obj))
1977         x = gen_raw_REG (DECL_MODE (obj), (*regno)++);
1978       break;
1979
1980     case VAR_DECL:
1981     case PARM_DECL:
1982     case RESULT_DECL:
1983       *ws = 0;
1984       obj = *expr_p;
1985
1986       if (DECL_RTL_SET_P (obj))
1987         break;
1988
1989       if (DECL_MODE (obj) == BLKmode)
1990         x = produce_memory_decl_rtl (obj, regno);
1991       else
1992         x = gen_raw_REG (DECL_MODE (obj), (*regno)++);
1993
1994       break;
1995
1996     default:
1997       break;
1998     }
1999
2000   if (x)
2001     {
2002       VARRAY_PUSH_GENERIC_PTR_NOGC (decl_rtl_to_reset, obj);
2003       SET_DECL_RTL (obj, x);
2004     }
2005
2006   return NULL_TREE;
2007 }
2008
2009 /* Determines cost of the computation of EXPR.  */
2010
2011 static unsigned
2012 computation_cost (tree expr)
2013 {
2014   rtx seq, rslt;
2015   tree type = TREE_TYPE (expr);
2016   unsigned cost;
2017   int regno = 0;
2018
2019   walk_tree (&expr, prepare_decl_rtl, &regno, NULL);
2020   start_sequence ();
2021   rslt = expand_expr (expr, NULL_RTX, TYPE_MODE (type), EXPAND_NORMAL);
2022   seq = get_insns ();
2023   end_sequence ();
2024
2025   cost = seq_cost (seq);
2026   if (GET_CODE (rslt) == MEM)
2027     cost += address_cost (XEXP (rslt, 0), TYPE_MODE (type));
2028
2029   return cost;
2030 }
2031
2032 /* Returns variable containing the value of candidate CAND at statement AT.  */
2033
2034 static tree
2035 var_at_stmt (struct loop *loop, struct iv_cand *cand, tree stmt)
2036 {
2037   if (stmt_after_increment (loop, cand, stmt))
2038     return cand->var_after;
2039   else
2040     return cand->var_before;
2041 }
2042
2043 /* Determines the expression by that USE is expressed from induction variable
2044    CAND at statement AT in LOOP.  */
2045
2046 static tree
2047 get_computation_at (struct loop *loop,
2048                     struct iv_use *use, struct iv_cand *cand, tree at)
2049 {
2050   tree ubase = use->iv->base;
2051   tree ustep = use->iv->step;
2052   tree cbase = cand->iv->base;
2053   tree cstep = cand->iv->step;
2054   tree utype = TREE_TYPE (ubase), ctype = TREE_TYPE (cbase);
2055   tree uutype;
2056   tree expr, delta;
2057   tree ratio;
2058   unsigned HOST_WIDE_INT ustepi, cstepi;
2059   HOST_WIDE_INT ratioi;
2060
2061   if (TYPE_PRECISION (utype) > TYPE_PRECISION (ctype))
2062     {
2063       /* We do not have a precision to express the values of use.  */
2064       return NULL_TREE;
2065     }
2066
2067   expr = var_at_stmt (loop, cand, at);
2068
2069   if (TREE_TYPE (expr) != ctype)
2070     {
2071       /* This may happen with the original ivs.  */
2072       expr = fold_convert (ctype, expr);
2073     }
2074
2075   if (TYPE_UNSIGNED (utype))
2076     uutype = utype;
2077   else
2078     {
2079       uutype = unsigned_type_for (utype);
2080       ubase = fold_convert (uutype, ubase);
2081       ustep = fold_convert (uutype, ustep);
2082     }
2083
2084   if (uutype != ctype)
2085     {
2086       expr = fold_convert (uutype, expr);
2087       cbase = fold_convert (uutype, cbase);
2088       cstep = fold_convert (uutype, cstep);
2089     }
2090
2091   if (!cst_and_fits_in_hwi (cstep)
2092       || !cst_and_fits_in_hwi (ustep))
2093     return NULL_TREE;
2094
2095   ustepi = int_cst_value (ustep);
2096   cstepi = int_cst_value (cstep);
2097
2098   if (!divide (TYPE_PRECISION (uutype), ustepi, cstepi, &ratioi))
2099     {
2100       /* TODO maybe consider case when ustep divides cstep and the ratio is
2101          a power of 2 (so that the division is fast to execute)?  We would
2102          need to be much more careful with overflows etc. then.  */
2103       return NULL_TREE;
2104     }
2105
2106   /* We may need to shift the value if we are after the increment.  */
2107   if (stmt_after_increment (loop, cand, at))
2108     cbase = fold (build2 (PLUS_EXPR, uutype, cbase, cstep));
2109
2110   /* use = ubase + ratio * (var - cbase).  If either cbase is a constant
2111      or |ratio| == 1, it is better to handle this like
2112      
2113      ubase - ratio * cbase + ratio * var.  */
2114
2115   if (ratioi == 1)
2116     {
2117       delta = fold (build2 (MINUS_EXPR, uutype, ubase, cbase));
2118       expr = fold (build2 (PLUS_EXPR, uutype, expr, delta));
2119     }
2120   else if (ratioi == -1)
2121     {
2122       delta = fold (build2 (PLUS_EXPR, uutype, ubase, cbase));
2123       expr = fold (build2 (MINUS_EXPR, uutype, delta, expr));
2124     }
2125   else if (TREE_CODE (cbase) == INTEGER_CST)
2126     {
2127       ratio = build_int_cst_type (uutype, ratioi);
2128       delta = fold (build2 (MULT_EXPR, uutype, ratio, cbase));
2129       delta = fold (build2 (MINUS_EXPR, uutype, ubase, delta));
2130       expr = fold (build2 (MULT_EXPR, uutype, ratio, expr));
2131       expr = fold (build2 (PLUS_EXPR, uutype, delta, expr));
2132     }
2133   else
2134     {
2135       expr = fold (build2 (MINUS_EXPR, uutype, expr, cbase));
2136       ratio = build_int_cst_type (uutype, ratioi);
2137       expr = fold (build2 (MULT_EXPR, uutype, ratio, expr));
2138       expr = fold (build2 (PLUS_EXPR, uutype, ubase, expr));
2139     }
2140
2141   return fold_convert (utype, expr);
2142 }
2143
2144 /* Determines the expression by that USE is expressed from induction variable
2145    CAND in LOOP.  */
2146
2147 static tree
2148 get_computation (struct loop *loop, struct iv_use *use, struct iv_cand *cand)
2149 {
2150   return get_computation_at (loop, use, cand, use->stmt);
2151 }
2152
2153 /* Strips constant offsets from EXPR and adds them to OFFSET.  */
2154
2155 static void
2156 strip_offset (tree *expr, unsigned HOST_WIDE_INT *offset)
2157 {
2158   tree op0, op1;
2159   enum tree_code code;
2160   
2161   while (1)
2162     {
2163       if (cst_and_fits_in_hwi (*expr))
2164         {
2165           *offset += int_cst_value (*expr);
2166           *expr = integer_zero_node;
2167           return;
2168         }
2169
2170       code = TREE_CODE (*expr);
2171      
2172       if (code != PLUS_EXPR && code != MINUS_EXPR)
2173         return;
2174
2175       op0 = TREE_OPERAND (*expr, 0);
2176       op1 = TREE_OPERAND (*expr, 1);
2177
2178       if (cst_and_fits_in_hwi (op1))
2179         {
2180           if (code == PLUS_EXPR)
2181             *offset += int_cst_value (op1);
2182           else
2183             *offset -= int_cst_value (op1);
2184
2185           *expr = op0;
2186           continue;
2187         }
2188
2189       if (code != PLUS_EXPR)
2190         return;
2191
2192       if (!cst_and_fits_in_hwi (op0))
2193         return;
2194
2195       *offset += int_cst_value (op0);
2196       *expr = op1;
2197     }
2198 }
2199
2200 /* Returns cost of addition in MODE.  */
2201
2202 static unsigned
2203 add_cost (enum machine_mode mode)
2204 {
2205   static unsigned costs[NUM_MACHINE_MODES];
2206   rtx seq;
2207   unsigned cost;
2208
2209   if (costs[mode])
2210     return costs[mode];
2211
2212   start_sequence ();
2213   force_operand (gen_rtx_fmt_ee (PLUS, mode,
2214                                  gen_raw_REG (mode, FIRST_PSEUDO_REGISTER),
2215                                  gen_raw_REG (mode, FIRST_PSEUDO_REGISTER + 1)),
2216                  NULL_RTX);
2217   seq = get_insns ();
2218   end_sequence ();
2219
2220   cost = seq_cost (seq);
2221   if (!cost)
2222     cost = 1;
2223
2224   costs[mode] = cost;
2225       
2226   if (dump_file && (dump_flags & TDF_DETAILS))
2227     fprintf (dump_file, "Addition in %s costs %d\n",
2228              GET_MODE_NAME (mode), cost);
2229   return cost;
2230 }
2231
2232 /* Entry in a hashtable of already known costs for multiplication.  */
2233 struct mbc_entry
2234 {
2235   HOST_WIDE_INT cst;            /* The constant to multiply by.  */
2236   enum machine_mode mode;       /* In mode.  */
2237   unsigned cost;                /* The cost.  */
2238 };
2239
2240 /* Counts hash value for the ENTRY.  */
2241
2242 static hashval_t
2243 mbc_entry_hash (const void *entry)
2244 {
2245   const struct mbc_entry *e = entry;
2246
2247   return 57 * (hashval_t) e->mode + (hashval_t) (e->cst % 877);
2248 }
2249
2250 /* Compares the hash table entries ENTRY1 and ENTRY2.  */
2251
2252 static int
2253 mbc_entry_eq (const void *entry1, const void *entry2)
2254 {
2255   const struct mbc_entry *e1 = entry1;
2256   const struct mbc_entry *e2 = entry2;
2257
2258   return (e1->mode == e2->mode
2259           && e1->cst == e2->cst);
2260 }
2261
2262 /* Returns cost of multiplication by constant CST in MODE.  */
2263
2264 static unsigned
2265 multiply_by_cost (HOST_WIDE_INT cst, enum machine_mode mode)
2266 {
2267   static htab_t costs;
2268   struct mbc_entry **cached, act;
2269   rtx seq;
2270   unsigned cost;
2271
2272   if (!costs)
2273     costs = htab_create (100, mbc_entry_hash, mbc_entry_eq, free);
2274
2275   act.mode = mode;
2276   act.cst = cst;
2277   cached = (struct mbc_entry **) htab_find_slot (costs, &act, INSERT);
2278   if (*cached)
2279     return (*cached)->cost;
2280
2281   *cached = xmalloc (sizeof (struct mbc_entry));
2282   (*cached)->mode = mode;
2283   (*cached)->cst = cst;
2284
2285   start_sequence ();
2286   expand_mult (mode, gen_raw_REG (mode, FIRST_PSEUDO_REGISTER), GEN_INT (cst),
2287                NULL_RTX, 0);
2288   seq = get_insns ();
2289   end_sequence ();
2290   
2291   cost = seq_cost (seq);
2292
2293   if (dump_file && (dump_flags & TDF_DETAILS))
2294     fprintf (dump_file, "Multiplication by %d in %s costs %d\n",
2295              (int) cst, GET_MODE_NAME (mode), cost);
2296
2297   (*cached)->cost = cost;
2298
2299   return cost;
2300 }
2301
2302 /* Returns cost of address in shape symbol + var + OFFSET + RATIO * index.
2303    If SYMBOL_PRESENT is false, symbol is omitted.  If VAR_PRESENT is false,
2304    variable is omitted.  The created memory accesses MODE.
2305    
2306    TODO -- there must be some better way.  This all is quite crude.  */
2307
2308 static unsigned
2309 get_address_cost (bool symbol_present, bool var_present,
2310                   unsigned HOST_WIDE_INT offset, HOST_WIDE_INT ratio)
2311 {
2312 #define MAX_RATIO 128
2313   static sbitmap valid_mult;
2314   static HOST_WIDE_INT rat, off;
2315   static HOST_WIDE_INT min_offset, max_offset;
2316   static unsigned costs[2][2][2][2];
2317   unsigned cost, acost;
2318   rtx seq, addr, base;
2319   bool offset_p, ratio_p;
2320   rtx reg1;
2321   HOST_WIDE_INT s_offset;
2322   unsigned HOST_WIDE_INT mask;
2323   unsigned bits;
2324
2325   if (!valid_mult)
2326     {
2327       HOST_WIDE_INT i;
2328
2329       reg1 = gen_raw_REG (Pmode, FIRST_PSEUDO_REGISTER);
2330
2331       addr = gen_rtx_fmt_ee (PLUS, Pmode, reg1, NULL_RTX);
2332       for (i = 1; i <= 1 << 20; i <<= 1)
2333         {
2334           XEXP (addr, 1) = GEN_INT (i);
2335           if (!memory_address_p (Pmode, addr))
2336             break;
2337         }
2338       max_offset = i >> 1;
2339       off = max_offset;
2340
2341       for (i = 1; i <= 1 << 20; i <<= 1)
2342         {
2343           XEXP (addr, 1) = GEN_INT (-i);
2344           if (!memory_address_p (Pmode, addr))
2345             break;
2346         }
2347       min_offset = -(i >> 1);
2348
2349       if (dump_file && (dump_flags & TDF_DETAILS))
2350         {
2351           fprintf (dump_file, "get_address_cost:\n");
2352           fprintf (dump_file, "  min offset %d\n", (int) min_offset);
2353           fprintf (dump_file, "  max offset %d\n", (int) max_offset);
2354         }
2355
2356       valid_mult = sbitmap_alloc (2 * MAX_RATIO + 1);
2357       sbitmap_zero (valid_mult);
2358       rat = 1;
2359       addr = gen_rtx_fmt_ee (MULT, Pmode, reg1, NULL_RTX);
2360       for (i = -MAX_RATIO; i <= MAX_RATIO; i++)
2361         {
2362           XEXP (addr, 1) = GEN_INT (i);
2363           if (memory_address_p (Pmode, addr))
2364             {
2365               SET_BIT (valid_mult, i + MAX_RATIO);
2366               rat = i;
2367             }
2368         }
2369
2370       if (dump_file && (dump_flags & TDF_DETAILS))
2371         {
2372           fprintf (dump_file, "  allowed multipliers:");
2373           for (i = -MAX_RATIO; i <= MAX_RATIO; i++)
2374             if (TEST_BIT (valid_mult, i + MAX_RATIO))
2375               fprintf (dump_file, " %d", (int) i);
2376           fprintf (dump_file, "\n");
2377           fprintf (dump_file, "\n");
2378         }
2379     }
2380
2381   bits = GET_MODE_BITSIZE (Pmode);
2382   mask = ~(~(unsigned HOST_WIDE_INT) 0 << (bits - 1) << 1);
2383   offset &= mask;
2384   if ((offset >> (bits - 1) & 1))
2385     offset |= ~mask;
2386   s_offset = offset;
2387
2388   cost = 0;
2389   offset_p = (min_offset <= s_offset && s_offset <= max_offset);
2390   ratio_p = (ratio != 1
2391              && -MAX_RATIO <= ratio && ratio <= MAX_RATIO
2392              && TEST_BIT (valid_mult, ratio + MAX_RATIO));
2393
2394   if (ratio != 1 && !ratio_p)
2395     cost += multiply_by_cost (ratio, Pmode);
2396
2397   if (s_offset && !offset_p && !symbol_present)
2398     {
2399       cost += add_cost (Pmode);
2400       var_present = true;
2401     }
2402
2403   acost = costs[symbol_present][var_present][offset_p][ratio_p];
2404   if (!acost)
2405     {
2406       acost = 0;
2407       
2408       addr = gen_raw_REG (Pmode, FIRST_PSEUDO_REGISTER);
2409       reg1 = gen_raw_REG (Pmode, FIRST_PSEUDO_REGISTER + 1);
2410       if (ratio_p)
2411         addr = gen_rtx_fmt_ee (MULT, Pmode, addr, GEN_INT (rat));
2412
2413       if (symbol_present)
2414         {
2415           base = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (""));
2416           if (offset_p)
2417             base = gen_rtx_fmt_e (CONST, Pmode,
2418                                   gen_rtx_fmt_ee (PLUS, Pmode,
2419                                                   base,
2420                                                   GEN_INT (off)));
2421           if (var_present)
2422             base = gen_rtx_fmt_ee (PLUS, Pmode, reg1, base);
2423         }
2424
2425       else if (var_present)
2426         {
2427           base = reg1;
2428           if (offset_p)
2429             base = gen_rtx_fmt_ee (PLUS, Pmode, base, GEN_INT (off));
2430         }
2431       else if (offset_p)
2432         base = GEN_INT (off);
2433       else
2434         base = NULL_RTX;
2435     
2436       if (base)
2437         addr = gen_rtx_fmt_ee (PLUS, Pmode, base, addr);
2438   
2439       start_sequence ();
2440       addr = memory_address (Pmode, addr);
2441       seq = get_insns ();
2442       end_sequence ();
2443   
2444       acost = seq_cost (seq);
2445       acost += address_cost (addr, Pmode);
2446
2447       if (!acost)
2448         acost = 1;
2449       costs[symbol_present][var_present][offset_p][ratio_p] = acost;
2450     }
2451
2452   return cost + acost;
2453 }
2454
2455 /* Records invariants in *EXPR_P.  Callback for walk_tree.  DATA contains
2456    the bitmap to that we should store it.  */
2457
2458 static struct ivopts_data *fd_ivopts_data;
2459 static tree
2460 find_depends (tree *expr_p, int *ws ATTRIBUTE_UNUSED, void *data)
2461 {
2462   bitmap *depends_on = data;
2463   struct version_info *info;
2464
2465   if (TREE_CODE (*expr_p) != SSA_NAME)
2466     return NULL_TREE;
2467   info = name_info (fd_ivopts_data, *expr_p);
2468
2469   if (!info->inv_id || info->has_nonlin_use)
2470     return NULL_TREE;
2471
2472   if (!*depends_on)
2473     *depends_on = BITMAP_XMALLOC ();
2474   bitmap_set_bit (*depends_on, info->inv_id);
2475
2476   return NULL_TREE;
2477 }
2478
2479 /* Estimates cost of forcing EXPR into variable.  DEPENDS_ON is a set of the
2480    invariants the computation depends on.  */
2481
2482 static unsigned
2483 force_var_cost (struct ivopts_data *data,
2484                 tree expr, bitmap *depends_on)
2485 {
2486   static bool costs_initialized = false;
2487   static unsigned integer_cost;
2488   static unsigned symbol_cost;
2489   static unsigned address_cost;
2490
2491   if (!costs_initialized)
2492     {
2493       tree var = create_tmp_var_raw (integer_type_node, "test_var");
2494       rtx x = gen_rtx_MEM (DECL_MODE (var),
2495                            gen_rtx_SYMBOL_REF (Pmode, "test_var"));
2496       tree addr;
2497       tree type = build_pointer_type (integer_type_node);
2498
2499       integer_cost = computation_cost (build_int_cst_type (integer_type_node,
2500                                                            2000));
2501
2502       SET_DECL_RTL (var, x);
2503       TREE_STATIC (var) = 1;
2504       addr = build1 (ADDR_EXPR, type, var);
2505       symbol_cost = computation_cost (addr) + 1;
2506
2507       address_cost
2508         = computation_cost (build2 (PLUS_EXPR, type,
2509                                     addr,
2510                                     build_int_cst_type (type, 2000))) + 1;
2511       if (dump_file && (dump_flags & TDF_DETAILS))
2512         {
2513           fprintf (dump_file, "force_var_cost:\n");
2514           fprintf (dump_file, "  integer %d\n", (int) integer_cost);
2515           fprintf (dump_file, "  symbol %d\n", (int) symbol_cost);
2516           fprintf (dump_file, "  address %d\n", (int) address_cost);
2517           fprintf (dump_file, "  other %d\n", (int) target_spill_cost);
2518           fprintf (dump_file, "\n");
2519         }
2520
2521       costs_initialized = true;
2522     }
2523
2524   if (depends_on)
2525     {
2526       fd_ivopts_data = data;
2527       walk_tree (&expr, find_depends, depends_on, NULL);
2528     }
2529
2530   if (SSA_VAR_P (expr))
2531     return 0;
2532
2533   if (TREE_INVARIANT (expr))
2534     {
2535       if (TREE_CODE (expr) == INTEGER_CST)
2536         return integer_cost;
2537
2538       if (TREE_CODE (expr) == ADDR_EXPR)
2539         {
2540           tree obj = TREE_OPERAND (expr, 0);
2541
2542           if (TREE_CODE (obj) == VAR_DECL
2543               || TREE_CODE (obj) == PARM_DECL
2544               || TREE_CODE (obj) == RESULT_DECL)
2545             return symbol_cost;
2546         }
2547
2548       return address_cost;
2549     }
2550
2551   /* Just an arbitrary value, FIXME.  */
2552   return target_spill_cost;
2553 }
2554
2555 /* Estimates cost of expressing address ADDR  as var + symbol + offset.  The
2556    value of offset is added to OFFSET, SYMBOL_PRESENT and VAR_PRESENT are set
2557    to false if the corresponding part is missing.  DEPENDS_ON is a set of the
2558    invariants the computation depends on.  */
2559
2560 static unsigned
2561 split_address_cost (struct ivopts_data *data,
2562                     tree addr, bool *symbol_present, bool *var_present,
2563                     unsigned HOST_WIDE_INT *offset, bitmap *depends_on)
2564 {
2565   tree core;
2566   HOST_WIDE_INT bitsize;
2567   HOST_WIDE_INT bitpos;
2568   tree toffset;
2569   enum machine_mode mode;
2570   int unsignedp, volatilep;
2571   
2572   core = get_inner_reference (addr, &bitsize, &bitpos, &toffset, &mode,
2573                               &unsignedp, &volatilep);
2574
2575   if (toffset != 0
2576       || bitpos % BITS_PER_UNIT != 0
2577       || TREE_CODE (core) != VAR_DECL)
2578     {
2579       *symbol_present = false;
2580       *var_present = true;
2581       fd_ivopts_data = data;
2582       walk_tree (&addr, find_depends, depends_on, NULL);
2583       return target_spill_cost;
2584     }
2585
2586   *offset += bitpos / BITS_PER_UNIT;
2587   if (TREE_STATIC (core)
2588       || DECL_EXTERNAL (core))
2589     {
2590       *symbol_present = true;
2591       *var_present = false;
2592       return 0;
2593     }
2594       
2595   *symbol_present = false;
2596   *var_present = true;
2597   return 0;
2598 }
2599
2600 /* Estimates cost of expressing difference of addresses E1 - E2 as
2601    var + symbol + offset.  The value of offset is added to OFFSET,
2602    SYMBOL_PRESENT and VAR_PRESENT are set to false if the corresponding
2603    part is missing.  DEPENDS_ON is a set of the invariants the computation
2604    depends on.  */
2605
2606 static unsigned
2607 ptr_difference_cost (struct ivopts_data *data,
2608                      tree e1, tree e2, bool *symbol_present, bool *var_present,
2609                      unsigned HOST_WIDE_INT *offset, bitmap *depends_on)
2610 {
2611   HOST_WIDE_INT diff = 0;
2612   unsigned cost;
2613
2614   gcc_assert (TREE_CODE (e1) == ADDR_EXPR);
2615
2616   if (TREE_CODE (e2) == ADDR_EXPR
2617       && ptr_difference_const (TREE_OPERAND (e1, 0),
2618                                TREE_OPERAND (e2, 0), &diff))
2619     {
2620       *offset += diff;
2621       *symbol_present = false;
2622       *var_present = false;
2623       return 0;
2624     }
2625
2626   if (e2 == integer_zero_node)
2627     return split_address_cost (data, TREE_OPERAND (e1, 0),
2628                                symbol_present, var_present, offset, depends_on);
2629
2630   *symbol_present = false;
2631   *var_present = true;
2632   
2633   cost = force_var_cost (data, e1, depends_on);
2634   cost += force_var_cost (data, e2, depends_on);
2635   cost += add_cost (Pmode);
2636
2637   return cost;
2638 }
2639
2640 /* Estimates cost of expressing difference E1 - E2 as
2641    var + symbol + offset.  The value of offset is added to OFFSET,
2642    SYMBOL_PRESENT and VAR_PRESENT are set to false if the corresponding
2643    part is missing.  DEPENDS_ON is a set of the invariants the computation
2644    depends on.  */
2645
2646 static unsigned
2647 difference_cost (struct ivopts_data *data,
2648                  tree e1, tree e2, bool *symbol_present, bool *var_present,
2649                  unsigned HOST_WIDE_INT *offset, bitmap *depends_on)
2650 {
2651   unsigned cost;
2652   enum machine_mode mode = TYPE_MODE (TREE_TYPE (e1));
2653
2654   strip_offset (&e1, offset);
2655   *offset = -*offset;
2656   strip_offset (&e2, offset);
2657   *offset = -*offset;
2658
2659   if (TREE_CODE (e1) == ADDR_EXPR)
2660     return ptr_difference_cost (data, e1, e2, symbol_present, var_present, offset,
2661                                 depends_on);
2662   *symbol_present = false;
2663
2664   if (operand_equal_p (e1, e2, 0))
2665     {
2666       *var_present = false;
2667       return 0;
2668     }
2669   *var_present = true;
2670   if (zero_p (e2))
2671     return force_var_cost (data, e1, depends_on);
2672
2673   if (zero_p (e1))
2674     {
2675       cost = force_var_cost (data, e2, depends_on);
2676       cost += multiply_by_cost (-1, mode);
2677
2678       return cost;
2679     }
2680
2681   cost = force_var_cost (data, e1, depends_on);
2682   cost += force_var_cost (data, e2, depends_on);
2683   cost += add_cost (mode);
2684
2685   return cost;
2686 }
2687
2688 /* Determines the cost of the computation by that USE is expressed
2689    from induction variable CAND.  If ADDRESS_P is true, we just need
2690    to create an address from it, otherwise we want to get it into
2691    register.  A set of invariants we depend on is stored in
2692    DEPENDS_ON.  AT is the statement at that the value is computed.  */
2693
2694 static unsigned
2695 get_computation_cost_at (struct ivopts_data *data,
2696                          struct iv_use *use, struct iv_cand *cand,
2697                          bool address_p, bitmap *depends_on, tree at)
2698 {
2699   tree ubase = use->iv->base, ustep = use->iv->step;
2700   tree cbase, cstep;
2701   tree utype = TREE_TYPE (ubase), ctype;
2702   unsigned HOST_WIDE_INT ustepi, cstepi, offset = 0;
2703   HOST_WIDE_INT ratio, aratio;
2704   bool var_present, symbol_present;
2705   unsigned cost = 0, n_sums;
2706
2707   *depends_on = NULL;
2708
2709   /* Only consider real candidates.  */
2710   if (!cand->iv)
2711     return INFTY;
2712
2713   cbase = cand->iv->base;
2714   cstep = cand->iv->step;
2715   ctype = TREE_TYPE (cbase);
2716
2717   if (TYPE_PRECISION (utype) > TYPE_PRECISION (ctype))
2718     {
2719       /* We do not have a precision to express the values of use.  */
2720       return INFTY;
2721     }
2722
2723   if (!cst_and_fits_in_hwi (ustep)
2724       || !cst_and_fits_in_hwi (cstep))
2725     return INFTY;
2726
2727   if (TREE_CODE (ubase) == INTEGER_CST
2728       && !cst_and_fits_in_hwi (ubase))
2729     goto fallback;
2730
2731   if (TREE_CODE (cbase) == INTEGER_CST
2732       && !cst_and_fits_in_hwi (cbase))
2733     goto fallback;
2734     
2735   ustepi = int_cst_value (ustep);
2736   cstepi = int_cst_value (cstep);
2737
2738   if (TYPE_PRECISION (utype) != TYPE_PRECISION (ctype))
2739     {
2740       /* TODO -- add direct handling of this case.  */
2741       goto fallback;
2742     }
2743
2744   if (!divide (TYPE_PRECISION (utype), ustepi, cstepi, &ratio))
2745     return INFTY;
2746
2747   /* use = ubase + ratio * (var - cbase).  If either cbase is a constant
2748      or ratio == 1, it is better to handle this like
2749      
2750      ubase - ratio * cbase + ratio * var
2751      
2752      (also holds in the case ratio == -1, TODO.  */
2753
2754   if (TREE_CODE (cbase) == INTEGER_CST)
2755     {
2756       offset = - ratio * int_cst_value (cbase); 
2757       cost += difference_cost (data,
2758                                ubase, integer_zero_node,
2759                                &symbol_present, &var_present, &offset,
2760                                depends_on);
2761     }
2762   else if (ratio == 1)
2763     {
2764       cost += difference_cost (data,
2765                                ubase, cbase,
2766                                &symbol_present, &var_present, &offset,
2767                                depends_on);
2768     }
2769   else
2770     {
2771       cost += force_var_cost (data, cbase, depends_on);
2772       cost += add_cost (TYPE_MODE (ctype));
2773       cost += difference_cost (data,
2774                                ubase, integer_zero_node,
2775                                &symbol_present, &var_present, &offset,
2776                                depends_on);
2777     }
2778
2779   /* If we are after the increment, the value of the candidate is higher by
2780      one iteration.  */
2781   if (stmt_after_increment (data->current_loop, cand, at))
2782     offset -= ratio * cstepi;
2783
2784   /* Now the computation is in shape symbol + var1 + const + ratio * var2.
2785      (symbol/var/const parts may be omitted).  If we are looking for an address,
2786      find the cost of addressing this.  */
2787   if (address_p)
2788     return get_address_cost (symbol_present, var_present, offset, ratio);
2789
2790   /* Otherwise estimate the costs for computing the expression.  */
2791   aratio = ratio > 0 ? ratio : -ratio;
2792   if (!symbol_present && !var_present && !offset)
2793     {
2794       if (ratio != 1)
2795         cost += multiply_by_cost (ratio, TYPE_MODE (ctype));
2796
2797       return cost;
2798     }
2799
2800   if (aratio != 1)
2801     cost += multiply_by_cost (aratio, TYPE_MODE (ctype));
2802
2803   n_sums = 1;
2804   if (var_present
2805       /* Symbol + offset should be compile-time computable.  */
2806       && (symbol_present || offset))
2807     n_sums++;
2808
2809   return cost + n_sums * add_cost (TYPE_MODE (ctype));
2810
2811 fallback:
2812   {
2813     /* Just get the expression, expand it and measure the cost.  */
2814     tree comp = get_computation_at (data->current_loop, use, cand, at);
2815
2816     if (!comp)
2817       return INFTY;
2818
2819     if (address_p)
2820       comp = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (comp)), comp);
2821
2822     return computation_cost (comp);
2823   }
2824 }
2825
2826 /* Determines the cost of the computation by that USE is expressed
2827    from induction variable CAND.  If ADDRESS_P is true, we just need
2828    to create an address from it, otherwise we want to get it into
2829    register.  A set of invariants we depend on is stored in
2830    DEPENDS_ON.  */
2831
2832 static unsigned
2833 get_computation_cost (struct ivopts_data *data,
2834                       struct iv_use *use, struct iv_cand *cand,
2835                       bool address_p, bitmap *depends_on)
2836 {
2837   return get_computation_cost_at (data,
2838                                   use, cand, address_p, depends_on, use->stmt);
2839 }
2840
2841 /* Determines cost of basing replacement of USE on CAND in a generic
2842    expression.  */
2843
2844 static void
2845 determine_use_iv_cost_generic (struct ivopts_data *data,
2846                                struct iv_use *use, struct iv_cand *cand)
2847 {
2848   bitmap depends_on;
2849   unsigned cost = get_computation_cost (data, use, cand, false, &depends_on);
2850
2851   set_use_iv_cost (data, use, cand, cost, depends_on);
2852 }
2853
2854 /* Determines cost of basing replacement of USE on CAND in an address.  */
2855
2856 static void
2857 determine_use_iv_cost_address (struct ivopts_data *data,
2858                                struct iv_use *use, struct iv_cand *cand)
2859 {
2860   bitmap depends_on;
2861   unsigned cost = get_computation_cost (data, use, cand, true, &depends_on);
2862
2863   set_use_iv_cost (data, use, cand, cost, depends_on);
2864 }
2865
2866 /* Computes value of induction variable IV in iteration NITER.  */
2867
2868 static tree
2869 iv_value (struct iv *iv, tree niter)
2870 {
2871   tree val;
2872   tree type = TREE_TYPE (iv->base);
2873
2874   niter = fold_convert (type, niter);
2875   val = fold (build2 (MULT_EXPR, type, iv->step, niter));
2876
2877   return fold (build2 (PLUS_EXPR, type, iv->base, val));
2878 }
2879
2880 /* Computes value of candidate CAND at position AT in iteration NITER.  */
2881
2882 static tree
2883 cand_value_at (struct loop *loop, struct iv_cand *cand, tree at, tree niter)
2884 {
2885   tree val = iv_value (cand->iv, niter);
2886   tree type = TREE_TYPE (cand->iv->base);
2887
2888   if (stmt_after_increment (loop, cand, at))
2889     val = fold (build2 (PLUS_EXPR, type, val, cand->iv->step));
2890
2891   return val;
2892 }
2893
2894 /* Check whether it is possible to express the condition in USE by comparison
2895    of candidate CAND.  If so, store the comparison code to COMPARE and the
2896    value compared with to BOUND.  */
2897
2898 static bool
2899 may_eliminate_iv (struct loop *loop,
2900                   struct iv_use *use, struct iv_cand *cand,
2901                   enum tree_code *compare, tree *bound)
2902 {
2903   edge exit;
2904   struct tree_niter_desc *niter, new_niter;
2905   tree wider_type, type, base;
2906
2907   /* For now just very primitive -- we work just for the single exit condition,
2908      and are quite conservative about the possible overflows.  TODO -- both of
2909      these can be improved.  */
2910   exit = single_dom_exit (loop);
2911   if (!exit)
2912     return false;
2913   if (use->stmt != last_stmt (exit->src))
2914     return false;
2915
2916   niter = &loop_data (loop)->niter;
2917   if (!niter->niter
2918       || !integer_nonzerop (niter->assumptions)
2919       || !integer_zerop (niter->may_be_zero))
2920     return false;
2921
2922   if (exit->flags & EDGE_TRUE_VALUE)
2923     *compare = EQ_EXPR;
2924   else
2925     *compare = NE_EXPR;
2926
2927   *bound = cand_value_at (loop, cand, use->stmt, niter->niter);
2928
2929   /* Let us check there is not some problem with overflows, by checking that
2930      the number of iterations is unchanged.  */
2931   base = cand->iv->base;
2932   type = TREE_TYPE (base);
2933   if (stmt_after_increment (loop, cand, use->stmt))
2934     base = fold (build2 (PLUS_EXPR, type, base, cand->iv->step));
2935
2936   new_niter.niter = NULL_TREE;
2937   number_of_iterations_cond (TREE_TYPE (cand->iv->base), base,
2938                              cand->iv->step, NE_EXPR, *bound, NULL_TREE,
2939                              &new_niter);
2940   if (!new_niter.niter
2941       || !integer_nonzerop (new_niter.assumptions)
2942       || !integer_zerop (new_niter.may_be_zero))
2943     return false;
2944
2945   wider_type = TREE_TYPE (new_niter.niter);
2946   if (TYPE_PRECISION (wider_type) < TYPE_PRECISION (TREE_TYPE (niter->niter)))
2947     wider_type = TREE_TYPE (niter->niter);
2948   if (!operand_equal_p (fold_convert (wider_type, niter->niter),
2949                         fold_convert (wider_type, new_niter.niter), 0))
2950     return false;
2951
2952   return true;
2953 }
2954
2955 /* Determines cost of basing replacement of USE on CAND in a condition.  */
2956
2957 static void
2958 determine_use_iv_cost_condition (struct ivopts_data *data,
2959                                  struct iv_use *use, struct iv_cand *cand)
2960 {
2961   tree bound;
2962   enum tree_code compare;
2963
2964   /* Only consider real candidates.  */
2965   if (!cand->iv)
2966     {
2967       set_use_iv_cost (data, use, cand, INFTY, NULL);
2968       return;
2969     }
2970
2971   if (may_eliminate_iv (data->current_loop, use, cand, &compare, &bound))
2972     {
2973       bitmap depends_on = NULL;
2974       unsigned cost = force_var_cost (data, bound, &depends_on);
2975
2976       set_use_iv_cost (data, use, cand, cost, depends_on);
2977       return;
2978     }
2979
2980   /* The induction variable elimination failed; just express the original
2981      giv.  If it is compared with an invariant, note that we cannot get
2982      rid of it.  */
2983   if (TREE_CODE (*use->op_p) == SSA_NAME)
2984     record_invariant (data, *use->op_p, true);
2985   else
2986     {
2987       record_invariant (data, TREE_OPERAND (*use->op_p, 0), true);
2988       record_invariant (data, TREE_OPERAND (*use->op_p, 1), true);
2989     }
2990
2991   determine_use_iv_cost_generic (data, use, cand);
2992 }
2993
2994 /* Checks whether it is possible to replace the final value of USE by
2995    a direct computation.  If so, the formula is stored to *VALUE.  */
2996
2997 static bool
2998 may_replace_final_value (struct loop *loop, struct iv_use *use, tree *value)
2999 {
3000   edge exit;
3001   struct tree_niter_desc *niter;
3002
3003   exit = single_dom_exit (loop);
3004   if (!exit)
3005     return false;
3006
3007   gcc_assert (dominated_by_p (CDI_DOMINATORS, exit->src,
3008                               bb_for_stmt (use->stmt)));
3009
3010   niter = &loop_data (loop)->niter;
3011   if (!niter->niter
3012       || !operand_equal_p (niter->assumptions, boolean_true_node, 0)
3013       || !operand_equal_p (niter->may_be_zero, boolean_false_node, 0))
3014     return false;
3015
3016   *value = iv_value (use->iv, niter->niter);
3017
3018   return true;
3019 }
3020
3021 /* Determines cost of replacing final value of USE using CAND.  */
3022
3023 static void
3024 determine_use_iv_cost_outer (struct ivopts_data *data,
3025                              struct iv_use *use, struct iv_cand *cand)
3026 {
3027   bitmap depends_on;
3028   unsigned cost;
3029   edge exit;
3030   tree value;
3031   struct loop *loop = data->current_loop;
3032           
3033   if (!cand->iv)
3034     {
3035       if (!may_replace_final_value (loop, use, &value))
3036         {
3037           set_use_iv_cost (data, use, cand, INFTY, NULL);
3038           return;
3039         }
3040
3041       depends_on = NULL;
3042       cost = force_var_cost (data, value, &depends_on);
3043
3044       cost /= AVG_LOOP_NITER (loop);
3045
3046       set_use_iv_cost (data, use, cand, cost, depends_on);
3047       return;
3048     }
3049
3050   exit = single_dom_exit (loop);
3051   if (exit)
3052     {
3053       /* If there is just a single exit, we may use value of the candidate
3054          after we take it to determine the value of use.  */
3055       cost = get_computation_cost_at (data, use, cand, false, &depends_on,
3056                                       last_stmt (exit->src));
3057       if (cost != INFTY)
3058         cost /= AVG_LOOP_NITER (loop);
3059     }
3060   else
3061     {
3062       /* Otherwise we just need to compute the iv.  */
3063       cost = get_computation_cost (data, use, cand, false, &depends_on);
3064     }
3065                                    
3066   set_use_iv_cost (data, use, cand, cost, depends_on);
3067 }
3068
3069 /* Determines cost of basing replacement of USE on CAND.  */
3070
3071 static void
3072 determine_use_iv_cost (struct ivopts_data *data,
3073                        struct iv_use *use, struct iv_cand *cand)
3074 {
3075   switch (use->type)
3076     {
3077     case USE_NONLINEAR_EXPR:
3078       determine_use_iv_cost_generic (data, use, cand);
3079       break;
3080
3081     case USE_OUTER:
3082       determine_use_iv_cost_outer (data, use, cand);
3083       break;
3084
3085     case USE_ADDRESS:
3086       determine_use_iv_cost_address (data, use, cand);
3087       break;
3088
3089     case USE_COMPARE:
3090       determine_use_iv_cost_condition (data, use, cand);
3091       break;
3092
3093     default:
3094       gcc_unreachable ();
3095     }
3096 }
3097
3098 /* Determines costs of basing the use of the iv on an iv candidate.  */
3099
3100 static void
3101 determine_use_iv_costs (struct ivopts_data *data)
3102 {
3103   unsigned i, j;
3104   struct iv_use *use;
3105   struct iv_cand *cand;
3106
3107   data->consider_all_candidates = (n_iv_cands (data)
3108                                    <= CONSIDER_ALL_CANDIDATES_BOUND);
3109
3110   alloc_use_cost_map (data);
3111
3112   if (!data->consider_all_candidates)
3113     {
3114       /* Add the important candidate entries.  */
3115       for (j = 0; j < n_iv_cands (data); j++)
3116         {
3117           cand = iv_cand (data, j);
3118           if (!cand->important)
3119             continue;
3120           for (i = 0; i < n_iv_uses (data); i++)
3121             {
3122               use = iv_use (data, i);
3123               determine_use_iv_cost (data, use, cand);
3124             }
3125         }
3126     }
3127
3128   for (i = 0; i < n_iv_uses (data); i++)
3129     {
3130       use = iv_use (data, i);
3131
3132       if (data->consider_all_candidates)
3133         {
3134           for (j = 0; j < n_iv_cands (data); j++)
3135             {
3136               cand = iv_cand (data, j);
3137               determine_use_iv_cost (data, use, cand);
3138             }
3139         }
3140       else
3141         {
3142           EXECUTE_IF_SET_IN_BITMAP (use->related_cands, 0, j,
3143             {
3144               cand = iv_cand (data, j);
3145               if (!cand->important)
3146                 determine_use_iv_cost (data, use, cand);
3147             });
3148         }
3149     }
3150
3151   if (dump_file && (dump_flags & TDF_DETAILS))
3152     {
3153       fprintf (dump_file, "Use-candidate costs:\n");
3154
3155       for (i = 0; i < n_iv_uses (data); i++)
3156         {
3157           use = iv_use (data, i);
3158
3159           fprintf (dump_file, "Use %d:\n", i);
3160           fprintf (dump_file, "  cand\tcost\tdepends on\n");
3161           for (j = 0; j < use->n_map_members; j++)
3162             {
3163               if (!use->cost_map[j].cand
3164                   || use->cost_map[j].cost == INFTY)
3165                 continue;
3166
3167               fprintf (dump_file, "  %d\t%d\t",
3168                        use->cost_map[j].cand->id,
3169                        use->cost_map[j].cost);
3170               if (use->cost_map[j].depends_on)
3171                 bitmap_print (dump_file,
3172                               use->cost_map[j].depends_on, "","");
3173               fprintf (dump_file, "\n");
3174             }
3175
3176           fprintf (dump_file, "\n");
3177         }
3178       fprintf (dump_file, "\n");
3179     }
3180 }
3181
3182 /* Determines cost of the candidate CAND.  */
3183
3184 static void
3185 determine_iv_cost (struct ivopts_data *data, struct iv_cand *cand)
3186 {
3187   unsigned cost_base, cost_step;
3188   tree base, last;
3189   basic_block bb;
3190
3191   if (!cand->iv)
3192     {
3193       cand->cost = 0;
3194       return;
3195     }
3196
3197   /* There are two costs associated with the candidate -- its increment
3198      and its initialization.  The second is almost negligible for any loop
3199      that rolls enough, so we take it just very little into account.  */
3200
3201   base = cand->iv->base;
3202   cost_base = force_var_cost (data, base, NULL);
3203   cost_step = add_cost (TYPE_MODE (TREE_TYPE (base)));
3204
3205   cand->cost = cost_step + cost_base / AVG_LOOP_NITER (current_loop);
3206
3207   /* Prefer the original iv unless we may gain something by replacing it.  */
3208   if (cand->pos == IP_ORIGINAL)
3209     cand->cost--;
3210   
3211   /* Prefer not to insert statements into latch unless there are some
3212      already (so that we do not create unnecessary jumps).  */
3213   if (cand->pos == IP_END)
3214     {
3215       bb = ip_end_pos (data->current_loop);
3216       last = last_stmt (bb);
3217
3218       if (!last
3219           || TREE_CODE (last) == LABEL_EXPR)
3220         cand->cost++;
3221     }
3222 }
3223
3224 /* Determines costs of computation of the candidates.  */
3225
3226 static void
3227 determine_iv_costs (struct ivopts_data *data)
3228 {
3229   unsigned i;
3230
3231   if (dump_file && (dump_flags & TDF_DETAILS))
3232     {
3233       fprintf (dump_file, "Candidate costs:\n");
3234       fprintf (dump_file, "  cand\tcost\n");
3235     }
3236
3237   for (i = 0; i < n_iv_cands (data); i++)
3238     {
3239       struct iv_cand *cand = iv_cand (data, i);
3240
3241       determine_iv_cost (data, cand);
3242
3243       if (dump_file && (dump_flags & TDF_DETAILS))
3244         fprintf (dump_file, "  %d\t%d\n", i, cand->cost);
3245     }
3246   
3247 if (dump_file && (dump_flags & TDF_DETAILS))
3248       fprintf (dump_file, "\n");
3249 }
3250
3251 /* Calculates cost for having SIZE induction variables.  */
3252
3253 static unsigned
3254 ivopts_global_cost_for_size (struct ivopts_data *data, unsigned size)
3255 {
3256   return global_cost_for_size (size,
3257                                loop_data (data->current_loop)->regs_used,
3258                                n_iv_uses (data));
3259 }
3260
3261 /* For each size of the induction variable set determine the penalty.  */
3262
3263 static void
3264 determine_set_costs (struct ivopts_data *data)
3265 {
3266   unsigned j, n;
3267   tree phi, op;
3268   struct loop *loop = data->current_loop;
3269
3270   /* We use the following model (definitely improvable, especially the
3271      cost function -- TODO):
3272
3273      We estimate the number of registers available (using MD data), name it A.
3274
3275      We estimate the number of registers used by the loop, name it U.  This
3276      number is obtained as the number of loop phi nodes (not counting virtual
3277      registers and bivs) + the number of variables from outside of the loop.
3278
3279      We set a reserve R (free regs that are used for temporary computations,
3280      etc.).  For now the reserve is a constant 3.
3281
3282      Let I be the number of induction variables.
3283      
3284      -- if U + I + R <= A, the cost is I * SMALL_COST (just not to encourage
3285         make a lot of ivs without a reason).
3286      -- if A - R < U + I <= A, the cost is I * PRES_COST
3287      -- if U + I > A, the cost is I * PRES_COST and
3288         number of uses * SPILL_COST * (U + I - A) / (U + I) is added.  */
3289
3290   if (dump_file && (dump_flags & TDF_DETAILS))
3291     {
3292       fprintf (dump_file, "Global costs:\n");
3293       fprintf (dump_file, "  target_avail_regs %d\n", target_avail_regs);
3294       fprintf (dump_file, "  target_small_cost %d\n", target_small_cost);
3295       fprintf (dump_file, "  target_pres_cost %d\n", target_pres_cost);
3296       fprintf (dump_file, "  target_spill_cost %d\n", target_spill_cost);
3297     }
3298
3299   n = 0;
3300   for (phi = phi_nodes (loop->header); phi; phi = TREE_CHAIN (phi))
3301     {
3302       op = PHI_RESULT (phi);
3303
3304       if (!is_gimple_reg (op))
3305         continue;
3306
3307       if (get_iv (data, op))
3308         continue;
3309
3310       n++;
3311     }
3312
3313   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, j,
3314     {
3315       struct version_info *info = ver_info (data, j);
3316
3317       if (info->inv_id && info->has_nonlin_use)
3318         n++;
3319     });
3320
3321   loop_data (loop)->regs_used = n;
3322   if (dump_file && (dump_flags & TDF_DETAILS))
3323     fprintf (dump_file, "  regs_used %d\n", n);
3324
3325   if (dump_file && (dump_flags & TDF_DETAILS))
3326     {
3327       fprintf (dump_file, "  cost for size:\n");
3328       fprintf (dump_file, "  ivs\tcost\n");
3329       for (j = 0; j <= 2 * target_avail_regs; j++)
3330         fprintf (dump_file, "  %d\t%d\n", j,
3331                  ivopts_global_cost_for_size (data, j));
3332       fprintf (dump_file, "\n");
3333     }
3334 }
3335
3336 /* Finds a best candidate for USE and stores it to CAND.  The candidates are
3337    taken from the set SOL and they may depend on invariants in the set INV.
3338    The really used candidate and invariants are noted to USED_IVS and
3339    USED_INV.  */
3340
3341 static unsigned
3342 find_best_candidate (struct ivopts_data *data,
3343                      struct iv_use *use, bitmap sol, bitmap inv,
3344                      bitmap used_ivs, bitmap used_inv, struct iv_cand **cand)
3345 {
3346   unsigned c, d;
3347   unsigned best_cost = INFTY, cost;
3348   struct iv_cand *cnd = NULL, *acnd;
3349   bitmap depends_on = NULL, asol;
3350
3351   if (data->consider_all_candidates)
3352     asol = sol;
3353   else
3354     {
3355       asol = BITMAP_XMALLOC ();
3356       bitmap_a_and_b (asol, sol, use->related_cands);
3357     }
3358
3359   EXECUTE_IF_SET_IN_BITMAP (asol, 0, c,
3360     {
3361       acnd = iv_cand (data, c);
3362       cost = get_use_iv_cost (data, use, acnd, &depends_on);
3363
3364       if (cost == INFTY)
3365         goto next_cand;
3366       if (cost > best_cost)
3367         goto next_cand;
3368       if (cost == best_cost)
3369         {
3370           /* Prefer the cheaper iv.  */
3371           if (acnd->cost >= cnd->cost)
3372             goto next_cand;
3373         }
3374
3375       if (depends_on)
3376         {
3377           EXECUTE_IF_AND_COMPL_IN_BITMAP (depends_on, inv, 0, d,
3378                                           goto next_cand);
3379           if (used_inv)
3380             bitmap_a_or_b (used_inv, used_inv, depends_on);
3381         }
3382
3383       cnd = acnd;
3384       best_cost = cost;
3385 next_cand: ;
3386     });
3387
3388   if (cnd && used_ivs)
3389     bitmap_set_bit (used_ivs, cnd->id);
3390
3391   if (cand)
3392     *cand = cnd;
3393
3394   if (!data->consider_all_candidates)
3395     BITMAP_XFREE (asol);
3396
3397   return best_cost;
3398 }
3399
3400 /* Returns cost of set of ivs SOL + invariants INV.  Removes unnecessary
3401    induction variable candidates and invariants from the sets.  Only
3402    uses 0 .. MAX_USE - 1 are taken into account.  */
3403
3404 static unsigned
3405 set_cost_up_to (struct ivopts_data *data, bitmap sol, bitmap inv,
3406                 unsigned max_use)
3407 {
3408   unsigned i;
3409   unsigned cost = 0, size = 0, acost;
3410   struct iv_use *use;
3411   struct iv_cand *cand;
3412   bitmap used_ivs = BITMAP_XMALLOC (), used_inv = BITMAP_XMALLOC ();
3413
3414   for (i = 0; i < max_use; i++)
3415     {
3416       use = iv_use (data, i);
3417       acost = find_best_candidate (data, use, sol, inv,
3418                                    used_ivs, used_inv, NULL);
3419       if (acost == INFTY)
3420         {
3421           BITMAP_XFREE (used_ivs);
3422           BITMAP_XFREE (used_inv);
3423           return INFTY;
3424         }
3425       cost += acost;
3426     }
3427
3428   EXECUTE_IF_SET_IN_BITMAP (used_ivs, 0, i,
3429     {
3430       cand = iv_cand (data, i);
3431
3432       /* Do not count the pseudocandidates.  */
3433       if (cand->iv)
3434         size++;
3435
3436       cost += cand->cost;
3437     });
3438   EXECUTE_IF_SET_IN_BITMAP (used_inv, 0, i, size++);
3439   cost += ivopts_global_cost_for_size (data, size);
3440
3441   bitmap_copy (sol, used_ivs);
3442   bitmap_copy (inv, used_inv);
3443
3444   BITMAP_XFREE (used_ivs);
3445   BITMAP_XFREE (used_inv);
3446
3447   return cost;
3448 }
3449
3450 /* Computes cost of set of ivs SOL + invariants INV.  Removes unnecessary
3451    induction variable candidates and invariants from the sets.  */
3452
3453 static unsigned
3454 set_cost (struct ivopts_data *data, bitmap sol, bitmap inv)
3455 {
3456   return set_cost_up_to (data, sol, inv, n_iv_uses (data));
3457 }
3458
3459 /* Tries to extend the sets IVS and INV in the best possible way in order
3460    to express the USE.  */
3461
3462 static bool
3463 try_add_cand_for (struct ivopts_data *data, bitmap ivs, bitmap inv,
3464                   struct iv_use *use)
3465 {
3466   unsigned best_cost = set_cost_up_to (data, ivs, inv, use->id + 1), act_cost;
3467   bitmap best_ivs = BITMAP_XMALLOC ();
3468   bitmap best_inv = BITMAP_XMALLOC ();
3469   bitmap act_ivs = BITMAP_XMALLOC ();
3470   bitmap act_inv = BITMAP_XMALLOC ();
3471   unsigned i;
3472   struct cost_pair *cp;
3473
3474   bitmap_copy (best_ivs, ivs);
3475   bitmap_copy (best_inv, inv);
3476
3477   for (i = 0; i < use->n_map_members; i++)
3478     {
3479       cp = use->cost_map + i;
3480       if (cp->cost == INFTY)
3481         continue;
3482
3483       bitmap_copy (act_ivs, ivs);
3484       bitmap_set_bit (act_ivs, cp->cand->id);
3485       if (cp->depends_on)
3486         bitmap_a_or_b (act_inv, inv, cp->depends_on);
3487       else
3488         bitmap_copy (act_inv, inv);
3489       act_cost = set_cost_up_to (data, act_ivs, act_inv, use->id + 1);
3490
3491       if (act_cost < best_cost)
3492         {
3493           best_cost = act_cost;
3494           bitmap_copy (best_ivs, act_ivs);
3495           bitmap_copy (best_inv, act_inv);
3496         }
3497     }
3498
3499   bitmap_copy (ivs, best_ivs);
3500   bitmap_copy (inv, best_inv);
3501
3502   BITMAP_XFREE (best_ivs);
3503   BITMAP_XFREE (best_inv);
3504   BITMAP_XFREE (act_ivs);
3505   BITMAP_XFREE (act_inv);
3506
3507   return (best_cost != INFTY);
3508 }
3509
3510 /* Finds an initial set of IVS and invariants INV.  We do this by simply
3511    choosing the best candidate for each use.  */
3512
3513 static unsigned
3514 get_initial_solution (struct ivopts_data *data, bitmap ivs, bitmap inv)
3515 {
3516   unsigned i;
3517
3518   for (i = 0; i < n_iv_uses (data); i++)
3519     if (!try_add_cand_for (data, ivs, inv, iv_use (data, i)))
3520       return INFTY;
3521
3522   return set_cost (data, ivs, inv);
3523 }
3524
3525 /* Tries to improve set of induction variables IVS and invariants INV to get
3526    it better than COST.  */
3527
3528 static bool
3529 try_improve_iv_set (struct ivopts_data *data,
3530                     bitmap ivs, bitmap inv, unsigned *cost)
3531 {
3532   unsigned i, acost;
3533   bitmap new_ivs = BITMAP_XMALLOC (), new_inv = BITMAP_XMALLOC ();
3534   bitmap best_new_ivs = NULL, best_new_inv = NULL;
3535
3536   /* Try altering the set of induction variables by one.  */
3537   for (i = 0; i < n_iv_cands (data); i++)
3538     {
3539       bitmap_copy (new_ivs, ivs);
3540       bitmap_copy (new_inv, inv);
3541
3542       if (bitmap_bit_p (ivs, i))
3543         bitmap_clear_bit (new_ivs, i);
3544       else
3545         bitmap_set_bit (new_ivs, i);
3546
3547       acost = set_cost (data, new_ivs, new_inv);
3548       if (acost >= *cost)
3549         continue;
3550
3551       if (!best_new_ivs)
3552         {
3553           best_new_ivs = BITMAP_XMALLOC ();
3554           best_new_inv = BITMAP_XMALLOC ();
3555         }
3556
3557       *cost = acost;
3558       bitmap_copy (best_new_ivs, new_ivs);
3559       bitmap_copy (best_new_inv, new_inv);
3560     }
3561
3562   /* Ditto for invariants.  */
3563   for (i = 1; i <= data->max_inv_id; i++)
3564     {
3565       if (ver_info (data, i)->has_nonlin_use)
3566         continue;
3567
3568       bitmap_copy (new_ivs, ivs);
3569       bitmap_copy (new_inv, inv);
3570
3571       if (bitmap_bit_p (inv, i))
3572         bitmap_clear_bit (new_inv, i);
3573       else
3574         bitmap_set_bit (new_inv, i);
3575
3576       acost = set_cost (data, new_ivs, new_inv);
3577       if (acost >= *cost)
3578         continue;
3579
3580       if (!best_new_ivs)
3581         {
3582           best_new_ivs = BITMAP_XMALLOC ();
3583           best_new_inv = BITMAP_XMALLOC ();
3584         }
3585
3586       *cost = acost;
3587       bitmap_copy (best_new_ivs, new_ivs);
3588       bitmap_copy (best_new_inv, new_inv);
3589     }
3590
3591   BITMAP_XFREE (new_ivs);
3592   BITMAP_XFREE (new_inv);
3593
3594   if (!best_new_ivs)
3595     return false;
3596
3597   bitmap_copy (ivs, best_new_ivs);
3598   bitmap_copy (inv, best_new_inv);
3599   BITMAP_XFREE (best_new_ivs);
3600   BITMAP_XFREE (best_new_inv);
3601   return true;
3602 }
3603
3604 /* Attempts to find the optimal set of induction variables.  We do simple
3605    greedy heuristic -- we try to replace at most one candidate in the selected
3606    solution and remove the unused ivs while this improves the cost.  */
3607
3608 static bitmap
3609 find_optimal_iv_set (struct ivopts_data *data)
3610 {
3611   unsigned cost, i;
3612   bitmap set = BITMAP_XMALLOC ();
3613   bitmap inv = BITMAP_XMALLOC ();
3614   struct iv_use *use;
3615
3616   /* Set the upper bound.  */
3617   cost = get_initial_solution (data, set, inv);
3618   if (cost == INFTY)
3619     {
3620       if (dump_file && (dump_flags & TDF_DETAILS))
3621         fprintf (dump_file, "Unable to substitute for ivs, failed.\n");
3622       BITMAP_XFREE (inv);
3623       BITMAP_XFREE (set);
3624       return NULL;
3625     }
3626
3627   if (dump_file && (dump_flags & TDF_DETAILS))
3628     {
3629       fprintf (dump_file, "Initial set of candidates (cost %d): ", cost);
3630       bitmap_print (dump_file, set, "", "");
3631       fprintf (dump_file, " invariants ");
3632       bitmap_print (dump_file, inv, "", "");
3633       fprintf (dump_file, "\n");
3634     }
3635
3636   while (try_improve_iv_set (data, set, inv, &cost))
3637     {
3638       if (dump_file && (dump_flags & TDF_DETAILS))
3639         {
3640           fprintf (dump_file, "Improved to (cost %d): ", cost);
3641           bitmap_print (dump_file, set, "", "");
3642           fprintf (dump_file, " invariants ");
3643           bitmap_print (dump_file, inv, "", "");
3644           fprintf (dump_file, "\n");
3645         }
3646     }
3647
3648   if (dump_file && (dump_flags & TDF_DETAILS))
3649     fprintf (dump_file, "Final cost %d\n\n", cost);
3650
3651   for (i = 0; i < n_iv_uses (data); i++)
3652     {
3653       use = iv_use (data, i);
3654       find_best_candidate (data, use, set, inv, NULL, NULL, &use->selected);
3655     }
3656
3657   BITMAP_XFREE (inv);
3658
3659   return set;
3660 }
3661
3662 /* Creates a new induction variable corresponding to CAND.  */
3663
3664 static void
3665 create_new_iv (struct ivopts_data *data, struct iv_cand *cand)
3666 {
3667   block_stmt_iterator incr_pos;
3668   tree base;
3669   bool after = false;
3670
3671   if (!cand->iv)
3672     return;
3673
3674   switch (cand->pos)
3675     {
3676     case IP_NORMAL:
3677       incr_pos = bsi_last (ip_normal_pos (data->current_loop));
3678       break;
3679
3680     case IP_END:
3681       incr_pos = bsi_last (ip_end_pos (data->current_loop));
3682       after = true;
3683       break;
3684
3685     case IP_ORIGINAL:
3686       /* Mark that the iv is preserved.  */
3687       name_info (data, cand->var_before)->preserve_biv = true;
3688       name_info (data, cand->var_after)->preserve_biv = true;
3689
3690       /* Rewrite the increment so that it uses var_before directly.  */
3691       find_interesting_uses_op (data, cand->var_after)->selected = cand;
3692       
3693       return;
3694     }
3695  
3696   gimple_add_tmp_var (cand->var_before);
3697   add_referenced_tmp_var (cand->var_before);
3698
3699   base = unshare_expr (cand->iv->base);
3700
3701   create_iv (base, cand->iv->step, cand->var_before, data->current_loop,
3702              &incr_pos, after, &cand->var_before, &cand->var_after);
3703 }
3704
3705 /* Creates new induction variables described in SET.  */
3706
3707 static void
3708 create_new_ivs (struct ivopts_data *data, bitmap set)
3709 {
3710   unsigned i;
3711   struct iv_cand *cand;
3712
3713   EXECUTE_IF_SET_IN_BITMAP (set, 0, i,
3714     {
3715       cand = iv_cand (data, i);
3716       create_new_iv (data, cand);
3717     });
3718 }
3719
3720 /* Removes statement STMT (real or a phi node).  If INCLUDING_DEFINED_NAME
3721    is true, remove also the ssa name defined by the statement.  */
3722
3723 static void
3724 remove_statement (tree stmt, bool including_defined_name)
3725 {
3726   if (TREE_CODE (stmt) == PHI_NODE)
3727     {
3728       if (!including_defined_name)
3729         {
3730           /* Prevent the ssa name defined by the statement from being removed.  */
3731           SET_PHI_RESULT (stmt, NULL);
3732         }
3733       remove_phi_node (stmt, NULL_TREE, bb_for_stmt (stmt));
3734     }
3735   else
3736     {
3737       block_stmt_iterator bsi = stmt_for_bsi (stmt);
3738
3739       bsi_remove (&bsi);
3740     }
3741 }
3742
3743 /* Rewrites USE (definition of iv used in a nonlinear expression)
3744    using candidate CAND.  */
3745
3746 static void
3747 rewrite_use_nonlinear_expr (struct ivopts_data *data,
3748                             struct iv_use *use, struct iv_cand *cand)
3749 {
3750   tree comp = unshare_expr (get_computation (data->current_loop,
3751                                              use, cand));
3752   tree op, stmts, tgt, ass;
3753   block_stmt_iterator bsi, pbsi;
3754  
3755   switch (TREE_CODE (use->stmt))
3756     {
3757     case PHI_NODE:
3758       tgt = PHI_RESULT (use->stmt);
3759
3760       /* If we should keep the biv, do not replace it.  */
3761       if (name_info (data, tgt)->preserve_biv)
3762         return;
3763
3764       pbsi = bsi = bsi_start (bb_for_stmt (use->stmt));
3765       while (!bsi_end_p (pbsi)
3766              && TREE_CODE (bsi_stmt (pbsi)) == LABEL_EXPR)
3767         {
3768           bsi = pbsi;
3769           bsi_next (&pbsi);
3770         }
3771       break;
3772
3773     case MODIFY_EXPR:
3774       tgt = TREE_OPERAND (use->stmt, 0);
3775       bsi = stmt_for_bsi (use->stmt);
3776       break;
3777
3778     default:
3779       gcc_unreachable ();
3780     }
3781
3782   op = force_gimple_operand (comp, &stmts, false, SSA_NAME_VAR (tgt));
3783
3784   if (TREE_CODE (use->stmt) == PHI_NODE)
3785     {
3786       if (stmts)
3787         bsi_insert_after (&bsi, stmts, BSI_CONTINUE_LINKING);
3788       ass = build2 (MODIFY_EXPR, TREE_TYPE (tgt), tgt, op);
3789       bsi_insert_after (&bsi, ass, BSI_NEW_STMT);
3790       remove_statement (use->stmt, false);
3791       SSA_NAME_DEF_STMT (tgt) = ass;
3792     }
3793   else
3794     {
3795       if (stmts)
3796         bsi_insert_before (&bsi, stmts, BSI_SAME_STMT);
3797       TREE_OPERAND (use->stmt, 1) = op;
3798     }
3799 }
3800
3801 /* Replaces ssa name in index IDX by its basic variable.  Callback for
3802    for_each_index.  */
3803
3804 static bool
3805 idx_remove_ssa_names (tree base ATTRIBUTE_UNUSED, tree *idx,
3806                       void *data ATTRIBUTE_UNUSED)
3807 {
3808   if (TREE_CODE (*idx) == SSA_NAME)
3809     *idx = SSA_NAME_VAR (*idx);
3810   return true;
3811 }
3812
3813 /* Unshares REF and replaces ssa names inside it by their basic variables.  */
3814
3815 static tree
3816 unshare_and_remove_ssa_names (tree ref)
3817 {
3818   ref = unshare_expr (ref);
3819   for_each_index (&ref, idx_remove_ssa_names, NULL);
3820
3821   return ref;
3822 }
3823
3824 /* Rewrites base of memory access OP with expression WITH in statement
3825    pointed to by BSI.  */
3826
3827 static void
3828 rewrite_address_base (block_stmt_iterator *bsi, tree *op, tree with)
3829 {
3830   tree var = get_base_address (*op), new_var, new_name, copy, name;
3831   tree orig;
3832
3833   if (!var || TREE_CODE (with) != SSA_NAME)
3834     goto do_rewrite;
3835
3836   if (TREE_CODE (var) == INDIRECT_REF)
3837     var = TREE_OPERAND (var, 0);
3838   if (TREE_CODE (var) == SSA_NAME)
3839     {
3840       name = var;
3841       var = SSA_NAME_VAR (var);
3842     }
3843   else if (DECL_P (var))
3844     name = NULL_TREE;
3845   else
3846     goto do_rewrite;
3847     
3848   if (var_ann (var)->type_mem_tag)
3849     var = var_ann (var)->type_mem_tag;
3850
3851   /* We need to add a memory tag for the variable.  But we do not want
3852      to add it to the temporary used for the computations, since this leads
3853      to problems in redundancy elimination when there are common parts
3854      in two computations referring to the different arrays.  So we copy
3855      the variable to a new temporary.  */
3856   copy = build2 (MODIFY_EXPR, void_type_node, NULL_TREE, with);
3857   if (name)
3858     new_name = duplicate_ssa_name (name, copy);
3859   else
3860     {
3861       new_var = create_tmp_var (TREE_TYPE (with), "ruatmp");
3862       add_referenced_tmp_var (new_var);
3863       var_ann (new_var)->type_mem_tag = var;
3864       new_name = make_ssa_name (new_var, copy);
3865     }
3866   TREE_OPERAND (copy, 0) = new_name;
3867   bsi_insert_before (bsi, copy, BSI_SAME_STMT);
3868   with = new_name;
3869
3870 do_rewrite:
3871
3872   orig = NULL_TREE;
3873   if (TREE_CODE (*op) == INDIRECT_REF)
3874     orig = REF_ORIGINAL (*op);
3875   if (!orig)
3876     orig = unshare_and_remove_ssa_names (*op);
3877
3878   *op = build1 (INDIRECT_REF, TREE_TYPE (*op), with);
3879   /* Record the original reference, for purposes of alias analysis.  */
3880   REF_ORIGINAL (*op) = orig;
3881 }
3882
3883 /* Rewrites USE (address that is an iv) using candidate CAND.  */
3884
3885 static void
3886 rewrite_use_address (struct ivopts_data *data,
3887                      struct iv_use *use, struct iv_cand *cand)
3888 {
3889   tree comp = unshare_expr (get_computation (data->current_loop,
3890                                              use, cand));
3891   block_stmt_iterator bsi = stmt_for_bsi (use->stmt);
3892   tree stmts;
3893   tree op = force_gimple_operand (comp, &stmts, true, NULL_TREE);
3894
3895   if (stmts)
3896     bsi_insert_before (&bsi, stmts, BSI_SAME_STMT);
3897
3898   rewrite_address_base (&bsi, use->op_p, op);
3899 }
3900
3901 /* Rewrites USE (the condition such that one of the arguments is an iv) using
3902    candidate CAND.  */
3903
3904 static void
3905 rewrite_use_compare (struct ivopts_data *data,
3906                      struct iv_use *use, struct iv_cand *cand)
3907 {
3908   tree comp;
3909   tree *op_p, cond, op, stmts, bound;
3910   block_stmt_iterator bsi = stmt_for_bsi (use->stmt);
3911   enum tree_code compare;
3912   
3913   if (may_eliminate_iv (data->current_loop,
3914                         use, cand, &compare, &bound))
3915     {
3916       op = force_gimple_operand (unshare_expr (bound), &stmts,
3917                                  true, NULL_TREE);
3918
3919       if (stmts)
3920         bsi_insert_before (&bsi, stmts, BSI_SAME_STMT);
3921
3922       *use->op_p = build2 (compare, boolean_type_node,
3923                           var_at_stmt (data->current_loop,
3924                                        cand, use->stmt), op);
3925       modify_stmt (use->stmt);
3926       return;
3927     }
3928
3929   /* The induction variable elimination failed; just express the original
3930      giv.  */
3931   comp = unshare_expr (get_computation (data->current_loop, use, cand));
3932
3933   cond = *use->op_p;
3934   op_p = &TREE_OPERAND (cond, 0);
3935   if (TREE_CODE (*op_p) != SSA_NAME
3936       || zero_p (get_iv (data, *op_p)->step))
3937     op_p = &TREE_OPERAND (cond, 1);
3938
3939   op = force_gimple_operand (comp, &stmts, true, SSA_NAME_VAR (*op_p));
3940   if (stmts)
3941     bsi_insert_before (&bsi, stmts, BSI_SAME_STMT);
3942
3943   *op_p = op;
3944 }
3945
3946 /* Ensure that operand *OP_P may be used at the end of EXIT without
3947    violating loop closed ssa form.  */
3948
3949 static void
3950 protect_loop_closed_ssa_form_use (edge exit, use_operand_p op_p)
3951 {
3952   basic_block def_bb;
3953   struct loop *def_loop;
3954   tree phi, use;
3955
3956   use = USE_FROM_PTR (op_p);
3957   if (TREE_CODE (use) != SSA_NAME)
3958     return;
3959
3960   def_bb = bb_for_stmt (SSA_NAME_DEF_STMT (use));
3961   if (!def_bb)
3962     return;
3963
3964   def_loop = def_bb->loop_father;
3965   if (flow_bb_inside_loop_p (def_loop, exit->dest))
3966     return;
3967
3968   /* Try finding a phi node that copies the value out of the loop.  */
3969   for (phi = phi_nodes (exit->dest); phi; phi = TREE_CHAIN (phi))
3970     if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == use)
3971       break;
3972
3973   if (!phi)
3974     {
3975       /* Create such a phi node.  */
3976       tree new_name = duplicate_ssa_name (use, NULL);
3977
3978       phi = create_phi_node (new_name, exit->dest);
3979       SSA_NAME_DEF_STMT (new_name) = phi;
3980       add_phi_arg (&phi, use, exit);
3981     }
3982
3983   SET_USE (op_p, PHI_RESULT (phi));
3984 }
3985
3986 /* Ensure that operands of STMT may be used at the end of EXIT without
3987    violating loop closed ssa form.  */
3988
3989 static void
3990 protect_loop_closed_ssa_form (edge exit, tree stmt)
3991 {
3992   use_optype uses;
3993   vuse_optype vuses;
3994   v_may_def_optype v_may_defs;
3995   unsigned i;
3996
3997   get_stmt_operands (stmt);
3998
3999   uses = STMT_USE_OPS (stmt);
4000   for (i = 0; i < NUM_USES (uses); i++)
4001     protect_loop_closed_ssa_form_use (exit, USE_OP_PTR (uses, i));
4002
4003   vuses = STMT_VUSE_OPS (stmt);
4004   for (i = 0; i < NUM_VUSES (vuses); i++)
4005     protect_loop_closed_ssa_form_use (exit, VUSE_OP_PTR (vuses, i));
4006
4007   v_may_defs = STMT_V_MAY_DEF_OPS (stmt);
4008   for (i = 0; i < NUM_V_MAY_DEFS (v_may_defs); i++)
4009     protect_loop_closed_ssa_form_use (exit, V_MAY_DEF_OP_PTR (v_may_defs, i));
4010 }
4011
4012 /* STMTS compute a value of a phi argument OP on EXIT of a loop.  Arrange things
4013    so that they are emitted on the correct place, and so that the loop closed
4014    ssa form is preserved.  */
4015
4016 static void
4017 compute_phi_arg_on_exit (edge exit, tree stmts, tree op)
4018 {
4019   tree_stmt_iterator tsi;
4020   block_stmt_iterator bsi;
4021   tree phi, stmt, def, next;
4022
4023   if (exit->dest->pred->pred_next)
4024     split_loop_exit_edge (exit);
4025
4026   if (TREE_CODE (stmts) == STATEMENT_LIST)
4027     {
4028       for (tsi = tsi_start (stmts); !tsi_end_p (tsi); tsi_next (&tsi))
4029         protect_loop_closed_ssa_form (exit, tsi_stmt (tsi));
4030     }
4031   else
4032     protect_loop_closed_ssa_form (exit, stmts);
4033
4034   /* Ensure there is label in exit->dest, so that we can
4035      insert after it.  */
4036   tree_block_label (exit->dest);
4037   bsi = bsi_after_labels (exit->dest);
4038   bsi_insert_after (&bsi, stmts, BSI_CONTINUE_LINKING);
4039
4040   if (!op)
4041     return;
4042
4043   for (phi = phi_nodes (exit->dest); phi; phi = next)
4044     {
4045       next = TREE_CHAIN (phi);
4046
4047       if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == op)
4048         {
4049           def = PHI_RESULT (phi);
4050           remove_statement (phi, false);
4051           stmt = build2 (MODIFY_EXPR, TREE_TYPE (op),
4052                         def, op);
4053           SSA_NAME_DEF_STMT (def) = stmt;
4054           bsi_insert_after (&bsi, stmt, BSI_CONTINUE_LINKING);
4055         }
4056     }
4057 }
4058
4059 /* Rewrites the final value of USE (that is only needed outside of the loop)
4060    using candidate CAND.  */
4061
4062 static void
4063 rewrite_use_outer (struct ivopts_data *data,
4064                    struct iv_use *use, struct iv_cand *cand)
4065 {
4066   edge exit;
4067   tree value, op, stmts, tgt;
4068   tree phi;
4069
4070   switch (TREE_CODE (use->stmt))
4071     {
4072     case PHI_NODE:
4073       tgt = PHI_RESULT (use->stmt);
4074       break;
4075     case MODIFY_EXPR:
4076       tgt = TREE_OPERAND (use->stmt, 0);
4077       break;
4078     default:
4079       gcc_unreachable ();
4080     }
4081
4082   exit = single_dom_exit (data->current_loop);
4083
4084   if (exit)
4085     {
4086       if (!cand->iv)
4087         {
4088           bool ok = may_replace_final_value (data->current_loop, use, &value);
4089           gcc_assert (ok);
4090         }
4091       else
4092         value = get_computation_at (data->current_loop,
4093                                     use, cand, last_stmt (exit->src));
4094
4095       value = unshare_expr (value);
4096       op = force_gimple_operand (value, &stmts, true, SSA_NAME_VAR (tgt));
4097           
4098       /* If we will preserve the iv anyway and we would need to perform
4099          some computation to replace the final value, do nothing.  */
4100       if (stmts && name_info (data, tgt)->preserve_biv)
4101         return;
4102
4103       for (phi = phi_nodes (exit->dest); phi; phi = TREE_CHAIN (phi))
4104         {
4105           use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, exit);
4106
4107           if (USE_FROM_PTR (use_p) == tgt)
4108             SET_USE (use_p, op);
4109         }
4110
4111       if (stmts)
4112         compute_phi_arg_on_exit (exit, stmts, op);
4113
4114       /* Enable removal of the statement.  We cannot remove it directly,
4115          since we may still need the aliasing information attached to the
4116          ssa name defined by it.  */
4117       name_info (data, tgt)->iv->have_use_for = false;
4118       return;
4119     }
4120
4121   /* If the variable is going to be preserved anyway, there is nothing to
4122      do.  */
4123   if (name_info (data, tgt)->preserve_biv)
4124     return;
4125
4126   /* Otherwise we just need to compute the iv.  */
4127   rewrite_use_nonlinear_expr (data, use, cand);
4128 }
4129
4130 /* Rewrites USE using candidate CAND.  */
4131
4132 static void
4133 rewrite_use (struct ivopts_data *data,
4134              struct iv_use *use, struct iv_cand *cand)
4135 {
4136   switch (use->type)
4137     {
4138       case USE_NONLINEAR_EXPR:
4139         rewrite_use_nonlinear_expr (data, use, cand);
4140         break;
4141
4142       case USE_OUTER:
4143         rewrite_use_outer (data, use, cand);
4144         break;
4145
4146       case USE_ADDRESS:
4147         rewrite_use_address (data, use, cand);
4148         break;
4149
4150       case USE_COMPARE:
4151         rewrite_use_compare (data, use, cand);
4152         break;
4153
4154       default:
4155         gcc_unreachable ();
4156     }
4157   modify_stmt (use->stmt);
4158 }
4159
4160 /* Rewrite the uses using the selected induction variables.  */
4161
4162 static void
4163 rewrite_uses (struct ivopts_data *data)
4164 {
4165   unsigned i;
4166   struct iv_cand *cand;
4167   struct iv_use *use;
4168
4169   for (i = 0; i < n_iv_uses (data); i++)
4170     {
4171       use = iv_use (data, i);
4172       cand = use->selected;
4173       gcc_assert (cand);
4174
4175       rewrite_use (data, use, cand);
4176     }
4177 }
4178
4179 /* Removes the ivs that are not used after rewriting.  */
4180
4181 static void
4182 remove_unused_ivs (struct ivopts_data *data)
4183 {
4184   unsigned j;
4185
4186   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, j,
4187     {
4188       struct version_info *info;
4189
4190       info = ver_info (data, j);
4191       if (info->iv
4192           && !zero_p (info->iv->step)
4193           && !info->inv_id
4194           && !info->iv->have_use_for
4195           && !info->preserve_biv)
4196         remove_statement (SSA_NAME_DEF_STMT (info->iv->ssa_name), true);
4197     });
4198 }
4199
4200 /* Frees data allocated by the optimization of a single loop.  */
4201
4202 static void
4203 free_loop_data (struct ivopts_data *data)
4204 {
4205   unsigned i, j;
4206
4207   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i,
4208     {
4209       struct version_info *info;
4210
4211       info = ver_info (data, i);
4212       if (info->iv)
4213         free (info->iv);
4214       info->iv = NULL;
4215       info->has_nonlin_use = false;
4216       info->preserve_biv = false;
4217       info->inv_id = 0;
4218     });
4219   bitmap_clear (data->relevant);
4220
4221   for (i = 0; i < n_iv_uses (data); i++)
4222     {
4223       struct iv_use *use = iv_use (data, i);
4224
4225       free (use->iv);
4226       BITMAP_XFREE (use->related_cands);
4227       for (j = 0; j < use->n_map_members; j++)
4228         if (use->cost_map[j].depends_on)
4229           BITMAP_XFREE (use->cost_map[j].depends_on);
4230       free (use->cost_map);
4231       free (use);
4232     }
4233   VARRAY_POP_ALL (data->iv_uses);
4234
4235   for (i = 0; i < n_iv_cands (data); i++)
4236     {
4237       struct iv_cand *cand = iv_cand (data, i);
4238
4239       if (cand->iv)
4240         free (cand->iv);
4241       free (cand);
4242     }
4243   VARRAY_POP_ALL (data->iv_candidates);
4244
4245   if (data->version_info_size < num_ssa_names)
4246     {
4247       data->version_info_size = 2 * num_ssa_names;
4248       free (data->version_info);
4249       data->version_info = xcalloc (data->version_info_size,
4250                                     sizeof (struct version_info));
4251     }
4252
4253   data->max_inv_id = 0;
4254
4255   for (i = 0; i < VARRAY_ACTIVE_SIZE (decl_rtl_to_reset); i++)
4256     {
4257       tree obj = VARRAY_GENERIC_PTR_NOGC (decl_rtl_to_reset, i);
4258
4259       SET_DECL_RTL (obj, NULL_RTX);
4260     }
4261   VARRAY_POP_ALL (decl_rtl_to_reset);
4262 }
4263
4264 /* Finalizes data structures used by the iv optimization pass.  LOOPS is the
4265    loop tree.  */
4266
4267 static void
4268 tree_ssa_iv_optimize_finalize (struct loops *loops, struct ivopts_data *data)
4269 {
4270   unsigned i;
4271
4272   for (i = 1; i < loops->num; i++)
4273     if (loops->parray[i])
4274       {
4275         free (loops->parray[i]->aux);
4276         loops->parray[i]->aux = NULL;
4277       }
4278
4279   free_loop_data (data);
4280   free (data->version_info);
4281   BITMAP_XFREE (data->relevant);
4282
4283   VARRAY_FREE (decl_rtl_to_reset);
4284   VARRAY_FREE (data->iv_uses);
4285   VARRAY_FREE (data->iv_candidates);
4286 }
4287
4288 /* Optimizes the LOOP.  Returns true if anything changed.  */
4289
4290 static bool
4291 tree_ssa_iv_optimize_loop (struct ivopts_data *data, struct loop *loop)
4292 {
4293   bool changed = false;
4294   bitmap iv_set;
4295   edge exit;
4296
4297   data->current_loop = loop;
4298
4299   if (dump_file && (dump_flags & TDF_DETAILS))
4300     {
4301       fprintf (dump_file, "Processing loop %d\n", loop->num);
4302       
4303       exit = single_dom_exit (loop);
4304       if (exit)
4305         {
4306           fprintf (dump_file, "  single exit %d -> %d, exit condition ",
4307                    exit->src->index, exit->dest->index);
4308           print_generic_expr (dump_file, last_stmt (exit->src), TDF_SLIM);
4309           fprintf (dump_file, "\n");
4310         }
4311
4312       fprintf (dump_file, "\n");
4313     }
4314
4315   /* For each ssa name determines whether it behaves as an induction variable
4316      in some loop.  */
4317   if (!find_induction_variables (data))
4318     goto finish;
4319
4320   /* Finds interesting uses (item 1).  */
4321   find_interesting_uses (data);
4322   if (n_iv_uses (data) > MAX_CONSIDERED_USES)
4323     goto finish;
4324
4325   /* Finds candidates for the induction variables (item 2).  */
4326   find_iv_candidates (data);
4327
4328   /* Calculates the costs (item 3, part 1).  */
4329   determine_use_iv_costs (data);
4330   determine_iv_costs (data);
4331   determine_set_costs (data);
4332
4333   /* Find the optimal set of induction variables (item 3, part 2).  */
4334   iv_set = find_optimal_iv_set (data);
4335   if (!iv_set)
4336     goto finish;
4337   changed = true;
4338
4339   /* Create the new induction variables (item 4, part 1).  */
4340   create_new_ivs (data, iv_set);
4341   
4342   /* Rewrite the uses (item 4, part 2).  */
4343   rewrite_uses (data);
4344
4345   /* Remove the ivs that are unused after rewriting.  */
4346   remove_unused_ivs (data);
4347
4348   loop_commit_inserts ();
4349
4350   BITMAP_XFREE (iv_set);
4351
4352   /* We have changed the structure of induction variables; it might happen
4353      that definitions in the scev database refer to some of them that were
4354      eliminated.  */
4355   scev_reset ();
4356
4357 finish:
4358   free_loop_data (data);
4359
4360   return changed;
4361 }
4362
4363 /* Main entry point.  Optimizes induction variables in LOOPS.  */
4364
4365 void
4366 tree_ssa_iv_optimize (struct loops *loops)
4367 {
4368   struct loop *loop;
4369   struct ivopts_data data;
4370
4371   tree_ssa_iv_optimize_init (loops, &data);
4372
4373   /* Optimize the loops starting with the innermost ones.  */
4374   loop = loops->tree_root;
4375   while (loop->inner)
4376     loop = loop->inner;
4377
4378 #ifdef ENABLE_CHECKING
4379   verify_loop_closed_ssa ();
4380   verify_stmts ();
4381 #endif
4382
4383   /* Scan the loops, inner ones first.  */
4384   while (loop != loops->tree_root)
4385     {
4386       if (dump_file && (dump_flags & TDF_DETAILS))
4387         flow_loop_dump (loop, dump_file, NULL, 1);
4388       if (tree_ssa_iv_optimize_loop (&data, loop))
4389         {
4390 #ifdef ENABLE_CHECKING
4391           verify_loop_closed_ssa ();
4392           verify_stmts ();
4393 #endif
4394         }
4395
4396       if (loop->next)
4397         {
4398           loop = loop->next;
4399           while (loop->inner)
4400             loop = loop->inner;
4401         }
4402       else
4403         loop = loop->outer;
4404     }
4405
4406   tree_ssa_iv_optimize_finalize (loops, &data);
4407 }