OSDN Git Service

* tree-ssa-loop-ivopts.c (find_bivs, find_givs_in_stmt_scev): Apply
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-loop-ivopts.c
1 /* Induction variable optimizations.
2    Copyright (C) 2003, 2004, 2005 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 #include "langhooks.h"
92
93 /* The infinite cost.  */
94 #define INFTY 10000000
95
96 /* The expected number of loop iterations.  TODO -- use profiling instead of
97    this.  */
98 #define AVG_LOOP_NITER(LOOP) 5
99
100
101 /* Representation of the induction variable.  */
102 struct iv
103 {
104   tree base;            /* Initial value of the iv.  */
105   tree base_object;     /* A memory object to that the induction variable points.  */
106   tree step;            /* Step of the iv (constant only).  */
107   tree ssa_name;        /* The ssa name with the value.  */
108   bool biv_p;           /* Is it a biv?  */
109   bool have_use_for;    /* Do we already have a use for it?  */
110   unsigned use_id;      /* The identifier in the use if it is the case.  */
111 };
112
113 /* Per-ssa version information (induction variable descriptions, etc.).  */
114 struct version_info
115 {
116   tree name;            /* The ssa name.  */
117   struct iv *iv;        /* Induction variable description.  */
118   bool has_nonlin_use;  /* For a loop-level invariant, whether it is used in
119                            an expression that is not an induction variable.  */
120   unsigned inv_id;      /* Id of an invariant.  */
121   bool preserve_biv;    /* For the original biv, whether to preserve it.  */
122 };
123
124 /* Information attached to loop.  */
125 struct loop_data
126 {
127   unsigned regs_used;   /* Number of registers used.  */
128 };
129
130 /* Types of uses.  */
131 enum use_type
132 {
133   USE_NONLINEAR_EXPR,   /* Use in a nonlinear expression.  */
134   USE_OUTER,            /* The induction variable is used outside the loop.  */
135   USE_ADDRESS,          /* Use in an address.  */
136   USE_COMPARE           /* Use is a compare.  */
137 };
138
139 /* The candidate - cost pair.  */
140 struct cost_pair
141 {
142   struct iv_cand *cand; /* The candidate.  */
143   unsigned cost;        /* The cost.  */
144   bitmap depends_on;    /* The list of invariants that have to be
145                            preserved.  */
146   tree value;           /* For final value elimination, the expression for
147                            the final value of the iv.  For iv elimination,
148                            the new bound to compare with.  */
149 };
150
151 /* Use.  */
152 struct iv_use
153 {
154   unsigned id;          /* The id of the use.  */
155   enum use_type type;   /* Type of the use.  */
156   struct iv *iv;        /* The induction variable it is based on.  */
157   tree stmt;            /* Statement in that it occurs.  */
158   tree *op_p;           /* The place where it occurs.  */
159   bitmap related_cands; /* The set of "related" iv candidates, plus the common
160                            important ones.  */
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   bitmap depends_on;    /* The list of invariants that are used in step of the
195                            biv.  */
196 };
197
198 /* The data used by the induction variable optimizations.  */
199
200 typedef struct iv_use *iv_use_p;
201 DEF_VEC_P(iv_use_p);
202 DEF_VEC_ALLOC_P(iv_use_p,heap);
203
204 typedef struct iv_cand *iv_cand_p;
205 DEF_VEC_P(iv_cand_p);
206 DEF_VEC_ALLOC_P(iv_cand_p,heap);
207
208 struct ivopts_data
209 {
210   /* The currently optimized loop.  */
211   struct loop *current_loop;
212
213   /* Numbers of iterations for all exits of the current loop.  */
214   htab_t niters;
215
216   /* The size of version_info array allocated.  */
217   unsigned version_info_size;
218
219   /* The array of information for the ssa names.  */
220   struct version_info *version_info;
221
222   /* The bitmap of indices in version_info whose value was changed.  */
223   bitmap relevant;
224
225   /* The maximum invariant id.  */
226   unsigned max_inv_id;
227
228   /* The uses of induction variables.  */
229   VEC(iv_use_p,heap) *iv_uses;
230
231   /* The candidates.  */
232   VEC(iv_cand_p,heap) *iv_candidates;
233
234   /* A bitmap of important candidates.  */
235   bitmap important_candidates;
236
237   /* Whether to consider just related and important candidates when replacing a
238      use.  */
239   bool consider_all_candidates;
240 };
241
242 /* An assignment of iv candidates to uses.  */
243
244 struct iv_ca
245 {
246   /* The number of uses covered by the assignment.  */
247   unsigned upto;
248
249   /* Number of uses that cannot be expressed by the candidates in the set.  */
250   unsigned bad_uses;
251
252   /* Candidate assigned to a use, together with the related costs.  */
253   struct cost_pair **cand_for_use;
254
255   /* Number of times each candidate is used.  */
256   unsigned *n_cand_uses;
257
258   /* The candidates used.  */
259   bitmap cands;
260
261   /* The number of candidates in the set.  */
262   unsigned n_cands;
263
264   /* Total number of registers needed.  */
265   unsigned n_regs;
266
267   /* Total cost of expressing uses.  */
268   unsigned cand_use_cost;
269
270   /* Total cost of candidates.  */
271   unsigned cand_cost;
272
273   /* Number of times each invariant is used.  */
274   unsigned *n_invariant_uses;
275
276   /* Total cost of the assignment.  */
277   unsigned cost;
278 };
279
280 /* Difference of two iv candidate assignments.  */
281
282 struct iv_ca_delta
283 {
284   /* Changed use.  */
285   struct iv_use *use;
286
287   /* An old assignment (for rollback purposes).  */
288   struct cost_pair *old_cp;
289
290   /* A new assignment.  */
291   struct cost_pair *new_cp;
292
293   /* Next change in the list.  */
294   struct iv_ca_delta *next_change;
295 };
296
297 /* Bound on number of candidates below that all candidates are considered.  */
298
299 #define CONSIDER_ALL_CANDIDATES_BOUND \
300   ((unsigned) PARAM_VALUE (PARAM_IV_CONSIDER_ALL_CANDIDATES_BOUND))
301
302 /* If there are more iv occurrences, we just give up (it is quite unlikely that
303    optimizing such a loop would help, and it would take ages).  */
304
305 #define MAX_CONSIDERED_USES \
306   ((unsigned) PARAM_VALUE (PARAM_IV_MAX_CONSIDERED_USES))
307
308 /* If there are at most this number of ivs in the set, try removing unnecessary
309    ivs from the set always.  */
310
311 #define ALWAYS_PRUNE_CAND_SET_BOUND \
312   ((unsigned) PARAM_VALUE (PARAM_IV_ALWAYS_PRUNE_CAND_SET_BOUND))
313
314 /* The list of trees for that the decl_rtl field must be reset is stored
315    here.  */
316
317 static VEC(tree,heap) *decl_rtl_to_reset;
318
319 /* Number of uses recorded in DATA.  */
320
321 static inline unsigned
322 n_iv_uses (struct ivopts_data *data)
323 {
324   return VEC_length (iv_use_p, data->iv_uses);
325 }
326
327 /* Ith use recorded in DATA.  */
328
329 static inline struct iv_use *
330 iv_use (struct ivopts_data *data, unsigned i)
331 {
332   return VEC_index (iv_use_p, data->iv_uses, i);
333 }
334
335 /* Number of candidates recorded in DATA.  */
336
337 static inline unsigned
338 n_iv_cands (struct ivopts_data *data)
339 {
340   return VEC_length (iv_cand_p, data->iv_candidates);
341 }
342
343 /* Ith candidate recorded in DATA.  */
344
345 static inline struct iv_cand *
346 iv_cand (struct ivopts_data *data, unsigned i)
347 {
348   return VEC_index (iv_cand_p, data->iv_candidates, i);
349 }
350
351 /* The data for LOOP.  */
352
353 static inline struct loop_data *
354 loop_data (struct loop *loop)
355 {
356   return loop->aux;
357 }
358
359 /* The single loop exit if it dominates the latch, NULL otherwise.  */
360
361 static edge
362 single_dom_exit (struct loop *loop)
363 {
364   edge exit = loop->single_exit;
365
366   if (!exit)
367     return NULL;
368
369   if (!just_once_each_iteration_p (loop, exit->src))
370     return NULL;
371
372   return exit;
373 }
374
375 /* Dumps information about the induction variable IV to FILE.  */
376
377 extern void dump_iv (FILE *, struct iv *);
378 void
379 dump_iv (FILE *file, struct iv *iv)
380 {
381   if (iv->ssa_name)
382     {
383       fprintf (file, "ssa name ");
384       print_generic_expr (file, iv->ssa_name, TDF_SLIM);
385       fprintf (file, "\n");
386     }
387
388   fprintf (file, "  type ");
389   print_generic_expr (file, TREE_TYPE (iv->base), TDF_SLIM);
390   fprintf (file, "\n");
391
392   if (iv->step)
393     {
394       fprintf (file, "  base ");
395       print_generic_expr (file, iv->base, TDF_SLIM);
396       fprintf (file, "\n");
397
398       fprintf (file, "  step ");
399       print_generic_expr (file, iv->step, TDF_SLIM);
400       fprintf (file, "\n");
401     }
402   else
403     {
404       fprintf (file, "  invariant ");
405       print_generic_expr (file, iv->base, TDF_SLIM);
406       fprintf (file, "\n");
407     }
408
409   if (iv->base_object)
410     {
411       fprintf (file, "  base object ");
412       print_generic_expr (file, iv->base_object, TDF_SLIM);
413       fprintf (file, "\n");
414     }
415
416   if (iv->biv_p)
417     fprintf (file, "  is a biv\n");
418 }
419
420 /* Dumps information about the USE to FILE.  */
421
422 extern void dump_use (FILE *, struct iv_use *);
423 void
424 dump_use (FILE *file, struct iv_use *use)
425 {
426   fprintf (file, "use %d\n", use->id);
427
428   switch (use->type)
429     {
430     case USE_NONLINEAR_EXPR:
431       fprintf (file, "  generic\n");
432       break;
433
434     case USE_OUTER:
435       fprintf (file, "  outside\n");
436       break;
437
438     case USE_ADDRESS:
439       fprintf (file, "  address\n");
440       break;
441
442     case USE_COMPARE:
443       fprintf (file, "  compare\n");
444       break;
445
446     default:
447       gcc_unreachable ();
448     }
449
450   fprintf (file, "  in statement ");
451   print_generic_expr (file, use->stmt, TDF_SLIM);
452   fprintf (file, "\n");
453
454   fprintf (file, "  at position ");
455   if (use->op_p)
456     print_generic_expr (file, *use->op_p, TDF_SLIM);
457   fprintf (file, "\n");
458
459   dump_iv (file, use->iv);
460
461   if (use->related_cands)
462     {
463       fprintf (file, "  related candidates ");
464       dump_bitmap (file, use->related_cands);
465     }
466 }
467
468 /* Dumps information about the uses to FILE.  */
469
470 extern void dump_uses (FILE *, struct ivopts_data *);
471 void
472 dump_uses (FILE *file, struct ivopts_data *data)
473 {
474   unsigned i;
475   struct iv_use *use;
476
477   for (i = 0; i < n_iv_uses (data); i++)
478     {
479       use = iv_use (data, i);
480
481       dump_use (file, use);
482       fprintf (file, "\n");
483     }
484 }
485
486 /* Dumps information about induction variable candidate CAND to FILE.  */
487
488 extern void dump_cand (FILE *, struct iv_cand *);
489 void
490 dump_cand (FILE *file, struct iv_cand *cand)
491 {
492   struct iv *iv = cand->iv;
493
494   fprintf (file, "candidate %d%s\n",
495            cand->id, cand->important ? " (important)" : "");
496
497   if (cand->depends_on)
498     {
499       fprintf (file, "  depends on ");
500       dump_bitmap (file, cand->depends_on);
501     }
502
503   if (!iv)
504     {
505       fprintf (file, "  final value replacement\n");
506       return;
507     }
508
509   switch (cand->pos)
510     {
511     case IP_NORMAL:
512       fprintf (file, "  incremented before exit test\n");
513       break;
514
515     case IP_END:
516       fprintf (file, "  incremented at end\n");
517       break;
518
519     case IP_ORIGINAL:
520       fprintf (file, "  original biv\n");
521       break;
522     }
523
524   dump_iv (file, iv);
525 }
526
527 /* Returns the info for ssa version VER.  */
528
529 static inline struct version_info *
530 ver_info (struct ivopts_data *data, unsigned ver)
531 {
532   return data->version_info + ver;
533 }
534
535 /* Returns the info for ssa name NAME.  */
536
537 static inline struct version_info *
538 name_info (struct ivopts_data *data, tree name)
539 {
540   return ver_info (data, SSA_NAME_VERSION (name));
541 }
542
543 /* Checks whether there exists number X such that X * B = A, counting modulo
544    2^BITS.  */
545
546 static bool
547 divide (unsigned bits, unsigned HOST_WIDE_INT a, unsigned HOST_WIDE_INT b,
548         HOST_WIDE_INT *x)
549 {
550   unsigned HOST_WIDE_INT mask = ~(~(unsigned HOST_WIDE_INT) 0 << (bits - 1) << 1);
551   unsigned HOST_WIDE_INT inv, ex, val;
552   unsigned i;
553
554   a &= mask;
555   b &= mask;
556
557   /* First divide the whole equation by 2 as long as possible.  */
558   while (!(a & 1) && !(b & 1))
559     {
560       a >>= 1;
561       b >>= 1;
562       bits--;
563       mask >>= 1;
564     }
565
566   if (!(b & 1))
567     {
568       /* If b is still even, a is odd and there is no such x.  */
569       return false;
570     }
571
572   /* Find the inverse of b.  We compute it as
573      b^(2^(bits - 1) - 1) (mod 2^bits).  */
574   inv = 1;
575   ex = b;
576   for (i = 0; i < bits - 1; i++)
577     {
578       inv = (inv * ex) & mask;
579       ex = (ex * ex) & mask;
580     }
581
582   val = (a * inv) & mask;
583
584   gcc_assert (((val * b) & mask) == a);
585
586   if ((val >> (bits - 1)) & 1)
587     val |= ~mask;
588
589   *x = val;
590
591   return true;
592 }
593
594 /* Returns true if STMT is after the place where the IP_NORMAL ivs will be
595    emitted in LOOP.  */
596
597 static bool
598 stmt_after_ip_normal_pos (struct loop *loop, tree stmt)
599 {
600   basic_block bb = ip_normal_pos (loop), sbb = bb_for_stmt (stmt);
601
602   gcc_assert (bb);
603
604   if (sbb == loop->latch)
605     return true;
606
607   if (sbb != bb)
608     return false;
609
610   return stmt == last_stmt (bb);
611 }
612
613 /* Returns true if STMT if after the place where the original induction
614    variable CAND is incremented.  */
615
616 static bool
617 stmt_after_ip_original_pos (struct iv_cand *cand, tree stmt)
618 {
619   basic_block cand_bb = bb_for_stmt (cand->incremented_at);
620   basic_block stmt_bb = bb_for_stmt (stmt);
621   block_stmt_iterator bsi;
622
623   if (!dominated_by_p (CDI_DOMINATORS, stmt_bb, cand_bb))
624     return false;
625
626   if (stmt_bb != cand_bb)
627     return true;
628
629   /* Scan the block from the end, since the original ivs are usually
630      incremented at the end of the loop body.  */
631   for (bsi = bsi_last (stmt_bb); ; bsi_prev (&bsi))
632     {
633       if (bsi_stmt (bsi) == cand->incremented_at)
634         return false;
635       if (bsi_stmt (bsi) == stmt)
636         return true;
637     }
638 }
639
640 /* Returns true if STMT if after the place where the induction variable
641    CAND is incremented in LOOP.  */
642
643 static bool
644 stmt_after_increment (struct loop *loop, struct iv_cand *cand, tree stmt)
645 {
646   switch (cand->pos)
647     {
648     case IP_END:
649       return false;
650
651     case IP_NORMAL:
652       return stmt_after_ip_normal_pos (loop, stmt);
653
654     case IP_ORIGINAL:
655       return stmt_after_ip_original_pos (cand, stmt);
656
657     default:
658       gcc_unreachable ();
659     }
660 }
661
662 /* Element of the table in that we cache the numbers of iterations obtained
663    from exits of the loop.  */
664
665 struct nfe_cache_elt
666 {
667   /* The edge for that the number of iterations is cached.  */
668   edge exit;
669
670   /* True if the # of iterations was successfully determined.  */
671   bool valid_p;
672
673   /* Description of # of iterations.  */
674   struct tree_niter_desc niter;
675 };
676
677 /* Hash function for nfe_cache_elt E.  */
678
679 static hashval_t
680 nfe_hash (const void *e)
681 {
682   const struct nfe_cache_elt *elt = e;
683
684   return htab_hash_pointer (elt->exit);
685 }
686
687 /* Equality function for nfe_cache_elt E1 and edge E2.  */
688
689 static int
690 nfe_eq (const void *e1, const void *e2)
691 {
692   const struct nfe_cache_elt *elt1 = e1;
693
694   return elt1->exit == e2;
695 }
696
697 /*  Returns structure describing number of iterations determined from
698     EXIT of DATA->current_loop, or NULL if something goes wrong.  */
699
700 static struct tree_niter_desc *
701 niter_for_exit (struct ivopts_data *data, edge exit)
702 {
703   struct nfe_cache_elt *nfe_desc;
704   PTR *slot;
705
706   slot = htab_find_slot_with_hash (data->niters, exit,
707                                    htab_hash_pointer (exit),
708                                    INSERT);
709
710   if (!*slot)
711     {
712       nfe_desc = xmalloc (sizeof (struct nfe_cache_elt));
713       nfe_desc->exit = exit;
714       nfe_desc->valid_p = number_of_iterations_exit (data->current_loop,
715                                                      exit, &nfe_desc->niter);
716       *slot = nfe_desc;
717     }
718   else
719     nfe_desc = *slot;
720
721   if (!nfe_desc->valid_p)
722     return NULL;
723
724   return &nfe_desc->niter;
725 }
726
727 /* Returns structure describing number of iterations determined from
728    single dominating exit of DATA->current_loop, or NULL if something
729    goes wrong.  */
730
731 static struct tree_niter_desc *
732 niter_for_single_dom_exit (struct ivopts_data *data)
733 {
734   edge exit = single_dom_exit (data->current_loop);
735
736   if (!exit)
737     return NULL;
738
739   return niter_for_exit (data, exit);
740 }
741
742 /* Initializes data structures used by the iv optimization pass, stored
743    in DATA.  LOOPS is the loop tree.  */
744
745 static void
746 tree_ssa_iv_optimize_init (struct loops *loops, struct ivopts_data *data)
747 {
748   unsigned i;
749
750   data->version_info_size = 2 * num_ssa_names;
751   data->version_info = xcalloc (data->version_info_size,
752                                 sizeof (struct version_info));
753   data->relevant = BITMAP_ALLOC (NULL);
754   data->important_candidates = BITMAP_ALLOC (NULL);
755   data->max_inv_id = 0;
756   data->niters = htab_create (10, nfe_hash, nfe_eq, free);
757
758   for (i = 1; i < loops->num; i++)
759     if (loops->parray[i])
760       loops->parray[i]->aux = xcalloc (1, sizeof (struct loop_data));
761
762   data->iv_uses = VEC_alloc (iv_use_p, heap, 20);
763   data->iv_candidates = VEC_alloc (iv_cand_p, heap, 20);
764   decl_rtl_to_reset = VEC_alloc (tree, heap, 20);
765 }
766
767 /* Returns a memory object to that EXPR points.  In case we are able to
768    determine that it does not point to any such object, NULL is returned.  */
769
770 static tree
771 determine_base_object (tree expr)
772 {
773   enum tree_code code = TREE_CODE (expr);
774   tree base, obj, op0, op1;
775
776   if (!POINTER_TYPE_P (TREE_TYPE (expr)))
777     return NULL_TREE;
778
779   switch (code)
780     {
781     case INTEGER_CST:
782       return NULL_TREE;
783
784     case ADDR_EXPR:
785       obj = TREE_OPERAND (expr, 0);
786       base = get_base_address (obj);
787
788       if (!base)
789         return expr;
790
791       if (TREE_CODE (base) == INDIRECT_REF)
792         return determine_base_object (TREE_OPERAND (base, 0));
793
794       return fold (build1 (ADDR_EXPR, ptr_type_node, base));
795
796     case PLUS_EXPR:
797     case MINUS_EXPR:
798       op0 = determine_base_object (TREE_OPERAND (expr, 0));
799       op1 = determine_base_object (TREE_OPERAND (expr, 1));
800       
801       if (!op1)
802         return op0;
803
804       if (!op0)
805         return (code == PLUS_EXPR
806                 ? op1
807                 : fold (build1 (NEGATE_EXPR, ptr_type_node, op1)));
808
809       return fold (build (code, ptr_type_node, op0, op1));
810
811     case NOP_EXPR:
812     case CONVERT_EXPR:
813       return determine_base_object (TREE_OPERAND (expr, 0));
814
815     default:
816       return fold_convert (ptr_type_node, expr);
817     }
818 }
819
820 /* Allocates an induction variable with given initial value BASE and step STEP
821    for loop LOOP.  */
822
823 static struct iv *
824 alloc_iv (tree base, tree step)
825 {
826   struct iv *iv = xcalloc (1, sizeof (struct iv));
827
828   if (step && integer_zerop (step))
829     step = NULL_TREE;
830
831   iv->base = base;
832   iv->base_object = determine_base_object (base);
833   iv->step = step;
834   iv->biv_p = false;
835   iv->have_use_for = false;
836   iv->use_id = 0;
837   iv->ssa_name = NULL_TREE;
838
839   return iv;
840 }
841
842 /* Sets STEP and BASE for induction variable IV.  */
843
844 static void
845 set_iv (struct ivopts_data *data, tree iv, tree base, tree step)
846 {
847   struct version_info *info = name_info (data, iv);
848
849   gcc_assert (!info->iv);
850
851   bitmap_set_bit (data->relevant, SSA_NAME_VERSION (iv));
852   info->iv = alloc_iv (base, step);
853   info->iv->ssa_name = iv;
854 }
855
856 /* Finds induction variable declaration for VAR.  */
857
858 static struct iv *
859 get_iv (struct ivopts_data *data, tree var)
860 {
861   basic_block bb;
862   
863   if (!name_info (data, var)->iv)
864     {
865       bb = bb_for_stmt (SSA_NAME_DEF_STMT (var));
866
867       if (!bb
868           || !flow_bb_inside_loop_p (data->current_loop, bb))
869         set_iv (data, var, var, NULL_TREE);
870     }
871
872   return name_info (data, var)->iv;
873 }
874
875 /* Determines the step of a biv defined in PHI.  Returns NULL if PHI does
876    not define a simple affine biv with nonzero step.  */
877
878 static tree
879 determine_biv_step (tree phi)
880 {
881   struct loop *loop = bb_for_stmt (phi)->loop_father;
882   tree name = PHI_RESULT (phi), base, step;
883
884   if (!is_gimple_reg (name))
885     return NULL_TREE;
886
887   if (!simple_iv (loop, phi, name, &base, &step, true))
888     return NULL_TREE;
889
890   if (zero_p (step))
891     return NULL_TREE;
892
893   return step;
894 }
895
896 /* Returns true if EXP is a ssa name that occurs in an abnormal phi node.  */
897
898 static bool
899 abnormal_ssa_name_p (tree exp)
900 {
901   if (!exp)
902     return false;
903
904   if (TREE_CODE (exp) != SSA_NAME)
905     return false;
906
907   return SSA_NAME_OCCURS_IN_ABNORMAL_PHI (exp) != 0;
908 }
909
910 /* Returns false if BASE or INDEX contains a ssa name that occurs in an
911    abnormal phi node.  Callback for for_each_index.  */
912
913 static bool
914 idx_contains_abnormal_ssa_name_p (tree base, tree *index,
915                                   void *data ATTRIBUTE_UNUSED)
916 {
917   if (TREE_CODE (base) == ARRAY_REF)
918     {
919       if (abnormal_ssa_name_p (TREE_OPERAND (base, 2)))
920         return false;
921       if (abnormal_ssa_name_p (TREE_OPERAND (base, 3)))
922         return false;
923     }
924
925   return !abnormal_ssa_name_p (*index);
926 }
927
928 /* Returns true if EXPR contains a ssa name that occurs in an
929    abnormal phi node.  */
930
931 static bool
932 contains_abnormal_ssa_name_p (tree expr)
933 {
934   enum tree_code code;
935   enum tree_code_class class;
936
937   if (!expr)
938     return false;
939
940   code = TREE_CODE (expr);
941   class = TREE_CODE_CLASS (code);
942
943   if (code == SSA_NAME)
944     return SSA_NAME_OCCURS_IN_ABNORMAL_PHI (expr) != 0;
945
946   if (code == INTEGER_CST
947       || is_gimple_min_invariant (expr))
948     return false;
949
950   if (code == ADDR_EXPR)
951     return !for_each_index (&TREE_OPERAND (expr, 0),
952                             idx_contains_abnormal_ssa_name_p,
953                             NULL);
954
955   switch (class)
956     {
957     case tcc_binary:
958     case tcc_comparison:
959       if (contains_abnormal_ssa_name_p (TREE_OPERAND (expr, 1)))
960         return true;
961
962       /* Fallthru.  */
963     case tcc_unary:
964       if (contains_abnormal_ssa_name_p (TREE_OPERAND (expr, 0)))
965         return true;
966
967       break;
968
969     default:
970       gcc_unreachable ();
971     }
972
973   return false;
974 }
975
976 /* Finds basic ivs.  */
977
978 static bool
979 find_bivs (struct ivopts_data *data)
980 {
981   tree phi, step, type, base;
982   bool found = false;
983   struct loop *loop = data->current_loop;
984
985   for (phi = phi_nodes (loop->header); phi; phi = PHI_CHAIN (phi))
986     {
987       if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (PHI_RESULT (phi)))
988         continue;
989
990       step = determine_biv_step (phi);
991       if (!step)
992         continue;
993
994       base = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
995       base = expand_simple_operations (base);
996       if (contains_abnormal_ssa_name_p (base)
997           || contains_abnormal_ssa_name_p (step))
998         continue;
999
1000       type = TREE_TYPE (PHI_RESULT (phi));
1001       base = fold_convert (type, base);
1002       if (step)
1003         step = fold_convert (type, step);
1004
1005       set_iv (data, PHI_RESULT (phi), base, step);
1006       found = true;
1007     }
1008
1009   return found;
1010 }
1011
1012 /* Marks basic ivs.  */
1013
1014 static void
1015 mark_bivs (struct ivopts_data *data)
1016 {
1017   tree phi, var;
1018   struct iv *iv, *incr_iv;
1019   struct loop *loop = data->current_loop;
1020   basic_block incr_bb;
1021
1022   for (phi = phi_nodes (loop->header); phi; phi = PHI_CHAIN (phi))
1023     {
1024       iv = get_iv (data, PHI_RESULT (phi));
1025       if (!iv)
1026         continue;
1027
1028       var = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
1029       incr_iv = get_iv (data, var);
1030       if (!incr_iv)
1031         continue;
1032
1033       /* If the increment is in the subloop, ignore it.  */
1034       incr_bb = bb_for_stmt (SSA_NAME_DEF_STMT (var));
1035       if (incr_bb->loop_father != data->current_loop
1036           || (incr_bb->flags & BB_IRREDUCIBLE_LOOP))
1037         continue;
1038
1039       iv->biv_p = true;
1040       incr_iv->biv_p = true;
1041     }
1042 }
1043
1044 /* Checks whether STMT defines a linear induction variable and stores its
1045    parameters to BASE and STEP.  */
1046
1047 static bool
1048 find_givs_in_stmt_scev (struct ivopts_data *data, tree stmt,
1049                         tree *base, tree *step)
1050 {
1051   tree lhs;
1052   struct loop *loop = data->current_loop;
1053
1054   *base = NULL_TREE;
1055   *step = NULL_TREE;
1056
1057   if (TREE_CODE (stmt) != MODIFY_EXPR)
1058     return false;
1059
1060   lhs = TREE_OPERAND (stmt, 0);
1061   if (TREE_CODE (lhs) != SSA_NAME)
1062     return false;
1063
1064   if (!simple_iv (loop, stmt, TREE_OPERAND (stmt, 1), base, step, true))
1065     return false;
1066   *base = expand_simple_operations (*base);
1067
1068   if (contains_abnormal_ssa_name_p (*base)
1069       || contains_abnormal_ssa_name_p (*step))
1070     return false;
1071
1072   return true;
1073 }
1074
1075 /* Finds general ivs in statement STMT.  */
1076
1077 static void
1078 find_givs_in_stmt (struct ivopts_data *data, tree stmt)
1079 {
1080   tree base, step;
1081
1082   if (!find_givs_in_stmt_scev (data, stmt, &base, &step))
1083     return;
1084
1085   set_iv (data, TREE_OPERAND (stmt, 0), base, step);
1086 }
1087
1088 /* Finds general ivs in basic block BB.  */
1089
1090 static void
1091 find_givs_in_bb (struct ivopts_data *data, basic_block bb)
1092 {
1093   block_stmt_iterator bsi;
1094
1095   for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1096     find_givs_in_stmt (data, bsi_stmt (bsi));
1097 }
1098
1099 /* Finds general ivs.  */
1100
1101 static void
1102 find_givs (struct ivopts_data *data)
1103 {
1104   struct loop *loop = data->current_loop;
1105   basic_block *body = get_loop_body_in_dom_order (loop);
1106   unsigned i;
1107
1108   for (i = 0; i < loop->num_nodes; i++)
1109     find_givs_in_bb (data, body[i]);
1110   free (body);
1111 }
1112
1113 /* For each ssa name defined in LOOP determines whether it is an induction
1114    variable and if so, its initial value and step.  */
1115
1116 static bool
1117 find_induction_variables (struct ivopts_data *data)
1118 {
1119   unsigned i;
1120   bitmap_iterator bi;
1121
1122   if (!find_bivs (data))
1123     return false;
1124
1125   find_givs (data);
1126   mark_bivs (data);
1127
1128   if (dump_file && (dump_flags & TDF_DETAILS))
1129     {
1130       struct tree_niter_desc *niter;
1131
1132       niter = niter_for_single_dom_exit (data);
1133
1134       if (niter)
1135         {
1136           fprintf (dump_file, "  number of iterations ");
1137           print_generic_expr (dump_file, niter->niter, TDF_SLIM);
1138           fprintf (dump_file, "\n");
1139
1140           fprintf (dump_file, "  may be zero if ");
1141           print_generic_expr (dump_file, niter->may_be_zero, TDF_SLIM);
1142           fprintf (dump_file, "\n");
1143           fprintf (dump_file, "\n");
1144         };
1145  
1146       fprintf (dump_file, "Induction variables:\n\n");
1147
1148       EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
1149         {
1150           if (ver_info (data, i)->iv)
1151             dump_iv (dump_file, ver_info (data, i)->iv);
1152         }
1153     }
1154
1155   return true;
1156 }
1157
1158 /* Records a use of type USE_TYPE at *USE_P in STMT whose value is IV.  */
1159
1160 static struct iv_use *
1161 record_use (struct ivopts_data *data, tree *use_p, struct iv *iv,
1162             tree stmt, enum use_type use_type)
1163 {
1164   struct iv_use *use = xcalloc (1, sizeof (struct iv_use));
1165
1166   use->id = n_iv_uses (data);
1167   use->type = use_type;
1168   use->iv = iv;
1169   use->stmt = stmt;
1170   use->op_p = use_p;
1171   use->related_cands = BITMAP_ALLOC (NULL);
1172
1173   /* To avoid showing ssa name in the dumps, if it was not reset by the
1174      caller.  */
1175   iv->ssa_name = NULL_TREE;
1176
1177   if (dump_file && (dump_flags & TDF_DETAILS))
1178     dump_use (dump_file, use);
1179
1180   VEC_safe_push (iv_use_p, heap, data->iv_uses, use);
1181
1182   return use;
1183 }
1184
1185 /* Checks whether OP is a loop-level invariant and if so, records it.
1186    NONLINEAR_USE is true if the invariant is used in a way we do not
1187    handle specially.  */
1188
1189 static void
1190 record_invariant (struct ivopts_data *data, tree op, bool nonlinear_use)
1191 {
1192   basic_block bb;
1193   struct version_info *info;
1194
1195   if (TREE_CODE (op) != SSA_NAME
1196       || !is_gimple_reg (op))
1197     return;
1198
1199   bb = bb_for_stmt (SSA_NAME_DEF_STMT (op));
1200   if (bb
1201       && flow_bb_inside_loop_p (data->current_loop, bb))
1202     return;
1203
1204   info = name_info (data, op);
1205   info->name = op;
1206   info->has_nonlin_use |= nonlinear_use;
1207   if (!info->inv_id)
1208     info->inv_id = ++data->max_inv_id;
1209   bitmap_set_bit (data->relevant, SSA_NAME_VERSION (op));
1210 }
1211
1212 /* Checks whether the use OP is interesting and if so, records it
1213    as TYPE.  */
1214
1215 static struct iv_use *
1216 find_interesting_uses_outer_or_nonlin (struct ivopts_data *data, tree op,
1217                                        enum use_type type)
1218 {
1219   struct iv *iv;
1220   struct iv *civ;
1221   tree stmt;
1222   struct iv_use *use;
1223
1224   if (TREE_CODE (op) != SSA_NAME)
1225     return NULL;
1226
1227   iv = get_iv (data, op);
1228   if (!iv)
1229     return NULL;
1230   
1231   if (iv->have_use_for)
1232     {
1233       use = iv_use (data, iv->use_id);
1234
1235       gcc_assert (use->type == USE_NONLINEAR_EXPR
1236                   || use->type == USE_OUTER);
1237
1238       if (type == USE_NONLINEAR_EXPR)
1239         use->type = USE_NONLINEAR_EXPR;
1240       return use;
1241     }
1242
1243   if (zero_p (iv->step))
1244     {
1245       record_invariant (data, op, true);
1246       return NULL;
1247     }
1248   iv->have_use_for = true;
1249
1250   civ = xmalloc (sizeof (struct iv));
1251   *civ = *iv;
1252
1253   stmt = SSA_NAME_DEF_STMT (op);
1254   gcc_assert (TREE_CODE (stmt) == PHI_NODE
1255               || TREE_CODE (stmt) == MODIFY_EXPR);
1256
1257   use = record_use (data, NULL, civ, stmt, type);
1258   iv->use_id = use->id;
1259
1260   return use;
1261 }
1262
1263 /* Checks whether the use OP is interesting and if so, records it.  */
1264
1265 static struct iv_use *
1266 find_interesting_uses_op (struct ivopts_data *data, tree op)
1267 {
1268   return find_interesting_uses_outer_or_nonlin (data, op, USE_NONLINEAR_EXPR);
1269 }
1270
1271 /* Records a definition of induction variable OP that is used outside of the
1272    loop.  */
1273
1274 static struct iv_use *
1275 find_interesting_uses_outer (struct ivopts_data *data, tree op)
1276 {
1277   return find_interesting_uses_outer_or_nonlin (data, op, USE_OUTER);
1278 }
1279
1280 /* Checks whether the condition *COND_P in STMT is interesting
1281    and if so, records it.  */
1282
1283 static void
1284 find_interesting_uses_cond (struct ivopts_data *data, tree stmt, tree *cond_p)
1285 {
1286   tree *op0_p;
1287   tree *op1_p;
1288   struct iv *iv0 = NULL, *iv1 = NULL, *civ;
1289   struct iv const_iv;
1290   tree zero = integer_zero_node;
1291
1292   const_iv.step = NULL_TREE;
1293
1294   if (TREE_CODE (*cond_p) != SSA_NAME
1295       && !COMPARISON_CLASS_P (*cond_p))
1296     return;
1297
1298   if (TREE_CODE (*cond_p) == SSA_NAME)
1299     {
1300       op0_p = cond_p;
1301       op1_p = &zero;
1302     }
1303   else
1304     {
1305       op0_p = &TREE_OPERAND (*cond_p, 0);
1306       op1_p = &TREE_OPERAND (*cond_p, 1);
1307     }
1308
1309   if (TREE_CODE (*op0_p) == SSA_NAME)
1310     iv0 = get_iv (data, *op0_p);
1311   else
1312     iv0 = &const_iv;
1313
1314   if (TREE_CODE (*op1_p) == SSA_NAME)
1315     iv1 = get_iv (data, *op1_p);
1316   else
1317     iv1 = &const_iv;
1318
1319   if (/* When comparing with non-invariant value, we may not do any senseful
1320          induction variable elimination.  */
1321       (!iv0 || !iv1)
1322       /* Eliminating condition based on two ivs would be nontrivial.
1323          ??? TODO -- it is not really important to handle this case.  */
1324       || (!zero_p (iv0->step) && !zero_p (iv1->step)))
1325     {
1326       find_interesting_uses_op (data, *op0_p);
1327       find_interesting_uses_op (data, *op1_p);
1328       return;
1329     }
1330
1331   if (zero_p (iv0->step) && zero_p (iv1->step))
1332     {
1333       /* If both are invariants, this is a work for unswitching.  */
1334       return;
1335     }
1336
1337   civ = xmalloc (sizeof (struct iv));
1338   *civ = zero_p (iv0->step) ? *iv1: *iv0;
1339   record_use (data, cond_p, civ, stmt, USE_COMPARE);
1340 }
1341
1342 /* Returns true if expression EXPR is obviously invariant in LOOP,
1343    i.e. if all its operands are defined outside of the LOOP.  */
1344
1345 bool
1346 expr_invariant_in_loop_p (struct loop *loop, tree expr)
1347 {
1348   basic_block def_bb;
1349   unsigned i, len;
1350
1351   if (is_gimple_min_invariant (expr))
1352     return true;
1353
1354   if (TREE_CODE (expr) == SSA_NAME)
1355     {
1356       def_bb = bb_for_stmt (SSA_NAME_DEF_STMT (expr));
1357       if (def_bb
1358           && flow_bb_inside_loop_p (loop, def_bb))
1359         return false;
1360
1361       return true;
1362     }
1363
1364   if (!EXPR_P (expr))
1365     return false;
1366
1367   len = TREE_CODE_LENGTH (TREE_CODE (expr));
1368   for (i = 0; i < len; i++)
1369     if (!expr_invariant_in_loop_p (loop, TREE_OPERAND (expr, i)))
1370       return false;
1371
1372   return true;
1373 }
1374
1375 /* Cumulates the steps of indices into DATA and replaces their values with the
1376    initial ones.  Returns false when the value of the index cannot be determined.
1377    Callback for for_each_index.  */
1378
1379 struct ifs_ivopts_data
1380 {
1381   struct ivopts_data *ivopts_data;
1382   tree stmt;
1383   tree *step_p;
1384 };
1385
1386 static bool
1387 idx_find_step (tree base, tree *idx, void *data)
1388 {
1389   struct ifs_ivopts_data *dta = data;
1390   struct iv *iv;
1391   tree step, type, iv_type, iv_step, lbound, off;
1392   struct loop *loop = dta->ivopts_data->current_loop;
1393
1394   if (TREE_CODE (base) == MISALIGNED_INDIRECT_REF
1395       || TREE_CODE (base) == ALIGN_INDIRECT_REF)
1396     return false;
1397
1398   /* If base is a component ref, require that the offset of the reference
1399      be invariant.  */
1400   if (TREE_CODE (base) == COMPONENT_REF)
1401     {
1402       off = component_ref_field_offset (base);
1403       return expr_invariant_in_loop_p (loop, off);
1404     }
1405
1406   /* If base is array, first check whether we will be able to move the
1407      reference out of the loop (in order to take its address in strength
1408      reduction).  In order for this to work we need both lower bound
1409      and step to be loop invariants.  */
1410   if (TREE_CODE (base) == ARRAY_REF)
1411     {
1412       step = array_ref_element_size (base);
1413       lbound = array_ref_low_bound (base);
1414
1415       if (!expr_invariant_in_loop_p (loop, step)
1416           || !expr_invariant_in_loop_p (loop, lbound))
1417         return false;
1418     }
1419
1420   if (TREE_CODE (*idx) != SSA_NAME)
1421     return true;
1422
1423   iv = get_iv (dta->ivopts_data, *idx);
1424   if (!iv)
1425     return false;
1426
1427   *idx = iv->base;
1428
1429   if (!iv->step)
1430     return true;
1431
1432   iv_type = TREE_TYPE (iv->base);
1433   type = build_pointer_type (TREE_TYPE (base));
1434   if (TREE_CODE (base) == ARRAY_REF)
1435     {
1436       step = array_ref_element_size (base);
1437
1438       /* We only handle addresses whose step is an integer constant.  */
1439       if (TREE_CODE (step) != INTEGER_CST)
1440         return false;
1441     }
1442   else
1443     /* The step for pointer arithmetics already is 1 byte.  */
1444     step = build_int_cst (type, 1);
1445
1446   if (TYPE_PRECISION (iv_type) < TYPE_PRECISION (type))
1447     iv_step = can_count_iv_in_wider_type (dta->ivopts_data->current_loop,
1448                                           type, iv->base, iv->step, dta->stmt);
1449   else
1450     iv_step = fold_convert (iv_type, iv->step);
1451
1452   if (!iv_step)
1453     {
1454       /* The index might wrap.  */
1455       return false;
1456     }
1457
1458   step = fold_build2 (MULT_EXPR, type, step, iv_step);
1459
1460   if (!*dta->step_p)
1461     *dta->step_p = step;
1462   else
1463     *dta->step_p = fold_build2 (PLUS_EXPR, type, *dta->step_p, step);
1464
1465   return true;
1466 }
1467
1468 /* Records use in index IDX.  Callback for for_each_index.  Ivopts data
1469    object is passed to it in DATA.  */
1470
1471 static bool
1472 idx_record_use (tree base, tree *idx,
1473                 void *data)
1474 {
1475   find_interesting_uses_op (data, *idx);
1476   if (TREE_CODE (base) == ARRAY_REF)
1477     {
1478       find_interesting_uses_op (data, array_ref_element_size (base));
1479       find_interesting_uses_op (data, array_ref_low_bound (base));
1480     }
1481   return true;
1482 }
1483
1484 /* Returns true if memory reference REF may be unaligned.  */
1485
1486 static bool
1487 may_be_unaligned_p (tree ref)
1488 {
1489   tree base;
1490   tree base_type;
1491   HOST_WIDE_INT bitsize;
1492   HOST_WIDE_INT bitpos;
1493   tree toffset;
1494   enum machine_mode mode;
1495   int unsignedp, volatilep;
1496   unsigned base_align;
1497
1498   /* The test below is basically copy of what expr.c:normal_inner_ref
1499      does to check whether the object must be loaded by parts when
1500      STRICT_ALIGNMENT is true.  */
1501   base = get_inner_reference (ref, &bitsize, &bitpos, &toffset, &mode,
1502                               &unsignedp, &volatilep, true);
1503   base_type = TREE_TYPE (base);
1504   base_align = TYPE_ALIGN (base_type);
1505
1506   if (mode != BLKmode
1507       && (base_align < GET_MODE_ALIGNMENT (mode)
1508           || bitpos % GET_MODE_ALIGNMENT (mode) != 0
1509           || bitpos % BITS_PER_UNIT != 0))
1510     return true;
1511
1512   return false;
1513 }
1514
1515 /* Builds ADDR_EXPR of object OBJ.  If OBJ is an INDIRECT_REF, the indirect_ref
1516    is stripped instead.  */
1517
1518 static tree
1519 build_addr_strip_iref (tree obj)
1520 {
1521   tree type;
1522
1523   if (TREE_CODE (obj) == INDIRECT_REF)
1524     {
1525       type = build_pointer_type (TREE_TYPE (obj));
1526       obj = fold_convert (type, TREE_OPERAND (obj, 0));
1527     }
1528   else
1529     obj = build_addr (obj);
1530
1531   return obj;
1532 }
1533
1534 /* Finds addresses in *OP_P inside STMT.  */
1535
1536 static void
1537 find_interesting_uses_address (struct ivopts_data *data, tree stmt, tree *op_p)
1538 {
1539   tree base = unshare_expr (*op_p), step = NULL;
1540   struct iv *civ;
1541   struct ifs_ivopts_data ifs_ivopts_data;
1542
1543   /* Do not play with volatile memory references.  A bit too conservative,
1544      perhaps, but safe.  */
1545   if (stmt_ann (stmt)->has_volatile_ops)
1546     goto fail;
1547
1548   /* Ignore bitfields for now.  Not really something terribly complicated
1549      to handle.  TODO.  */
1550   if (TREE_CODE (base) == COMPONENT_REF
1551       && DECL_NONADDRESSABLE_P (TREE_OPERAND (base, 1)))
1552     goto fail;
1553
1554   if (STRICT_ALIGNMENT
1555       && may_be_unaligned_p (base))
1556     goto fail;
1557
1558   ifs_ivopts_data.ivopts_data = data;
1559   ifs_ivopts_data.stmt = stmt;
1560   ifs_ivopts_data.step_p = &step;
1561   if (!for_each_index (&base, idx_find_step, &ifs_ivopts_data)
1562       || zero_p (step))
1563     goto fail;
1564
1565   gcc_assert (TREE_CODE (base) != ALIGN_INDIRECT_REF);
1566   gcc_assert (TREE_CODE (base) != MISALIGNED_INDIRECT_REF);
1567
1568   base = build_addr_strip_iref (base);
1569
1570   civ = alloc_iv (base, step);
1571   record_use (data, op_p, civ, stmt, USE_ADDRESS);
1572   return;
1573
1574 fail:
1575   for_each_index (op_p, idx_record_use, data);
1576 }
1577
1578 /* Finds and records invariants used in STMT.  */
1579
1580 static void
1581 find_invariants_stmt (struct ivopts_data *data, tree stmt)
1582 {
1583   ssa_op_iter iter;
1584   use_operand_p use_p;
1585   tree op;
1586
1587   FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, iter, SSA_OP_USE)
1588     {
1589       op = USE_FROM_PTR (use_p);
1590       record_invariant (data, op, false);
1591     }
1592 }
1593
1594 /* Finds interesting uses of induction variables in the statement STMT.  */
1595
1596 static void
1597 find_interesting_uses_stmt (struct ivopts_data *data, tree stmt)
1598 {
1599   struct iv *iv;
1600   tree op, lhs, rhs;
1601   ssa_op_iter iter;
1602   use_operand_p use_p;
1603
1604   find_invariants_stmt (data, stmt);
1605
1606   if (TREE_CODE (stmt) == COND_EXPR)
1607     {
1608       find_interesting_uses_cond (data, stmt, &COND_EXPR_COND (stmt));
1609       return;
1610     }
1611
1612   if (TREE_CODE (stmt) == MODIFY_EXPR)
1613     {
1614       lhs = TREE_OPERAND (stmt, 0);
1615       rhs = TREE_OPERAND (stmt, 1);
1616
1617       if (TREE_CODE (lhs) == SSA_NAME)
1618         {
1619           /* If the statement defines an induction variable, the uses are not
1620              interesting by themselves.  */
1621
1622           iv = get_iv (data, lhs);
1623
1624           if (iv && !zero_p (iv->step))
1625             return;
1626         }
1627
1628       switch (TREE_CODE_CLASS (TREE_CODE (rhs)))
1629         {
1630         case tcc_comparison:
1631           find_interesting_uses_cond (data, stmt, &TREE_OPERAND (stmt, 1));
1632           return;
1633
1634         case tcc_reference:
1635           find_interesting_uses_address (data, stmt, &TREE_OPERAND (stmt, 1));
1636           if (REFERENCE_CLASS_P (lhs))
1637             find_interesting_uses_address (data, stmt, &TREE_OPERAND (stmt, 0));
1638           return;
1639
1640         default: ;
1641         }
1642
1643       if (REFERENCE_CLASS_P (lhs)
1644           && is_gimple_val (rhs))
1645         {
1646           find_interesting_uses_address (data, stmt, &TREE_OPERAND (stmt, 0));
1647           find_interesting_uses_op (data, rhs);
1648           return;
1649         }
1650
1651       /* TODO -- we should also handle address uses of type
1652
1653          memory = call (whatever);
1654
1655          and
1656
1657          call (memory).  */
1658     }
1659
1660   if (TREE_CODE (stmt) == PHI_NODE
1661       && bb_for_stmt (stmt) == data->current_loop->header)
1662     {
1663       lhs = PHI_RESULT (stmt);
1664       iv = get_iv (data, lhs);
1665
1666       if (iv && !zero_p (iv->step))
1667         return;
1668     }
1669
1670   FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, iter, SSA_OP_USE)
1671     {
1672       op = USE_FROM_PTR (use_p);
1673
1674       if (TREE_CODE (op) != SSA_NAME)
1675         continue;
1676
1677       iv = get_iv (data, op);
1678       if (!iv)
1679         continue;
1680
1681       find_interesting_uses_op (data, op);
1682     }
1683 }
1684
1685 /* Finds interesting uses of induction variables outside of loops
1686    on loop exit edge EXIT.  */
1687
1688 static void
1689 find_interesting_uses_outside (struct ivopts_data *data, edge exit)
1690 {
1691   tree phi, def;
1692
1693   for (phi = phi_nodes (exit->dest); phi; phi = PHI_CHAIN (phi))
1694     {
1695       def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
1696       find_interesting_uses_outer (data, def);
1697     }
1698 }
1699
1700 /* Finds uses of the induction variables that are interesting.  */
1701
1702 static void
1703 find_interesting_uses (struct ivopts_data *data)
1704 {
1705   basic_block bb;
1706   block_stmt_iterator bsi;
1707   tree phi;
1708   basic_block *body = get_loop_body (data->current_loop);
1709   unsigned i;
1710   struct version_info *info;
1711   edge e;
1712
1713   if (dump_file && (dump_flags & TDF_DETAILS))
1714     fprintf (dump_file, "Uses:\n\n");
1715
1716   for (i = 0; i < data->current_loop->num_nodes; i++)
1717     {
1718       edge_iterator ei;
1719       bb = body[i];
1720
1721       FOR_EACH_EDGE (e, ei, bb->succs)
1722         if (e->dest != EXIT_BLOCK_PTR
1723             && !flow_bb_inside_loop_p (data->current_loop, e->dest))
1724           find_interesting_uses_outside (data, e);
1725
1726       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1727         find_interesting_uses_stmt (data, phi);
1728       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1729         find_interesting_uses_stmt (data, bsi_stmt (bsi));
1730     }
1731
1732   if (dump_file && (dump_flags & TDF_DETAILS))
1733     {
1734       bitmap_iterator bi;
1735
1736       fprintf (dump_file, "\n");
1737
1738       EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
1739         {
1740           info = ver_info (data, i);
1741           if (info->inv_id)
1742             {
1743               fprintf (dump_file, "  ");
1744               print_generic_expr (dump_file, info->name, TDF_SLIM);
1745               fprintf (dump_file, " is invariant (%d)%s\n",
1746                        info->inv_id, info->has_nonlin_use ? "" : ", eliminable");
1747             }
1748         }
1749
1750       fprintf (dump_file, "\n");
1751     }
1752
1753   free (body);
1754 }
1755
1756 /* Strips constant offsets from EXPR and stores them to OFFSET.  If INSIDE_ADDR
1757    is true, assume we are inside an address.  If TOP_COMPREF is true, assume
1758    we are at the top-level of the processed address.  */
1759
1760 static tree
1761 strip_offset_1 (tree expr, bool inside_addr, bool top_compref,
1762                 unsigned HOST_WIDE_INT *offset)
1763 {
1764   tree op0 = NULL_TREE, op1 = NULL_TREE, tmp, step;
1765   enum tree_code code;
1766   tree type, orig_type = TREE_TYPE (expr);
1767   unsigned HOST_WIDE_INT off0, off1, st;
1768   tree orig_expr = expr;
1769
1770   STRIP_NOPS (expr);
1771
1772   type = TREE_TYPE (expr);
1773   code = TREE_CODE (expr);
1774   *offset = 0;
1775
1776   switch (code)
1777     {
1778     case INTEGER_CST:
1779       if (!cst_and_fits_in_hwi (expr)
1780           || zero_p (expr))
1781         return orig_expr;
1782
1783       *offset = int_cst_value (expr);
1784       return build_int_cst_type (orig_type, 0);
1785
1786     case PLUS_EXPR:
1787     case MINUS_EXPR:
1788       op0 = TREE_OPERAND (expr, 0);
1789       op1 = TREE_OPERAND (expr, 1);
1790
1791       op0 = strip_offset_1 (op0, false, false, &off0);
1792       op1 = strip_offset_1 (op1, false, false, &off1);
1793
1794       *offset = (code == PLUS_EXPR ? off0 + off1 : off0 - off1);
1795       if (op0 == TREE_OPERAND (expr, 0)
1796           && op1 == TREE_OPERAND (expr, 1))
1797         return orig_expr;
1798
1799       if (zero_p (op1))
1800         expr = op0;
1801       else if (zero_p (op0))
1802         {
1803           if (code == PLUS_EXPR)
1804             expr = op1;
1805           else
1806             expr = fold_build1 (NEGATE_EXPR, type, op1);
1807         }
1808       else
1809         expr = fold_build2 (code, type, op0, op1);
1810
1811       return fold_convert (orig_type, expr);
1812
1813     case ARRAY_REF:
1814       if (!inside_addr)
1815         return orig_expr;
1816
1817       step = array_ref_element_size (expr);
1818       if (!cst_and_fits_in_hwi (step))
1819         break;
1820
1821       st = int_cst_value (step);
1822       op1 = TREE_OPERAND (expr, 1);
1823       op1 = strip_offset_1 (op1, false, false, &off1);
1824       *offset = off1 * st;
1825
1826       if (top_compref
1827           && zero_p (op1))
1828         {
1829           /* Strip the component reference completely.  */
1830           op0 = TREE_OPERAND (expr, 0);
1831           op0 = strip_offset_1 (op0, inside_addr, top_compref, &off0);
1832           *offset += off0;
1833           return op0;
1834         }
1835       break;
1836
1837     case COMPONENT_REF:
1838       if (!inside_addr)
1839         return orig_expr;
1840
1841       tmp = component_ref_field_offset (expr);
1842       if (top_compref
1843           && cst_and_fits_in_hwi (tmp))
1844         {
1845           /* Strip the component reference completely.  */
1846           op0 = TREE_OPERAND (expr, 0);
1847           op0 = strip_offset_1 (op0, inside_addr, top_compref, &off0);
1848           *offset = off0 + int_cst_value (tmp);
1849           return op0;
1850         }
1851       break;
1852
1853     case ADDR_EXPR:
1854       op0 = TREE_OPERAND (expr, 0);
1855       op0 = strip_offset_1 (op0, true, true, &off0);
1856       *offset += off0;
1857
1858       if (op0 == TREE_OPERAND (expr, 0))
1859         return orig_expr;
1860
1861       expr = build_addr_strip_iref (op0);
1862       return fold_convert (orig_type, expr);
1863
1864     case INDIRECT_REF:
1865       inside_addr = false;
1866       break;
1867
1868     default:
1869       return orig_expr;
1870     }
1871
1872   /* Default handling of expressions for that we want to recurse into
1873      the first operand.  */
1874   op0 = TREE_OPERAND (expr, 0);
1875   op0 = strip_offset_1 (op0, inside_addr, false, &off0);
1876   *offset += off0;
1877
1878   if (op0 == TREE_OPERAND (expr, 0)
1879       && (!op1 || op1 == TREE_OPERAND (expr, 1)))
1880     return orig_expr;
1881
1882   expr = copy_node (expr);
1883   TREE_OPERAND (expr, 0) = op0;
1884   if (op1)
1885     TREE_OPERAND (expr, 1) = op1;
1886
1887   /* Inside address, we might strip the top level component references,
1888      thus changing type of the expresion.  Handling of ADDR_EXPR
1889      will fix that.  */
1890   expr = fold_convert (orig_type, expr);
1891
1892   return expr;
1893 }
1894
1895 /* Strips constant offsets from EXPR and stores them to OFFSET.  */
1896
1897 static tree
1898 strip_offset (tree expr, unsigned HOST_WIDE_INT *offset)
1899 {
1900   return strip_offset_1 (expr, false, false, offset);
1901 }
1902
1903 /* Returns variant of TYPE that can be used as base for different uses.
1904    For integer types, we return unsigned variant of the type, which
1905    avoids problems with overflows.  For pointer types, we return void *.  */
1906
1907 static tree
1908 generic_type_for (tree type)
1909 {
1910   if (POINTER_TYPE_P (type))
1911     return ptr_type_node;
1912
1913   if (TYPE_UNSIGNED (type))
1914     return type;
1915
1916   return unsigned_type_for (type);
1917 }
1918
1919 /* Records invariants in *EXPR_P.  Callback for walk_tree.  DATA contains
1920    the bitmap to that we should store it.  */
1921
1922 static struct ivopts_data *fd_ivopts_data;
1923 static tree
1924 find_depends (tree *expr_p, int *ws ATTRIBUTE_UNUSED, void *data)
1925 {
1926   bitmap *depends_on = data;
1927   struct version_info *info;
1928
1929   if (TREE_CODE (*expr_p) != SSA_NAME)
1930     return NULL_TREE;
1931   info = name_info (fd_ivopts_data, *expr_p);
1932
1933   if (!info->inv_id || info->has_nonlin_use)
1934     return NULL_TREE;
1935
1936   if (!*depends_on)
1937     *depends_on = BITMAP_ALLOC (NULL);
1938   bitmap_set_bit (*depends_on, info->inv_id);
1939
1940   return NULL_TREE;
1941 }
1942
1943 /* Adds a candidate BASE + STEP * i.  Important field is set to IMPORTANT and
1944    position to POS.  If USE is not NULL, the candidate is set as related to
1945    it.  If both BASE and STEP are NULL, we add a pseudocandidate for the
1946    replacement of the final value of the iv by a direct computation.  */
1947
1948 static struct iv_cand *
1949 add_candidate_1 (struct ivopts_data *data,
1950                  tree base, tree step, bool important, enum iv_position pos,
1951                  struct iv_use *use, tree incremented_at)
1952 {
1953   unsigned i;
1954   struct iv_cand *cand = NULL;
1955   tree type, orig_type;
1956   
1957   if (base)
1958     {
1959       orig_type = TREE_TYPE (base);
1960       type = generic_type_for (orig_type);
1961       if (type != orig_type)
1962         {
1963           base = fold_convert (type, base);
1964           if (step)
1965             step = fold_convert (type, step);
1966         }
1967     }
1968
1969   for (i = 0; i < n_iv_cands (data); i++)
1970     {
1971       cand = iv_cand (data, i);
1972
1973       if (cand->pos != pos)
1974         continue;
1975
1976       if (cand->incremented_at != incremented_at)
1977         continue;
1978
1979       if (!cand->iv)
1980         {
1981           if (!base && !step)
1982             break;
1983
1984           continue;
1985         }
1986
1987       if (!base && !step)
1988         continue;
1989
1990       if (!operand_equal_p (base, cand->iv->base, 0))
1991         continue;
1992
1993       if (zero_p (cand->iv->step))
1994         {
1995           if (zero_p (step))
1996             break;
1997         }
1998       else
1999         {
2000           if (step && operand_equal_p (step, cand->iv->step, 0))
2001             break;
2002         }
2003     }
2004
2005   if (i == n_iv_cands (data))
2006     {
2007       cand = xcalloc (1, sizeof (struct iv_cand));
2008       cand->id = i;
2009
2010       if (!base && !step)
2011         cand->iv = NULL;
2012       else
2013         cand->iv = alloc_iv (base, step);
2014
2015       cand->pos = pos;
2016       if (pos != IP_ORIGINAL && cand->iv)
2017         {
2018           cand->var_before = create_tmp_var_raw (TREE_TYPE (base), "ivtmp");
2019           cand->var_after = cand->var_before;
2020         }
2021       cand->important = important;
2022       cand->incremented_at = incremented_at;
2023       VEC_safe_push (iv_cand_p, heap, data->iv_candidates, cand);
2024
2025       if (step
2026           && TREE_CODE (step) != INTEGER_CST)
2027         {
2028           fd_ivopts_data = data;
2029           walk_tree (&step, find_depends, &cand->depends_on, NULL);
2030         }
2031
2032       if (dump_file && (dump_flags & TDF_DETAILS))
2033         dump_cand (dump_file, cand);
2034     }
2035
2036   if (important && !cand->important)
2037     {
2038       cand->important = true;
2039       if (dump_file && (dump_flags & TDF_DETAILS))
2040         fprintf (dump_file, "Candidate %d is important\n", cand->id);
2041     }
2042
2043   if (use)
2044     {
2045       bitmap_set_bit (use->related_cands, i);
2046       if (dump_file && (dump_flags & TDF_DETAILS))
2047         fprintf (dump_file, "Candidate %d is related to use %d\n",
2048                  cand->id, use->id);
2049     }
2050
2051   return cand;
2052 }
2053
2054 /* Returns true if incrementing the induction variable at the end of the LOOP
2055    is allowed.
2056
2057    The purpose is to avoid splitting latch edge with a biv increment, thus
2058    creating a jump, possibly confusing other optimization passes and leaving
2059    less freedom to scheduler.  So we allow IP_END_POS only if IP_NORMAL_POS
2060    is not available (so we do not have a better alternative), or if the latch
2061    edge is already nonempty.  */
2062
2063 static bool
2064 allow_ip_end_pos_p (struct loop *loop)
2065 {
2066   if (!ip_normal_pos (loop))
2067     return true;
2068
2069   if (!empty_block_p (ip_end_pos (loop)))
2070     return true;
2071
2072   return false;
2073 }
2074
2075 /* Adds a candidate BASE + STEP * i.  Important field is set to IMPORTANT and
2076    position to POS.  If USE is not NULL, the candidate is set as related to
2077    it.  The candidate computation is scheduled on all available positions.  */
2078
2079 static void
2080 add_candidate (struct ivopts_data *data, 
2081                tree base, tree step, bool important, struct iv_use *use)
2082 {
2083   if (ip_normal_pos (data->current_loop))
2084     add_candidate_1 (data, base, step, important, IP_NORMAL, use, NULL_TREE);
2085   if (ip_end_pos (data->current_loop)
2086       && allow_ip_end_pos_p (data->current_loop))
2087     add_candidate_1 (data, base, step, important, IP_END, use, NULL_TREE);
2088 }
2089
2090 /* Add a standard "0 + 1 * iteration" iv candidate for a
2091    type with SIZE bits.  */
2092
2093 static void
2094 add_standard_iv_candidates_for_size (struct ivopts_data *data,
2095                                      unsigned int size)
2096 {
2097   tree type = lang_hooks.types.type_for_size (size, true);
2098   add_candidate (data, build_int_cst (type, 0), build_int_cst (type, 1),
2099                  true, NULL);
2100 }
2101
2102 /* Adds standard iv candidates.  */
2103
2104 static void
2105 add_standard_iv_candidates (struct ivopts_data *data)
2106 {
2107   add_standard_iv_candidates_for_size (data, INT_TYPE_SIZE);
2108
2109   /* The same for a double-integer type if it is still fast enough.  */
2110   if (BITS_PER_WORD >= INT_TYPE_SIZE * 2)
2111     add_standard_iv_candidates_for_size (data, INT_TYPE_SIZE * 2);
2112 }
2113
2114
2115 /* Adds candidates bases on the old induction variable IV.  */
2116
2117 static void
2118 add_old_iv_candidates (struct ivopts_data *data, struct iv *iv)
2119 {
2120   tree phi, def;
2121   struct iv_cand *cand;
2122
2123   add_candidate (data, iv->base, iv->step, true, NULL);
2124
2125   /* The same, but with initial value zero.  */
2126   add_candidate (data,
2127                  build_int_cst (TREE_TYPE (iv->base), 0),
2128                  iv->step, true, NULL);
2129
2130   phi = SSA_NAME_DEF_STMT (iv->ssa_name);
2131   if (TREE_CODE (phi) == PHI_NODE)
2132     {
2133       /* Additionally record the possibility of leaving the original iv
2134          untouched.  */
2135       def = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (data->current_loop));
2136       cand = add_candidate_1 (data,
2137                               iv->base, iv->step, true, IP_ORIGINAL, NULL,
2138                               SSA_NAME_DEF_STMT (def));
2139       cand->var_before = iv->ssa_name;
2140       cand->var_after = def;
2141     }
2142 }
2143
2144 /* Adds candidates based on the old induction variables.  */
2145
2146 static void
2147 add_old_ivs_candidates (struct ivopts_data *data)
2148 {
2149   unsigned i;
2150   struct iv *iv;
2151   bitmap_iterator bi;
2152
2153   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
2154     {
2155       iv = ver_info (data, i)->iv;
2156       if (iv && iv->biv_p && !zero_p (iv->step))
2157         add_old_iv_candidates (data, iv);
2158     }
2159 }
2160
2161 /* Adds candidates based on the value of the induction variable IV and USE.  */
2162
2163 static void
2164 add_iv_value_candidates (struct ivopts_data *data,
2165                          struct iv *iv, struct iv_use *use)
2166 {
2167   unsigned HOST_WIDE_INT offset;
2168   tree base;
2169
2170   add_candidate (data, iv->base, iv->step, false, use);
2171
2172   /* The same, but with initial value zero.  Make such variable important,
2173      since it is generic enough so that possibly many uses may be based
2174      on it.  */
2175   add_candidate (data, build_int_cst (TREE_TYPE (iv->base), 0),
2176                  iv->step, true, use);
2177
2178   /* Third, try removing the constant offset.  */
2179   base = strip_offset (iv->base, &offset);
2180   if (offset)
2181     add_candidate (data, base, iv->step, false, use);
2182 }
2183
2184 /* Possibly adds pseudocandidate for replacing the final value of USE by
2185    a direct computation.  */
2186
2187 static void
2188 add_iv_outer_candidates (struct ivopts_data *data, struct iv_use *use)
2189 {
2190   struct tree_niter_desc *niter;
2191
2192   /* We must know where we exit the loop and how many times does it roll.  */
2193   niter = niter_for_single_dom_exit (data);
2194   if (!niter
2195       || !zero_p (niter->may_be_zero))
2196     return;
2197
2198   add_candidate_1 (data, NULL, NULL, false, IP_NORMAL, use, NULL_TREE);
2199 }
2200
2201 /* Adds candidates based on the uses.  */
2202
2203 static void
2204 add_derived_ivs_candidates (struct ivopts_data *data)
2205 {
2206   unsigned i;
2207
2208   for (i = 0; i < n_iv_uses (data); i++)
2209     {
2210       struct iv_use *use = iv_use (data, i);
2211
2212       if (!use)
2213         continue;
2214
2215       switch (use->type)
2216         {
2217         case USE_NONLINEAR_EXPR:
2218         case USE_COMPARE:
2219         case USE_ADDRESS:
2220           /* Just add the ivs based on the value of the iv used here.  */
2221           add_iv_value_candidates (data, use->iv, use);
2222           break;
2223
2224         case USE_OUTER:
2225           add_iv_value_candidates (data, use->iv, use);
2226
2227           /* Additionally, add the pseudocandidate for the possibility to
2228              replace the final value by a direct computation.  */
2229           add_iv_outer_candidates (data, use);
2230           break;
2231
2232         default:
2233           gcc_unreachable ();
2234         }
2235     }
2236 }
2237
2238 /* Record important candidates and add them to related_cands bitmaps
2239    if needed.  */
2240
2241 static void
2242 record_important_candidates (struct ivopts_data *data)
2243 {
2244   unsigned i;
2245   struct iv_use *use;
2246
2247   for (i = 0; i < n_iv_cands (data); i++)
2248     {
2249       struct iv_cand *cand = iv_cand (data, i);
2250
2251       if (cand->important)
2252         bitmap_set_bit (data->important_candidates, i);
2253     }
2254
2255   data->consider_all_candidates = (n_iv_cands (data)
2256                                    <= CONSIDER_ALL_CANDIDATES_BOUND);
2257
2258   if (data->consider_all_candidates)
2259     {
2260       /* We will not need "related_cands" bitmaps in this case,
2261          so release them to decrease peak memory consumption.  */
2262       for (i = 0; i < n_iv_uses (data); i++)
2263         {
2264           use = iv_use (data, i);
2265           BITMAP_FREE (use->related_cands);
2266         }
2267     }
2268   else
2269     {
2270       /* Add important candidates to the related_cands bitmaps.  */
2271       for (i = 0; i < n_iv_uses (data); i++)
2272         bitmap_ior_into (iv_use (data, i)->related_cands,
2273                          data->important_candidates);
2274     }
2275 }
2276
2277 /* Finds the candidates for the induction variables.  */
2278
2279 static void
2280 find_iv_candidates (struct ivopts_data *data)
2281 {
2282   /* Add commonly used ivs.  */
2283   add_standard_iv_candidates (data);
2284
2285   /* Add old induction variables.  */
2286   add_old_ivs_candidates (data);
2287
2288   /* Add induction variables derived from uses.  */
2289   add_derived_ivs_candidates (data);
2290
2291   /* Record the important candidates.  */
2292   record_important_candidates (data);
2293 }
2294
2295 /* Allocates the data structure mapping the (use, candidate) pairs to costs.
2296    If consider_all_candidates is true, we use a two-dimensional array, otherwise
2297    we allocate a simple list to every use.  */
2298
2299 static void
2300 alloc_use_cost_map (struct ivopts_data *data)
2301 {
2302   unsigned i, size, s, j;
2303
2304   for (i = 0; i < n_iv_uses (data); i++)
2305     {
2306       struct iv_use *use = iv_use (data, i);
2307       bitmap_iterator bi;
2308
2309       if (data->consider_all_candidates)
2310         size = n_iv_cands (data);
2311       else
2312         {
2313           s = 0;
2314           EXECUTE_IF_SET_IN_BITMAP (use->related_cands, 0, j, bi)
2315             {
2316               s++;
2317             }
2318
2319           /* Round up to the power of two, so that moduling by it is fast.  */
2320           for (size = 1; size < s; size <<= 1)
2321             continue;
2322         }
2323
2324       use->n_map_members = size;
2325       use->cost_map = xcalloc (size, sizeof (struct cost_pair));
2326     }
2327 }
2328
2329 /* Sets cost of (USE, CANDIDATE) pair to COST and record that it depends
2330    on invariants DEPENDS_ON and that the value used in expressing it
2331    is VALUE.*/
2332
2333 static void
2334 set_use_iv_cost (struct ivopts_data *data,
2335                  struct iv_use *use, struct iv_cand *cand, unsigned cost,
2336                  bitmap depends_on, tree value)
2337 {
2338   unsigned i, s;
2339
2340   if (cost == INFTY)
2341     {
2342       BITMAP_FREE (depends_on);
2343       return;
2344     }
2345
2346   if (data->consider_all_candidates)
2347     {
2348       use->cost_map[cand->id].cand = cand;
2349       use->cost_map[cand->id].cost = cost;
2350       use->cost_map[cand->id].depends_on = depends_on;
2351       use->cost_map[cand->id].value = value;
2352       return;
2353     }
2354
2355   /* n_map_members is a power of two, so this computes modulo.  */
2356   s = cand->id & (use->n_map_members - 1);
2357   for (i = s; i < use->n_map_members; i++)
2358     if (!use->cost_map[i].cand)
2359       goto found;
2360   for (i = 0; i < s; i++)
2361     if (!use->cost_map[i].cand)
2362       goto found;
2363
2364   gcc_unreachable ();
2365
2366 found:
2367   use->cost_map[i].cand = cand;
2368   use->cost_map[i].cost = cost;
2369   use->cost_map[i].depends_on = depends_on;
2370   use->cost_map[i].value = value;
2371 }
2372
2373 /* Gets cost of (USE, CANDIDATE) pair.  */
2374
2375 static struct cost_pair *
2376 get_use_iv_cost (struct ivopts_data *data, struct iv_use *use,
2377                  struct iv_cand *cand)
2378 {
2379   unsigned i, s;
2380   struct cost_pair *ret;
2381
2382   if (!cand)
2383     return NULL;
2384
2385   if (data->consider_all_candidates)
2386     {
2387       ret = use->cost_map + cand->id;
2388       if (!ret->cand)
2389         return NULL;
2390
2391       return ret;
2392     }
2393       
2394   /* n_map_members is a power of two, so this computes modulo.  */
2395   s = cand->id & (use->n_map_members - 1);
2396   for (i = s; i < use->n_map_members; i++)
2397     if (use->cost_map[i].cand == cand)
2398       return use->cost_map + i;
2399
2400   for (i = 0; i < s; i++)
2401     if (use->cost_map[i].cand == cand)
2402       return use->cost_map + i;
2403
2404   return NULL;
2405 }
2406
2407 /* Returns estimate on cost of computing SEQ.  */
2408
2409 static unsigned
2410 seq_cost (rtx seq)
2411 {
2412   unsigned cost = 0;
2413   rtx set;
2414
2415   for (; seq; seq = NEXT_INSN (seq))
2416     {
2417       set = single_set (seq);
2418       if (set)
2419         cost += rtx_cost (set, SET);
2420       else
2421         cost++;
2422     }
2423
2424   return cost;
2425 }
2426
2427 /* Produce DECL_RTL for object obj so it looks like it is stored in memory.  */
2428 static rtx
2429 produce_memory_decl_rtl (tree obj, int *regno)
2430 {
2431   rtx x;
2432   
2433   gcc_assert (obj);
2434   if (TREE_STATIC (obj) || DECL_EXTERNAL (obj))
2435     {
2436       const char *name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (obj));
2437       x = gen_rtx_SYMBOL_REF (Pmode, name);
2438     }
2439   else
2440     x = gen_raw_REG (Pmode, (*regno)++);
2441
2442   return gen_rtx_MEM (DECL_MODE (obj), x);
2443 }
2444
2445 /* Prepares decl_rtl for variables referred in *EXPR_P.  Callback for
2446    walk_tree.  DATA contains the actual fake register number.  */
2447
2448 static tree
2449 prepare_decl_rtl (tree *expr_p, int *ws, void *data)
2450 {
2451   tree obj = NULL_TREE;
2452   rtx x = NULL_RTX;
2453   int *regno = data;
2454
2455   switch (TREE_CODE (*expr_p))
2456     {
2457     case ADDR_EXPR:
2458       for (expr_p = &TREE_OPERAND (*expr_p, 0);
2459            handled_component_p (*expr_p);
2460            expr_p = &TREE_OPERAND (*expr_p, 0))
2461         continue;
2462       obj = *expr_p;
2463       if (DECL_P (obj))
2464         x = produce_memory_decl_rtl (obj, regno);
2465       break;
2466
2467     case SSA_NAME:
2468       *ws = 0;
2469       obj = SSA_NAME_VAR (*expr_p);
2470       if (!DECL_RTL_SET_P (obj))
2471         x = gen_raw_REG (DECL_MODE (obj), (*regno)++);
2472       break;
2473
2474     case VAR_DECL:
2475     case PARM_DECL:
2476     case RESULT_DECL:
2477       *ws = 0;
2478       obj = *expr_p;
2479
2480       if (DECL_RTL_SET_P (obj))
2481         break;
2482
2483       if (DECL_MODE (obj) == BLKmode)
2484         x = produce_memory_decl_rtl (obj, regno);
2485       else
2486         x = gen_raw_REG (DECL_MODE (obj), (*regno)++);
2487
2488       break;
2489
2490     default:
2491       break;
2492     }
2493
2494   if (x)
2495     {
2496       VEC_safe_push (tree, heap, decl_rtl_to_reset, obj);
2497       SET_DECL_RTL (obj, x);
2498     }
2499
2500   return NULL_TREE;
2501 }
2502
2503 /* Determines cost of the computation of EXPR.  */
2504
2505 static unsigned
2506 computation_cost (tree expr)
2507 {
2508   rtx seq, rslt;
2509   tree type = TREE_TYPE (expr);
2510   unsigned cost;
2511   /* Avoid using hard regs in ways which may be unsupported.  */
2512   int regno = LAST_VIRTUAL_REGISTER + 1;
2513
2514   walk_tree (&expr, prepare_decl_rtl, &regno, NULL);
2515   start_sequence ();
2516   rslt = expand_expr (expr, NULL_RTX, TYPE_MODE (type), EXPAND_NORMAL);
2517   seq = get_insns ();
2518   end_sequence ();
2519
2520   cost = seq_cost (seq);
2521   if (MEM_P (rslt))
2522     cost += address_cost (XEXP (rslt, 0), TYPE_MODE (type));
2523
2524   return cost;
2525 }
2526
2527 /* Returns variable containing the value of candidate CAND at statement AT.  */
2528
2529 static tree
2530 var_at_stmt (struct loop *loop, struct iv_cand *cand, tree stmt)
2531 {
2532   if (stmt_after_increment (loop, cand, stmt))
2533     return cand->var_after;
2534   else
2535     return cand->var_before;
2536 }
2537
2538 /* Return the most significant (sign) bit of T.  Similar to tree_int_cst_msb,
2539    but the bit is determined from TYPE_PRECISION, not MODE_BITSIZE.  */
2540
2541 int
2542 tree_int_cst_sign_bit (tree t)
2543 {
2544   unsigned bitno = TYPE_PRECISION (TREE_TYPE (t)) - 1;
2545   unsigned HOST_WIDE_INT w;
2546
2547   if (bitno < HOST_BITS_PER_WIDE_INT)
2548     w = TREE_INT_CST_LOW (t);
2549   else
2550     {
2551       w = TREE_INT_CST_HIGH (t);
2552       bitno -= HOST_BITS_PER_WIDE_INT;
2553     }
2554
2555   return (w >> bitno) & 1;
2556 }
2557
2558 /* If we can prove that TOP = cst * BOT for some constant cst in TYPE,
2559    return cst.  Otherwise return NULL_TREE.  */
2560
2561 static tree
2562 constant_multiple_of (tree type, tree top, tree bot)
2563 {
2564   tree res, mby, p0, p1;
2565   enum tree_code code;
2566   bool negate;
2567
2568   STRIP_NOPS (top);
2569   STRIP_NOPS (bot);
2570
2571   if (operand_equal_p (top, bot, 0))
2572     return build_int_cst (type, 1);
2573
2574   code = TREE_CODE (top);
2575   switch (code)
2576     {
2577     case MULT_EXPR:
2578       mby = TREE_OPERAND (top, 1);
2579       if (TREE_CODE (mby) != INTEGER_CST)
2580         return NULL_TREE;
2581
2582       res = constant_multiple_of (type, TREE_OPERAND (top, 0), bot);
2583       if (!res)
2584         return NULL_TREE;
2585
2586       return fold_binary_to_constant (MULT_EXPR, type, res,
2587                                       fold_convert (type, mby));
2588
2589     case PLUS_EXPR:
2590     case MINUS_EXPR:
2591       p0 = constant_multiple_of (type, TREE_OPERAND (top, 0), bot);
2592       if (!p0)
2593         return NULL_TREE;
2594       p1 = constant_multiple_of (type, TREE_OPERAND (top, 1), bot);
2595       if (!p1)
2596         return NULL_TREE;
2597
2598       return fold_binary_to_constant (code, type, p0, p1);
2599
2600     case INTEGER_CST:
2601       if (TREE_CODE (bot) != INTEGER_CST)
2602         return NULL_TREE;
2603
2604       bot = fold_convert (type, bot);
2605       top = fold_convert (type, top);
2606
2607       /* If BOT seems to be negative, try dividing by -BOT instead, and negate
2608          the result afterwards.  */
2609       if (tree_int_cst_sign_bit (bot))
2610         {
2611           negate = true;
2612           bot = fold_unary_to_constant (NEGATE_EXPR, type, bot);
2613         }
2614       else
2615         negate = false;
2616
2617       /* Ditto for TOP.  */
2618       if (tree_int_cst_sign_bit (top))
2619         {
2620           negate = !negate;
2621           top = fold_unary_to_constant (NEGATE_EXPR, type, top);
2622         }
2623
2624       if (!zero_p (fold_binary_to_constant (TRUNC_MOD_EXPR, type, top, bot)))
2625         return NULL_TREE;
2626
2627       res = fold_binary_to_constant (EXACT_DIV_EXPR, type, top, bot);
2628       if (negate)
2629         res = fold_unary_to_constant (NEGATE_EXPR, type, res);
2630       return res;
2631
2632     default:
2633       return NULL_TREE;
2634     }
2635 }
2636
2637 /* Affine combination of trees.  We keep track of at most MAX_AFF_ELTS elements
2638    to make things simpler; this is sufficient in most cases.  */
2639
2640 #define MAX_AFF_ELTS 8
2641
2642 struct affine_tree_combination
2643 {
2644   /* Type of the result of the combination.  */
2645   tree type;
2646
2647   /* Mask modulo that the operations are performed.  */
2648   unsigned HOST_WIDE_INT mask;
2649
2650   /* Constant offset.  */
2651   unsigned HOST_WIDE_INT offset;
2652
2653   /* Number of elements of the combination.  */
2654   unsigned n;
2655
2656   /* Elements and their coefficients.  */
2657   tree elts[MAX_AFF_ELTS];
2658   unsigned HOST_WIDE_INT coefs[MAX_AFF_ELTS];
2659
2660   /* Remainder of the expression.  */
2661   tree rest;
2662 };
2663
2664 /* Sets COMB to CST.  */
2665
2666 static void
2667 aff_combination_const (struct affine_tree_combination *comb, tree type,
2668                        unsigned HOST_WIDE_INT cst)
2669 {
2670   unsigned prec = TYPE_PRECISION (type);
2671
2672   comb->type = type;
2673   comb->mask = (((unsigned HOST_WIDE_INT) 2 << (prec - 1)) - 1);
2674
2675   comb->n = 0;
2676   comb->rest = NULL_TREE;
2677   comb->offset = cst & comb->mask;
2678 }
2679
2680 /* Sets COMB to single element ELT.  */
2681
2682 static void
2683 aff_combination_elt (struct affine_tree_combination *comb, tree type, tree elt)
2684 {
2685   unsigned prec = TYPE_PRECISION (type);
2686
2687   comb->type = type;
2688   comb->mask = (((unsigned HOST_WIDE_INT) 2 << (prec - 1)) - 1);
2689
2690   comb->n = 1;
2691   comb->elts[0] = elt;
2692   comb->coefs[0] = 1;
2693   comb->rest = NULL_TREE;
2694   comb->offset = 0;
2695 }
2696
2697 /* Scales COMB by SCALE.  */
2698
2699 static void
2700 aff_combination_scale (struct affine_tree_combination *comb,
2701                        unsigned HOST_WIDE_INT scale)
2702 {
2703   unsigned i, j;
2704
2705   if (scale == 1)
2706     return;
2707
2708   if (scale == 0)
2709     {
2710       aff_combination_const (comb, comb->type, 0);
2711       return;
2712     }
2713
2714   comb->offset = (scale * comb->offset) & comb->mask;
2715   for (i = 0, j = 0; i < comb->n; i++)
2716     {
2717       comb->coefs[j] = (scale * comb->coefs[i]) & comb->mask;
2718       comb->elts[j] = comb->elts[i];
2719       if (comb->coefs[j] != 0)
2720         j++;
2721     }
2722   comb->n = j;
2723
2724   if (comb->rest)
2725     {
2726       if (comb->n < MAX_AFF_ELTS)
2727         {
2728           comb->coefs[comb->n] = scale;
2729           comb->elts[comb->n] = comb->rest;
2730           comb->rest = NULL_TREE;
2731           comb->n++;
2732         }
2733       else
2734         comb->rest = fold_build2 (MULT_EXPR, comb->type, comb->rest,
2735                                   build_int_cst_type (comb->type, scale));
2736     }
2737 }
2738
2739 /* Adds ELT * SCALE to COMB.  */
2740
2741 static void
2742 aff_combination_add_elt (struct affine_tree_combination *comb, tree elt,
2743                          unsigned HOST_WIDE_INT scale)
2744 {
2745   unsigned i;
2746
2747   if (scale == 0)
2748     return;
2749
2750   for (i = 0; i < comb->n; i++)
2751     if (operand_equal_p (comb->elts[i], elt, 0))
2752       {
2753         comb->coefs[i] = (comb->coefs[i] + scale) & comb->mask;
2754         if (comb->coefs[i])
2755           return;
2756
2757         comb->n--;
2758         comb->coefs[i] = comb->coefs[comb->n];
2759         comb->elts[i] = comb->elts[comb->n];
2760         return;
2761       }
2762   if (comb->n < MAX_AFF_ELTS)
2763     {
2764       comb->coefs[comb->n] = scale;
2765       comb->elts[comb->n] = elt;
2766       comb->n++;
2767       return;
2768     }
2769
2770   if (scale == 1)
2771     elt = fold_convert (comb->type, elt);
2772   else
2773     elt = fold_build2 (MULT_EXPR, comb->type,
2774                        fold_convert (comb->type, elt),
2775                        build_int_cst_type (comb->type, scale)); 
2776
2777   if (comb->rest)
2778     comb->rest = fold_build2 (PLUS_EXPR, comb->type, comb->rest, elt);
2779   else
2780     comb->rest = elt;
2781 }
2782
2783 /* Adds COMB2 to COMB1.  */
2784
2785 static void
2786 aff_combination_add (struct affine_tree_combination *comb1,
2787                      struct affine_tree_combination *comb2)
2788 {
2789   unsigned i;
2790
2791   comb1->offset = (comb1->offset + comb2->offset) & comb1->mask;
2792   for (i = 0; i < comb2-> n; i++)
2793     aff_combination_add_elt (comb1, comb2->elts[i], comb2->coefs[i]);
2794   if (comb2->rest)
2795     aff_combination_add_elt (comb1, comb2->rest, 1);
2796 }
2797
2798 /* Splits EXPR into an affine combination of parts.  */
2799
2800 static void
2801 tree_to_aff_combination (tree expr, tree type,
2802                          struct affine_tree_combination *comb)
2803 {
2804   struct affine_tree_combination tmp;
2805   enum tree_code code;
2806   tree cst, core, toffset;
2807   HOST_WIDE_INT bitpos, bitsize;
2808   enum machine_mode mode;
2809   int unsignedp, volatilep;
2810
2811   STRIP_NOPS (expr);
2812
2813   code = TREE_CODE (expr);
2814   switch (code)
2815     {
2816     case INTEGER_CST:
2817       aff_combination_const (comb, type, int_cst_value (expr));
2818       return;
2819
2820     case PLUS_EXPR:
2821     case MINUS_EXPR:
2822       tree_to_aff_combination (TREE_OPERAND (expr, 0), type, comb);
2823       tree_to_aff_combination (TREE_OPERAND (expr, 1), type, &tmp);
2824       if (code == MINUS_EXPR)
2825         aff_combination_scale (&tmp, -1);
2826       aff_combination_add (comb, &tmp);
2827       return;
2828
2829     case MULT_EXPR:
2830       cst = TREE_OPERAND (expr, 1);
2831       if (TREE_CODE (cst) != INTEGER_CST)
2832         break;
2833       tree_to_aff_combination (TREE_OPERAND (expr, 0), type, comb);
2834       aff_combination_scale (comb, int_cst_value (cst));
2835       return;
2836
2837     case NEGATE_EXPR:
2838       tree_to_aff_combination (TREE_OPERAND (expr, 0), type, comb);
2839       aff_combination_scale (comb, -1);
2840       return;
2841
2842     case ADDR_EXPR:
2843       core = get_inner_reference (TREE_OPERAND (expr, 0), &bitsize, &bitpos,
2844                                   &toffset, &mode, &unsignedp, &volatilep,
2845                                   false);
2846       if (bitpos % BITS_PER_UNIT != 0)
2847         break;
2848       aff_combination_const (comb, type, bitpos / BITS_PER_UNIT);
2849       core = build_addr_strip_iref (core);
2850       if (TREE_CODE (core) == ADDR_EXPR)
2851         aff_combination_add_elt (comb, core, 1);
2852       else
2853         {
2854           tree_to_aff_combination (core, type, &tmp);
2855           aff_combination_add (comb, &tmp);
2856         }
2857       if (toffset)
2858         {
2859           tree_to_aff_combination (toffset, type, &tmp);
2860           aff_combination_add (comb, &tmp);
2861         }
2862       return;
2863
2864     default:
2865       break;
2866     }
2867
2868   aff_combination_elt (comb, type, expr);
2869 }
2870
2871 /* Creates EXPR + ELT * SCALE in TYPE.  MASK is the mask for width of TYPE.  */
2872
2873 static tree
2874 add_elt_to_tree (tree expr, tree type, tree elt, unsigned HOST_WIDE_INT scale,
2875                  unsigned HOST_WIDE_INT mask)
2876 {
2877   enum tree_code code;
2878
2879   scale &= mask;
2880   elt = fold_convert (type, elt);
2881
2882   if (scale == 1)
2883     {
2884       if (!expr)
2885         return elt;
2886
2887       return fold_build2 (PLUS_EXPR, type, expr, elt);
2888     }
2889
2890   if (scale == mask)
2891     {
2892       if (!expr)
2893         return fold_build1 (NEGATE_EXPR, type, elt);
2894
2895       return fold_build2 (MINUS_EXPR, type, expr, elt);
2896     }
2897
2898   if (!expr)
2899     return fold_build2 (MULT_EXPR, type, elt,
2900                         build_int_cst_type (type, scale));
2901
2902   if ((scale | (mask >> 1)) == mask)
2903     {
2904       /* Scale is negative.  */
2905       code = MINUS_EXPR;
2906       scale = (-scale) & mask;
2907     }
2908   else
2909     code = PLUS_EXPR;
2910
2911   elt = fold_build2 (MULT_EXPR, type, elt,
2912                      build_int_cst_type (type, scale));
2913   return fold_build2 (code, type, expr, elt);
2914 }
2915
2916 /* Makes tree from the affine combination COMB.  */
2917
2918 static tree
2919 aff_combination_to_tree (struct affine_tree_combination *comb)
2920 {
2921   tree type = comb->type;
2922   tree expr = comb->rest;
2923   unsigned i;
2924   unsigned HOST_WIDE_INT off, sgn;
2925
2926   gcc_assert (comb->n == MAX_AFF_ELTS || comb->rest == NULL_TREE);
2927
2928   for (i = 0; i < comb->n; i++)
2929     expr = add_elt_to_tree (expr, type, comb->elts[i], comb->coefs[i],
2930                             comb->mask);
2931
2932   if ((comb->offset | (comb->mask >> 1)) == comb->mask)
2933     {
2934       /* Offset is negative.  */
2935       off = (-comb->offset) & comb->mask;
2936       sgn = comb->mask;
2937     }
2938   else
2939     {
2940       off = comb->offset;
2941       sgn = 1;
2942     }
2943   return add_elt_to_tree (expr, type, build_int_cst_type (type, off), sgn,
2944                           comb->mask);
2945 }
2946
2947 /* Folds X + RATIO * Y in TYPE.  */
2948
2949 static tree
2950 fold_affine_sum (tree type, tree x, tree y, HOST_WIDE_INT ratio)
2951 {
2952   enum tree_code code;
2953   tree cst;
2954   struct affine_tree_combination cx, cy;
2955
2956   if (TYPE_PRECISION (type) > HOST_BITS_PER_WIDE_INT)
2957     {
2958       if (ratio == 1)
2959         return fold_build2 (PLUS_EXPR, type, x, y);
2960       if (ratio == -1)
2961         return fold_build2 (MINUS_EXPR, type, x, y);
2962
2963       if (ratio < 0)
2964         {
2965           code = MINUS_EXPR;
2966           ratio = -ratio;
2967         }
2968       else
2969         code = PLUS_EXPR;
2970
2971       cst = build_int_cst_type (type, ratio);
2972       y = fold_build2 (MULT_EXPR, type, y, cst);
2973       return fold_build2 (code, type, x, y);
2974     }
2975
2976   tree_to_aff_combination (x, type, &cx);
2977   tree_to_aff_combination (y, type, &cy);
2978   aff_combination_scale (&cy, ratio);
2979   aff_combination_add (&cx, &cy);
2980
2981   return aff_combination_to_tree (&cx);
2982 }
2983
2984 /* Determines the expression by that USE is expressed from induction variable
2985    CAND at statement AT in LOOP.  */
2986
2987 static tree
2988 get_computation_at (struct loop *loop,
2989                     struct iv_use *use, struct iv_cand *cand, tree at)
2990 {
2991   tree ubase = use->iv->base;
2992   tree ustep = use->iv->step;
2993   tree cbase = cand->iv->base;
2994   tree cstep = cand->iv->step;
2995   tree utype = TREE_TYPE (ubase), ctype = TREE_TYPE (cbase);
2996   tree uutype;
2997   tree expr, delta;
2998   tree ratio;
2999   unsigned HOST_WIDE_INT ustepi, cstepi;
3000   HOST_WIDE_INT ratioi;
3001
3002   if (TYPE_PRECISION (utype) > TYPE_PRECISION (ctype))
3003     {
3004       /* We do not have a precision to express the values of use.  */
3005       return NULL_TREE;
3006     }
3007
3008   expr = var_at_stmt (loop, cand, at);
3009
3010   if (TREE_TYPE (expr) != ctype)
3011     {
3012       /* This may happen with the original ivs.  */
3013       expr = fold_convert (ctype, expr);
3014     }
3015
3016   if (TYPE_UNSIGNED (utype))
3017     uutype = utype;
3018   else
3019     {
3020       uutype = unsigned_type_for (utype);
3021       ubase = fold_convert (uutype, ubase);
3022       ustep = fold_convert (uutype, ustep);
3023     }
3024
3025   if (uutype != ctype)
3026     {
3027       expr = fold_convert (uutype, expr);
3028       cbase = fold_convert (uutype, cbase);
3029       cstep = fold_convert (uutype, cstep);
3030     }
3031
3032   if (cst_and_fits_in_hwi (cstep)
3033       && cst_and_fits_in_hwi (ustep))
3034     {
3035       ustepi = int_cst_value (ustep);
3036       cstepi = int_cst_value (cstep);
3037
3038       if (!divide (TYPE_PRECISION (uutype), ustepi, cstepi, &ratioi))
3039         {
3040           /* TODO maybe consider case when ustep divides cstep and the ratio is
3041              a power of 2 (so that the division is fast to execute)?  We would
3042              need to be much more careful with overflows etc. then.  */
3043           return NULL_TREE;
3044         }
3045
3046       ratio = build_int_cst_type (uutype, ratioi);
3047     }
3048   else
3049     {
3050       ratio = constant_multiple_of (uutype, ustep, cstep);
3051       if (!ratio)
3052         return NULL_TREE;
3053
3054       /* Ratioi is only used to detect special cases when the multiplicative
3055          factor is 1 or -1, so if we cannot convert ratio to HOST_WIDE_INT,
3056          we may set it to 0.  We prefer cst_and_fits_in_hwi/int_cst_value
3057          to integer_onep/integer_all_onesp, since the former ignores
3058          TREE_OVERFLOW.  */
3059       if (cst_and_fits_in_hwi (ratio))
3060         ratioi = int_cst_value (ratio);
3061       else if (integer_onep (ratio))
3062         ratioi = 1;
3063       else if (integer_all_onesp (ratio))
3064         ratioi = -1;
3065       else
3066         ratioi = 0;
3067     }
3068
3069   /* We may need to shift the value if we are after the increment.  */
3070   if (stmt_after_increment (loop, cand, at))
3071     cbase = fold (build2 (PLUS_EXPR, uutype, cbase, cstep));
3072
3073   /* use = ubase - ratio * cbase + ratio * var.
3074
3075      In general case ubase + ratio * (var - cbase) could be better (one less
3076      multiplication), but often it is possible to eliminate redundant parts
3077      of computations from (ubase - ratio * cbase) term, and if it does not
3078      happen, fold is able to apply the distributive law to obtain this form
3079      anyway.  */
3080
3081   if (ratioi == 1)
3082     {
3083       delta = fold_affine_sum (uutype, ubase, cbase, -1);
3084       expr = fold_build2 (PLUS_EXPR, uutype, expr, delta);
3085     }
3086   else if (ratioi == -1)
3087     {
3088       delta = fold_affine_sum (uutype, ubase, cbase, 1);
3089       expr = fold_build2 (MINUS_EXPR, uutype, delta, expr);
3090     }
3091   else
3092     {
3093       if (ratioi)
3094         delta = fold_affine_sum (uutype, ubase, cbase, -ratioi);
3095       else
3096         {
3097           delta = fold_build2 (MULT_EXPR, uutype, ratio, cbase);
3098           delta = fold_affine_sum (uutype, ubase, delta, -1);
3099         }
3100       expr = fold_build2 (MULT_EXPR, uutype, ratio, expr);
3101       expr = fold_build2 (PLUS_EXPR, uutype, delta, expr);
3102     }
3103
3104   return fold_convert (utype, expr);
3105 }
3106
3107 /* Determines the expression by that USE is expressed from induction variable
3108    CAND in LOOP.  */
3109
3110 static tree
3111 get_computation (struct loop *loop, struct iv_use *use, struct iv_cand *cand)
3112 {
3113   return get_computation_at (loop, use, cand, use->stmt);
3114 }
3115
3116 /* Returns cost of addition in MODE.  */
3117
3118 static unsigned
3119 add_cost (enum machine_mode mode)
3120 {
3121   static unsigned costs[NUM_MACHINE_MODES];
3122   rtx seq;
3123   unsigned cost;
3124
3125   if (costs[mode])
3126     return costs[mode];
3127
3128   start_sequence ();
3129   force_operand (gen_rtx_fmt_ee (PLUS, mode,
3130                                  gen_raw_REG (mode, FIRST_PSEUDO_REGISTER),
3131                                  gen_raw_REG (mode, FIRST_PSEUDO_REGISTER + 1)),
3132                  NULL_RTX);
3133   seq = get_insns ();
3134   end_sequence ();
3135
3136   cost = seq_cost (seq);
3137   if (!cost)
3138     cost = 1;
3139
3140   costs[mode] = cost;
3141       
3142   if (dump_file && (dump_flags & TDF_DETAILS))
3143     fprintf (dump_file, "Addition in %s costs %d\n",
3144              GET_MODE_NAME (mode), cost);
3145   return cost;
3146 }
3147
3148 /* Entry in a hashtable of already known costs for multiplication.  */
3149 struct mbc_entry
3150 {
3151   HOST_WIDE_INT cst;            /* The constant to multiply by.  */
3152   enum machine_mode mode;       /* In mode.  */
3153   unsigned cost;                /* The cost.  */
3154 };
3155
3156 /* Counts hash value for the ENTRY.  */
3157
3158 static hashval_t
3159 mbc_entry_hash (const void *entry)
3160 {
3161   const struct mbc_entry *e = entry;
3162
3163   return 57 * (hashval_t) e->mode + (hashval_t) (e->cst % 877);
3164 }
3165
3166 /* Compares the hash table entries ENTRY1 and ENTRY2.  */
3167
3168 static int
3169 mbc_entry_eq (const void *entry1, const void *entry2)
3170 {
3171   const struct mbc_entry *e1 = entry1;
3172   const struct mbc_entry *e2 = entry2;
3173
3174   return (e1->mode == e2->mode
3175           && e1->cst == e2->cst);
3176 }
3177
3178 /* Returns cost of multiplication by constant CST in MODE.  */
3179
3180 static unsigned
3181 multiply_by_cost (HOST_WIDE_INT cst, enum machine_mode mode)
3182 {
3183   static htab_t costs;
3184   struct mbc_entry **cached, act;
3185   rtx seq;
3186   unsigned cost;
3187
3188   if (!costs)
3189     costs = htab_create (100, mbc_entry_hash, mbc_entry_eq, free);
3190
3191   act.mode = mode;
3192   act.cst = cst;
3193   cached = (struct mbc_entry **) htab_find_slot (costs, &act, INSERT);
3194   if (*cached)
3195     return (*cached)->cost;
3196
3197   *cached = xmalloc (sizeof (struct mbc_entry));
3198   (*cached)->mode = mode;
3199   (*cached)->cst = cst;
3200
3201   start_sequence ();
3202   expand_mult (mode, gen_raw_REG (mode, FIRST_PSEUDO_REGISTER), GEN_INT (cst),
3203                NULL_RTX, 0);
3204   seq = get_insns ();
3205   end_sequence ();
3206   
3207   cost = seq_cost (seq);
3208
3209   if (dump_file && (dump_flags & TDF_DETAILS))
3210     fprintf (dump_file, "Multiplication by %d in %s costs %d\n",
3211              (int) cst, GET_MODE_NAME (mode), cost);
3212
3213   (*cached)->cost = cost;
3214
3215   return cost;
3216 }
3217
3218 /* Returns cost of address in shape symbol + var + OFFSET + RATIO * index.
3219    If SYMBOL_PRESENT is false, symbol is omitted.  If VAR_PRESENT is false,
3220    variable is omitted.  The created memory accesses MODE.
3221    
3222    TODO -- there must be some better way.  This all is quite crude.  */
3223
3224 static unsigned
3225 get_address_cost (bool symbol_present, bool var_present,
3226                   unsigned HOST_WIDE_INT offset, HOST_WIDE_INT ratio)
3227 {
3228 #define MAX_RATIO 128
3229   static sbitmap valid_mult;
3230   static HOST_WIDE_INT rat, off;
3231   static HOST_WIDE_INT min_offset, max_offset;
3232   static unsigned costs[2][2][2][2];
3233   unsigned cost, acost;
3234   rtx seq, addr, base;
3235   bool offset_p, ratio_p;
3236   rtx reg1;
3237   HOST_WIDE_INT s_offset;
3238   unsigned HOST_WIDE_INT mask;
3239   unsigned bits;
3240
3241   if (!valid_mult)
3242     {
3243       HOST_WIDE_INT i;
3244
3245       reg1 = gen_raw_REG (Pmode, FIRST_PSEUDO_REGISTER);
3246
3247       addr = gen_rtx_fmt_ee (PLUS, Pmode, reg1, NULL_RTX);
3248       for (i = 1; i <= 1 << 20; i <<= 1)
3249         {
3250           XEXP (addr, 1) = GEN_INT (i);
3251           if (!memory_address_p (Pmode, addr))
3252             break;
3253         }
3254       max_offset = i >> 1;
3255       off = max_offset;
3256
3257       for (i = 1; i <= 1 << 20; i <<= 1)
3258         {
3259           XEXP (addr, 1) = GEN_INT (-i);
3260           if (!memory_address_p (Pmode, addr))
3261             break;
3262         }
3263       min_offset = -(i >> 1);
3264
3265       if (dump_file && (dump_flags & TDF_DETAILS))
3266         {
3267           fprintf (dump_file, "get_address_cost:\n");
3268           fprintf (dump_file, "  min offset %d\n", (int) min_offset);
3269           fprintf (dump_file, "  max offset %d\n", (int) max_offset);
3270         }
3271
3272       valid_mult = sbitmap_alloc (2 * MAX_RATIO + 1);
3273       sbitmap_zero (valid_mult);
3274       rat = 1;
3275       addr = gen_rtx_fmt_ee (MULT, Pmode, reg1, NULL_RTX);
3276       for (i = -MAX_RATIO; i <= MAX_RATIO; i++)
3277         {
3278           XEXP (addr, 1) = GEN_INT (i);
3279           if (memory_address_p (Pmode, addr))
3280             {
3281               SET_BIT (valid_mult, i + MAX_RATIO);
3282               rat = i;
3283             }
3284         }
3285
3286       if (dump_file && (dump_flags & TDF_DETAILS))
3287         {
3288           fprintf (dump_file, "  allowed multipliers:");
3289           for (i = -MAX_RATIO; i <= MAX_RATIO; i++)
3290             if (TEST_BIT (valid_mult, i + MAX_RATIO))
3291               fprintf (dump_file, " %d", (int) i);
3292           fprintf (dump_file, "\n");
3293           fprintf (dump_file, "\n");
3294         }
3295     }
3296
3297   bits = GET_MODE_BITSIZE (Pmode);
3298   mask = ~(~(unsigned HOST_WIDE_INT) 0 << (bits - 1) << 1);
3299   offset &= mask;
3300   if ((offset >> (bits - 1) & 1))
3301     offset |= ~mask;
3302   s_offset = offset;
3303
3304   cost = 0;
3305   offset_p = (s_offset != 0
3306               && min_offset <= s_offset && s_offset <= max_offset);
3307   ratio_p = (ratio != 1
3308              && -MAX_RATIO <= ratio && ratio <= MAX_RATIO
3309              && TEST_BIT (valid_mult, ratio + MAX_RATIO));
3310
3311   if (ratio != 1 && !ratio_p)
3312     cost += multiply_by_cost (ratio, Pmode);
3313
3314   if (s_offset && !offset_p && !symbol_present)
3315     {
3316       cost += add_cost (Pmode);
3317       var_present = true;
3318     }
3319
3320   acost = costs[symbol_present][var_present][offset_p][ratio_p];
3321   if (!acost)
3322     {
3323       acost = 0;
3324       
3325       addr = gen_raw_REG (Pmode, FIRST_PSEUDO_REGISTER);
3326       reg1 = gen_raw_REG (Pmode, FIRST_PSEUDO_REGISTER + 1);
3327       if (ratio_p)
3328         addr = gen_rtx_fmt_ee (MULT, Pmode, addr, GEN_INT (rat));
3329
3330       if (var_present)
3331         addr = gen_rtx_fmt_ee (PLUS, Pmode, addr, reg1);
3332
3333       if (symbol_present)
3334         {
3335           base = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (""));
3336           if (offset_p)
3337             base = gen_rtx_fmt_e (CONST, Pmode,
3338                                   gen_rtx_fmt_ee (PLUS, Pmode,
3339                                                   base,
3340                                                   GEN_INT (off)));
3341         }
3342       else if (offset_p)
3343         base = GEN_INT (off);
3344       else
3345         base = NULL_RTX;
3346     
3347       if (base)
3348         addr = gen_rtx_fmt_ee (PLUS, Pmode, addr, base);
3349   
3350       start_sequence ();
3351       addr = memory_address (Pmode, addr);
3352       seq = get_insns ();
3353       end_sequence ();
3354   
3355       acost = seq_cost (seq);
3356       acost += address_cost (addr, Pmode);
3357
3358       if (!acost)
3359         acost = 1;
3360       costs[symbol_present][var_present][offset_p][ratio_p] = acost;
3361     }
3362
3363   return cost + acost;
3364 }
3365 /* Estimates cost of forcing EXPR into a variable.  DEPENDS_ON is a set of the
3366    invariants the computation depends on.  */
3367
3368 static unsigned
3369 force_var_cost (struct ivopts_data *data,
3370                 tree expr, bitmap *depends_on)
3371 {
3372   static bool costs_initialized = false;
3373   static unsigned integer_cost;
3374   static unsigned symbol_cost;
3375   static unsigned address_cost;
3376   tree op0, op1;
3377   unsigned cost0, cost1, cost;
3378   enum machine_mode mode;
3379
3380   if (!costs_initialized)
3381     {
3382       tree var = create_tmp_var_raw (integer_type_node, "test_var");
3383       rtx x = gen_rtx_MEM (DECL_MODE (var),
3384                            gen_rtx_SYMBOL_REF (Pmode, "test_var"));
3385       tree addr;
3386       tree type = build_pointer_type (integer_type_node);
3387
3388       integer_cost = computation_cost (build_int_cst_type (integer_type_node,
3389                                                            2000));
3390
3391       SET_DECL_RTL (var, x);
3392       TREE_STATIC (var) = 1;
3393       addr = build1 (ADDR_EXPR, type, var);
3394       symbol_cost = computation_cost (addr) + 1;
3395
3396       address_cost
3397         = computation_cost (build2 (PLUS_EXPR, type,
3398                                     addr,
3399                                     build_int_cst_type (type, 2000))) + 1;
3400       if (dump_file && (dump_flags & TDF_DETAILS))
3401         {
3402           fprintf (dump_file, "force_var_cost:\n");
3403           fprintf (dump_file, "  integer %d\n", (int) integer_cost);
3404           fprintf (dump_file, "  symbol %d\n", (int) symbol_cost);
3405           fprintf (dump_file, "  address %d\n", (int) address_cost);
3406           fprintf (dump_file, "  other %d\n", (int) target_spill_cost);
3407           fprintf (dump_file, "\n");
3408         }
3409
3410       costs_initialized = true;
3411     }
3412
3413   STRIP_NOPS (expr);
3414
3415   if (depends_on)
3416     {
3417       fd_ivopts_data = data;
3418       walk_tree (&expr, find_depends, depends_on, NULL);
3419     }
3420
3421   if (SSA_VAR_P (expr))
3422     return 0;
3423
3424   if (TREE_INVARIANT (expr))
3425     {
3426       if (TREE_CODE (expr) == INTEGER_CST)
3427         return integer_cost;
3428
3429       if (TREE_CODE (expr) == ADDR_EXPR)
3430         {
3431           tree obj = TREE_OPERAND (expr, 0);
3432
3433           if (TREE_CODE (obj) == VAR_DECL
3434               || TREE_CODE (obj) == PARM_DECL
3435               || TREE_CODE (obj) == RESULT_DECL)
3436             return symbol_cost;
3437         }
3438
3439       return address_cost;
3440     }
3441
3442   switch (TREE_CODE (expr))
3443     {
3444     case PLUS_EXPR:
3445     case MINUS_EXPR:
3446     case MULT_EXPR:
3447       op0 = TREE_OPERAND (expr, 0);
3448       op1 = TREE_OPERAND (expr, 1);
3449       STRIP_NOPS (op0);
3450       STRIP_NOPS (op1);
3451
3452       if (is_gimple_val (op0))
3453         cost0 = 0;
3454       else
3455         cost0 = force_var_cost (data, op0, NULL);
3456
3457       if (is_gimple_val (op1))
3458         cost1 = 0;
3459       else
3460         cost1 = force_var_cost (data, op1, NULL);
3461
3462       break;
3463
3464     default:
3465       /* Just an arbitrary value, FIXME.  */
3466       return target_spill_cost;
3467     }
3468
3469   mode = TYPE_MODE (TREE_TYPE (expr));
3470   switch (TREE_CODE (expr))
3471     {
3472     case PLUS_EXPR:
3473     case MINUS_EXPR:
3474       cost = add_cost (mode);
3475       break;
3476
3477     case MULT_EXPR:
3478       if (cst_and_fits_in_hwi (op0))
3479         cost = multiply_by_cost (int_cst_value (op0), mode);
3480       else if (cst_and_fits_in_hwi (op1))
3481         cost = multiply_by_cost (int_cst_value (op1), mode);
3482       else
3483         return target_spill_cost;
3484       break;
3485
3486     default:
3487       gcc_unreachable ();
3488     }
3489
3490   cost += cost0;
3491   cost += cost1;
3492
3493   /* Bound the cost by target_spill_cost.  The parts of complicated
3494      computations often are either loop invariant or at least can
3495      be shared between several iv uses, so letting this grow without
3496      limits would not give reasonable results.  */
3497   return cost < target_spill_cost ? cost : target_spill_cost;
3498 }
3499
3500 /* Estimates cost of expressing address ADDR  as var + symbol + offset.  The
3501    value of offset is added to OFFSET, SYMBOL_PRESENT and VAR_PRESENT are set
3502    to false if the corresponding part is missing.  DEPENDS_ON is a set of the
3503    invariants the computation depends on.  */
3504
3505 static unsigned
3506 split_address_cost (struct ivopts_data *data,
3507                     tree addr, bool *symbol_present, bool *var_present,
3508                     unsigned HOST_WIDE_INT *offset, bitmap *depends_on)
3509 {
3510   tree core;
3511   HOST_WIDE_INT bitsize;
3512   HOST_WIDE_INT bitpos;
3513   tree toffset;
3514   enum machine_mode mode;
3515   int unsignedp, volatilep;
3516   
3517   core = get_inner_reference (addr, &bitsize, &bitpos, &toffset, &mode,
3518                               &unsignedp, &volatilep, false);
3519
3520   if (toffset != 0
3521       || bitpos % BITS_PER_UNIT != 0
3522       || TREE_CODE (core) != VAR_DECL)
3523     {
3524       *symbol_present = false;
3525       *var_present = true;
3526       fd_ivopts_data = data;
3527       walk_tree (&addr, find_depends, depends_on, NULL);
3528       return target_spill_cost;
3529     }
3530
3531   *offset += bitpos / BITS_PER_UNIT;
3532   if (TREE_STATIC (core)
3533       || DECL_EXTERNAL (core))
3534     {
3535       *symbol_present = true;
3536       *var_present = false;
3537       return 0;
3538     }
3539       
3540   *symbol_present = false;
3541   *var_present = true;
3542   return 0;
3543 }
3544
3545 /* Estimates cost of expressing difference of addresses E1 - E2 as
3546    var + symbol + offset.  The value of offset is added to OFFSET,
3547    SYMBOL_PRESENT and VAR_PRESENT are set to false if the corresponding
3548    part is missing.  DEPENDS_ON is a set of the invariants the computation
3549    depends on.  */
3550
3551 static unsigned
3552 ptr_difference_cost (struct ivopts_data *data,
3553                      tree e1, tree e2, bool *symbol_present, bool *var_present,
3554                      unsigned HOST_WIDE_INT *offset, bitmap *depends_on)
3555 {
3556   HOST_WIDE_INT diff = 0;
3557   unsigned cost;
3558
3559   gcc_assert (TREE_CODE (e1) == ADDR_EXPR);
3560
3561   if (ptr_difference_const (e1, e2, &diff))
3562     {
3563       *offset += diff;
3564       *symbol_present = false;
3565       *var_present = false;
3566       return 0;
3567     }
3568
3569   if (e2 == integer_zero_node)
3570     return split_address_cost (data, TREE_OPERAND (e1, 0),
3571                                symbol_present, var_present, offset, depends_on);
3572
3573   *symbol_present = false;
3574   *var_present = true;
3575   
3576   cost = force_var_cost (data, e1, depends_on);
3577   cost += force_var_cost (data, e2, depends_on);
3578   cost += add_cost (Pmode);
3579
3580   return cost;
3581 }
3582
3583 /* Estimates cost of expressing difference E1 - E2 as
3584    var + symbol + offset.  The value of offset is added to OFFSET,
3585    SYMBOL_PRESENT and VAR_PRESENT are set to false if the corresponding
3586    part is missing.  DEPENDS_ON is a set of the invariants the computation
3587    depends on.  */
3588
3589 static unsigned
3590 difference_cost (struct ivopts_data *data,
3591                  tree e1, tree e2, bool *symbol_present, bool *var_present,
3592                  unsigned HOST_WIDE_INT *offset, bitmap *depends_on)
3593 {
3594   unsigned cost;
3595   enum machine_mode mode = TYPE_MODE (TREE_TYPE (e1));
3596   unsigned HOST_WIDE_INT off1, off2;
3597
3598   e1 = strip_offset (e1, &off1);
3599   e2 = strip_offset (e2, &off2);
3600   *offset += off1 - off2;
3601
3602   STRIP_NOPS (e1);
3603   STRIP_NOPS (e2);
3604
3605   if (TREE_CODE (e1) == ADDR_EXPR)
3606     return ptr_difference_cost (data, e1, e2, symbol_present, var_present, offset,
3607                                 depends_on);
3608   *symbol_present = false;
3609
3610   if (operand_equal_p (e1, e2, 0))
3611     {
3612       *var_present = false;
3613       return 0;
3614     }
3615   *var_present = true;
3616   if (zero_p (e2))
3617     return force_var_cost (data, e1, depends_on);
3618
3619   if (zero_p (e1))
3620     {
3621       cost = force_var_cost (data, e2, depends_on);
3622       cost += multiply_by_cost (-1, mode);
3623
3624       return cost;
3625     }
3626
3627   cost = force_var_cost (data, e1, depends_on);
3628   cost += force_var_cost (data, e2, depends_on);
3629   cost += add_cost (mode);
3630
3631   return cost;
3632 }
3633
3634 /* Determines the cost of the computation by that USE is expressed
3635    from induction variable CAND.  If ADDRESS_P is true, we just need
3636    to create an address from it, otherwise we want to get it into
3637    register.  A set of invariants we depend on is stored in
3638    DEPENDS_ON.  AT is the statement at that the value is computed.  */
3639
3640 static unsigned
3641 get_computation_cost_at (struct ivopts_data *data,
3642                          struct iv_use *use, struct iv_cand *cand,
3643                          bool address_p, bitmap *depends_on, tree at)
3644 {
3645   tree ubase = use->iv->base, ustep = use->iv->step;
3646   tree cbase, cstep;
3647   tree utype = TREE_TYPE (ubase), ctype;
3648   unsigned HOST_WIDE_INT ustepi, cstepi, offset = 0;
3649   HOST_WIDE_INT ratio, aratio;
3650   bool var_present, symbol_present;
3651   unsigned cost = 0, n_sums;
3652
3653   *depends_on = NULL;
3654
3655   /* Only consider real candidates.  */
3656   if (!cand->iv)
3657     return INFTY;
3658
3659   cbase = cand->iv->base;
3660   cstep = cand->iv->step;
3661   ctype = TREE_TYPE (cbase);
3662
3663   if (TYPE_PRECISION (utype) > TYPE_PRECISION (ctype))
3664     {
3665       /* We do not have a precision to express the values of use.  */
3666       return INFTY;
3667     }
3668
3669   if (address_p)
3670     {
3671       /* Do not try to express address of an object with computation based
3672          on address of a different object.  This may cause problems in rtl
3673          level alias analysis (that does not expect this to be happening,
3674          as this is illegal in C), and would be unlikely to be useful
3675          anyway.  */
3676       if (use->iv->base_object
3677           && cand->iv->base_object
3678           && !operand_equal_p (use->iv->base_object, cand->iv->base_object, 0))
3679         return INFTY;
3680     }
3681
3682   if (TYPE_PRECISION (utype) != TYPE_PRECISION (ctype))
3683     {
3684       /* TODO -- add direct handling of this case.  */
3685       goto fallback;
3686     }
3687
3688   /* CSTEPI is removed from the offset in case statement is after the
3689      increment.  If the step is not constant, we use zero instead.
3690      This is a bit imprecise (there is the extra addition), but
3691      redundancy elimination is likely to transform the code so that
3692      it uses value of the variable before increment anyway,
3693      so it is not that much unrealistic.  */
3694   if (cst_and_fits_in_hwi (cstep))
3695     cstepi = int_cst_value (cstep);
3696   else
3697     cstepi = 0;
3698
3699   if (cst_and_fits_in_hwi (ustep)
3700       && cst_and_fits_in_hwi (cstep))
3701     {
3702       ustepi = int_cst_value (ustep);
3703
3704       if (!divide (TYPE_PRECISION (utype), ustepi, cstepi, &ratio))
3705         return INFTY;
3706     }
3707   else
3708     {
3709       tree rat;
3710       
3711       rat = constant_multiple_of (utype, ustep, cstep);
3712     
3713       if (!rat)
3714         return INFTY;
3715
3716       if (cst_and_fits_in_hwi (rat))
3717         ratio = int_cst_value (rat);
3718       else if (integer_onep (rat))
3719         ratio = 1;
3720       else if (integer_all_onesp (rat))
3721         ratio = -1;
3722       else
3723         return INFTY;
3724     }
3725
3726   /* use = ubase + ratio * (var - cbase).  If either cbase is a constant
3727      or ratio == 1, it is better to handle this like
3728      
3729      ubase - ratio * cbase + ratio * var
3730      
3731      (also holds in the case ratio == -1, TODO.  */
3732
3733   if (cst_and_fits_in_hwi (cbase))
3734     {
3735       offset = - ratio * int_cst_value (cbase); 
3736       cost += difference_cost (data,
3737                                ubase, integer_zero_node,
3738                                &symbol_present, &var_present, &offset,
3739                                depends_on);
3740     }
3741   else if (ratio == 1)
3742     {
3743       cost += difference_cost (data,
3744                                ubase, cbase,
3745                                &symbol_present, &var_present, &offset,
3746                                depends_on);
3747     }
3748   else
3749     {
3750       cost += force_var_cost (data, cbase, depends_on);
3751       cost += add_cost (TYPE_MODE (ctype));
3752       cost += difference_cost (data,
3753                                ubase, integer_zero_node,
3754                                &symbol_present, &var_present, &offset,
3755                                depends_on);
3756     }
3757
3758   /* If we are after the increment, the value of the candidate is higher by
3759      one iteration.  */
3760   if (stmt_after_increment (data->current_loop, cand, at))
3761     offset -= ratio * cstepi;
3762
3763   /* Now the computation is in shape symbol + var1 + const + ratio * var2.
3764      (symbol/var/const parts may be omitted).  If we are looking for an address,
3765      find the cost of addressing this.  */
3766   if (address_p)
3767     return cost + get_address_cost (symbol_present, var_present, offset, ratio);
3768
3769   /* Otherwise estimate the costs for computing the expression.  */
3770   aratio = ratio > 0 ? ratio : -ratio;
3771   if (!symbol_present && !var_present && !offset)
3772     {
3773       if (ratio != 1)
3774         cost += multiply_by_cost (ratio, TYPE_MODE (ctype));
3775
3776       return cost;
3777     }
3778
3779   if (aratio != 1)
3780     cost += multiply_by_cost (aratio, TYPE_MODE (ctype));
3781
3782   n_sums = 1;
3783   if (var_present
3784       /* Symbol + offset should be compile-time computable.  */
3785       && (symbol_present || offset))
3786     n_sums++;
3787
3788   return cost + n_sums * add_cost (TYPE_MODE (ctype));
3789
3790 fallback:
3791   {
3792     /* Just get the expression, expand it and measure the cost.  */
3793     tree comp = get_computation_at (data->current_loop, use, cand, at);
3794
3795     if (!comp)
3796       return INFTY;
3797
3798     if (address_p)
3799       comp = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (comp)), comp);
3800
3801     return computation_cost (comp);
3802   }
3803 }
3804
3805 /* Determines the cost of the computation by that USE is expressed
3806    from induction variable CAND.  If ADDRESS_P is true, we just need
3807    to create an address from it, otherwise we want to get it into
3808    register.  A set of invariants we depend on is stored in
3809    DEPENDS_ON.  */
3810
3811 static unsigned
3812 get_computation_cost (struct ivopts_data *data,
3813                       struct iv_use *use, struct iv_cand *cand,
3814                       bool address_p, bitmap *depends_on)
3815 {
3816   return get_computation_cost_at (data,
3817                                   use, cand, address_p, depends_on, use->stmt);
3818 }
3819
3820 /* Determines cost of basing replacement of USE on CAND in a generic
3821    expression.  */
3822
3823 static bool
3824 determine_use_iv_cost_generic (struct ivopts_data *data,
3825                                struct iv_use *use, struct iv_cand *cand)
3826 {
3827   bitmap depends_on;
3828   unsigned cost;
3829
3830   /* The simple case first -- if we need to express value of the preserved
3831      original biv, the cost is 0.  This also prevents us from counting the
3832      cost of increment twice -- once at this use and once in the cost of
3833      the candidate.  */
3834   if (cand->pos == IP_ORIGINAL
3835       && cand->incremented_at == use->stmt)
3836     {
3837       set_use_iv_cost (data, use, cand, 0, NULL, NULL_TREE);
3838       return true;
3839     }
3840
3841   cost = get_computation_cost (data, use, cand, false, &depends_on);
3842   set_use_iv_cost (data, use, cand, cost, depends_on, NULL_TREE);
3843
3844   return cost != INFTY;
3845 }
3846
3847 /* Determines cost of basing replacement of USE on CAND in an address.  */
3848
3849 static bool
3850 determine_use_iv_cost_address (struct ivopts_data *data,
3851                                struct iv_use *use, struct iv_cand *cand)
3852 {
3853   bitmap depends_on;
3854   unsigned cost = get_computation_cost (data, use, cand, true, &depends_on);
3855
3856   set_use_iv_cost (data, use, cand, cost, depends_on, NULL_TREE);
3857
3858   return cost != INFTY;
3859 }
3860
3861 /* Computes value of induction variable IV in iteration NITER.  */
3862
3863 static tree
3864 iv_value (struct iv *iv, tree niter)
3865 {
3866   tree val;
3867   tree type = TREE_TYPE (iv->base);
3868
3869   niter = fold_convert (type, niter);
3870   val = fold (build2 (MULT_EXPR, type, iv->step, niter));
3871
3872   return fold (build2 (PLUS_EXPR, type, iv->base, val));
3873 }
3874
3875 /* Computes value of candidate CAND at position AT in iteration NITER.  */
3876
3877 static tree
3878 cand_value_at (struct loop *loop, struct iv_cand *cand, tree at, tree niter)
3879 {
3880   tree val = iv_value (cand->iv, niter);
3881   tree type = TREE_TYPE (cand->iv->base);
3882
3883   if (stmt_after_increment (loop, cand, at))
3884     val = fold (build2 (PLUS_EXPR, type, val, cand->iv->step));
3885
3886   return val;
3887 }
3888
3889 /* Returns period of induction variable iv.  */
3890
3891 static tree
3892 iv_period (struct iv *iv)
3893 {
3894   tree step = iv->step, period, type;
3895   tree pow2div;
3896
3897   gcc_assert (step && TREE_CODE (step) == INTEGER_CST);
3898
3899   /* Period of the iv is gcd (step, type range).  Since type range is power
3900      of two, it suffices to determine the maximum power of two that divides
3901      step.  */
3902   pow2div = num_ending_zeros (step);
3903   type = unsigned_type_for (TREE_TYPE (step));
3904
3905   period = build_low_bits_mask (type,
3906                                 (TYPE_PRECISION (type)
3907                                  - tree_low_cst (pow2div, 1)));
3908
3909   return period;
3910 }
3911
3912 /* Returns the comparison operator used when eliminating the iv USE.  */
3913
3914 static enum tree_code
3915 iv_elimination_compare (struct ivopts_data *data, struct iv_use *use)
3916 {
3917   struct loop *loop = data->current_loop;
3918   basic_block ex_bb;
3919   edge exit;
3920
3921   ex_bb = bb_for_stmt (use->stmt);
3922   exit = EDGE_SUCC (ex_bb, 0);
3923   if (flow_bb_inside_loop_p (loop, exit->dest))
3924     exit = EDGE_SUCC (ex_bb, 1);
3925
3926   return (exit->flags & EDGE_TRUE_VALUE ? EQ_EXPR : NE_EXPR);
3927 }
3928
3929 /* Check whether it is possible to express the condition in USE by comparison
3930    of candidate CAND.  If so, store the value compared with to BOUND.  */
3931
3932 static bool
3933 may_eliminate_iv (struct ivopts_data *data,
3934                   struct iv_use *use, struct iv_cand *cand, tree *bound)
3935 {
3936   basic_block ex_bb;
3937   edge exit;
3938   struct tree_niter_desc *niter;
3939   tree nit, nit_type;
3940   tree wider_type, period, per_type;
3941   struct loop *loop = data->current_loop;
3942   
3943   if (TREE_CODE (cand->iv->step) != INTEGER_CST)
3944     return false;
3945
3946   /* For now works only for exits that dominate the loop latch.  TODO -- extend
3947      for other conditions inside loop body.  */
3948   ex_bb = bb_for_stmt (use->stmt);
3949   if (use->stmt != last_stmt (ex_bb)
3950       || TREE_CODE (use->stmt) != COND_EXPR)
3951     return false;
3952   if (!dominated_by_p (CDI_DOMINATORS, loop->latch, ex_bb))
3953     return false;
3954
3955   exit = EDGE_SUCC (ex_bb, 0);
3956   if (flow_bb_inside_loop_p (loop, exit->dest))
3957     exit = EDGE_SUCC (ex_bb, 1);
3958   if (flow_bb_inside_loop_p (loop, exit->dest))
3959     return false;
3960
3961   niter = niter_for_exit (data, exit);
3962   if (!niter
3963       || !zero_p (niter->may_be_zero))
3964     return false;
3965
3966   nit = niter->niter;
3967   nit_type = TREE_TYPE (nit);
3968
3969   /* Determine whether we may use the variable to test whether niter iterations
3970      elapsed.  This is the case iff the period of the induction variable is
3971      greater than the number of iterations.  */
3972   period = iv_period (cand->iv);
3973   if (!period)
3974     return false;
3975   per_type = TREE_TYPE (period);
3976
3977   wider_type = TREE_TYPE (period);
3978   if (TYPE_PRECISION (nit_type) < TYPE_PRECISION (per_type))
3979     wider_type = per_type;
3980   else
3981     wider_type = nit_type;
3982
3983   if (!integer_nonzerop (fold (build2 (GE_EXPR, boolean_type_node,
3984                                        fold_convert (wider_type, period),
3985                                        fold_convert (wider_type, nit)))))
3986     return false;
3987
3988   *bound = cand_value_at (loop, cand, use->stmt, nit);
3989   return true;
3990 }
3991
3992 /* Determines cost of basing replacement of USE on CAND in a condition.  */
3993
3994 static bool
3995 determine_use_iv_cost_condition (struct ivopts_data *data,
3996                                  struct iv_use *use, struct iv_cand *cand)
3997 {
3998   tree bound = NULL_TREE, op, cond;
3999   bitmap depends_on = NULL;
4000   unsigned cost;
4001
4002   /* Only consider real candidates.  */
4003   if (!cand->iv)
4004     {
4005       set_use_iv_cost (data, use, cand, INFTY, NULL, NULL_TREE);
4006       return false;
4007     }
4008
4009   if (may_eliminate_iv (data, use, cand, &bound))
4010     {
4011       cost = force_var_cost (data, bound, &depends_on);
4012
4013       set_use_iv_cost (data, use, cand, cost, depends_on, bound);
4014       return cost != INFTY;
4015     }
4016
4017   /* The induction variable elimination failed; just express the original
4018      giv.  If it is compared with an invariant, note that we cannot get
4019      rid of it.  */
4020   cost = get_computation_cost (data, use, cand, false, &depends_on);
4021
4022   cond = *use->op_p;
4023   if (TREE_CODE (cond) != SSA_NAME)
4024     {
4025       op = TREE_OPERAND (cond, 0);
4026       if (TREE_CODE (op) == SSA_NAME && !zero_p (get_iv (data, op)->step))
4027         op = TREE_OPERAND (cond, 1);
4028       if (TREE_CODE (op) == SSA_NAME)
4029         {
4030           op = get_iv (data, op)->base;
4031           fd_ivopts_data = data;
4032           walk_tree (&op, find_depends, &depends_on, NULL);
4033         }
4034     }
4035
4036   set_use_iv_cost (data, use, cand, cost, depends_on, NULL);
4037   return cost != INFTY;
4038 }
4039
4040 /* Checks whether it is possible to replace the final value of USE by
4041    a direct computation.  If so, the formula is stored to *VALUE.  */
4042
4043 static bool
4044 may_replace_final_value (struct ivopts_data *data, struct iv_use *use,
4045                          tree *value)
4046 {
4047   struct loop *loop = data->current_loop;
4048   edge exit;
4049   struct tree_niter_desc *niter;
4050
4051   exit = single_dom_exit (loop);
4052   if (!exit)
4053     return false;
4054
4055   gcc_assert (dominated_by_p (CDI_DOMINATORS, exit->src,
4056                               bb_for_stmt (use->stmt)));
4057
4058   niter = niter_for_single_dom_exit (data);
4059   if (!niter
4060       || !zero_p (niter->may_be_zero))
4061     return false;
4062
4063   *value = iv_value (use->iv, niter->niter);
4064
4065   return true;
4066 }
4067
4068 /* Determines cost of replacing final value of USE using CAND.  */
4069
4070 static bool
4071 determine_use_iv_cost_outer (struct ivopts_data *data,
4072                              struct iv_use *use, struct iv_cand *cand)
4073 {
4074   bitmap depends_on;
4075   unsigned cost;
4076   edge exit;
4077   tree value = NULL_TREE;
4078   struct loop *loop = data->current_loop;
4079
4080   /* The simple case first -- if we need to express value of the preserved
4081      original biv, the cost is 0.  This also prevents us from counting the
4082      cost of increment twice -- once at this use and once in the cost of
4083      the candidate.  */
4084   if (cand->pos == IP_ORIGINAL
4085       && cand->incremented_at == use->stmt)
4086     {
4087       set_use_iv_cost (data, use, cand, 0, NULL, NULL_TREE);
4088       return true;
4089     }
4090
4091   if (!cand->iv)
4092     {
4093       if (!may_replace_final_value (data, use, &value))
4094         {
4095           set_use_iv_cost (data, use, cand, INFTY, NULL, NULL_TREE);
4096           return false;
4097         }
4098
4099       depends_on = NULL;
4100       cost = force_var_cost (data, value, &depends_on);
4101
4102       cost /= AVG_LOOP_NITER (loop);
4103
4104       set_use_iv_cost (data, use, cand, cost, depends_on, value);
4105       return cost != INFTY;
4106     }
4107
4108   exit = single_dom_exit (loop);
4109   if (exit)
4110     {
4111       /* If there is just a single exit, we may use value of the candidate
4112          after we take it to determine the value of use.  */
4113       cost = get_computation_cost_at (data, use, cand, false, &depends_on,
4114                                       last_stmt (exit->src));
4115       if (cost != INFTY)
4116         cost /= AVG_LOOP_NITER (loop);
4117     }
4118   else
4119     {
4120       /* Otherwise we just need to compute the iv.  */
4121       cost = get_computation_cost (data, use, cand, false, &depends_on);
4122     }
4123                                    
4124   set_use_iv_cost (data, use, cand, cost, depends_on, NULL_TREE);
4125
4126   return cost != INFTY;
4127 }
4128
4129 /* Determines cost of basing replacement of USE on CAND.  Returns false
4130    if USE cannot be based on CAND.  */
4131
4132 static bool
4133 determine_use_iv_cost (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       return determine_use_iv_cost_generic (data, use, cand);
4140
4141     case USE_OUTER:
4142       return determine_use_iv_cost_outer (data, use, cand);
4143
4144     case USE_ADDRESS:
4145       return determine_use_iv_cost_address (data, use, cand);
4146
4147     case USE_COMPARE:
4148       return determine_use_iv_cost_condition (data, use, cand);
4149
4150     default:
4151       gcc_unreachable ();
4152     }
4153 }
4154
4155 /* Determines costs of basing the use of the iv on an iv candidate.  */
4156
4157 static void
4158 determine_use_iv_costs (struct ivopts_data *data)
4159 {
4160   unsigned i, j;
4161   struct iv_use *use;
4162   struct iv_cand *cand;
4163   bitmap to_clear = BITMAP_ALLOC (NULL);
4164
4165   alloc_use_cost_map (data);
4166
4167   for (i = 0; i < n_iv_uses (data); i++)
4168     {
4169       use = iv_use (data, i);
4170
4171       if (data->consider_all_candidates)
4172         {
4173           for (j = 0; j < n_iv_cands (data); j++)
4174             {
4175               cand = iv_cand (data, j);
4176               determine_use_iv_cost (data, use, cand);
4177             }
4178         }
4179       else
4180         {
4181           bitmap_iterator bi;
4182
4183           EXECUTE_IF_SET_IN_BITMAP (use->related_cands, 0, j, bi)
4184             {
4185               cand = iv_cand (data, j);
4186               if (!determine_use_iv_cost (data, use, cand))
4187                 bitmap_set_bit (to_clear, j);
4188             }
4189
4190           /* Remove the candidates for that the cost is infinite from
4191              the list of related candidates.  */
4192           bitmap_and_compl_into (use->related_cands, to_clear);
4193           bitmap_clear (to_clear);
4194         }
4195     }
4196
4197   BITMAP_FREE (to_clear);
4198
4199   if (dump_file && (dump_flags & TDF_DETAILS))
4200     {
4201       fprintf (dump_file, "Use-candidate costs:\n");
4202
4203       for (i = 0; i < n_iv_uses (data); i++)
4204         {
4205           use = iv_use (data, i);
4206
4207           fprintf (dump_file, "Use %d:\n", i);
4208           fprintf (dump_file, "  cand\tcost\tdepends on\n");
4209           for (j = 0; j < use->n_map_members; j++)
4210             {
4211               if (!use->cost_map[j].cand
4212                   || use->cost_map[j].cost == INFTY)
4213                 continue;
4214
4215               fprintf (dump_file, "  %d\t%d\t",
4216                        use->cost_map[j].cand->id,
4217                        use->cost_map[j].cost);
4218               if (use->cost_map[j].depends_on)
4219                 bitmap_print (dump_file,
4220                               use->cost_map[j].depends_on, "","");
4221               fprintf (dump_file, "\n");
4222             }
4223
4224           fprintf (dump_file, "\n");
4225         }
4226       fprintf (dump_file, "\n");
4227     }
4228 }
4229
4230 /* Determines cost of the candidate CAND.  */
4231
4232 static void
4233 determine_iv_cost (struct ivopts_data *data, struct iv_cand *cand)
4234 {
4235   unsigned cost_base, cost_step;
4236   tree base;
4237
4238   if (!cand->iv)
4239     {
4240       cand->cost = 0;
4241       return;
4242     }
4243
4244   /* There are two costs associated with the candidate -- its increment
4245      and its initialization.  The second is almost negligible for any loop
4246      that rolls enough, so we take it just very little into account.  */
4247
4248   base = cand->iv->base;
4249   cost_base = force_var_cost (data, base, NULL);
4250   cost_step = add_cost (TYPE_MODE (TREE_TYPE (base)));
4251
4252   cand->cost = cost_step + cost_base / AVG_LOOP_NITER (current_loop);
4253
4254   /* Prefer the original iv unless we may gain something by replacing it;
4255      this is not really relevant for artificial ivs created by other
4256      passes.  */
4257   if (cand->pos == IP_ORIGINAL
4258       && !DECL_ARTIFICIAL (SSA_NAME_VAR (cand->var_before)))
4259     cand->cost--;
4260   
4261   /* Prefer not to insert statements into latch unless there are some
4262      already (so that we do not create unnecessary jumps).  */
4263   if (cand->pos == IP_END
4264       && empty_block_p (ip_end_pos (data->current_loop)))
4265     cand->cost++;
4266 }
4267
4268 /* Determines costs of computation of the candidates.  */
4269
4270 static void
4271 determine_iv_costs (struct ivopts_data *data)
4272 {
4273   unsigned i;
4274
4275   if (dump_file && (dump_flags & TDF_DETAILS))
4276     {
4277       fprintf (dump_file, "Candidate costs:\n");
4278       fprintf (dump_file, "  cand\tcost\n");
4279     }
4280
4281   for (i = 0; i < n_iv_cands (data); i++)
4282     {
4283       struct iv_cand *cand = iv_cand (data, i);
4284
4285       determine_iv_cost (data, cand);
4286
4287       if (dump_file && (dump_flags & TDF_DETAILS))
4288         fprintf (dump_file, "  %d\t%d\n", i, cand->cost);
4289     }
4290   
4291 if (dump_file && (dump_flags & TDF_DETAILS))
4292       fprintf (dump_file, "\n");
4293 }
4294
4295 /* Calculates cost for having SIZE induction variables.  */
4296
4297 static unsigned
4298 ivopts_global_cost_for_size (struct ivopts_data *data, unsigned size)
4299 {
4300   return global_cost_for_size (size,
4301                                loop_data (data->current_loop)->regs_used,
4302                                n_iv_uses (data));
4303 }
4304
4305 /* For each size of the induction variable set determine the penalty.  */
4306
4307 static void
4308 determine_set_costs (struct ivopts_data *data)
4309 {
4310   unsigned j, n;
4311   tree phi, op;
4312   struct loop *loop = data->current_loop;
4313   bitmap_iterator bi;
4314
4315   /* We use the following model (definitely improvable, especially the
4316      cost function -- TODO):
4317
4318      We estimate the number of registers available (using MD data), name it A.
4319
4320      We estimate the number of registers used by the loop, name it U.  This
4321      number is obtained as the number of loop phi nodes (not counting virtual
4322      registers and bivs) + the number of variables from outside of the loop.
4323
4324      We set a reserve R (free regs that are used for temporary computations,
4325      etc.).  For now the reserve is a constant 3.
4326
4327      Let I be the number of induction variables.
4328      
4329      -- if U + I + R <= A, the cost is I * SMALL_COST (just not to encourage
4330         make a lot of ivs without a reason).
4331      -- if A - R < U + I <= A, the cost is I * PRES_COST
4332      -- if U + I > A, the cost is I * PRES_COST and
4333         number of uses * SPILL_COST * (U + I - A) / (U + I) is added.  */
4334
4335   if (dump_file && (dump_flags & TDF_DETAILS))
4336     {
4337       fprintf (dump_file, "Global costs:\n");
4338       fprintf (dump_file, "  target_avail_regs %d\n", target_avail_regs);
4339       fprintf (dump_file, "  target_small_cost %d\n", target_small_cost);
4340       fprintf (dump_file, "  target_pres_cost %d\n", target_pres_cost);
4341       fprintf (dump_file, "  target_spill_cost %d\n", target_spill_cost);
4342     }
4343
4344   n = 0;
4345   for (phi = phi_nodes (loop->header); phi; phi = PHI_CHAIN (phi))
4346     {
4347       op = PHI_RESULT (phi);
4348
4349       if (!is_gimple_reg (op))
4350         continue;
4351
4352       if (get_iv (data, op))
4353         continue;
4354
4355       n++;
4356     }
4357
4358   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, j, bi)
4359     {
4360       struct version_info *info = ver_info (data, j);
4361
4362       if (info->inv_id && info->has_nonlin_use)
4363         n++;
4364     }
4365
4366   loop_data (loop)->regs_used = n;
4367   if (dump_file && (dump_flags & TDF_DETAILS))
4368     fprintf (dump_file, "  regs_used %d\n", n);
4369
4370   if (dump_file && (dump_flags & TDF_DETAILS))
4371     {
4372       fprintf (dump_file, "  cost for size:\n");
4373       fprintf (dump_file, "  ivs\tcost\n");
4374       for (j = 0; j <= 2 * target_avail_regs; j++)
4375         fprintf (dump_file, "  %d\t%d\n", j,
4376                  ivopts_global_cost_for_size (data, j));
4377       fprintf (dump_file, "\n");
4378     }
4379 }
4380
4381 /* Returns true if A is a cheaper cost pair than B.  */
4382
4383 static bool
4384 cheaper_cost_pair (struct cost_pair *a, struct cost_pair *b)
4385 {
4386   if (!a)
4387     return false;
4388
4389   if (!b)
4390     return true;
4391
4392   if (a->cost < b->cost)
4393     return true;
4394
4395   if (a->cost > b->cost)
4396     return false;
4397
4398   /* In case the costs are the same, prefer the cheaper candidate.  */
4399   if (a->cand->cost < b->cand->cost)
4400     return true;
4401
4402   return false;
4403 }
4404
4405 /* Computes the cost field of IVS structure.  */
4406
4407 static void
4408 iv_ca_recount_cost (struct ivopts_data *data, struct iv_ca *ivs)
4409 {
4410   unsigned cost = 0;
4411
4412   cost += ivs->cand_use_cost;
4413   cost += ivs->cand_cost;
4414   cost += ivopts_global_cost_for_size (data, ivs->n_regs);
4415
4416   ivs->cost = cost;
4417 }
4418
4419 /* Remove invariants in set INVS to set IVS.  */
4420
4421 static void
4422 iv_ca_set_remove_invariants (struct iv_ca *ivs, bitmap invs)
4423 {
4424   bitmap_iterator bi;
4425   unsigned iid;
4426
4427   if (!invs)
4428     return;
4429
4430   EXECUTE_IF_SET_IN_BITMAP (invs, 0, iid, bi)
4431     {
4432       ivs->n_invariant_uses[iid]--;
4433       if (ivs->n_invariant_uses[iid] == 0)
4434         ivs->n_regs--;
4435     }
4436 }
4437
4438 /* Set USE not to be expressed by any candidate in IVS.  */
4439
4440 static void
4441 iv_ca_set_no_cp (struct ivopts_data *data, struct iv_ca *ivs,
4442                  struct iv_use *use)
4443 {
4444   unsigned uid = use->id, cid;
4445   struct cost_pair *cp;
4446
4447   cp = ivs->cand_for_use[uid];
4448   if (!cp)
4449     return;
4450   cid = cp->cand->id;
4451
4452   ivs->bad_uses++;
4453   ivs->cand_for_use[uid] = NULL;
4454   ivs->n_cand_uses[cid]--;
4455
4456   if (ivs->n_cand_uses[cid] == 0)
4457     {
4458       bitmap_clear_bit (ivs->cands, cid);
4459       /* Do not count the pseudocandidates.  */
4460       if (cp->cand->iv)
4461         ivs->n_regs--;
4462       ivs->n_cands--;
4463       ivs->cand_cost -= cp->cand->cost;
4464
4465       iv_ca_set_remove_invariants (ivs, cp->cand->depends_on);
4466     }
4467
4468   ivs->cand_use_cost -= cp->cost;
4469
4470   iv_ca_set_remove_invariants (ivs, cp->depends_on);
4471   iv_ca_recount_cost (data, ivs);
4472 }
4473
4474 /* Add invariants in set INVS to set IVS.  */
4475
4476 static void
4477 iv_ca_set_add_invariants (struct iv_ca *ivs, bitmap invs)
4478 {
4479   bitmap_iterator bi;
4480   unsigned iid;
4481
4482   if (!invs)
4483     return;
4484
4485   EXECUTE_IF_SET_IN_BITMAP (invs, 0, iid, bi)
4486     {
4487       ivs->n_invariant_uses[iid]++;
4488       if (ivs->n_invariant_uses[iid] == 1)
4489         ivs->n_regs++;
4490     }
4491 }
4492
4493 /* Set cost pair for USE in set IVS to CP.  */
4494
4495 static void
4496 iv_ca_set_cp (struct ivopts_data *data, struct iv_ca *ivs,
4497               struct iv_use *use, struct cost_pair *cp)
4498 {
4499   unsigned uid = use->id, cid;
4500
4501   if (ivs->cand_for_use[uid] == cp)
4502     return;
4503
4504   if (ivs->cand_for_use[uid])
4505     iv_ca_set_no_cp (data, ivs, use);
4506
4507   if (cp)
4508     {
4509       cid = cp->cand->id;
4510
4511       ivs->bad_uses--;
4512       ivs->cand_for_use[uid] = cp;
4513       ivs->n_cand_uses[cid]++;
4514       if (ivs->n_cand_uses[cid] == 1)
4515         {
4516           bitmap_set_bit (ivs->cands, cid);
4517           /* Do not count the pseudocandidates.  */
4518           if (cp->cand->iv)
4519             ivs->n_regs++;
4520           ivs->n_cands++;
4521           ivs->cand_cost += cp->cand->cost;
4522
4523           iv_ca_set_add_invariants (ivs, cp->cand->depends_on);
4524         }
4525
4526       ivs->cand_use_cost += cp->cost;
4527       iv_ca_set_add_invariants (ivs, cp->depends_on);
4528       iv_ca_recount_cost (data, ivs);
4529     }
4530 }
4531
4532 /* Extend set IVS by expressing USE by some of the candidates in it
4533    if possible.  */
4534
4535 static void
4536 iv_ca_add_use (struct ivopts_data *data, struct iv_ca *ivs,
4537                struct iv_use *use)
4538 {
4539   struct cost_pair *best_cp = NULL, *cp;
4540   bitmap_iterator bi;
4541   unsigned i;
4542
4543   gcc_assert (ivs->upto >= use->id);
4544
4545   if (ivs->upto == use->id)
4546     {
4547       ivs->upto++;
4548       ivs->bad_uses++;
4549     }
4550
4551   EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, i, bi)
4552     {
4553       cp = get_use_iv_cost (data, use, iv_cand (data, i));
4554
4555       if (cheaper_cost_pair (cp, best_cp))
4556         best_cp = cp;
4557     }
4558
4559   iv_ca_set_cp (data, ivs, use, best_cp);
4560 }
4561
4562 /* Get cost for assignment IVS.  */
4563
4564 static unsigned
4565 iv_ca_cost (struct iv_ca *ivs)
4566 {
4567   return (ivs->bad_uses ? INFTY : ivs->cost);
4568 }
4569
4570 /* Returns true if all dependences of CP are among invariants in IVS.  */
4571
4572 static bool
4573 iv_ca_has_deps (struct iv_ca *ivs, struct cost_pair *cp)
4574 {
4575   unsigned i;
4576   bitmap_iterator bi;
4577
4578   if (!cp->depends_on)
4579     return true;
4580
4581   EXECUTE_IF_SET_IN_BITMAP (cp->depends_on, 0, i, bi)
4582     {
4583       if (ivs->n_invariant_uses[i] == 0)
4584         return false;
4585     }
4586
4587   return true;
4588 }
4589
4590 /* Creates change of expressing USE by NEW_CP instead of OLD_CP and chains
4591    it before NEXT_CHANGE.  */
4592
4593 static struct iv_ca_delta *
4594 iv_ca_delta_add (struct iv_use *use, struct cost_pair *old_cp,
4595                  struct cost_pair *new_cp, struct iv_ca_delta *next_change)
4596 {
4597   struct iv_ca_delta *change = xmalloc (sizeof (struct iv_ca_delta));
4598
4599   change->use = use;
4600   change->old_cp = old_cp;
4601   change->new_cp = new_cp;
4602   change->next_change = next_change;
4603
4604   return change;
4605 }
4606
4607 /* Joins two lists of changes L1 and L2.  Destructive -- old lists
4608    are rewritten.  */
4609
4610 static struct iv_ca_delta *
4611 iv_ca_delta_join (struct iv_ca_delta *l1, struct iv_ca_delta *l2)
4612 {
4613   struct iv_ca_delta *last;
4614
4615   if (!l2)
4616     return l1;
4617
4618   if (!l1)
4619     return l2;
4620
4621   for (last = l1; last->next_change; last = last->next_change)
4622     continue;
4623   last->next_change = l2;
4624
4625   return l1;
4626 }
4627
4628 /* Returns candidate by that USE is expressed in IVS.  */
4629
4630 static struct cost_pair *
4631 iv_ca_cand_for_use (struct iv_ca *ivs, struct iv_use *use)
4632 {
4633   return ivs->cand_for_use[use->id];
4634 }
4635
4636 /* Reverse the list of changes DELTA, forming the inverse to it.  */
4637
4638 static struct iv_ca_delta *
4639 iv_ca_delta_reverse (struct iv_ca_delta *delta)
4640 {
4641   struct iv_ca_delta *act, *next, *prev = NULL;
4642   struct cost_pair *tmp;
4643
4644   for (act = delta; act; act = next)
4645     {
4646       next = act->next_change;
4647       act->next_change = prev;
4648       prev = act;
4649
4650       tmp = act->old_cp;
4651       act->old_cp = act->new_cp;
4652       act->new_cp = tmp;
4653     }
4654
4655   return prev;
4656 }
4657
4658 /* Commit changes in DELTA to IVS.  If FORWARD is false, the changes are
4659    reverted instead.  */
4660
4661 static void
4662 iv_ca_delta_commit (struct ivopts_data *data, struct iv_ca *ivs,
4663                     struct iv_ca_delta *delta, bool forward)
4664 {
4665   struct cost_pair *from, *to;
4666   struct iv_ca_delta *act;
4667
4668   if (!forward)
4669     delta = iv_ca_delta_reverse (delta);
4670
4671   for (act = delta; act; act = act->next_change)
4672     {
4673       from = act->old_cp;
4674       to = act->new_cp;
4675       gcc_assert (iv_ca_cand_for_use (ivs, act->use) == from);
4676       iv_ca_set_cp (data, ivs, act->use, to);
4677     }
4678
4679   if (!forward)
4680     iv_ca_delta_reverse (delta);
4681 }
4682
4683 /* Returns true if CAND is used in IVS.  */
4684
4685 static bool
4686 iv_ca_cand_used_p (struct iv_ca *ivs, struct iv_cand *cand)
4687 {
4688   return ivs->n_cand_uses[cand->id] > 0;
4689 }
4690
4691 /* Returns number of induction variable candidates in the set IVS.  */
4692
4693 static unsigned
4694 iv_ca_n_cands (struct iv_ca *ivs)
4695 {
4696   return ivs->n_cands;
4697 }
4698
4699 /* Free the list of changes DELTA.  */
4700
4701 static void
4702 iv_ca_delta_free (struct iv_ca_delta **delta)
4703 {
4704   struct iv_ca_delta *act, *next;
4705
4706   for (act = *delta; act; act = next)
4707     {
4708       next = act->next_change;
4709       free (act);
4710     }
4711
4712   *delta = NULL;
4713 }
4714
4715 /* Allocates new iv candidates assignment.  */
4716
4717 static struct iv_ca *
4718 iv_ca_new (struct ivopts_data *data)
4719 {
4720   struct iv_ca *nw = xmalloc (sizeof (struct iv_ca));
4721
4722   nw->upto = 0;
4723   nw->bad_uses = 0;
4724   nw->cand_for_use = xcalloc (n_iv_uses (data), sizeof (struct cost_pair *));
4725   nw->n_cand_uses = xcalloc (n_iv_cands (data), sizeof (unsigned));
4726   nw->cands = BITMAP_ALLOC (NULL);
4727   nw->n_cands = 0;
4728   nw->n_regs = 0;
4729   nw->cand_use_cost = 0;
4730   nw->cand_cost = 0;
4731   nw->n_invariant_uses = xcalloc (data->max_inv_id + 1, sizeof (unsigned));
4732   nw->cost = 0;
4733
4734   return nw;
4735 }
4736
4737 /* Free memory occupied by the set IVS.  */
4738
4739 static void
4740 iv_ca_free (struct iv_ca **ivs)
4741 {
4742   free ((*ivs)->cand_for_use);
4743   free ((*ivs)->n_cand_uses);
4744   BITMAP_FREE ((*ivs)->cands);
4745   free ((*ivs)->n_invariant_uses);
4746   free (*ivs);
4747   *ivs = NULL;
4748 }
4749
4750 /* Dumps IVS to FILE.  */
4751
4752 static void
4753 iv_ca_dump (struct ivopts_data *data, FILE *file, struct iv_ca *ivs)
4754 {
4755   const char *pref = "  invariants ";
4756   unsigned i;
4757
4758   fprintf (file, "  cost %d\n", iv_ca_cost (ivs));
4759   bitmap_print (file, ivs->cands, "  candidates ","\n");
4760
4761   for (i = 1; i <= data->max_inv_id; i++)
4762     if (ivs->n_invariant_uses[i])
4763       {
4764         fprintf (file, "%s%d", pref, i);
4765         pref = ", ";
4766       }
4767   fprintf (file, "\n");
4768 }
4769
4770 /* Try changing candidate in IVS to CAND for each use.  Return cost of the
4771    new set, and store differences in DELTA.  Number of induction variables
4772    in the new set is stored to N_IVS.  */
4773
4774 static unsigned
4775 iv_ca_extend (struct ivopts_data *data, struct iv_ca *ivs,
4776               struct iv_cand *cand, struct iv_ca_delta **delta,
4777               unsigned *n_ivs)
4778 {
4779   unsigned i, cost;
4780   struct iv_use *use;
4781   struct cost_pair *old_cp, *new_cp;
4782
4783   *delta = NULL;
4784   for (i = 0; i < ivs->upto; i++)
4785     {
4786       use = iv_use (data, i);
4787       old_cp = iv_ca_cand_for_use (ivs, use);
4788
4789       if (old_cp
4790           && old_cp->cand == cand)
4791         continue;
4792
4793       new_cp = get_use_iv_cost (data, use, cand);
4794       if (!new_cp)
4795         continue;
4796
4797       if (!iv_ca_has_deps (ivs, new_cp))
4798         continue;
4799       
4800       if (!cheaper_cost_pair (new_cp, old_cp))
4801         continue;
4802
4803       *delta = iv_ca_delta_add (use, old_cp, new_cp, *delta);
4804     }
4805
4806   iv_ca_delta_commit (data, ivs, *delta, true);
4807   cost = iv_ca_cost (ivs);
4808   if (n_ivs)
4809     *n_ivs = iv_ca_n_cands (ivs);
4810   iv_ca_delta_commit (data, ivs, *delta, false);
4811
4812   return cost;
4813 }
4814
4815 /* Try narrowing set IVS by removing CAND.  Return the cost of
4816    the new set and store the differences in DELTA.  */
4817
4818 static unsigned
4819 iv_ca_narrow (struct ivopts_data *data, struct iv_ca *ivs,
4820               struct iv_cand *cand, struct iv_ca_delta **delta)
4821 {
4822   unsigned i, ci;
4823   struct iv_use *use;
4824   struct cost_pair *old_cp, *new_cp, *cp;
4825   bitmap_iterator bi;
4826   struct iv_cand *cnd;
4827   unsigned cost;
4828
4829   *delta = NULL;
4830   for (i = 0; i < n_iv_uses (data); i++)
4831     {
4832       use = iv_use (data, i);
4833
4834       old_cp = iv_ca_cand_for_use (ivs, use);
4835       if (old_cp->cand != cand)
4836         continue;
4837
4838       new_cp = NULL;
4839
4840       if (data->consider_all_candidates)
4841         {
4842           EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, ci, bi)
4843             {
4844               if (ci == cand->id)
4845                 continue;
4846
4847               cnd = iv_cand (data, ci);
4848
4849               cp = get_use_iv_cost (data, use, cnd);
4850               if (!cp)
4851                 continue;
4852               if (!iv_ca_has_deps (ivs, cp))
4853                 continue;
4854       
4855               if (!cheaper_cost_pair (cp, new_cp))
4856                 continue;
4857
4858               new_cp = cp;
4859             }
4860         }
4861       else
4862         {
4863           EXECUTE_IF_AND_IN_BITMAP (use->related_cands, ivs->cands, 0, ci, bi)
4864             {
4865               if (ci == cand->id)
4866                 continue;
4867
4868               cnd = iv_cand (data, ci);
4869
4870               cp = get_use_iv_cost (data, use, cnd);
4871               if (!cp)
4872                 continue;
4873               if (!iv_ca_has_deps (ivs, cp))
4874                 continue;
4875       
4876               if (!cheaper_cost_pair (cp, new_cp))
4877                 continue;
4878
4879               new_cp = cp;
4880             }
4881         }
4882
4883       if (!new_cp)
4884         {
4885           iv_ca_delta_free (delta);
4886           return INFTY;
4887         }
4888
4889       *delta = iv_ca_delta_add (use, old_cp, new_cp, *delta);
4890     }
4891
4892   iv_ca_delta_commit (data, ivs, *delta, true);
4893   cost = iv_ca_cost (ivs);
4894   iv_ca_delta_commit (data, ivs, *delta, false);
4895
4896   return cost;
4897 }
4898
4899 /* Try optimizing the set of candidates IVS by removing candidates different
4900    from to EXCEPT_CAND from it.  Return cost of the new set, and store
4901    differences in DELTA.  */
4902
4903 static unsigned
4904 iv_ca_prune (struct ivopts_data *data, struct iv_ca *ivs,
4905              struct iv_cand *except_cand, struct iv_ca_delta **delta)
4906 {
4907   bitmap_iterator bi;
4908   struct iv_ca_delta *act_delta, *best_delta;
4909   unsigned i, best_cost, acost;
4910   struct iv_cand *cand;
4911
4912   best_delta = NULL;
4913   best_cost = iv_ca_cost (ivs);
4914
4915   EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, i, bi)
4916     {
4917       cand = iv_cand (data, i);
4918
4919       if (cand == except_cand)
4920         continue;
4921
4922       acost = iv_ca_narrow (data, ivs, cand, &act_delta);
4923
4924       if (acost < best_cost)
4925         {
4926           best_cost = acost;
4927           iv_ca_delta_free (&best_delta);
4928           best_delta = act_delta;
4929         }
4930       else
4931         iv_ca_delta_free (&act_delta);
4932     }
4933
4934   if (!best_delta)
4935     {
4936       *delta = NULL;
4937       return best_cost;
4938     }
4939
4940   /* Recurse to possibly remove other unnecessary ivs.  */
4941   iv_ca_delta_commit (data, ivs, best_delta, true);
4942   best_cost = iv_ca_prune (data, ivs, except_cand, delta);
4943   iv_ca_delta_commit (data, ivs, best_delta, false);
4944   *delta = iv_ca_delta_join (best_delta, *delta);
4945   return best_cost;
4946 }
4947
4948 /* Tries to extend the sets IVS in the best possible way in order
4949    to express the USE.  */
4950
4951 static bool
4952 try_add_cand_for (struct ivopts_data *data, struct iv_ca *ivs,
4953                   struct iv_use *use)
4954 {
4955   unsigned best_cost, act_cost;
4956   unsigned i;
4957   bitmap_iterator bi;
4958   struct iv_cand *cand;
4959   struct iv_ca_delta *best_delta = NULL, *act_delta;
4960   struct cost_pair *cp;
4961
4962   iv_ca_add_use (data, ivs, use);
4963   best_cost = iv_ca_cost (ivs);
4964
4965   cp = iv_ca_cand_for_use (ivs, use);
4966   if (cp)
4967     {
4968       best_delta = iv_ca_delta_add (use, NULL, cp, NULL);
4969       iv_ca_set_no_cp (data, ivs, use);
4970     }
4971
4972   /* First try important candidates.  Only if it fails, try the specific ones.
4973      Rationale -- in loops with many variables the best choice often is to use
4974      just one generic biv.  If we added here many ivs specific to the uses,
4975      the optimization algorithm later would be likely to get stuck in a local
4976      minimum, thus causing us to create too many ivs.  The approach from
4977      few ivs to more seems more likely to be successful -- starting from few
4978      ivs, replacing an expensive use by a specific iv should always be a
4979      win.  */
4980   EXECUTE_IF_SET_IN_BITMAP (data->important_candidates, 0, i, bi)
4981     {
4982       cand = iv_cand (data, i);
4983
4984       if (iv_ca_cand_used_p (ivs, cand))
4985         continue;
4986
4987       cp = get_use_iv_cost (data, use, cand);
4988       if (!cp)
4989         continue;
4990
4991       iv_ca_set_cp (data, ivs, use, cp);
4992       act_cost = iv_ca_extend (data, ivs, cand, &act_delta, NULL);
4993       iv_ca_set_no_cp (data, ivs, use);
4994       act_delta = iv_ca_delta_add (use, NULL, cp, act_delta);
4995
4996       if (act_cost < best_cost)
4997         {
4998           best_cost = act_cost;
4999
5000           iv_ca_delta_free (&best_delta);
5001           best_delta = act_delta;
5002         }
5003       else
5004         iv_ca_delta_free (&act_delta);
5005     }
5006
5007   if (best_cost == INFTY)
5008     {
5009       for (i = 0; i < use->n_map_members; i++)
5010         {
5011           cp = use->cost_map + i;
5012           cand = cp->cand;
5013           if (!cand)
5014             continue;
5015
5016           /* Already tried this.  */
5017           if (cand->important)
5018             continue;
5019       
5020           if (iv_ca_cand_used_p (ivs, cand))
5021             continue;
5022
5023           act_delta = NULL;
5024           iv_ca_set_cp (data, ivs, use, cp);
5025           act_cost = iv_ca_extend (data, ivs, cand, &act_delta, NULL);
5026           iv_ca_set_no_cp (data, ivs, use);
5027           act_delta = iv_ca_delta_add (use, iv_ca_cand_for_use (ivs, use),
5028                                        cp, act_delta);
5029
5030           if (act_cost < best_cost)
5031             {
5032               best_cost = act_cost;
5033
5034               if (best_delta)
5035                 iv_ca_delta_free (&best_delta);
5036               best_delta = act_delta;
5037             }
5038           else
5039             iv_ca_delta_free (&act_delta);
5040         }
5041     }
5042
5043   iv_ca_delta_commit (data, ivs, best_delta, true);
5044   iv_ca_delta_free (&best_delta);
5045
5046   return (best_cost != INFTY);
5047 }
5048
5049 /* Finds an initial assignment of candidates to uses.  */
5050
5051 static struct iv_ca *
5052 get_initial_solution (struct ivopts_data *data)
5053 {
5054   struct iv_ca *ivs = iv_ca_new (data);
5055   unsigned i;
5056
5057   for (i = 0; i < n_iv_uses (data); i++)
5058     if (!try_add_cand_for (data, ivs, iv_use (data, i)))
5059       {
5060         iv_ca_free (&ivs);
5061         return NULL;
5062       }
5063
5064   return ivs;
5065 }
5066
5067 /* Tries to improve set of induction variables IVS.  */
5068
5069 static bool
5070 try_improve_iv_set (struct ivopts_data *data, struct iv_ca *ivs)
5071 {
5072   unsigned i, acost, best_cost = iv_ca_cost (ivs), n_ivs;
5073   struct iv_ca_delta *best_delta = NULL, *act_delta, *tmp_delta;
5074   struct iv_cand *cand;
5075
5076   /* Try extending the set of induction variables by one.  */
5077   for (i = 0; i < n_iv_cands (data); i++)
5078     {
5079       cand = iv_cand (data, i);
5080       
5081       if (iv_ca_cand_used_p (ivs, cand))
5082         continue;
5083
5084       acost = iv_ca_extend (data, ivs, cand, &act_delta, &n_ivs);
5085       if (!act_delta)
5086         continue;
5087
5088       /* If we successfully added the candidate and the set is small enough,
5089          try optimizing it by removing other candidates.  */
5090       if (n_ivs <= ALWAYS_PRUNE_CAND_SET_BOUND)
5091         {
5092           iv_ca_delta_commit (data, ivs, act_delta, true);
5093           acost = iv_ca_prune (data, ivs, cand, &tmp_delta);
5094           iv_ca_delta_commit (data, ivs, act_delta, false);
5095           act_delta = iv_ca_delta_join (act_delta, tmp_delta);
5096         }
5097
5098       if (acost < best_cost)
5099         {
5100           best_cost = acost;
5101           iv_ca_delta_free (&best_delta);
5102           best_delta = act_delta;
5103         }
5104       else
5105         iv_ca_delta_free (&act_delta);
5106     }
5107
5108   if (!best_delta)
5109     {
5110       /* Try removing the candidates from the set instead.  */
5111       best_cost = iv_ca_prune (data, ivs, NULL, &best_delta);
5112
5113       /* Nothing more we can do.  */
5114       if (!best_delta)
5115         return false;
5116     }
5117
5118   iv_ca_delta_commit (data, ivs, best_delta, true);
5119   gcc_assert (best_cost == iv_ca_cost (ivs));
5120   iv_ca_delta_free (&best_delta);
5121   return true;
5122 }
5123
5124 /* Attempts to find the optimal set of induction variables.  We do simple
5125    greedy heuristic -- we try to replace at most one candidate in the selected
5126    solution and remove the unused ivs while this improves the cost.  */
5127
5128 static struct iv_ca *
5129 find_optimal_iv_set (struct ivopts_data *data)
5130 {
5131   unsigned i;
5132   struct iv_ca *set;
5133   struct iv_use *use;
5134
5135   /* Get the initial solution.  */
5136   set = get_initial_solution (data);
5137   if (!set)
5138     {
5139       if (dump_file && (dump_flags & TDF_DETAILS))
5140         fprintf (dump_file, "Unable to substitute for ivs, failed.\n");
5141       return NULL;
5142     }
5143
5144   if (dump_file && (dump_flags & TDF_DETAILS))
5145     {
5146       fprintf (dump_file, "Initial set of candidates:\n");
5147       iv_ca_dump (data, dump_file, set);
5148     }
5149
5150   while (try_improve_iv_set (data, set))
5151     {
5152       if (dump_file && (dump_flags & TDF_DETAILS))
5153         {
5154           fprintf (dump_file, "Improved to:\n");
5155           iv_ca_dump (data, dump_file, set);
5156         }
5157     }
5158
5159   if (dump_file && (dump_flags & TDF_DETAILS))
5160     fprintf (dump_file, "Final cost %d\n\n", iv_ca_cost (set));
5161
5162   for (i = 0; i < n_iv_uses (data); i++)
5163     {
5164       use = iv_use (data, i);
5165       use->selected = iv_ca_cand_for_use (set, use)->cand;
5166     }
5167
5168   return set;
5169 }
5170
5171 /* Creates a new induction variable corresponding to CAND.  */
5172
5173 static void
5174 create_new_iv (struct ivopts_data *data, struct iv_cand *cand)
5175 {
5176   block_stmt_iterator incr_pos;
5177   tree base;
5178   bool after = false;
5179
5180   if (!cand->iv)
5181     return;
5182
5183   switch (cand->pos)
5184     {
5185     case IP_NORMAL:
5186       incr_pos = bsi_last (ip_normal_pos (data->current_loop));
5187       break;
5188
5189     case IP_END:
5190       incr_pos = bsi_last (ip_end_pos (data->current_loop));
5191       after = true;
5192       break;
5193
5194     case IP_ORIGINAL:
5195       /* Mark that the iv is preserved.  */
5196       name_info (data, cand->var_before)->preserve_biv = true;
5197       name_info (data, cand->var_after)->preserve_biv = true;
5198
5199       /* Rewrite the increment so that it uses var_before directly.  */
5200       find_interesting_uses_op (data, cand->var_after)->selected = cand;
5201       
5202       return;
5203     }
5204  
5205   gimple_add_tmp_var (cand->var_before);
5206   add_referenced_tmp_var (cand->var_before);
5207
5208   base = unshare_expr (cand->iv->base);
5209
5210   create_iv (base, unshare_expr (cand->iv->step),
5211              cand->var_before, data->current_loop,
5212              &incr_pos, after, &cand->var_before, &cand->var_after);
5213 }
5214
5215 /* Creates new induction variables described in SET.  */
5216
5217 static void
5218 create_new_ivs (struct ivopts_data *data, struct iv_ca *set)
5219 {
5220   unsigned i;
5221   struct iv_cand *cand;
5222   bitmap_iterator bi;
5223
5224   EXECUTE_IF_SET_IN_BITMAP (set->cands, 0, i, bi)
5225     {
5226       cand = iv_cand (data, i);
5227       create_new_iv (data, cand);
5228     }
5229 }
5230
5231 /* Removes statement STMT (real or a phi node).  If INCLUDING_DEFINED_NAME
5232    is true, remove also the ssa name defined by the statement.  */
5233
5234 static void
5235 remove_statement (tree stmt, bool including_defined_name)
5236 {
5237   if (TREE_CODE (stmt) == PHI_NODE)
5238     {
5239       if (!including_defined_name)
5240         {
5241           /* Prevent the ssa name defined by the statement from being removed.  */
5242           SET_PHI_RESULT (stmt, NULL);
5243         }
5244       remove_phi_node (stmt, NULL_TREE);
5245     }
5246   else
5247     {
5248       block_stmt_iterator bsi = bsi_for_stmt (stmt);
5249
5250       bsi_remove (&bsi);
5251     }
5252 }
5253
5254 /* Rewrites USE (definition of iv used in a nonlinear expression)
5255    using candidate CAND.  */
5256
5257 static void
5258 rewrite_use_nonlinear_expr (struct ivopts_data *data,
5259                             struct iv_use *use, struct iv_cand *cand)
5260 {
5261   tree comp;
5262   tree op, stmts, tgt, ass;
5263   block_stmt_iterator bsi, pbsi;
5264
5265   /* An important special case -- if we are asked to express value of
5266      the original iv by itself, just exit; there is no need to
5267      introduce a new computation (that might also need casting the
5268      variable to unsigned and back).  */
5269   if (cand->pos == IP_ORIGINAL
5270       && TREE_CODE (use->stmt) == MODIFY_EXPR
5271       && TREE_OPERAND (use->stmt, 0) == cand->var_after)
5272     {
5273       op = TREE_OPERAND (use->stmt, 1);
5274
5275       /* Be a bit careful.  In case variable is expressed in some
5276          complicated way, rewrite it so that we may get rid of this
5277          complicated expression.  */
5278       if ((TREE_CODE (op) == PLUS_EXPR
5279            || TREE_CODE (op) == MINUS_EXPR)
5280           && TREE_OPERAND (op, 0) == cand->var_before
5281           && TREE_CODE (TREE_OPERAND (op, 1)) == INTEGER_CST)
5282         return;
5283     }
5284
5285   comp = unshare_expr (get_computation (data->current_loop,
5286                                         use, cand));
5287   switch (TREE_CODE (use->stmt))
5288     {
5289     case PHI_NODE:
5290       tgt = PHI_RESULT (use->stmt);
5291
5292       /* If we should keep the biv, do not replace it.  */
5293       if (name_info (data, tgt)->preserve_biv)
5294         return;
5295
5296       pbsi = bsi = bsi_start (bb_for_stmt (use->stmt));
5297       while (!bsi_end_p (pbsi)
5298              && TREE_CODE (bsi_stmt (pbsi)) == LABEL_EXPR)
5299         {
5300           bsi = pbsi;
5301           bsi_next (&pbsi);
5302         }
5303       break;
5304
5305     case MODIFY_EXPR:
5306       tgt = TREE_OPERAND (use->stmt, 0);
5307       bsi = bsi_for_stmt (use->stmt);
5308       break;
5309
5310     default:
5311       gcc_unreachable ();
5312     }
5313
5314   op = force_gimple_operand (comp, &stmts, false, SSA_NAME_VAR (tgt));
5315
5316   if (TREE_CODE (use->stmt) == PHI_NODE)
5317     {
5318       if (stmts)
5319         bsi_insert_after (&bsi, stmts, BSI_CONTINUE_LINKING);
5320       ass = build2 (MODIFY_EXPR, TREE_TYPE (tgt), tgt, op);
5321       bsi_insert_after (&bsi, ass, BSI_NEW_STMT);
5322       remove_statement (use->stmt, false);
5323       SSA_NAME_DEF_STMT (tgt) = ass;
5324     }
5325   else
5326     {
5327       if (stmts)
5328         bsi_insert_before (&bsi, stmts, BSI_SAME_STMT);
5329       TREE_OPERAND (use->stmt, 1) = op;
5330     }
5331 }
5332
5333 /* Replaces ssa name in index IDX by its basic variable.  Callback for
5334    for_each_index.  */
5335
5336 static bool
5337 idx_remove_ssa_names (tree base, tree *idx,
5338                       void *data ATTRIBUTE_UNUSED)
5339 {
5340   tree *op;
5341
5342   if (TREE_CODE (*idx) == SSA_NAME)
5343     *idx = SSA_NAME_VAR (*idx);
5344
5345   if (TREE_CODE (base) == ARRAY_REF)
5346     {
5347       op = &TREE_OPERAND (base, 2);
5348       if (*op
5349           && TREE_CODE (*op) == SSA_NAME)
5350         *op = SSA_NAME_VAR (*op);
5351       op = &TREE_OPERAND (base, 3);
5352       if (*op
5353           && TREE_CODE (*op) == SSA_NAME)
5354         *op = SSA_NAME_VAR (*op);
5355     }
5356
5357   return true;
5358 }
5359
5360 /* Unshares REF and replaces ssa names inside it by their basic variables.  */
5361
5362 static tree
5363 unshare_and_remove_ssa_names (tree ref)
5364 {
5365   ref = unshare_expr (ref);
5366   for_each_index (&ref, idx_remove_ssa_names, NULL);
5367
5368   return ref;
5369 }
5370
5371 /* Rewrites base of memory access OP with expression WITH in statement
5372    pointed to by BSI.  */
5373
5374 static void
5375 rewrite_address_base (block_stmt_iterator *bsi, tree *op, tree with)
5376 {
5377   tree bvar, var, new_name, copy, name;
5378   tree orig;
5379
5380   var = bvar = get_base_address (*op);
5381
5382   if (!var || TREE_CODE (with) != SSA_NAME)
5383     goto do_rewrite;
5384
5385   gcc_assert (TREE_CODE (var) != ALIGN_INDIRECT_REF);
5386   gcc_assert (TREE_CODE (var) != MISALIGNED_INDIRECT_REF);
5387   if (TREE_CODE (var) == INDIRECT_REF)
5388     var = TREE_OPERAND (var, 0);
5389   if (TREE_CODE (var) == SSA_NAME)
5390     {
5391       name = var;
5392       var = SSA_NAME_VAR (var);
5393     }
5394   else if (DECL_P (var))
5395     name = NULL_TREE;
5396   else
5397     goto do_rewrite;
5398     
5399   /* We need to add a memory tag for the variable.  But we do not want
5400      to add it to the temporary used for the computations, since this leads
5401      to problems in redundancy elimination when there are common parts
5402      in two computations referring to the different arrays.  So we copy
5403      the variable to a new temporary.  */
5404   copy = build2 (MODIFY_EXPR, void_type_node, NULL_TREE, with);
5405
5406   if (name)
5407     new_name = duplicate_ssa_name (name, copy);
5408   else
5409     {
5410       tree tag = var_ann (var)->type_mem_tag;
5411       tree new_ptr = create_tmp_var (TREE_TYPE (with), "ruatmp");
5412       add_referenced_tmp_var (new_ptr);
5413       if (tag)
5414         var_ann (new_ptr)->type_mem_tag = tag;
5415       else
5416         add_type_alias (new_ptr, var);
5417       new_name = make_ssa_name (new_ptr, copy);
5418     }
5419
5420   TREE_OPERAND (copy, 0) = new_name;
5421   bsi_insert_before (bsi, copy, BSI_SAME_STMT);
5422   with = new_name;
5423
5424 do_rewrite:
5425
5426   orig = NULL_TREE;
5427   gcc_assert (TREE_CODE (*op) != ALIGN_INDIRECT_REF);
5428   gcc_assert (TREE_CODE (*op) != MISALIGNED_INDIRECT_REF);
5429
5430   if (TREE_CODE (*op) == INDIRECT_REF)
5431     orig = REF_ORIGINAL (*op);
5432   if (!orig)
5433     orig = unshare_and_remove_ssa_names (*op);
5434
5435   *op = build1 (INDIRECT_REF, TREE_TYPE (*op), with);
5436
5437   /* Record the original reference, for purposes of alias analysis.  */
5438   REF_ORIGINAL (*op) = orig;
5439
5440   /* Virtual operands in the original statement may have to be renamed
5441      because of the replacement.  */
5442   mark_new_vars_to_rename (bsi_stmt (*bsi));
5443 }
5444
5445 /* Rewrites USE (address that is an iv) using candidate CAND.  */
5446
5447 static void
5448 rewrite_use_address (struct ivopts_data *data,
5449                      struct iv_use *use, struct iv_cand *cand)
5450 {
5451   tree comp = unshare_expr (get_computation (data->current_loop,
5452                                              use, cand));
5453   block_stmt_iterator bsi = bsi_for_stmt (use->stmt);
5454   tree stmts;
5455   tree op = force_gimple_operand (comp, &stmts, true, NULL_TREE);
5456
5457   if (stmts)
5458     bsi_insert_before (&bsi, stmts, BSI_SAME_STMT);
5459
5460   rewrite_address_base (&bsi, use->op_p, op);
5461 }
5462
5463 /* Rewrites USE (the condition such that one of the arguments is an iv) using
5464    candidate CAND.  */
5465
5466 static void
5467 rewrite_use_compare (struct ivopts_data *data,
5468                      struct iv_use *use, struct iv_cand *cand)
5469 {
5470   tree comp;
5471   tree *op_p, cond, op, stmts, bound;
5472   block_stmt_iterator bsi = bsi_for_stmt (use->stmt);
5473   enum tree_code compare;
5474   struct cost_pair *cp = get_use_iv_cost (data, use, cand);
5475   
5476   bound = cp->value;
5477   if (bound)
5478     {
5479       tree var = var_at_stmt (data->current_loop, cand, use->stmt);
5480       tree var_type = TREE_TYPE (var);
5481
5482       compare = iv_elimination_compare (data, use);
5483       bound = fold_convert (var_type, bound);
5484       op = force_gimple_operand (unshare_expr (bound), &stmts,
5485                                  true, NULL_TREE);
5486
5487       if (stmts)
5488         bsi_insert_before (&bsi, stmts, BSI_SAME_STMT);
5489
5490       *use->op_p = build2 (compare, boolean_type_node, var, op);
5491       update_stmt (use->stmt);
5492       return;
5493     }
5494
5495   /* The induction variable elimination failed; just express the original
5496      giv.  */
5497   comp = unshare_expr (get_computation (data->current_loop, use, cand));
5498
5499   cond = *use->op_p;
5500   op_p = &TREE_OPERAND (cond, 0);
5501   if (TREE_CODE (*op_p) != SSA_NAME
5502       || zero_p (get_iv (data, *op_p)->step))
5503     op_p = &TREE_OPERAND (cond, 1);
5504
5505   op = force_gimple_operand (comp, &stmts, true, SSA_NAME_VAR (*op_p));
5506   if (stmts)
5507     bsi_insert_before (&bsi, stmts, BSI_SAME_STMT);
5508
5509   *op_p = op;
5510 }
5511
5512 /* Ensure that operand *OP_P may be used at the end of EXIT without
5513    violating loop closed ssa form.  */
5514
5515 static void
5516 protect_loop_closed_ssa_form_use (edge exit, use_operand_p op_p)
5517 {
5518   basic_block def_bb;
5519   struct loop *def_loop;
5520   tree phi, use;
5521
5522   use = USE_FROM_PTR (op_p);
5523   if (TREE_CODE (use) != SSA_NAME)
5524     return;
5525
5526   def_bb = bb_for_stmt (SSA_NAME_DEF_STMT (use));
5527   if (!def_bb)
5528     return;
5529
5530   def_loop = def_bb->loop_father;
5531   if (flow_bb_inside_loop_p (def_loop, exit->dest))
5532     return;
5533
5534   /* Try finding a phi node that copies the value out of the loop.  */
5535   for (phi = phi_nodes (exit->dest); phi; phi = PHI_CHAIN (phi))
5536     if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == use)
5537       break;
5538
5539   if (!phi)
5540     {
5541       /* Create such a phi node.  */
5542       tree new_name = duplicate_ssa_name (use, NULL);
5543
5544       phi = create_phi_node (new_name, exit->dest);
5545       SSA_NAME_DEF_STMT (new_name) = phi;
5546       add_phi_arg (phi, use, exit);
5547     }
5548
5549   SET_USE (op_p, PHI_RESULT (phi));
5550 }
5551
5552 /* Ensure that operands of STMT may be used at the end of EXIT without
5553    violating loop closed ssa form.  */
5554
5555 static void
5556 protect_loop_closed_ssa_form (edge exit, tree stmt)
5557 {
5558   ssa_op_iter iter;
5559   use_operand_p use_p;
5560
5561   FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_ALL_USES)
5562     protect_loop_closed_ssa_form_use (exit, use_p);
5563 }
5564
5565 /* STMTS compute a value of a phi argument OP on EXIT of a loop.  Arrange things
5566    so that they are emitted on the correct place, and so that the loop closed
5567    ssa form is preserved.  */
5568
5569 static void
5570 compute_phi_arg_on_exit (edge exit, tree stmts, tree op)
5571 {
5572   tree_stmt_iterator tsi;
5573   block_stmt_iterator bsi;
5574   tree phi, stmt, def, next;
5575
5576   if (!single_pred_p (exit->dest))
5577     split_loop_exit_edge (exit);
5578
5579   /* Ensure there is label in exit->dest, so that we can
5580      insert after it.  */
5581   tree_block_label (exit->dest);
5582   bsi = bsi_after_labels (exit->dest);
5583
5584   if (TREE_CODE (stmts) == STATEMENT_LIST)
5585     {
5586       for (tsi = tsi_start (stmts); !tsi_end_p (tsi); tsi_next (&tsi))
5587         {
5588           bsi_insert_after (&bsi, tsi_stmt (tsi), BSI_NEW_STMT);
5589           protect_loop_closed_ssa_form (exit, bsi_stmt (bsi));
5590         }
5591     }
5592   else
5593     {
5594       bsi_insert_after (&bsi, stmts, BSI_NEW_STMT);
5595       protect_loop_closed_ssa_form (exit, bsi_stmt (bsi));
5596     }
5597
5598   if (!op)
5599     return;
5600
5601   for (phi = phi_nodes (exit->dest); phi; phi = next)
5602     {
5603       next = PHI_CHAIN (phi);
5604
5605       if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == op)
5606         {
5607           def = PHI_RESULT (phi);
5608           remove_statement (phi, false);
5609           stmt = build2 (MODIFY_EXPR, TREE_TYPE (op),
5610                         def, op);
5611           SSA_NAME_DEF_STMT (def) = stmt;
5612           bsi_insert_after (&bsi, stmt, BSI_CONTINUE_LINKING);
5613         }
5614     }
5615 }
5616
5617 /* Rewrites the final value of USE (that is only needed outside of the loop)
5618    using candidate CAND.  */
5619
5620 static void
5621 rewrite_use_outer (struct ivopts_data *data,
5622                    struct iv_use *use, struct iv_cand *cand)
5623 {
5624   edge exit;
5625   tree value, op, stmts, tgt;
5626   tree phi;
5627
5628   switch (TREE_CODE (use->stmt))
5629     {
5630     case PHI_NODE:
5631       tgt = PHI_RESULT (use->stmt);
5632       break;
5633     case MODIFY_EXPR:
5634       tgt = TREE_OPERAND (use->stmt, 0);
5635       break;
5636     default:
5637       gcc_unreachable ();
5638     }
5639
5640   exit = single_dom_exit (data->current_loop);
5641
5642   if (exit)
5643     {
5644       if (!cand->iv)
5645         {
5646           struct cost_pair *cp = get_use_iv_cost (data, use, cand);
5647           value = cp->value;
5648         }
5649       else
5650         value = get_computation_at (data->current_loop,
5651                                     use, cand, last_stmt (exit->src));
5652
5653       value = unshare_expr (value);
5654       op = force_gimple_operand (value, &stmts, true, SSA_NAME_VAR (tgt));
5655           
5656       /* If we will preserve the iv anyway and we would need to perform
5657          some computation to replace the final value, do nothing.  */
5658       if (stmts && name_info (data, tgt)->preserve_biv)
5659         return;
5660
5661       for (phi = phi_nodes (exit->dest); phi; phi = PHI_CHAIN (phi))
5662         {
5663           use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, exit);
5664
5665           if (USE_FROM_PTR (use_p) == tgt)
5666             SET_USE (use_p, op);
5667         }
5668
5669       if (stmts)
5670         compute_phi_arg_on_exit (exit, stmts, op);
5671
5672       /* Enable removal of the statement.  We cannot remove it directly,
5673          since we may still need the aliasing information attached to the
5674          ssa name defined by it.  */
5675       name_info (data, tgt)->iv->have_use_for = false;
5676       return;
5677     }
5678
5679   /* If the variable is going to be preserved anyway, there is nothing to
5680      do.  */
5681   if (name_info (data, tgt)->preserve_biv)
5682     return;
5683
5684   /* Otherwise we just need to compute the iv.  */
5685   rewrite_use_nonlinear_expr (data, use, cand);
5686 }
5687
5688 /* Rewrites USE using candidate CAND.  */
5689
5690 static void
5691 rewrite_use (struct ivopts_data *data,
5692              struct iv_use *use, struct iv_cand *cand)
5693 {
5694   switch (use->type)
5695     {
5696       case USE_NONLINEAR_EXPR:
5697         rewrite_use_nonlinear_expr (data, use, cand);
5698         break;
5699
5700       case USE_OUTER:
5701         rewrite_use_outer (data, use, cand);
5702         break;
5703
5704       case USE_ADDRESS:
5705         rewrite_use_address (data, use, cand);
5706         break;
5707
5708       case USE_COMPARE:
5709         rewrite_use_compare (data, use, cand);
5710         break;
5711
5712       default:
5713         gcc_unreachable ();
5714     }
5715   update_stmt (use->stmt);
5716 }
5717
5718 /* Rewrite the uses using the selected induction variables.  */
5719
5720 static void
5721 rewrite_uses (struct ivopts_data *data)
5722 {
5723   unsigned i;
5724   struct iv_cand *cand;
5725   struct iv_use *use;
5726
5727   for (i = 0; i < n_iv_uses (data); i++)
5728     {
5729       use = iv_use (data, i);
5730       cand = use->selected;
5731       gcc_assert (cand);
5732
5733       rewrite_use (data, use, cand);
5734     }
5735 }
5736
5737 /* Removes the ivs that are not used after rewriting.  */
5738
5739 static void
5740 remove_unused_ivs (struct ivopts_data *data)
5741 {
5742   unsigned j;
5743   bitmap_iterator bi;
5744
5745   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, j, bi)
5746     {
5747       struct version_info *info;
5748
5749       info = ver_info (data, j);
5750       if (info->iv
5751           && !zero_p (info->iv->step)
5752           && !info->inv_id
5753           && !info->iv->have_use_for
5754           && !info->preserve_biv)
5755         remove_statement (SSA_NAME_DEF_STMT (info->iv->ssa_name), true);
5756     }
5757 }
5758
5759 /* Frees data allocated by the optimization of a single loop.  */
5760
5761 static void
5762 free_loop_data (struct ivopts_data *data)
5763 {
5764   unsigned i, j;
5765   bitmap_iterator bi;
5766   tree obj;
5767
5768   htab_empty (data->niters);
5769
5770   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
5771     {
5772       struct version_info *info;
5773
5774       info = ver_info (data, i);
5775       if (info->iv)
5776         free (info->iv);
5777       info->iv = NULL;
5778       info->has_nonlin_use = false;
5779       info->preserve_biv = false;
5780       info->inv_id = 0;
5781     }
5782   bitmap_clear (data->relevant);
5783   bitmap_clear (data->important_candidates);
5784
5785   for (i = 0; i < n_iv_uses (data); i++)
5786     {
5787       struct iv_use *use = iv_use (data, i);
5788
5789       free (use->iv);
5790       BITMAP_FREE (use->related_cands);
5791       for (j = 0; j < use->n_map_members; j++)
5792         if (use->cost_map[j].depends_on)
5793           BITMAP_FREE (use->cost_map[j].depends_on);
5794       free (use->cost_map);
5795       free (use);
5796     }
5797   VEC_truncate (iv_use_p, data->iv_uses, 0);
5798
5799   for (i = 0; i < n_iv_cands (data); i++)
5800     {
5801       struct iv_cand *cand = iv_cand (data, i);
5802
5803       if (cand->iv)
5804         free (cand->iv);
5805       if (cand->depends_on)
5806         BITMAP_FREE (cand->depends_on);
5807       free (cand);
5808     }
5809   VEC_truncate (iv_cand_p, data->iv_candidates, 0);
5810
5811   if (data->version_info_size < num_ssa_names)
5812     {
5813       data->version_info_size = 2 * num_ssa_names;
5814       free (data->version_info);
5815       data->version_info = xcalloc (data->version_info_size,
5816                                     sizeof (struct version_info));
5817     }
5818
5819   data->max_inv_id = 0;
5820
5821   for (i = 0; VEC_iterate (tree, decl_rtl_to_reset, i, obj); i++)
5822     SET_DECL_RTL (obj, NULL_RTX);
5823
5824   VEC_truncate (tree, decl_rtl_to_reset, 0);
5825 }
5826
5827 /* Finalizes data structures used by the iv optimization pass.  LOOPS is the
5828    loop tree.  */
5829
5830 static void
5831 tree_ssa_iv_optimize_finalize (struct loops *loops, struct ivopts_data *data)
5832 {
5833   unsigned i;
5834
5835   for (i = 1; i < loops->num; i++)
5836     if (loops->parray[i])
5837       {
5838         free (loops->parray[i]->aux);
5839         loops->parray[i]->aux = NULL;
5840       }
5841
5842   free_loop_data (data);
5843   free (data->version_info);
5844   BITMAP_FREE (data->relevant);
5845   BITMAP_FREE (data->important_candidates);
5846   htab_delete (data->niters);
5847
5848   VEC_free (tree, heap, decl_rtl_to_reset);
5849   VEC_free (iv_use_p, heap, data->iv_uses);
5850   VEC_free (iv_cand_p, heap, data->iv_candidates);
5851 }
5852
5853 /* Optimizes the LOOP.  Returns true if anything changed.  */
5854
5855 static bool
5856 tree_ssa_iv_optimize_loop (struct ivopts_data *data, struct loop *loop)
5857 {
5858   bool changed = false;
5859   struct iv_ca *iv_ca;
5860   edge exit;
5861
5862   data->current_loop = loop;
5863
5864   if (dump_file && (dump_flags & TDF_DETAILS))
5865     {
5866       fprintf (dump_file, "Processing loop %d\n", loop->num);
5867       
5868       exit = single_dom_exit (loop);
5869       if (exit)
5870         {
5871           fprintf (dump_file, "  single exit %d -> %d, exit condition ",
5872                    exit->src->index, exit->dest->index);
5873           print_generic_expr (dump_file, last_stmt (exit->src), TDF_SLIM);
5874           fprintf (dump_file, "\n");
5875         }
5876
5877       fprintf (dump_file, "\n");
5878     }
5879
5880   /* For each ssa name determines whether it behaves as an induction variable
5881      in some loop.  */
5882   if (!find_induction_variables (data))
5883     goto finish;
5884
5885   /* Finds interesting uses (item 1).  */
5886   find_interesting_uses (data);
5887   if (n_iv_uses (data) > MAX_CONSIDERED_USES)
5888     goto finish;
5889
5890   /* Finds candidates for the induction variables (item 2).  */
5891   find_iv_candidates (data);
5892
5893   /* Calculates the costs (item 3, part 1).  */
5894   determine_use_iv_costs (data);
5895   determine_iv_costs (data);
5896   determine_set_costs (data);
5897
5898   /* Find the optimal set of induction variables (item 3, part 2).  */
5899   iv_ca = find_optimal_iv_set (data);
5900   if (!iv_ca)
5901     goto finish;
5902   changed = true;
5903
5904   /* Create the new induction variables (item 4, part 1).  */
5905   create_new_ivs (data, iv_ca);
5906   iv_ca_free (&iv_ca);
5907   
5908   /* Rewrite the uses (item 4, part 2).  */
5909   rewrite_uses (data);
5910
5911   /* Remove the ivs that are unused after rewriting.  */
5912   remove_unused_ivs (data);
5913
5914   /* We have changed the structure of induction variables; it might happen
5915      that definitions in the scev database refer to some of them that were
5916      eliminated.  */
5917   scev_reset ();
5918
5919 finish:
5920   free_loop_data (data);
5921
5922   return changed;
5923 }
5924
5925 /* Main entry point.  Optimizes induction variables in LOOPS.  */
5926
5927 void
5928 tree_ssa_iv_optimize (struct loops *loops)
5929 {
5930   struct loop *loop;
5931   struct ivopts_data data;
5932
5933   tree_ssa_iv_optimize_init (loops, &data);
5934
5935   /* Optimize the loops starting with the innermost ones.  */
5936   loop = loops->tree_root;
5937   while (loop->inner)
5938     loop = loop->inner;
5939
5940   /* Scan the loops, inner ones first.  */
5941   while (loop != loops->tree_root)
5942     {
5943       if (dump_file && (dump_flags & TDF_DETAILS))
5944         flow_loop_dump (loop, dump_file, NULL, 1);
5945
5946       tree_ssa_iv_optimize_loop (&data, loop);
5947
5948       if (loop->next)
5949         {
5950           loop = loop->next;
5951           while (loop->inner)
5952             loop = loop->inner;
5953         }
5954       else
5955         loop = loop->outer;
5956     }
5957
5958   /* FIXME.  IV opts introduces new aliases and call-clobbered
5959      variables, which need to be renamed.  However, when we call the
5960      renamer, not all statements will be scanned for operands.  In
5961      particular, the newly introduced aliases may appear in statements
5962      that are considered "unmodified", so the renamer will not get a
5963      chance to rename those operands.
5964
5965      Work around this problem by forcing an operand re-scan on every
5966      statement.  This will not be necessary once the new operand
5967      scanner is implemented.  */
5968   if (need_ssa_update_p ())
5969     {
5970       basic_block bb;
5971       block_stmt_iterator si;
5972       FOR_EACH_BB (bb)
5973         for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
5974           update_stmt (bsi_stmt (si));
5975     }
5976
5977   rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
5978   tree_ssa_iv_optimize_finalize (loops, &data);
5979 }