OSDN Git Service

2011-07-20 Richard Guenther <rguenther@suse.de>
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-loop-im.c
1 /* Loop invariant motion.
2    Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 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 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "tm_p.h"
27 #include "basic-block.h"
28 #include "output.h"
29 #include "tree-pretty-print.h"
30 #include "gimple-pretty-print.h"
31 #include "tree-flow.h"
32 #include "tree-dump.h"
33 #include "timevar.h"
34 #include "cfgloop.h"
35 #include "domwalk.h"
36 #include "params.h"
37 #include "tree-pass.h"
38 #include "flags.h"
39 #include "hashtab.h"
40 #include "tree-affine.h"
41 #include "pointer-set.h"
42 #include "tree-ssa-propagate.h"
43
44 /* TODO:  Support for predicated code motion.  I.e.
45
46    while (1)
47      {
48        if (cond)
49          {
50            a = inv;
51            something;
52          }
53      }
54
55    Where COND and INV are is invariants, but evaluating INV may trap or be
56    invalid from some other reason if !COND.  This may be transformed to
57
58    if (cond)
59      a = inv;
60    while (1)
61      {
62        if (cond)
63          something;
64      }  */
65
66 /* A type for the list of statements that have to be moved in order to be able
67    to hoist an invariant computation.  */
68
69 struct depend
70 {
71   gimple stmt;
72   struct depend *next;
73 };
74
75 /* The auxiliary data kept for each statement.  */
76
77 struct lim_aux_data
78 {
79   struct loop *max_loop;        /* The outermost loop in that the statement
80                                    is invariant.  */
81
82   struct loop *tgt_loop;        /* The loop out of that we want to move the
83                                    invariant.  */
84
85   struct loop *always_executed_in;
86                                 /* The outermost loop for that we are sure
87                                    the statement is executed if the loop
88                                    is entered.  */
89
90   unsigned cost;                /* Cost of the computation performed by the
91                                    statement.  */
92
93   struct depend *depends;       /* List of statements that must be also hoisted
94                                    out of the loop when this statement is
95                                    hoisted; i.e. those that define the operands
96                                    of the statement and are inside of the
97                                    MAX_LOOP loop.  */
98 };
99
100 /* Maps statements to their lim_aux_data.  */
101
102 static struct pointer_map_t *lim_aux_data_map;
103
104 /* Description of a memory reference location.  */
105
106 typedef struct mem_ref_loc
107 {
108   tree *ref;                    /* The reference itself.  */
109   gimple stmt;                  /* The statement in that it occurs.  */
110 } *mem_ref_loc_p;
111
112 DEF_VEC_P(mem_ref_loc_p);
113 DEF_VEC_ALLOC_P(mem_ref_loc_p, heap);
114
115 /* The list of memory reference locations in a loop.  */
116
117 typedef struct mem_ref_locs
118 {
119   VEC (mem_ref_loc_p, heap) *locs;
120 } *mem_ref_locs_p;
121
122 DEF_VEC_P(mem_ref_locs_p);
123 DEF_VEC_ALLOC_P(mem_ref_locs_p, heap);
124
125 /* Description of a memory reference.  */
126
127 typedef struct mem_ref
128 {
129   tree mem;                     /* The memory itself.  */
130   unsigned id;                  /* ID assigned to the memory reference
131                                    (its index in memory_accesses.refs_list)  */
132   hashval_t hash;               /* Its hash value.  */
133   bitmap stored;                /* The set of loops in that this memory location
134                                    is stored to.  */
135   VEC (mem_ref_locs_p, heap) *accesses_in_loop;
136                                 /* The locations of the accesses.  Vector
137                                    indexed by the loop number.  */
138   bitmap vops;                  /* Vops corresponding to this memory
139                                    location.  */
140
141   /* The following sets are computed on demand.  We keep both set and
142      its complement, so that we know whether the information was
143      already computed or not.  */
144   bitmap indep_loop;            /* The set of loops in that the memory
145                                    reference is independent, meaning:
146                                    If it is stored in the loop, this store
147                                      is independent on all other loads and
148                                      stores.
149                                    If it is only loaded, then it is independent
150                                      on all stores in the loop.  */
151   bitmap dep_loop;              /* The complement of INDEP_LOOP.  */
152
153   bitmap indep_ref;             /* The set of memory references on that
154                                    this reference is independent.  */
155   bitmap dep_ref;               /* The complement of DEP_REF.  */
156 } *mem_ref_p;
157
158 DEF_VEC_P(mem_ref_p);
159 DEF_VEC_ALLOC_P(mem_ref_p, heap);
160
161 DEF_VEC_P(bitmap);
162 DEF_VEC_ALLOC_P(bitmap, heap);
163
164 DEF_VEC_P(htab_t);
165 DEF_VEC_ALLOC_P(htab_t, heap);
166
167 /* Description of memory accesses in loops.  */
168
169 static struct
170 {
171   /* The hash table of memory references accessed in loops.  */
172   htab_t refs;
173
174   /* The list of memory references.  */
175   VEC (mem_ref_p, heap) *refs_list;
176
177   /* The set of memory references accessed in each loop.  */
178   VEC (bitmap, heap) *refs_in_loop;
179
180   /* The set of memory references accessed in each loop, including
181      subloops.  */
182   VEC (bitmap, heap) *all_refs_in_loop;
183
184   /* The set of virtual operands clobbered in a given loop.  */
185   VEC (bitmap, heap) *clobbered_vops;
186
187   /* Map from the pair (loop, virtual operand) to the set of refs that
188      touch the virtual operand in the loop.  */
189   VEC (htab_t, heap) *vop_ref_map;
190
191   /* Cache for expanding memory addresses.  */
192   struct pointer_map_t *ttae_cache;
193 } memory_accesses;
194
195 static bool ref_indep_loop_p (struct loop *, mem_ref_p);
196
197 /* Minimum cost of an expensive expression.  */
198 #define LIM_EXPENSIVE ((unsigned) PARAM_VALUE (PARAM_LIM_EXPENSIVE))
199
200 /* The outermost loop for which execution of the header guarantees that the
201    block will be executed.  */
202 #define ALWAYS_EXECUTED_IN(BB) ((struct loop *) (BB)->aux)
203 #define SET_ALWAYS_EXECUTED_IN(BB, VAL) ((BB)->aux = (void *) (VAL))
204
205 static struct lim_aux_data *
206 init_lim_data (gimple stmt)
207 {
208   void **p = pointer_map_insert (lim_aux_data_map, stmt);
209
210   *p = XCNEW (struct lim_aux_data);
211   return (struct lim_aux_data *) *p;
212 }
213
214 static struct lim_aux_data *
215 get_lim_data (gimple stmt)
216 {
217   void **p = pointer_map_contains (lim_aux_data_map, stmt);
218   if (!p)
219     return NULL;
220
221   return (struct lim_aux_data *) *p;
222 }
223
224 /* Releases the memory occupied by DATA.  */
225
226 static void
227 free_lim_aux_data (struct lim_aux_data *data)
228 {
229   struct depend *dep, *next;
230
231   for (dep = data->depends; dep; dep = next)
232     {
233       next = dep->next;
234       free (dep);
235     }
236   free (data);
237 }
238
239 static void
240 clear_lim_data (gimple stmt)
241 {
242   void **p = pointer_map_contains (lim_aux_data_map, stmt);
243   if (!p)
244     return;
245
246   free_lim_aux_data ((struct lim_aux_data *) *p);
247   *p = NULL;
248 }
249
250 /* Calls CBCK for each index in memory reference ADDR_P.  There are two
251    kinds situations handled; in each of these cases, the memory reference
252    and DATA are passed to the callback:
253
254    Access to an array: ARRAY_{RANGE_}REF (base, index).  In this case we also
255    pass the pointer to the index to the callback.
256
257    Pointer dereference: INDIRECT_REF (addr).  In this case we also pass the
258    pointer to addr to the callback.
259
260    If the callback returns false, the whole search stops and false is returned.
261    Otherwise the function returns true after traversing through the whole
262    reference *ADDR_P.  */
263
264 bool
265 for_each_index (tree *addr_p, bool (*cbck) (tree, tree *, void *), void *data)
266 {
267   tree *nxt, *idx;
268
269   for (; ; addr_p = nxt)
270     {
271       switch (TREE_CODE (*addr_p))
272         {
273         case SSA_NAME:
274           return cbck (*addr_p, addr_p, data);
275
276         case MEM_REF:
277           nxt = &TREE_OPERAND (*addr_p, 0);
278           return cbck (*addr_p, nxt, data);
279
280         case BIT_FIELD_REF:
281         case VIEW_CONVERT_EXPR:
282         case REALPART_EXPR:
283         case IMAGPART_EXPR:
284           nxt = &TREE_OPERAND (*addr_p, 0);
285           break;
286
287         case COMPONENT_REF:
288           /* If the component has varying offset, it behaves like index
289              as well.  */
290           idx = &TREE_OPERAND (*addr_p, 2);
291           if (*idx
292               && !cbck (*addr_p, idx, data))
293             return false;
294
295           nxt = &TREE_OPERAND (*addr_p, 0);
296           break;
297
298         case ARRAY_REF:
299         case ARRAY_RANGE_REF:
300           nxt = &TREE_OPERAND (*addr_p, 0);
301           if (!cbck (*addr_p, &TREE_OPERAND (*addr_p, 1), data))
302             return false;
303           break;
304
305         case VAR_DECL:
306         case PARM_DECL:
307         case STRING_CST:
308         case RESULT_DECL:
309         case VECTOR_CST:
310         case COMPLEX_CST:
311         case INTEGER_CST:
312         case REAL_CST:
313         case FIXED_CST:
314         case CONSTRUCTOR:
315           return true;
316
317         case ADDR_EXPR:
318           gcc_assert (is_gimple_min_invariant (*addr_p));
319           return true;
320
321         case TARGET_MEM_REF:
322           idx = &TMR_BASE (*addr_p);
323           if (*idx
324               && !cbck (*addr_p, idx, data))
325             return false;
326           idx = &TMR_INDEX (*addr_p);
327           if (*idx
328               && !cbck (*addr_p, idx, data))
329             return false;
330           idx = &TMR_INDEX2 (*addr_p);
331           if (*idx
332               && !cbck (*addr_p, idx, data))
333             return false;
334           return true;
335
336         default:
337           gcc_unreachable ();
338         }
339     }
340 }
341
342 /* If it is possible to hoist the statement STMT unconditionally,
343    returns MOVE_POSSIBLE.
344    If it is possible to hoist the statement STMT, but we must avoid making
345    it executed if it would not be executed in the original program (e.g.
346    because it may trap), return MOVE_PRESERVE_EXECUTION.
347    Otherwise return MOVE_IMPOSSIBLE.  */
348
349 enum move_pos
350 movement_possibility (gimple stmt)
351 {
352   tree lhs;
353   enum move_pos ret = MOVE_POSSIBLE;
354
355   if (flag_unswitch_loops
356       && gimple_code (stmt) == GIMPLE_COND)
357     {
358       /* If we perform unswitching, force the operands of the invariant
359          condition to be moved out of the loop.  */
360       return MOVE_POSSIBLE;
361     }
362
363   if (gimple_code (stmt) == GIMPLE_PHI
364       && gimple_phi_num_args (stmt) <= 2
365       && is_gimple_reg (gimple_phi_result (stmt))
366       && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_phi_result (stmt)))
367     return MOVE_POSSIBLE;
368
369   if (gimple_get_lhs (stmt) == NULL_TREE)
370     return MOVE_IMPOSSIBLE;
371
372   if (gimple_vdef (stmt))
373     return MOVE_IMPOSSIBLE;
374
375   if (stmt_ends_bb_p (stmt)
376       || gimple_has_volatile_ops (stmt)
377       || gimple_has_side_effects (stmt)
378       || stmt_could_throw_p (stmt))
379     return MOVE_IMPOSSIBLE;
380
381   if (is_gimple_call (stmt))
382     {
383       /* While pure or const call is guaranteed to have no side effects, we
384          cannot move it arbitrarily.  Consider code like
385
386          char *s = something ();
387
388          while (1)
389            {
390              if (s)
391                t = strlen (s);
392              else
393                t = 0;
394            }
395
396          Here the strlen call cannot be moved out of the loop, even though
397          s is invariant.  In addition to possibly creating a call with
398          invalid arguments, moving out a function call that is not executed
399          may cause performance regressions in case the call is costly and
400          not executed at all.  */
401       ret = MOVE_PRESERVE_EXECUTION;
402       lhs = gimple_call_lhs (stmt);
403     }
404   else if (is_gimple_assign (stmt))
405     lhs = gimple_assign_lhs (stmt);
406   else
407     return MOVE_IMPOSSIBLE;
408
409   if (TREE_CODE (lhs) == SSA_NAME
410       && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
411     return MOVE_IMPOSSIBLE;
412
413   if (TREE_CODE (lhs) != SSA_NAME
414       || gimple_could_trap_p (stmt))
415     return MOVE_PRESERVE_EXECUTION;
416
417   return ret;
418 }
419
420 /* Suppose that operand DEF is used inside the LOOP.  Returns the outermost
421    loop to that we could move the expression using DEF if it did not have
422    other operands, i.e. the outermost loop enclosing LOOP in that the value
423    of DEF is invariant.  */
424
425 static struct loop *
426 outermost_invariant_loop (tree def, struct loop *loop)
427 {
428   gimple def_stmt;
429   basic_block def_bb;
430   struct loop *max_loop;
431   struct lim_aux_data *lim_data;
432
433   if (!def)
434     return superloop_at_depth (loop, 1);
435
436   if (TREE_CODE (def) != SSA_NAME)
437     {
438       gcc_assert (is_gimple_min_invariant (def));
439       return superloop_at_depth (loop, 1);
440     }
441
442   def_stmt = SSA_NAME_DEF_STMT (def);
443   def_bb = gimple_bb (def_stmt);
444   if (!def_bb)
445     return superloop_at_depth (loop, 1);
446
447   max_loop = find_common_loop (loop, def_bb->loop_father);
448
449   lim_data = get_lim_data (def_stmt);
450   if (lim_data != NULL && lim_data->max_loop != NULL)
451     max_loop = find_common_loop (max_loop,
452                                  loop_outer (lim_data->max_loop));
453   if (max_loop == loop)
454     return NULL;
455   max_loop = superloop_at_depth (loop, loop_depth (max_loop) + 1);
456
457   return max_loop;
458 }
459
460 /* DATA is a structure containing information associated with a statement
461    inside LOOP.  DEF is one of the operands of this statement.
462
463    Find the outermost loop enclosing LOOP in that value of DEF is invariant
464    and record this in DATA->max_loop field.  If DEF itself is defined inside
465    this loop as well (i.e. we need to hoist it out of the loop if we want
466    to hoist the statement represented by DATA), record the statement in that
467    DEF is defined to the DATA->depends list.  Additionally if ADD_COST is true,
468    add the cost of the computation of DEF to the DATA->cost.
469
470    If DEF is not invariant in LOOP, return false.  Otherwise return TRUE.  */
471
472 static bool
473 add_dependency (tree def, struct lim_aux_data *data, struct loop *loop,
474                 bool add_cost)
475 {
476   gimple def_stmt = SSA_NAME_DEF_STMT (def);
477   basic_block def_bb = gimple_bb (def_stmt);
478   struct loop *max_loop;
479   struct depend *dep;
480   struct lim_aux_data *def_data;
481
482   if (!def_bb)
483     return true;
484
485   max_loop = outermost_invariant_loop (def, loop);
486   if (!max_loop)
487     return false;
488
489   if (flow_loop_nested_p (data->max_loop, max_loop))
490     data->max_loop = max_loop;
491
492   def_data = get_lim_data (def_stmt);
493   if (!def_data)
494     return true;
495
496   if (add_cost
497       /* Only add the cost if the statement defining DEF is inside LOOP,
498          i.e. if it is likely that by moving the invariants dependent
499          on it, we will be able to avoid creating a new register for
500          it (since it will be only used in these dependent invariants).  */
501       && def_bb->loop_father == loop)
502     data->cost += def_data->cost;
503
504   dep = XNEW (struct depend);
505   dep->stmt = def_stmt;
506   dep->next = data->depends;
507   data->depends = dep;
508
509   return true;
510 }
511
512 /* Returns an estimate for a cost of statement STMT.  TODO -- the values here
513    are just ad-hoc constants.  The estimates should be based on target-specific
514    values.  */
515
516 static unsigned
517 stmt_cost (gimple stmt)
518 {
519   tree fndecl;
520   unsigned cost = 1;
521
522   /* Always try to create possibilities for unswitching.  */
523   if (gimple_code (stmt) == GIMPLE_COND
524       || gimple_code (stmt) == GIMPLE_PHI)
525     return LIM_EXPENSIVE;
526
527   /* Hoisting memory references out should almost surely be a win.  */
528   if (gimple_references_memory_p (stmt))
529     cost += 20;
530
531   if (is_gimple_call (stmt))
532     {
533       /* We should be hoisting calls if possible.  */
534
535       /* Unless the call is a builtin_constant_p; this always folds to a
536          constant, so moving it is useless.  */
537       fndecl = gimple_call_fndecl (stmt);
538       if (fndecl
539           && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
540           && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CONSTANT_P)
541         return 0;
542
543       return cost + 20;
544     }
545
546   if (gimple_code (stmt) != GIMPLE_ASSIGN)
547     return cost;
548
549   switch (gimple_assign_rhs_code (stmt))
550     {
551     case MULT_EXPR:
552     case TRUNC_DIV_EXPR:
553     case CEIL_DIV_EXPR:
554     case FLOOR_DIV_EXPR:
555     case ROUND_DIV_EXPR:
556     case EXACT_DIV_EXPR:
557     case CEIL_MOD_EXPR:
558     case FLOOR_MOD_EXPR:
559     case ROUND_MOD_EXPR:
560     case TRUNC_MOD_EXPR:
561     case RDIV_EXPR:
562       /* Division and multiplication are usually expensive.  */
563       cost += 20;
564       break;
565
566     case LSHIFT_EXPR:
567     case RSHIFT_EXPR:
568       cost += 20;
569       break;
570
571     default:
572       break;
573     }
574
575   return cost;
576 }
577
578 /* Finds the outermost loop between OUTER and LOOP in that the memory reference
579    REF is independent.  If REF is not independent in LOOP, NULL is returned
580    instead.  */
581
582 static struct loop *
583 outermost_indep_loop (struct loop *outer, struct loop *loop, mem_ref_p ref)
584 {
585   struct loop *aloop;
586
587   if (bitmap_bit_p (ref->stored, loop->num))
588     return NULL;
589
590   for (aloop = outer;
591        aloop != loop;
592        aloop = superloop_at_depth (loop, loop_depth (aloop) + 1))
593     if (!bitmap_bit_p (ref->stored, aloop->num)
594         && ref_indep_loop_p (aloop, ref))
595       return aloop;
596
597   if (ref_indep_loop_p (loop, ref))
598     return loop;
599   else
600     return NULL;
601 }
602
603 /* If there is a simple load or store to a memory reference in STMT, returns
604    the location of the memory reference, and sets IS_STORE according to whether
605    it is a store or load.  Otherwise, returns NULL.  */
606
607 static tree *
608 simple_mem_ref_in_stmt (gimple stmt, bool *is_store)
609 {
610   tree *lhs;
611   enum tree_code code;
612
613   /* Recognize MEM = (SSA_NAME | invariant) and SSA_NAME = MEM patterns.  */
614   if (gimple_code (stmt) != GIMPLE_ASSIGN)
615     return NULL;
616
617   code = gimple_assign_rhs_code (stmt);
618
619   lhs = gimple_assign_lhs_ptr (stmt);
620
621   if (TREE_CODE (*lhs) == SSA_NAME)
622     {
623       if (get_gimple_rhs_class (code) != GIMPLE_SINGLE_RHS
624           || !is_gimple_addressable (gimple_assign_rhs1 (stmt)))
625         return NULL;
626
627       *is_store = false;
628       return gimple_assign_rhs1_ptr (stmt);
629     }
630   else if (code == SSA_NAME
631            || (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
632                && is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
633     {
634       *is_store = true;
635       return lhs;
636     }
637   else
638     return NULL;
639 }
640
641 /* Returns the memory reference contained in STMT.  */
642
643 static mem_ref_p
644 mem_ref_in_stmt (gimple stmt)
645 {
646   bool store;
647   tree *mem = simple_mem_ref_in_stmt (stmt, &store);
648   hashval_t hash;
649   mem_ref_p ref;
650
651   if (!mem)
652     return NULL;
653   gcc_assert (!store);
654
655   hash = iterative_hash_expr (*mem, 0);
656   ref = (mem_ref_p) htab_find_with_hash (memory_accesses.refs, *mem, hash);
657
658   gcc_assert (ref != NULL);
659   return ref;
660 }
661
662 /* From a controlling predicate in DOM determine the arguments from
663    the PHI node PHI that are chosen if the predicate evaluates to
664    true and false and store them to *TRUE_ARG_P and *FALSE_ARG_P if
665    they are non-NULL.  Returns true if the arguments can be determined,
666    else return false.  */
667
668 static bool
669 extract_true_false_args_from_phi (basic_block dom, gimple phi,
670                                   tree *true_arg_p, tree *false_arg_p)
671 {
672   basic_block bb = gimple_bb (phi);
673   edge true_edge, false_edge, tem;
674   tree arg0 = NULL_TREE, arg1 = NULL_TREE;
675
676   /* We have to verify that one edge into the PHI node is dominated
677      by the true edge of the predicate block and the other edge
678      dominated by the false edge.  This ensures that the PHI argument
679      we are going to take is completely determined by the path we
680      take from the predicate block.
681      We can only use BB dominance checks below if the destination of
682      the true/false edges are dominated by their edge, thus only
683      have a single predecessor.  */
684   extract_true_false_edges_from_block (dom, &true_edge, &false_edge);
685   tem = EDGE_PRED (bb, 0);
686   if (tem == true_edge
687       || (single_pred_p (true_edge->dest)
688           && (tem->src == true_edge->dest
689               || dominated_by_p (CDI_DOMINATORS,
690                                  tem->src, true_edge->dest))))
691     arg0 = PHI_ARG_DEF (phi, tem->dest_idx);
692   else if (tem == false_edge
693            || (single_pred_p (false_edge->dest)
694                && (tem->src == false_edge->dest
695                    || dominated_by_p (CDI_DOMINATORS,
696                                       tem->src, false_edge->dest))))
697     arg1 = PHI_ARG_DEF (phi, tem->dest_idx);
698   else
699     return false;
700   tem = EDGE_PRED (bb, 1);
701   if (tem == true_edge
702       || (single_pred_p (true_edge->dest)
703           && (tem->src == true_edge->dest
704               || dominated_by_p (CDI_DOMINATORS,
705                                  tem->src, true_edge->dest))))
706     arg0 = PHI_ARG_DEF (phi, tem->dest_idx);
707   else if (tem == false_edge
708            || (single_pred_p (false_edge->dest)
709                && (tem->src == false_edge->dest
710                    || dominated_by_p (CDI_DOMINATORS,
711                                       tem->src, false_edge->dest))))
712     arg1 = PHI_ARG_DEF (phi, tem->dest_idx);
713   else
714     return false;
715   if (!arg0 || !arg1)
716     return false;
717
718   if (true_arg_p)
719     *true_arg_p = arg0;
720   if (false_arg_p)
721     *false_arg_p = arg1;
722
723   return true;
724 }
725
726 /* Determine the outermost loop to that it is possible to hoist a statement
727    STMT and store it to LIM_DATA (STMT)->max_loop.  To do this we determine
728    the outermost loop in that the value computed by STMT is invariant.
729    If MUST_PRESERVE_EXEC is true, additionally choose such a loop that
730    we preserve the fact whether STMT is executed.  It also fills other related
731    information to LIM_DATA (STMT).
732
733    The function returns false if STMT cannot be hoisted outside of the loop it
734    is defined in, and true otherwise.  */
735
736 static bool
737 determine_max_movement (gimple stmt, bool must_preserve_exec)
738 {
739   basic_block bb = gimple_bb (stmt);
740   struct loop *loop = bb->loop_father;
741   struct loop *level;
742   struct lim_aux_data *lim_data = get_lim_data (stmt);
743   tree val;
744   ssa_op_iter iter;
745
746   if (must_preserve_exec)
747     level = ALWAYS_EXECUTED_IN (bb);
748   else
749     level = superloop_at_depth (loop, 1);
750   lim_data->max_loop = level;
751
752   if (gimple_code (stmt) == GIMPLE_PHI)
753     {
754       use_operand_p use_p;
755       unsigned min_cost = UINT_MAX;
756       unsigned total_cost = 0;
757       struct lim_aux_data *def_data;
758
759       /* We will end up promoting dependencies to be unconditionally
760          evaluated.  For this reason the PHI cost (and thus the
761          cost we remove from the loop by doing the invariant motion)
762          is that of the cheapest PHI argument dependency chain.  */
763       FOR_EACH_PHI_ARG (use_p, stmt, iter, SSA_OP_USE)
764         {
765           val = USE_FROM_PTR (use_p);
766           if (TREE_CODE (val) != SSA_NAME)
767             continue;
768           if (!add_dependency (val, lim_data, loop, false))
769             return false;
770           def_data = get_lim_data (SSA_NAME_DEF_STMT (val));
771           if (def_data)
772             {
773               min_cost = MIN (min_cost, def_data->cost);
774               total_cost += def_data->cost;
775             }
776         }
777
778       lim_data->cost += min_cost;
779
780       if (gimple_phi_num_args (stmt) > 1)
781         {
782           basic_block dom = get_immediate_dominator (CDI_DOMINATORS, bb);
783           gimple cond;
784           if (gsi_end_p (gsi_last_bb (dom)))
785             return false;
786           cond = gsi_stmt (gsi_last_bb (dom));
787           if (gimple_code (cond) != GIMPLE_COND)
788             return false;
789           /* Verify that this is an extended form of a diamond and
790              the PHI arguments are completely controlled by the
791              predicate in DOM.  */
792           if (!extract_true_false_args_from_phi (dom, stmt, NULL, NULL))
793             return false;
794
795           /* Fold in dependencies and cost of the condition.  */
796           FOR_EACH_SSA_TREE_OPERAND (val, cond, iter, SSA_OP_USE)
797             {
798               if (!add_dependency (val, lim_data, loop, false))
799                 return false;
800               def_data = get_lim_data (SSA_NAME_DEF_STMT (val));
801               if (def_data)
802                 total_cost += def_data->cost;
803             }
804
805           /* We want to avoid unconditionally executing very expensive
806              operations.  As costs for our dependencies cannot be
807              negative just claim we are not invariand for this case.
808              We also are not sure whether the control-flow inside the
809              loop will vanish.  */
810           if (total_cost - min_cost >= 2 * LIM_EXPENSIVE
811               && !(min_cost != 0
812                    && total_cost / min_cost <= 2))
813             return false;
814
815           /* Assume that the control-flow in the loop will vanish.
816              ???  We should verify this and not artificially increase
817              the cost if that is not the case.  */
818           lim_data->cost += stmt_cost (stmt);
819         }
820
821       return true;
822     }
823   else
824     FOR_EACH_SSA_TREE_OPERAND (val, stmt, iter, SSA_OP_USE)
825       if (!add_dependency (val, lim_data, loop, true))
826         return false;
827
828   if (gimple_vuse (stmt))
829     {
830       mem_ref_p ref = mem_ref_in_stmt (stmt);
831
832       if (ref)
833         {
834           lim_data->max_loop
835                   = outermost_indep_loop (lim_data->max_loop, loop, ref);
836           if (!lim_data->max_loop)
837             return false;
838         }
839       else
840         {
841           if ((val = gimple_vuse (stmt)) != NULL_TREE)
842             {
843               if (!add_dependency (val, lim_data, loop, false))
844                 return false;
845             }
846         }
847     }
848
849   lim_data->cost += stmt_cost (stmt);
850
851   return true;
852 }
853
854 /* Suppose that some statement in ORIG_LOOP is hoisted to the loop LEVEL,
855    and that one of the operands of this statement is computed by STMT.
856    Ensure that STMT (together with all the statements that define its
857    operands) is hoisted at least out of the loop LEVEL.  */
858
859 static void
860 set_level (gimple stmt, struct loop *orig_loop, struct loop *level)
861 {
862   struct loop *stmt_loop = gimple_bb (stmt)->loop_father;
863   struct depend *dep;
864   struct lim_aux_data *lim_data;
865
866   stmt_loop = find_common_loop (orig_loop, stmt_loop);
867   lim_data = get_lim_data (stmt);
868   if (lim_data != NULL && lim_data->tgt_loop != NULL)
869     stmt_loop = find_common_loop (stmt_loop,
870                                   loop_outer (lim_data->tgt_loop));
871   if (flow_loop_nested_p (stmt_loop, level))
872     return;
873
874   gcc_assert (level == lim_data->max_loop
875               || flow_loop_nested_p (lim_data->max_loop, level));
876
877   lim_data->tgt_loop = level;
878   for (dep = lim_data->depends; dep; dep = dep->next)
879     set_level (dep->stmt, orig_loop, level);
880 }
881
882 /* Determines an outermost loop from that we want to hoist the statement STMT.
883    For now we chose the outermost possible loop.  TODO -- use profiling
884    information to set it more sanely.  */
885
886 static void
887 set_profitable_level (gimple stmt)
888 {
889   set_level (stmt, gimple_bb (stmt)->loop_father, get_lim_data (stmt)->max_loop);
890 }
891
892 /* Returns true if STMT is a call that has side effects.  */
893
894 static bool
895 nonpure_call_p (gimple stmt)
896 {
897   if (gimple_code (stmt) != GIMPLE_CALL)
898     return false;
899
900   return gimple_has_side_effects (stmt);
901 }
902
903 /* Rewrite a/b to a*(1/b).  Return the invariant stmt to process.  */
904
905 static gimple
906 rewrite_reciprocal (gimple_stmt_iterator *bsi)
907 {
908   gimple stmt, stmt1, stmt2;
909   tree var, name, lhs, type;
910   tree real_one;
911   gimple_stmt_iterator gsi;
912
913   stmt = gsi_stmt (*bsi);
914   lhs = gimple_assign_lhs (stmt);
915   type = TREE_TYPE (lhs);
916
917   var = create_tmp_var (type, "reciptmp");
918   add_referenced_var (var);
919   DECL_GIMPLE_REG_P (var) = 1;
920
921   real_one = build_one_cst (type);
922
923   stmt1 = gimple_build_assign_with_ops (RDIV_EXPR,
924                 var, real_one, gimple_assign_rhs2 (stmt));
925   name = make_ssa_name (var, stmt1);
926   gimple_assign_set_lhs (stmt1, name);
927
928   stmt2 = gimple_build_assign_with_ops (MULT_EXPR, lhs, name,
929                                         gimple_assign_rhs1 (stmt));
930
931   /* Replace division stmt with reciprocal and multiply stmts.
932      The multiply stmt is not invariant, so update iterator
933      and avoid rescanning.  */
934   gsi = *bsi;
935   gsi_insert_before (bsi, stmt1, GSI_NEW_STMT);
936   gsi_replace (&gsi, stmt2, true);
937
938   /* Continue processing with invariant reciprocal statement.  */
939   return stmt1;
940 }
941
942 /* Check if the pattern at *BSI is a bittest of the form
943    (A >> B) & 1 != 0 and in this case rewrite it to A & (1 << B) != 0.  */
944
945 static gimple
946 rewrite_bittest (gimple_stmt_iterator *bsi)
947 {
948   gimple stmt, use_stmt, stmt1, stmt2;
949   tree lhs, var, name, t, a, b;
950   use_operand_p use;
951
952   stmt = gsi_stmt (*bsi);
953   lhs = gimple_assign_lhs (stmt);
954
955   /* Verify that the single use of lhs is a comparison against zero.  */
956   if (TREE_CODE (lhs) != SSA_NAME
957       || !single_imm_use (lhs, &use, &use_stmt)
958       || gimple_code (use_stmt) != GIMPLE_COND)
959     return stmt;
960   if (gimple_cond_lhs (use_stmt) != lhs
961       || (gimple_cond_code (use_stmt) != NE_EXPR
962           && gimple_cond_code (use_stmt) != EQ_EXPR)
963       || !integer_zerop (gimple_cond_rhs (use_stmt)))
964     return stmt;
965
966   /* Get at the operands of the shift.  The rhs is TMP1 & 1.  */
967   stmt1 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
968   if (gimple_code (stmt1) != GIMPLE_ASSIGN)
969     return stmt;
970
971   /* There is a conversion in between possibly inserted by fold.  */
972   if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt1)))
973     {
974       t = gimple_assign_rhs1 (stmt1);
975       if (TREE_CODE (t) != SSA_NAME
976           || !has_single_use (t))
977         return stmt;
978       stmt1 = SSA_NAME_DEF_STMT (t);
979       if (gimple_code (stmt1) != GIMPLE_ASSIGN)
980         return stmt;
981     }
982
983   /* Verify that B is loop invariant but A is not.  Verify that with
984      all the stmt walking we are still in the same loop.  */
985   if (gimple_assign_rhs_code (stmt1) != RSHIFT_EXPR
986       || loop_containing_stmt (stmt1) != loop_containing_stmt (stmt))
987     return stmt;
988
989   a = gimple_assign_rhs1 (stmt1);
990   b = gimple_assign_rhs2 (stmt1);
991
992   if (outermost_invariant_loop (b, loop_containing_stmt (stmt1)) != NULL
993       && outermost_invariant_loop (a, loop_containing_stmt (stmt1)) == NULL)
994     {
995       gimple_stmt_iterator rsi;
996
997       /* 1 << B */
998       var = create_tmp_var (TREE_TYPE (a), "shifttmp");
999       add_referenced_var (var);
1000       t = fold_build2 (LSHIFT_EXPR, TREE_TYPE (a),
1001                        build_int_cst (TREE_TYPE (a), 1), b);
1002       stmt1 = gimple_build_assign (var, t);
1003       name = make_ssa_name (var, stmt1);
1004       gimple_assign_set_lhs (stmt1, name);
1005
1006       /* A & (1 << B) */
1007       t = fold_build2 (BIT_AND_EXPR, TREE_TYPE (a), a, name);
1008       stmt2 = gimple_build_assign (var, t);
1009       name = make_ssa_name (var, stmt2);
1010       gimple_assign_set_lhs (stmt2, name);
1011
1012       /* Replace the SSA_NAME we compare against zero.  Adjust
1013          the type of zero accordingly.  */
1014       SET_USE (use, name);
1015       gimple_cond_set_rhs (use_stmt, build_int_cst_type (TREE_TYPE (name), 0));
1016
1017       /* Don't use gsi_replace here, none of the new assignments sets
1018          the variable originally set in stmt.  Move bsi to stmt1, and
1019          then remove the original stmt, so that we get a chance to
1020          retain debug info for it.  */
1021       rsi = *bsi;
1022       gsi_insert_before (bsi, stmt1, GSI_NEW_STMT);
1023       gsi_insert_before (&rsi, stmt2, GSI_SAME_STMT);
1024       gsi_remove (&rsi, true);
1025
1026       return stmt1;
1027     }
1028
1029   return stmt;
1030 }
1031
1032
1033 /* Determine the outermost loops in that statements in basic block BB are
1034    invariant, and record them to the LIM_DATA associated with the statements.
1035    Callback for walk_dominator_tree.  */
1036
1037 static void
1038 determine_invariantness_stmt (struct dom_walk_data *dw_data ATTRIBUTE_UNUSED,
1039                               basic_block bb)
1040 {
1041   enum move_pos pos;
1042   gimple_stmt_iterator bsi;
1043   gimple stmt;
1044   bool maybe_never = ALWAYS_EXECUTED_IN (bb) == NULL;
1045   struct loop *outermost = ALWAYS_EXECUTED_IN (bb);
1046   struct lim_aux_data *lim_data;
1047
1048   if (!loop_outer (bb->loop_father))
1049     return;
1050
1051   if (dump_file && (dump_flags & TDF_DETAILS))
1052     fprintf (dump_file, "Basic block %d (loop %d -- depth %d):\n\n",
1053              bb->index, bb->loop_father->num, loop_depth (bb->loop_father));
1054
1055   /* Look at PHI nodes, but only if there is at most two.
1056      ???  We could relax this further by post-processing the inserted
1057      code and transforming adjacent cond-exprs with the same predicate
1058      to control flow again.  */
1059   bsi = gsi_start_phis (bb);
1060   if (!gsi_end_p (bsi)
1061       && ((gsi_next (&bsi), gsi_end_p (bsi))
1062           || (gsi_next (&bsi), gsi_end_p (bsi))))
1063     for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1064       {
1065         stmt = gsi_stmt (bsi);
1066
1067         pos = movement_possibility (stmt);
1068         if (pos == MOVE_IMPOSSIBLE)
1069           continue;
1070
1071         lim_data = init_lim_data (stmt);
1072         lim_data->always_executed_in = outermost;
1073
1074         if (!determine_max_movement (stmt, false))
1075           {
1076             lim_data->max_loop = NULL;
1077             continue;
1078           }
1079
1080         if (dump_file && (dump_flags & TDF_DETAILS))
1081           {
1082             print_gimple_stmt (dump_file, stmt, 2, 0);
1083             fprintf (dump_file, "  invariant up to level %d, cost %d.\n\n",
1084                      loop_depth (lim_data->max_loop),
1085                      lim_data->cost);
1086           }
1087
1088         if (lim_data->cost >= LIM_EXPENSIVE)
1089           set_profitable_level (stmt);
1090       }
1091
1092   for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1093     {
1094       stmt = gsi_stmt (bsi);
1095
1096       pos = movement_possibility (stmt);
1097       if (pos == MOVE_IMPOSSIBLE)
1098         {
1099           if (nonpure_call_p (stmt))
1100             {
1101               maybe_never = true;
1102               outermost = NULL;
1103             }
1104           /* Make sure to note always_executed_in for stores to make
1105              store-motion work.  */
1106           else if (stmt_makes_single_store (stmt))
1107             {
1108               struct lim_aux_data *lim_data = init_lim_data (stmt);
1109               lim_data->always_executed_in = outermost;
1110             }
1111           continue;
1112         }
1113
1114       if (is_gimple_assign (stmt)
1115           && (get_gimple_rhs_class (gimple_assign_rhs_code (stmt))
1116               == GIMPLE_BINARY_RHS))
1117         {
1118           tree op0 = gimple_assign_rhs1 (stmt);
1119           tree op1 = gimple_assign_rhs2 (stmt);
1120           struct loop *ol1 = outermost_invariant_loop (op1,
1121                                         loop_containing_stmt (stmt));
1122
1123           /* If divisor is invariant, convert a/b to a*(1/b), allowing reciprocal
1124              to be hoisted out of loop, saving expensive divide.  */
1125           if (pos == MOVE_POSSIBLE
1126               && gimple_assign_rhs_code (stmt) == RDIV_EXPR
1127               && flag_unsafe_math_optimizations
1128               && !flag_trapping_math
1129               && ol1 != NULL
1130               && outermost_invariant_loop (op0, ol1) == NULL)
1131             stmt = rewrite_reciprocal (&bsi);
1132
1133           /* If the shift count is invariant, convert (A >> B) & 1 to
1134              A & (1 << B) allowing the bit mask to be hoisted out of the loop
1135              saving an expensive shift.  */
1136           if (pos == MOVE_POSSIBLE
1137               && gimple_assign_rhs_code (stmt) == BIT_AND_EXPR
1138               && integer_onep (op1)
1139               && TREE_CODE (op0) == SSA_NAME
1140               && has_single_use (op0))
1141             stmt = rewrite_bittest (&bsi);
1142         }
1143
1144       lim_data = init_lim_data (stmt);
1145       lim_data->always_executed_in = outermost;
1146
1147       if (maybe_never && pos == MOVE_PRESERVE_EXECUTION)
1148         continue;
1149
1150       if (!determine_max_movement (stmt, pos == MOVE_PRESERVE_EXECUTION))
1151         {
1152           lim_data->max_loop = NULL;
1153           continue;
1154         }
1155
1156       if (dump_file && (dump_flags & TDF_DETAILS))
1157         {
1158           print_gimple_stmt (dump_file, stmt, 2, 0);
1159           fprintf (dump_file, "  invariant up to level %d, cost %d.\n\n",
1160                    loop_depth (lim_data->max_loop),
1161                    lim_data->cost);
1162         }
1163
1164       if (lim_data->cost >= LIM_EXPENSIVE)
1165         set_profitable_level (stmt);
1166     }
1167 }
1168
1169 /* For each statement determines the outermost loop in that it is invariant,
1170    statements on whose motion it depends and the cost of the computation.
1171    This information is stored to the LIM_DATA structure associated with
1172    each statement.  */
1173
1174 static void
1175 determine_invariantness (void)
1176 {
1177   struct dom_walk_data walk_data;
1178
1179   memset (&walk_data, 0, sizeof (struct dom_walk_data));
1180   walk_data.dom_direction = CDI_DOMINATORS;
1181   walk_data.before_dom_children = determine_invariantness_stmt;
1182
1183   init_walk_dominator_tree (&walk_data);
1184   walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1185   fini_walk_dominator_tree (&walk_data);
1186 }
1187
1188 /* Hoist the statements in basic block BB out of the loops prescribed by
1189    data stored in LIM_DATA structures associated with each statement.  Callback
1190    for walk_dominator_tree.  */
1191
1192 static void
1193 move_computations_stmt (struct dom_walk_data *dw_data,
1194                         basic_block bb)
1195 {
1196   struct loop *level;
1197   gimple_stmt_iterator bsi;
1198   gimple stmt;
1199   unsigned cost = 0;
1200   struct lim_aux_data *lim_data;
1201
1202   if (!loop_outer (bb->loop_father))
1203     return;
1204
1205   for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); )
1206     {
1207       gimple new_stmt;
1208       stmt = gsi_stmt (bsi);
1209
1210       lim_data = get_lim_data (stmt);
1211       if (lim_data == NULL)
1212         {
1213           gsi_next (&bsi);
1214           continue;
1215         }
1216
1217       cost = lim_data->cost;
1218       level = lim_data->tgt_loop;
1219       clear_lim_data (stmt);
1220
1221       if (!level)
1222         {
1223           gsi_next (&bsi);
1224           continue;
1225         }
1226
1227       if (dump_file && (dump_flags & TDF_DETAILS))
1228         {
1229           fprintf (dump_file, "Moving PHI node\n");
1230           print_gimple_stmt (dump_file, stmt, 0, 0);
1231           fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
1232                    cost, level->num);
1233         }
1234
1235       if (gimple_phi_num_args (stmt) == 1)
1236         {
1237           tree arg = PHI_ARG_DEF (stmt, 0);
1238           new_stmt = gimple_build_assign_with_ops (TREE_CODE (arg),
1239                                                    gimple_phi_result (stmt),
1240                                                    arg, NULL_TREE);
1241           SSA_NAME_DEF_STMT (gimple_phi_result (stmt)) = new_stmt;
1242         }
1243       else
1244         {
1245           basic_block dom = get_immediate_dominator (CDI_DOMINATORS, bb);
1246           gimple cond = gsi_stmt (gsi_last_bb (dom));
1247           tree arg0 = NULL_TREE, arg1 = NULL_TREE, t;
1248           /* Get the PHI arguments corresponding to the true and false
1249              edges of COND.  */
1250           extract_true_false_args_from_phi (dom, stmt, &arg0, &arg1);
1251           gcc_assert (arg0 && arg1);
1252           t = build2 (gimple_cond_code (cond), boolean_type_node,
1253                       gimple_cond_lhs (cond), gimple_cond_rhs (cond));
1254           t = build3 (COND_EXPR, TREE_TYPE (gimple_phi_result (stmt)),
1255                       t, arg0, arg1);
1256           new_stmt = gimple_build_assign_with_ops (COND_EXPR,
1257                                                    gimple_phi_result (stmt),
1258                                                    t, NULL_TREE);
1259           SSA_NAME_DEF_STMT (gimple_phi_result (stmt)) = new_stmt;
1260           *((unsigned int *)(dw_data->global_data)) |= TODO_cleanup_cfg;
1261         }
1262       gsi_insert_on_edge (loop_preheader_edge (level), new_stmt);
1263       remove_phi_node (&bsi, false);
1264     }
1265
1266   for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); )
1267     {
1268       stmt = gsi_stmt (bsi);
1269
1270       lim_data = get_lim_data (stmt);
1271       if (lim_data == NULL)
1272         {
1273           gsi_next (&bsi);
1274           continue;
1275         }
1276
1277       cost = lim_data->cost;
1278       level = lim_data->tgt_loop;
1279       clear_lim_data (stmt);
1280
1281       if (!level)
1282         {
1283           gsi_next (&bsi);
1284           continue;
1285         }
1286
1287       /* We do not really want to move conditionals out of the loop; we just
1288          placed it here to force its operands to be moved if necessary.  */
1289       if (gimple_code (stmt) == GIMPLE_COND)
1290         continue;
1291
1292       if (dump_file && (dump_flags & TDF_DETAILS))
1293         {
1294           fprintf (dump_file, "Moving statement\n");
1295           print_gimple_stmt (dump_file, stmt, 0, 0);
1296           fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
1297                    cost, level->num);
1298         }
1299
1300       mark_virtual_ops_for_renaming (stmt);
1301       gsi_insert_on_edge (loop_preheader_edge (level), stmt);
1302       gsi_remove (&bsi, false);
1303     }
1304 }
1305
1306 /* Hoist the statements out of the loops prescribed by data stored in
1307    LIM_DATA structures associated with each statement.*/
1308
1309 static unsigned int
1310 move_computations (void)
1311 {
1312   struct dom_walk_data walk_data;
1313   unsigned int todo = 0;
1314
1315   memset (&walk_data, 0, sizeof (struct dom_walk_data));
1316   walk_data.global_data = &todo;
1317   walk_data.dom_direction = CDI_DOMINATORS;
1318   walk_data.before_dom_children = move_computations_stmt;
1319
1320   init_walk_dominator_tree (&walk_data);
1321   walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1322   fini_walk_dominator_tree (&walk_data);
1323
1324   gsi_commit_edge_inserts ();
1325   if (need_ssa_update_p (cfun))
1326     rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
1327
1328   return todo;
1329 }
1330
1331 /* Checks whether the statement defining variable *INDEX can be hoisted
1332    out of the loop passed in DATA.  Callback for for_each_index.  */
1333
1334 static bool
1335 may_move_till (tree ref, tree *index, void *data)
1336 {
1337   struct loop *loop = (struct loop *) data, *max_loop;
1338
1339   /* If REF is an array reference, check also that the step and the lower
1340      bound is invariant in LOOP.  */
1341   if (TREE_CODE (ref) == ARRAY_REF)
1342     {
1343       tree step = TREE_OPERAND (ref, 3);
1344       tree lbound = TREE_OPERAND (ref, 2);
1345
1346       max_loop = outermost_invariant_loop (step, loop);
1347       if (!max_loop)
1348         return false;
1349
1350       max_loop = outermost_invariant_loop (lbound, loop);
1351       if (!max_loop)
1352         return false;
1353     }
1354
1355   max_loop = outermost_invariant_loop (*index, loop);
1356   if (!max_loop)
1357     return false;
1358
1359   return true;
1360 }
1361
1362 /* If OP is SSA NAME, force the statement that defines it to be
1363    moved out of the LOOP.  ORIG_LOOP is the loop in that EXPR is used.  */
1364
1365 static void
1366 force_move_till_op (tree op, struct loop *orig_loop, struct loop *loop)
1367 {
1368   gimple stmt;
1369
1370   if (!op
1371       || is_gimple_min_invariant (op))
1372     return;
1373
1374   gcc_assert (TREE_CODE (op) == SSA_NAME);
1375
1376   stmt = SSA_NAME_DEF_STMT (op);
1377   if (gimple_nop_p (stmt))
1378     return;
1379
1380   set_level (stmt, orig_loop, loop);
1381 }
1382
1383 /* Forces statement defining invariants in REF (and *INDEX) to be moved out of
1384    the LOOP.  The reference REF is used in the loop ORIG_LOOP.  Callback for
1385    for_each_index.  */
1386
1387 struct fmt_data
1388 {
1389   struct loop *loop;
1390   struct loop *orig_loop;
1391 };
1392
1393 static bool
1394 force_move_till (tree ref, tree *index, void *data)
1395 {
1396   struct fmt_data *fmt_data = (struct fmt_data *) data;
1397
1398   if (TREE_CODE (ref) == ARRAY_REF)
1399     {
1400       tree step = TREE_OPERAND (ref, 3);
1401       tree lbound = TREE_OPERAND (ref, 2);
1402
1403       force_move_till_op (step, fmt_data->orig_loop, fmt_data->loop);
1404       force_move_till_op (lbound, fmt_data->orig_loop, fmt_data->loop);
1405     }
1406
1407   force_move_till_op (*index, fmt_data->orig_loop, fmt_data->loop);
1408
1409   return true;
1410 }
1411
1412 /* A hash function for struct mem_ref object OBJ.  */
1413
1414 static hashval_t
1415 memref_hash (const void *obj)
1416 {
1417   const struct mem_ref *const mem = (const struct mem_ref *) obj;
1418
1419   return mem->hash;
1420 }
1421
1422 /* An equality function for struct mem_ref object OBJ1 with
1423    memory reference OBJ2.  */
1424
1425 static int
1426 memref_eq (const void *obj1, const void *obj2)
1427 {
1428   const struct mem_ref *const mem1 = (const struct mem_ref *) obj1;
1429
1430   return operand_equal_p (mem1->mem, (const_tree) obj2, 0);
1431 }
1432
1433 /* Releases list of memory reference locations ACCS.  */
1434
1435 static void
1436 free_mem_ref_locs (mem_ref_locs_p accs)
1437 {
1438   unsigned i;
1439   mem_ref_loc_p loc;
1440
1441   if (!accs)
1442     return;
1443
1444   FOR_EACH_VEC_ELT (mem_ref_loc_p, accs->locs, i, loc)
1445     free (loc);
1446   VEC_free (mem_ref_loc_p, heap, accs->locs);
1447   free (accs);
1448 }
1449
1450 /* A function to free the mem_ref object OBJ.  */
1451
1452 static void
1453 memref_free (void *obj)
1454 {
1455   struct mem_ref *const mem = (struct mem_ref *) obj;
1456   unsigned i;
1457   mem_ref_locs_p accs;
1458
1459   BITMAP_FREE (mem->stored);
1460   BITMAP_FREE (mem->indep_loop);
1461   BITMAP_FREE (mem->dep_loop);
1462   BITMAP_FREE (mem->indep_ref);
1463   BITMAP_FREE (mem->dep_ref);
1464
1465   FOR_EACH_VEC_ELT (mem_ref_locs_p, mem->accesses_in_loop, i, accs)
1466     free_mem_ref_locs (accs);
1467   VEC_free (mem_ref_locs_p, heap, mem->accesses_in_loop);
1468
1469   BITMAP_FREE (mem->vops);
1470   free (mem);
1471 }
1472
1473 /* Allocates and returns a memory reference description for MEM whose hash
1474    value is HASH and id is ID.  */
1475
1476 static mem_ref_p
1477 mem_ref_alloc (tree mem, unsigned hash, unsigned id)
1478 {
1479   mem_ref_p ref = XNEW (struct mem_ref);
1480   ref->mem = mem;
1481   ref->id = id;
1482   ref->hash = hash;
1483   ref->stored = BITMAP_ALLOC (NULL);
1484   ref->indep_loop = BITMAP_ALLOC (NULL);
1485   ref->dep_loop = BITMAP_ALLOC (NULL);
1486   ref->indep_ref = BITMAP_ALLOC (NULL);
1487   ref->dep_ref = BITMAP_ALLOC (NULL);
1488   ref->accesses_in_loop = NULL;
1489   ref->vops = BITMAP_ALLOC (NULL);
1490
1491   return ref;
1492 }
1493
1494 /* Allocates and returns the new list of locations.  */
1495
1496 static mem_ref_locs_p
1497 mem_ref_locs_alloc (void)
1498 {
1499   mem_ref_locs_p accs = XNEW (struct mem_ref_locs);
1500   accs->locs = NULL;
1501   return accs;
1502 }
1503
1504 /* Records memory reference location *LOC in LOOP to the memory reference
1505    description REF.  The reference occurs in statement STMT.  */
1506
1507 static void
1508 record_mem_ref_loc (mem_ref_p ref, struct loop *loop, gimple stmt, tree *loc)
1509 {
1510   mem_ref_loc_p aref = XNEW (struct mem_ref_loc);
1511   mem_ref_locs_p accs;
1512   bitmap ril = VEC_index (bitmap, memory_accesses.refs_in_loop, loop->num);
1513
1514   if (VEC_length (mem_ref_locs_p, ref->accesses_in_loop)
1515       <= (unsigned) loop->num)
1516     VEC_safe_grow_cleared (mem_ref_locs_p, heap, ref->accesses_in_loop,
1517                            loop->num + 1);
1518   accs = VEC_index (mem_ref_locs_p, ref->accesses_in_loop, loop->num);
1519   if (!accs)
1520     {
1521       accs = mem_ref_locs_alloc ();
1522       VEC_replace (mem_ref_locs_p, ref->accesses_in_loop, loop->num, accs);
1523     }
1524
1525   aref->stmt = stmt;
1526   aref->ref = loc;
1527
1528   VEC_safe_push (mem_ref_loc_p, heap, accs->locs, aref);
1529   bitmap_set_bit (ril, ref->id);
1530 }
1531
1532 /* Marks reference REF as stored in LOOP.  */
1533
1534 static void
1535 mark_ref_stored (mem_ref_p ref, struct loop *loop)
1536 {
1537   for (;
1538        loop != current_loops->tree_root
1539        && !bitmap_bit_p (ref->stored, loop->num);
1540        loop = loop_outer (loop))
1541     bitmap_set_bit (ref->stored, loop->num);
1542 }
1543
1544 /* Gathers memory references in statement STMT in LOOP, storing the
1545    information about them in the memory_accesses structure.  Marks
1546    the vops accessed through unrecognized statements there as
1547    well.  */
1548
1549 static void
1550 gather_mem_refs_stmt (struct loop *loop, gimple stmt)
1551 {
1552   tree *mem = NULL;
1553   hashval_t hash;
1554   PTR *slot;
1555   mem_ref_p ref;
1556   tree vname;
1557   bool is_stored;
1558   bitmap clvops;
1559   unsigned id;
1560
1561   if (!gimple_vuse (stmt))
1562     return;
1563
1564   mem = simple_mem_ref_in_stmt (stmt, &is_stored);
1565   if (!mem)
1566     goto fail;
1567
1568   hash = iterative_hash_expr (*mem, 0);
1569   slot = htab_find_slot_with_hash (memory_accesses.refs, *mem, hash, INSERT);
1570
1571   if (*slot)
1572     {
1573       ref = (mem_ref_p) *slot;
1574       id = ref->id;
1575     }
1576   else
1577     {
1578       id = VEC_length (mem_ref_p, memory_accesses.refs_list);
1579       ref = mem_ref_alloc (*mem, hash, id);
1580       VEC_safe_push (mem_ref_p, heap, memory_accesses.refs_list, ref);
1581       *slot = ref;
1582
1583       if (dump_file && (dump_flags & TDF_DETAILS))
1584         {
1585           fprintf (dump_file, "Memory reference %u: ", id);
1586           print_generic_expr (dump_file, ref->mem, TDF_SLIM);
1587           fprintf (dump_file, "\n");
1588         }
1589     }
1590   if (is_stored)
1591     mark_ref_stored (ref, loop);
1592
1593   if ((vname = gimple_vuse (stmt)) != NULL_TREE)
1594     bitmap_set_bit (ref->vops, DECL_UID (SSA_NAME_VAR (vname)));
1595   record_mem_ref_loc (ref, loop, stmt, mem);
1596   return;
1597
1598 fail:
1599   clvops = VEC_index (bitmap, memory_accesses.clobbered_vops, loop->num);
1600   if ((vname = gimple_vuse (stmt)) != NULL_TREE)
1601     bitmap_set_bit (clvops, DECL_UID (SSA_NAME_VAR (vname)));
1602 }
1603
1604 /* Gathers memory references in loops.  */
1605
1606 static void
1607 gather_mem_refs_in_loops (void)
1608 {
1609   gimple_stmt_iterator bsi;
1610   basic_block bb;
1611   struct loop *loop;
1612   loop_iterator li;
1613   bitmap clvo, clvi;
1614   bitmap lrefs, alrefs, alrefso;
1615
1616   FOR_EACH_BB (bb)
1617     {
1618       loop = bb->loop_father;
1619       if (loop == current_loops->tree_root)
1620         continue;
1621
1622       for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1623         gather_mem_refs_stmt (loop, gsi_stmt (bsi));
1624     }
1625
1626   /* Propagate the information about clobbered vops and accessed memory
1627      references up the loop hierarchy.  */
1628   FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
1629     {
1630       lrefs = VEC_index (bitmap, memory_accesses.refs_in_loop, loop->num);
1631       alrefs = VEC_index (bitmap, memory_accesses.all_refs_in_loop, loop->num);
1632       bitmap_ior_into (alrefs, lrefs);
1633
1634       if (loop_outer (loop) == current_loops->tree_root)
1635         continue;
1636
1637       clvi = VEC_index (bitmap, memory_accesses.clobbered_vops, loop->num);
1638       clvo = VEC_index (bitmap, memory_accesses.clobbered_vops,
1639                         loop_outer (loop)->num);
1640       bitmap_ior_into (clvo, clvi);
1641
1642       alrefso = VEC_index (bitmap, memory_accesses.all_refs_in_loop,
1643                            loop_outer (loop)->num);
1644       bitmap_ior_into (alrefso, alrefs);
1645     }
1646 }
1647
1648 /* Element of the hash table that maps vops to memory references.  */
1649
1650 struct vop_to_refs_elt
1651 {
1652   /* DECL_UID of the vop.  */
1653   unsigned uid;
1654
1655   /* List of the all references.  */
1656   bitmap refs_all;
1657
1658   /* List of stored references.  */
1659   bitmap refs_stored;
1660 };
1661
1662 /* A hash function for struct vop_to_refs_elt object OBJ.  */
1663
1664 static hashval_t
1665 vtoe_hash (const void *obj)
1666 {
1667   const struct vop_to_refs_elt *const vtoe =
1668     (const struct vop_to_refs_elt *) obj;
1669
1670   return vtoe->uid;
1671 }
1672
1673 /* An equality function for struct vop_to_refs_elt object OBJ1 with
1674    uid of a vop OBJ2.  */
1675
1676 static int
1677 vtoe_eq (const void *obj1, const void *obj2)
1678 {
1679   const struct vop_to_refs_elt *const vtoe =
1680     (const struct vop_to_refs_elt *) obj1;
1681   const unsigned *const uid = (const unsigned *) obj2;
1682
1683   return vtoe->uid == *uid;
1684 }
1685
1686 /* A function to free the struct vop_to_refs_elt object.  */
1687
1688 static void
1689 vtoe_free (void *obj)
1690 {
1691   struct vop_to_refs_elt *const vtoe =
1692     (struct vop_to_refs_elt *) obj;
1693
1694   BITMAP_FREE (vtoe->refs_all);
1695   BITMAP_FREE (vtoe->refs_stored);
1696   free (vtoe);
1697 }
1698
1699 /* Records REF to hashtable VOP_TO_REFS for the index VOP.  STORED is true
1700    if the reference REF is stored.  */
1701
1702 static void
1703 record_vop_access (htab_t vop_to_refs, unsigned vop, unsigned ref, bool stored)
1704 {
1705   void **slot = htab_find_slot_with_hash (vop_to_refs, &vop, vop, INSERT);
1706   struct vop_to_refs_elt *vtoe;
1707
1708   if (!*slot)
1709     {
1710       vtoe = XNEW (struct vop_to_refs_elt);
1711       vtoe->uid = vop;
1712       vtoe->refs_all = BITMAP_ALLOC (NULL);
1713       vtoe->refs_stored = BITMAP_ALLOC (NULL);
1714       *slot = vtoe;
1715     }
1716   else
1717     vtoe = (struct vop_to_refs_elt *) *slot;
1718
1719   bitmap_set_bit (vtoe->refs_all, ref);
1720   if (stored)
1721     bitmap_set_bit (vtoe->refs_stored, ref);
1722 }
1723
1724 /* Returns the set of references that access VOP according to the table
1725    VOP_TO_REFS.  */
1726
1727 static bitmap
1728 get_vop_accesses (htab_t vop_to_refs, unsigned vop)
1729 {
1730   struct vop_to_refs_elt *const vtoe =
1731     (struct vop_to_refs_elt *) htab_find_with_hash (vop_to_refs, &vop, vop);
1732   return vtoe->refs_all;
1733 }
1734
1735 /* Returns the set of stores that access VOP according to the table
1736    VOP_TO_REFS.  */
1737
1738 static bitmap
1739 get_vop_stores (htab_t vop_to_refs, unsigned vop)
1740 {
1741   struct vop_to_refs_elt *const vtoe =
1742     (struct vop_to_refs_elt *) htab_find_with_hash (vop_to_refs, &vop, vop);
1743   return vtoe->refs_stored;
1744 }
1745
1746 /* Adds REF to mapping from virtual operands to references in LOOP.  */
1747
1748 static void
1749 add_vop_ref_mapping (struct loop *loop, mem_ref_p ref)
1750 {
1751   htab_t map = VEC_index (htab_t, memory_accesses.vop_ref_map, loop->num);
1752   bool stored = bitmap_bit_p (ref->stored, loop->num);
1753   bitmap clobbers = VEC_index (bitmap, memory_accesses.clobbered_vops,
1754                                loop->num);
1755   bitmap_iterator bi;
1756   unsigned vop;
1757
1758   EXECUTE_IF_AND_COMPL_IN_BITMAP (ref->vops, clobbers, 0, vop, bi)
1759     {
1760       record_vop_access (map, vop, ref->id, stored);
1761     }
1762 }
1763
1764 /* Create a mapping from virtual operands to references that touch them
1765    in LOOP.  */
1766
1767 static void
1768 create_vop_ref_mapping_loop (struct loop *loop)
1769 {
1770   bitmap refs = VEC_index (bitmap, memory_accesses.refs_in_loop, loop->num);
1771   struct loop *sloop;
1772   bitmap_iterator bi;
1773   unsigned i;
1774   mem_ref_p ref;
1775
1776   EXECUTE_IF_SET_IN_BITMAP (refs, 0, i, bi)
1777     {
1778       ref = VEC_index (mem_ref_p, memory_accesses.refs_list, i);
1779       for (sloop = loop; sloop != current_loops->tree_root; sloop = loop_outer (sloop))
1780         add_vop_ref_mapping (sloop, ref);
1781     }
1782 }
1783
1784 /* For each non-clobbered virtual operand and each loop, record the memory
1785    references in this loop that touch the operand.  */
1786
1787 static void
1788 create_vop_ref_mapping (void)
1789 {
1790   loop_iterator li;
1791   struct loop *loop;
1792
1793   FOR_EACH_LOOP (li, loop, 0)
1794     {
1795       create_vop_ref_mapping_loop (loop);
1796     }
1797 }
1798
1799 /* Gathers information about memory accesses in the loops.  */
1800
1801 static void
1802 analyze_memory_references (void)
1803 {
1804   unsigned i;
1805   bitmap empty;
1806   htab_t hempty;
1807
1808   memory_accesses.refs
1809           = htab_create (100, memref_hash, memref_eq, memref_free);
1810   memory_accesses.refs_list = NULL;
1811   memory_accesses.refs_in_loop = VEC_alloc (bitmap, heap,
1812                                             number_of_loops ());
1813   memory_accesses.all_refs_in_loop = VEC_alloc (bitmap, heap,
1814                                                 number_of_loops ());
1815   memory_accesses.clobbered_vops = VEC_alloc (bitmap, heap,
1816                                               number_of_loops ());
1817   memory_accesses.vop_ref_map = VEC_alloc (htab_t, heap,
1818                                            number_of_loops ());
1819
1820   for (i = 0; i < number_of_loops (); i++)
1821     {
1822       empty = BITMAP_ALLOC (NULL);
1823       VEC_quick_push (bitmap, memory_accesses.refs_in_loop, empty);
1824       empty = BITMAP_ALLOC (NULL);
1825       VEC_quick_push (bitmap, memory_accesses.all_refs_in_loop, empty);
1826       empty = BITMAP_ALLOC (NULL);
1827       VEC_quick_push (bitmap, memory_accesses.clobbered_vops, empty);
1828       hempty = htab_create (10, vtoe_hash, vtoe_eq, vtoe_free);
1829       VEC_quick_push (htab_t, memory_accesses.vop_ref_map, hempty);
1830     }
1831
1832   memory_accesses.ttae_cache = NULL;
1833
1834   gather_mem_refs_in_loops ();
1835   create_vop_ref_mapping ();
1836 }
1837
1838 /* Returns true if a region of size SIZE1 at position 0 and a region of
1839    size SIZE2 at position DIFF cannot overlap.  */
1840
1841 static bool
1842 cannot_overlap_p (aff_tree *diff, double_int size1, double_int size2)
1843 {
1844   double_int d, bound;
1845
1846   /* Unless the difference is a constant, we fail.  */
1847   if (diff->n != 0)
1848     return false;
1849
1850   d = diff->offset;
1851   if (double_int_negative_p (d))
1852     {
1853       /* The second object is before the first one, we succeed if the last
1854          element of the second object is before the start of the first one.  */
1855       bound = double_int_add (d, double_int_add (size2, double_int_minus_one));
1856       return double_int_negative_p (bound);
1857     }
1858   else
1859     {
1860       /* We succeed if the second object starts after the first one ends.  */
1861       return double_int_scmp (size1, d) <= 0;
1862     }
1863 }
1864
1865 /* Returns true if MEM1 and MEM2 may alias.  TTAE_CACHE is used as a cache in
1866    tree_to_aff_combination_expand.  */
1867
1868 static bool
1869 mem_refs_may_alias_p (tree mem1, tree mem2, struct pointer_map_t **ttae_cache)
1870 {
1871   /* Perform BASE + OFFSET analysis -- if MEM1 and MEM2 are based on the same
1872      object and their offset differ in such a way that the locations cannot
1873      overlap, then they cannot alias.  */
1874   double_int size1, size2;
1875   aff_tree off1, off2;
1876
1877   /* Perform basic offset and type-based disambiguation.  */
1878   if (!refs_may_alias_p (mem1, mem2))
1879     return false;
1880
1881   /* The expansion of addresses may be a bit expensive, thus we only do
1882      the check at -O2 and higher optimization levels.  */
1883   if (optimize < 2)
1884     return true;
1885
1886   get_inner_reference_aff (mem1, &off1, &size1);
1887   get_inner_reference_aff (mem2, &off2, &size2);
1888   aff_combination_expand (&off1, ttae_cache);
1889   aff_combination_expand (&off2, ttae_cache);
1890   aff_combination_scale (&off1, double_int_minus_one);
1891   aff_combination_add (&off2, &off1);
1892
1893   if (cannot_overlap_p (&off2, size1, size2))
1894     return false;
1895
1896   return true;
1897 }
1898
1899 /* Rewrites location LOC by TMP_VAR.  */
1900
1901 static void
1902 rewrite_mem_ref_loc (mem_ref_loc_p loc, tree tmp_var)
1903 {
1904   mark_virtual_ops_for_renaming (loc->stmt);
1905   *loc->ref = tmp_var;
1906   update_stmt (loc->stmt);
1907 }
1908
1909 /* Adds all locations of REF in LOOP and its subloops to LOCS.  */
1910
1911 static void
1912 get_all_locs_in_loop (struct loop *loop, mem_ref_p ref,
1913                       VEC (mem_ref_loc_p, heap) **locs)
1914 {
1915   mem_ref_locs_p accs;
1916   unsigned i;
1917   mem_ref_loc_p loc;
1918   bitmap refs = VEC_index (bitmap, memory_accesses.all_refs_in_loop,
1919                            loop->num);
1920   struct loop *subloop;
1921
1922   if (!bitmap_bit_p (refs, ref->id))
1923     return;
1924
1925   if (VEC_length (mem_ref_locs_p, ref->accesses_in_loop)
1926       > (unsigned) loop->num)
1927     {
1928       accs = VEC_index (mem_ref_locs_p, ref->accesses_in_loop, loop->num);
1929       if (accs)
1930         {
1931           FOR_EACH_VEC_ELT (mem_ref_loc_p, accs->locs, i, loc)
1932             VEC_safe_push (mem_ref_loc_p, heap, *locs, loc);
1933         }
1934     }
1935
1936   for (subloop = loop->inner; subloop != NULL; subloop = subloop->next)
1937     get_all_locs_in_loop (subloop, ref, locs);
1938 }
1939
1940 /* Rewrites all references to REF in LOOP by variable TMP_VAR.  */
1941
1942 static void
1943 rewrite_mem_refs (struct loop *loop, mem_ref_p ref, tree tmp_var)
1944 {
1945   unsigned i;
1946   mem_ref_loc_p loc;
1947   VEC (mem_ref_loc_p, heap) *locs = NULL;
1948
1949   get_all_locs_in_loop (loop, ref, &locs);
1950   FOR_EACH_VEC_ELT (mem_ref_loc_p, locs, i, loc)
1951     rewrite_mem_ref_loc (loc, tmp_var);
1952   VEC_free (mem_ref_loc_p, heap, locs);
1953 }
1954
1955 /* The name and the length of the currently generated variable
1956    for lsm.  */
1957 #define MAX_LSM_NAME_LENGTH 40
1958 static char lsm_tmp_name[MAX_LSM_NAME_LENGTH + 1];
1959 static int lsm_tmp_name_length;
1960
1961 /* Adds S to lsm_tmp_name.  */
1962
1963 static void
1964 lsm_tmp_name_add (const char *s)
1965 {
1966   int l = strlen (s) + lsm_tmp_name_length;
1967   if (l > MAX_LSM_NAME_LENGTH)
1968     return;
1969
1970   strcpy (lsm_tmp_name + lsm_tmp_name_length, s);
1971   lsm_tmp_name_length = l;
1972 }
1973
1974 /* Stores the name for temporary variable that replaces REF to
1975    lsm_tmp_name.  */
1976
1977 static void
1978 gen_lsm_tmp_name (tree ref)
1979 {
1980   const char *name;
1981
1982   switch (TREE_CODE (ref))
1983     {
1984     case MEM_REF:
1985     case TARGET_MEM_REF:
1986       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1987       lsm_tmp_name_add ("_");
1988       break;
1989
1990     case ADDR_EXPR:
1991       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1992       break;
1993
1994     case BIT_FIELD_REF:
1995     case VIEW_CONVERT_EXPR:
1996     case ARRAY_RANGE_REF:
1997       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1998       break;
1999
2000     case REALPART_EXPR:
2001       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
2002       lsm_tmp_name_add ("_RE");
2003       break;
2004
2005     case IMAGPART_EXPR:
2006       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
2007       lsm_tmp_name_add ("_IM");
2008       break;
2009
2010     case COMPONENT_REF:
2011       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
2012       lsm_tmp_name_add ("_");
2013       name = get_name (TREE_OPERAND (ref, 1));
2014       if (!name)
2015         name = "F";
2016       lsm_tmp_name_add (name);
2017       break;
2018
2019     case ARRAY_REF:
2020       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
2021       lsm_tmp_name_add ("_I");
2022       break;
2023
2024     case SSA_NAME:
2025       ref = SSA_NAME_VAR (ref);
2026       /* Fallthru.  */
2027
2028     case VAR_DECL:
2029     case PARM_DECL:
2030       name = get_name (ref);
2031       if (!name)
2032         name = "D";
2033       lsm_tmp_name_add (name);
2034       break;
2035
2036     case STRING_CST:
2037       lsm_tmp_name_add ("S");
2038       break;
2039
2040     case RESULT_DECL:
2041       lsm_tmp_name_add ("R");
2042       break;
2043
2044     case INTEGER_CST:
2045       /* Nothing.  */
2046       break;
2047
2048     default:
2049       gcc_unreachable ();
2050     }
2051 }
2052
2053 /* Determines name for temporary variable that replaces REF.
2054    The name is accumulated into the lsm_tmp_name variable.
2055    N is added to the name of the temporary.  */
2056
2057 char *
2058 get_lsm_tmp_name (tree ref, unsigned n)
2059 {
2060   char ns[2];
2061
2062   lsm_tmp_name_length = 0;
2063   gen_lsm_tmp_name (ref);
2064   lsm_tmp_name_add ("_lsm");
2065   if (n < 10)
2066     {
2067       ns[0] = '0' + n;
2068       ns[1] = 0;
2069       lsm_tmp_name_add (ns);
2070     }
2071   return lsm_tmp_name;
2072 }
2073
2074 /* Executes store motion of memory reference REF from LOOP.
2075    Exits from the LOOP are stored in EXITS.  The initialization of the
2076    temporary variable is put to the preheader of the loop, and assignments
2077    to the reference from the temporary variable are emitted to exits.  */
2078
2079 static void
2080 execute_sm (struct loop *loop, VEC (edge, heap) *exits, mem_ref_p ref)
2081 {
2082   tree tmp_var;
2083   unsigned i;
2084   gimple load, store;
2085   struct fmt_data fmt_data;
2086   edge ex;
2087   struct lim_aux_data *lim_data;
2088
2089   if (dump_file && (dump_flags & TDF_DETAILS))
2090     {
2091       fprintf (dump_file, "Executing store motion of ");
2092       print_generic_expr (dump_file, ref->mem, 0);
2093       fprintf (dump_file, " from loop %d\n", loop->num);
2094     }
2095
2096   tmp_var = make_rename_temp (TREE_TYPE (ref->mem),
2097                               get_lsm_tmp_name (ref->mem, ~0));
2098
2099   fmt_data.loop = loop;
2100   fmt_data.orig_loop = loop;
2101   for_each_index (&ref->mem, force_move_till, &fmt_data);
2102
2103   rewrite_mem_refs (loop, ref, tmp_var);
2104
2105   /* Emit the load & stores.  */
2106   load = gimple_build_assign (tmp_var, unshare_expr (ref->mem));
2107   lim_data = init_lim_data (load);
2108   lim_data->max_loop = loop;
2109   lim_data->tgt_loop = loop;
2110
2111   /* Put this into the latch, so that we are sure it will be processed after
2112      all dependencies.  */
2113   gsi_insert_on_edge (loop_latch_edge (loop), load);
2114
2115   FOR_EACH_VEC_ELT (edge, exits, i, ex)
2116     {
2117       store = gimple_build_assign (unshare_expr (ref->mem), tmp_var);
2118       gsi_insert_on_edge (ex, store);
2119     }
2120 }
2121
2122 /* Hoists memory references MEM_REFS out of LOOP.  EXITS is the list of exit
2123    edges of the LOOP.  */
2124
2125 static void
2126 hoist_memory_references (struct loop *loop, bitmap mem_refs,
2127                          VEC (edge, heap) *exits)
2128 {
2129   mem_ref_p ref;
2130   unsigned  i;
2131   bitmap_iterator bi;
2132
2133   EXECUTE_IF_SET_IN_BITMAP (mem_refs, 0, i, bi)
2134     {
2135       ref = VEC_index (mem_ref_p, memory_accesses.refs_list, i);
2136       execute_sm (loop, exits, ref);
2137     }
2138 }
2139
2140 /* Returns true if REF is always accessed in LOOP.  If STORED_P is true
2141    make sure REF is always stored to in LOOP.  */
2142
2143 static bool
2144 ref_always_accessed_p (struct loop *loop, mem_ref_p ref, bool stored_p)
2145 {
2146   VEC (mem_ref_loc_p, heap) *locs = NULL;
2147   unsigned i;
2148   mem_ref_loc_p loc;
2149   bool ret = false;
2150   struct loop *must_exec;
2151   tree base;
2152
2153   base = get_base_address (ref->mem);
2154   if (INDIRECT_REF_P (base)
2155       || TREE_CODE (base) == MEM_REF)
2156     base = TREE_OPERAND (base, 0);
2157
2158   get_all_locs_in_loop (loop, ref, &locs);
2159   FOR_EACH_VEC_ELT (mem_ref_loc_p, locs, i, loc)
2160     {
2161       if (!get_lim_data (loc->stmt))
2162         continue;
2163
2164       /* If we require an always executed store make sure the statement
2165          stores to the reference.  */
2166       if (stored_p)
2167         {
2168           tree lhs;
2169           if (!gimple_get_lhs (loc->stmt))
2170             continue;
2171           lhs = get_base_address (gimple_get_lhs (loc->stmt));
2172           if (!lhs)
2173             continue;
2174           if (INDIRECT_REF_P (lhs)
2175               || TREE_CODE (lhs) == MEM_REF)
2176             lhs = TREE_OPERAND (lhs, 0);
2177           if (lhs != base)
2178             continue;
2179         }
2180
2181       must_exec = get_lim_data (loc->stmt)->always_executed_in;
2182       if (!must_exec)
2183         continue;
2184
2185       if (must_exec == loop
2186           || flow_loop_nested_p (must_exec, loop))
2187         {
2188           ret = true;
2189           break;
2190         }
2191     }
2192   VEC_free (mem_ref_loc_p, heap, locs);
2193
2194   return ret;
2195 }
2196
2197 /* Returns true if REF1 and REF2 are independent.  */
2198
2199 static bool
2200 refs_independent_p (mem_ref_p ref1, mem_ref_p ref2)
2201 {
2202   if (ref1 == ref2
2203       || bitmap_bit_p (ref1->indep_ref, ref2->id))
2204     return true;
2205   if (bitmap_bit_p (ref1->dep_ref, ref2->id))
2206     return false;
2207
2208   if (dump_file && (dump_flags & TDF_DETAILS))
2209     fprintf (dump_file, "Querying dependency of refs %u and %u: ",
2210              ref1->id, ref2->id);
2211
2212   if (mem_refs_may_alias_p (ref1->mem, ref2->mem,
2213                             &memory_accesses.ttae_cache))
2214     {
2215       bitmap_set_bit (ref1->dep_ref, ref2->id);
2216       bitmap_set_bit (ref2->dep_ref, ref1->id);
2217       if (dump_file && (dump_flags & TDF_DETAILS))
2218         fprintf (dump_file, "dependent.\n");
2219       return false;
2220     }
2221   else
2222     {
2223       bitmap_set_bit (ref1->indep_ref, ref2->id);
2224       bitmap_set_bit (ref2->indep_ref, ref1->id);
2225       if (dump_file && (dump_flags & TDF_DETAILS))
2226         fprintf (dump_file, "independent.\n");
2227       return true;
2228     }
2229 }
2230
2231 /* Records the information whether REF is independent in LOOP (according
2232    to INDEP).  */
2233
2234 static void
2235 record_indep_loop (struct loop *loop, mem_ref_p ref, bool indep)
2236 {
2237   if (indep)
2238     bitmap_set_bit (ref->indep_loop, loop->num);
2239   else
2240     bitmap_set_bit (ref->dep_loop, loop->num);
2241 }
2242
2243 /* Returns true if REF is independent on all other memory references in
2244    LOOP.  */
2245
2246 static bool
2247 ref_indep_loop_p_1 (struct loop *loop, mem_ref_p ref)
2248 {
2249   bitmap clobbers, refs_to_check, refs;
2250   unsigned i;
2251   bitmap_iterator bi;
2252   bool ret = true, stored = bitmap_bit_p (ref->stored, loop->num);
2253   htab_t map;
2254   mem_ref_p aref;
2255
2256   /* If the reference is clobbered, it is not independent.  */
2257   clobbers = VEC_index (bitmap, memory_accesses.clobbered_vops, loop->num);
2258   if (bitmap_intersect_p (ref->vops, clobbers))
2259     return false;
2260
2261   refs_to_check = BITMAP_ALLOC (NULL);
2262
2263   map = VEC_index (htab_t, memory_accesses.vop_ref_map, loop->num);
2264   EXECUTE_IF_AND_COMPL_IN_BITMAP (ref->vops, clobbers, 0, i, bi)
2265     {
2266       if (stored)
2267         refs = get_vop_accesses (map, i);
2268       else
2269         refs = get_vop_stores (map, i);
2270
2271       bitmap_ior_into (refs_to_check, refs);
2272     }
2273
2274   EXECUTE_IF_SET_IN_BITMAP (refs_to_check, 0, i, bi)
2275     {
2276       aref = VEC_index (mem_ref_p, memory_accesses.refs_list, i);
2277       if (!refs_independent_p (ref, aref))
2278         {
2279           ret = false;
2280           record_indep_loop (loop, aref, false);
2281           break;
2282         }
2283     }
2284
2285   BITMAP_FREE (refs_to_check);
2286   return ret;
2287 }
2288
2289 /* Returns true if REF is independent on all other memory references in
2290    LOOP.  Wrapper over ref_indep_loop_p_1, caching its results.  */
2291
2292 static bool
2293 ref_indep_loop_p (struct loop *loop, mem_ref_p ref)
2294 {
2295   bool ret;
2296
2297   if (bitmap_bit_p (ref->indep_loop, loop->num))
2298     return true;
2299   if (bitmap_bit_p (ref->dep_loop, loop->num))
2300     return false;
2301
2302   ret = ref_indep_loop_p_1 (loop, ref);
2303
2304   if (dump_file && (dump_flags & TDF_DETAILS))
2305     fprintf (dump_file, "Querying dependencies of ref %u in loop %d: %s\n",
2306              ref->id, loop->num, ret ? "independent" : "dependent");
2307
2308   record_indep_loop (loop, ref, ret);
2309
2310   return ret;
2311 }
2312
2313 /* Returns true if we can perform store motion of REF from LOOP.  */
2314
2315 static bool
2316 can_sm_ref_p (struct loop *loop, mem_ref_p ref)
2317 {
2318   tree base;
2319
2320   /* Unless the reference is stored in the loop, there is nothing to do.  */
2321   if (!bitmap_bit_p (ref->stored, loop->num))
2322     return false;
2323
2324   /* It should be movable.  */
2325   if (!is_gimple_reg_type (TREE_TYPE (ref->mem))
2326       || TREE_THIS_VOLATILE (ref->mem)
2327       || !for_each_index (&ref->mem, may_move_till, loop))
2328     return false;
2329
2330   /* If it can throw fail, we do not properly update EH info.  */
2331   if (tree_could_throw_p (ref->mem))
2332     return false;
2333
2334   /* If it can trap, it must be always executed in LOOP.
2335      Readonly memory locations may trap when storing to them, but
2336      tree_could_trap_p is a predicate for rvalues, so check that
2337      explicitly.  */
2338   base = get_base_address (ref->mem);
2339   if ((tree_could_trap_p (ref->mem)
2340        || (DECL_P (base) && TREE_READONLY (base)))
2341       && !ref_always_accessed_p (loop, ref, true))
2342     return false;
2343
2344   /* And it must be independent on all other memory references
2345      in LOOP.  */
2346   if (!ref_indep_loop_p (loop, ref))
2347     return false;
2348
2349   return true;
2350 }
2351
2352 /* Marks the references in LOOP for that store motion should be performed
2353    in REFS_TO_SM.  SM_EXECUTED is the set of references for that store
2354    motion was performed in one of the outer loops.  */
2355
2356 static void
2357 find_refs_for_sm (struct loop *loop, bitmap sm_executed, bitmap refs_to_sm)
2358 {
2359   bitmap refs = VEC_index (bitmap, memory_accesses.all_refs_in_loop,
2360                            loop->num);
2361   unsigned i;
2362   bitmap_iterator bi;
2363   mem_ref_p ref;
2364
2365   EXECUTE_IF_AND_COMPL_IN_BITMAP (refs, sm_executed, 0, i, bi)
2366     {
2367       ref = VEC_index (mem_ref_p, memory_accesses.refs_list, i);
2368       if (can_sm_ref_p (loop, ref))
2369         bitmap_set_bit (refs_to_sm, i);
2370     }
2371 }
2372
2373 /* Checks whether LOOP (with exits stored in EXITS array) is suitable
2374    for a store motion optimization (i.e. whether we can insert statement
2375    on its exits).  */
2376
2377 static bool
2378 loop_suitable_for_sm (struct loop *loop ATTRIBUTE_UNUSED,
2379                       VEC (edge, heap) *exits)
2380 {
2381   unsigned i;
2382   edge ex;
2383
2384   FOR_EACH_VEC_ELT (edge, exits, i, ex)
2385     if (ex->flags & (EDGE_ABNORMAL | EDGE_EH))
2386       return false;
2387
2388   return true;
2389 }
2390
2391 /* Try to perform store motion for all memory references modified inside
2392    LOOP.  SM_EXECUTED is the bitmap of the memory references for that
2393    store motion was executed in one of the outer loops.  */
2394
2395 static void
2396 store_motion_loop (struct loop *loop, bitmap sm_executed)
2397 {
2398   VEC (edge, heap) *exits = get_loop_exit_edges (loop);
2399   struct loop *subloop;
2400   bitmap sm_in_loop = BITMAP_ALLOC (NULL);
2401
2402   if (loop_suitable_for_sm (loop, exits))
2403     {
2404       find_refs_for_sm (loop, sm_executed, sm_in_loop);
2405       hoist_memory_references (loop, sm_in_loop, exits);
2406     }
2407   VEC_free (edge, heap, exits);
2408
2409   bitmap_ior_into (sm_executed, sm_in_loop);
2410   for (subloop = loop->inner; subloop != NULL; subloop = subloop->next)
2411     store_motion_loop (subloop, sm_executed);
2412   bitmap_and_compl_into (sm_executed, sm_in_loop);
2413   BITMAP_FREE (sm_in_loop);
2414 }
2415
2416 /* Try to perform store motion for all memory references modified inside
2417    loops.  */
2418
2419 static void
2420 store_motion (void)
2421 {
2422   struct loop *loop;
2423   bitmap sm_executed = BITMAP_ALLOC (NULL);
2424
2425   for (loop = current_loops->tree_root->inner; loop != NULL; loop = loop->next)
2426     store_motion_loop (loop, sm_executed);
2427
2428   BITMAP_FREE (sm_executed);
2429   gsi_commit_edge_inserts ();
2430 }
2431
2432 /* Fills ALWAYS_EXECUTED_IN information for basic blocks of LOOP, i.e.
2433    for each such basic block bb records the outermost loop for that execution
2434    of its header implies execution of bb.  CONTAINS_CALL is the bitmap of
2435    blocks that contain a nonpure call.  */
2436
2437 static void
2438 fill_always_executed_in (struct loop *loop, sbitmap contains_call)
2439 {
2440   basic_block bb = NULL, *bbs, last = NULL;
2441   unsigned i;
2442   edge e;
2443   struct loop *inn_loop = loop;
2444
2445   if (ALWAYS_EXECUTED_IN (loop->header) == NULL)
2446     {
2447       bbs = get_loop_body_in_dom_order (loop);
2448
2449       for (i = 0; i < loop->num_nodes; i++)
2450         {
2451           edge_iterator ei;
2452           bb = bbs[i];
2453
2454           if (dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
2455             last = bb;
2456
2457           if (TEST_BIT (contains_call, bb->index))
2458             break;
2459
2460           FOR_EACH_EDGE (e, ei, bb->succs)
2461             if (!flow_bb_inside_loop_p (loop, e->dest))
2462               break;
2463           if (e)
2464             break;
2465
2466           /* A loop might be infinite (TODO use simple loop analysis
2467              to disprove this if possible).  */
2468           if (bb->flags & BB_IRREDUCIBLE_LOOP)
2469             break;
2470
2471           if (!flow_bb_inside_loop_p (inn_loop, bb))
2472             break;
2473
2474           if (bb->loop_father->header == bb)
2475             {
2476               if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
2477                 break;
2478
2479               /* In a loop that is always entered we may proceed anyway.
2480                  But record that we entered it and stop once we leave it.  */
2481               inn_loop = bb->loop_father;
2482             }
2483         }
2484
2485       while (1)
2486         {
2487           SET_ALWAYS_EXECUTED_IN (last, loop);
2488           if (last == loop->header)
2489             break;
2490           last = get_immediate_dominator (CDI_DOMINATORS, last);
2491         }
2492
2493       free (bbs);
2494     }
2495
2496   for (loop = loop->inner; loop; loop = loop->next)
2497     fill_always_executed_in (loop, contains_call);
2498 }
2499
2500 /* Compute the global information needed by the loop invariant motion pass.  */
2501
2502 static void
2503 tree_ssa_lim_initialize (void)
2504 {
2505   sbitmap contains_call = sbitmap_alloc (last_basic_block);
2506   gimple_stmt_iterator bsi;
2507   struct loop *loop;
2508   basic_block bb;
2509
2510   sbitmap_zero (contains_call);
2511   FOR_EACH_BB (bb)
2512     {
2513       for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
2514         {
2515           if (nonpure_call_p (gsi_stmt (bsi)))
2516             break;
2517         }
2518
2519       if (!gsi_end_p (bsi))
2520         SET_BIT (contains_call, bb->index);
2521     }
2522
2523   for (loop = current_loops->tree_root->inner; loop; loop = loop->next)
2524     fill_always_executed_in (loop, contains_call);
2525
2526   sbitmap_free (contains_call);
2527
2528   lim_aux_data_map = pointer_map_create ();
2529 }
2530
2531 /* Cleans up after the invariant motion pass.  */
2532
2533 static void
2534 tree_ssa_lim_finalize (void)
2535 {
2536   basic_block bb;
2537   unsigned i;
2538   bitmap b;
2539   htab_t h;
2540
2541   FOR_EACH_BB (bb)
2542     SET_ALWAYS_EXECUTED_IN (bb, NULL);
2543
2544   pointer_map_destroy (lim_aux_data_map);
2545
2546   VEC_free (mem_ref_p, heap, memory_accesses.refs_list);
2547   htab_delete (memory_accesses.refs);
2548
2549   FOR_EACH_VEC_ELT (bitmap, memory_accesses.refs_in_loop, i, b)
2550     BITMAP_FREE (b);
2551   VEC_free (bitmap, heap, memory_accesses.refs_in_loop);
2552
2553   FOR_EACH_VEC_ELT (bitmap, memory_accesses.all_refs_in_loop, i, b)
2554     BITMAP_FREE (b);
2555   VEC_free (bitmap, heap, memory_accesses.all_refs_in_loop);
2556
2557   FOR_EACH_VEC_ELT (bitmap, memory_accesses.clobbered_vops, i, b)
2558     BITMAP_FREE (b);
2559   VEC_free (bitmap, heap, memory_accesses.clobbered_vops);
2560
2561   FOR_EACH_VEC_ELT (htab_t, memory_accesses.vop_ref_map, i, h)
2562     htab_delete (h);
2563   VEC_free (htab_t, heap, memory_accesses.vop_ref_map);
2564
2565   if (memory_accesses.ttae_cache)
2566     pointer_map_destroy (memory_accesses.ttae_cache);
2567 }
2568
2569 /* Moves invariants from loops.  Only "expensive" invariants are moved out --
2570    i.e. those that are likely to be win regardless of the register pressure.  */
2571
2572 unsigned int
2573 tree_ssa_lim (void)
2574 {
2575   unsigned int todo;
2576
2577   tree_ssa_lim_initialize ();
2578
2579   /* Gathers information about memory accesses in the loops.  */
2580   analyze_memory_references ();
2581
2582   /* For each statement determine the outermost loop in that it is
2583      invariant and cost for computing the invariant.  */
2584   determine_invariantness ();
2585
2586   /* Execute store motion.  Force the necessary invariants to be moved
2587      out of the loops as well.  */
2588   store_motion ();
2589
2590   /* Move the expressions that are expensive enough.  */
2591   todo = move_computations ();
2592
2593   tree_ssa_lim_finalize ();
2594
2595   return todo;
2596 }