OSDN Git Service

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