OSDN Git Service

2008-05-15 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 Free Software Foundation, Inc.
3    
4 This file is part of GCC.
5    
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
10    
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15    
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "tree.h"
25 #include "rtl.h"
26 #include "tm_p.h"
27 #include "hard-reg-set.h"
28 #include "basic-block.h"
29 #include "output.h"
30 #include "diagnostic.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 "real.h"
40 #include "hashtab.h"
41 #include "tree-affine.h"
42 #include "pointer-set.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   tree 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 #define LIM_DATA(STMT) (TREE_CODE (STMT) == PHI_NODE \
101                         ? NULL \
102                         : (struct lim_aux_data *) (stmt_ann (STMT)->common.aux))
103
104 /* Description of a memory reference location.  */
105
106 typedef struct mem_ref_loc
107 {
108   tree *ref;                    /* The reference itself.  */
109   tree 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 locatio
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 that execution of the header guarantees that the
201    block will be executed.  */
202 #define ALWAYS_EXECUTED_IN(BB) ((struct loop *) (BB)->aux)
203
204 /* Calls CBCK for each index in memory reference ADDR_P.  There are two
205    kinds situations handled; in each of these cases, the memory reference
206    and DATA are passed to the callback:
207    
208    Access to an array: ARRAY_{RANGE_}REF (base, index).  In this case we also
209    pass the pointer to the index to the callback.
210
211    Pointer dereference: INDIRECT_REF (addr).  In this case we also pass the
212    pointer to addr to the callback.
213    
214    If the callback returns false, the whole search stops and false is returned.
215    Otherwise the function returns true after traversing through the whole
216    reference *ADDR_P.  */
217
218 bool
219 for_each_index (tree *addr_p, bool (*cbck) (tree, tree *, void *), void *data)
220 {
221   tree *nxt, *idx;
222
223   for (; ; addr_p = nxt)
224     {
225       switch (TREE_CODE (*addr_p))
226         {
227         case SSA_NAME:
228           return cbck (*addr_p, addr_p, data);
229
230         case MISALIGNED_INDIRECT_REF:
231         case ALIGN_INDIRECT_REF:
232         case INDIRECT_REF:
233           nxt = &TREE_OPERAND (*addr_p, 0);
234           return cbck (*addr_p, nxt, data);
235
236         case BIT_FIELD_REF:
237         case VIEW_CONVERT_EXPR:
238         case REALPART_EXPR:
239         case IMAGPART_EXPR:
240           nxt = &TREE_OPERAND (*addr_p, 0);
241           break;
242
243         case COMPONENT_REF:
244           /* If the component has varying offset, it behaves like index
245              as well.  */
246           idx = &TREE_OPERAND (*addr_p, 2);
247           if (*idx
248               && !cbck (*addr_p, idx, data))
249             return false;
250
251           nxt = &TREE_OPERAND (*addr_p, 0);
252           break;
253
254         case ARRAY_REF:
255         case ARRAY_RANGE_REF:
256           nxt = &TREE_OPERAND (*addr_p, 0);
257           if (!cbck (*addr_p, &TREE_OPERAND (*addr_p, 1), data))
258             return false;
259           break;
260
261         case VAR_DECL:
262         case PARM_DECL:
263         case STRING_CST:
264         case RESULT_DECL:
265         case VECTOR_CST:
266         case COMPLEX_CST:
267         case INTEGER_CST:
268         case REAL_CST:
269         case FIXED_CST:
270         case CONSTRUCTOR:
271           return true;
272
273         case ADDR_EXPR:
274           gcc_assert (is_gimple_min_invariant (*addr_p));
275           return true;
276
277         case TARGET_MEM_REF:
278           idx = &TMR_BASE (*addr_p);
279           if (*idx
280               && !cbck (*addr_p, idx, data))
281             return false;
282           idx = &TMR_INDEX (*addr_p);
283           if (*idx
284               && !cbck (*addr_p, idx, data))
285             return false;
286           return true;
287
288         default:
289           gcc_unreachable ();
290         }
291     }
292 }
293
294 /* If it is possible to hoist the statement STMT unconditionally,
295    returns MOVE_POSSIBLE.
296    If it is possible to hoist the statement STMT, but we must avoid making
297    it executed if it would not be executed in the original program (e.g.
298    because it may trap), return MOVE_PRESERVE_EXECUTION.
299    Otherwise return MOVE_IMPOSSIBLE.  */
300
301 enum move_pos
302 movement_possibility (tree stmt)
303 {
304   tree lhs, rhs;
305
306   if (flag_unswitch_loops
307       && TREE_CODE (stmt) == COND_EXPR)
308     {
309       /* If we perform unswitching, force the operands of the invariant
310          condition to be moved out of the loop.  */
311       return MOVE_POSSIBLE;
312     }
313
314   if (TREE_CODE (stmt) != GIMPLE_MODIFY_STMT)
315     return MOVE_IMPOSSIBLE;
316
317   if (!ZERO_SSA_OPERANDS (stmt, SSA_OP_VIRTUAL_DEFS))
318     return MOVE_IMPOSSIBLE;
319
320   if (stmt_ends_bb_p (stmt))
321     return MOVE_IMPOSSIBLE;
322
323   if (stmt_ann (stmt)->has_volatile_ops)
324     return MOVE_IMPOSSIBLE;
325
326   lhs = GIMPLE_STMT_OPERAND (stmt, 0);
327   if (TREE_CODE (lhs) == SSA_NAME
328       && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
329     return MOVE_IMPOSSIBLE;
330
331   rhs = GIMPLE_STMT_OPERAND (stmt, 1);
332
333   if (TREE_SIDE_EFFECTS (rhs)
334       || tree_could_throw_p (rhs))
335     return MOVE_IMPOSSIBLE;
336
337   if (TREE_CODE (lhs) != SSA_NAME
338       || tree_could_trap_p (rhs))
339     return MOVE_PRESERVE_EXECUTION;
340
341   if (get_call_expr_in (stmt))
342     {
343       /* While pure or const call is guaranteed to have no side effects, we
344          cannot move it arbitrarily.  Consider code like
345
346          char *s = something ();
347
348          while (1)
349            {
350              if (s)
351                t = strlen (s);
352              else
353                t = 0;
354            }
355
356          Here the strlen call cannot be moved out of the loop, even though
357          s is invariant.  In addition to possibly creating a call with
358          invalid arguments, moving out a function call that is not executed
359          may cause performance regressions in case the call is costly and
360          not executed at all.  */
361       return MOVE_PRESERVE_EXECUTION;
362     }
363   return MOVE_POSSIBLE;
364 }
365
366 /* Suppose that operand DEF is used inside the LOOP.  Returns the outermost
367    loop to that we could move the expression using DEF if it did not have
368    other operands, i.e. the outermost loop enclosing LOOP in that the value
369    of DEF is invariant.  */
370
371 static struct loop *
372 outermost_invariant_loop (tree def, struct loop *loop)
373 {
374   tree def_stmt;
375   basic_block def_bb;
376   struct loop *max_loop;
377
378   if (TREE_CODE (def) != SSA_NAME)
379     return superloop_at_depth (loop, 1);
380
381   def_stmt = SSA_NAME_DEF_STMT (def);
382   def_bb = bb_for_stmt (def_stmt);
383   if (!def_bb)
384     return superloop_at_depth (loop, 1);
385
386   max_loop = find_common_loop (loop, def_bb->loop_father);
387
388   if (LIM_DATA (def_stmt) && LIM_DATA (def_stmt)->max_loop)
389     max_loop = find_common_loop (max_loop,
390                                  loop_outer (LIM_DATA (def_stmt)->max_loop));
391   if (max_loop == loop)
392     return NULL;
393   max_loop = superloop_at_depth (loop, loop_depth (max_loop) + 1);
394
395   return max_loop;
396 }
397
398 /* Returns the outermost superloop of LOOP in that the expression EXPR is
399    invariant.  */
400
401 static struct loop *
402 outermost_invariant_loop_expr (tree expr, struct loop *loop)
403 {
404   enum tree_code_class codeclass = TREE_CODE_CLASS (TREE_CODE (expr));
405   unsigned i, nops;
406   struct loop *max_loop = superloop_at_depth (loop, 1), *aloop;
407
408   if (TREE_CODE (expr) == SSA_NAME
409       || TREE_CODE (expr) == INTEGER_CST
410       || is_gimple_min_invariant (expr))
411     return outermost_invariant_loop (expr, loop);
412
413   if (codeclass != tcc_unary
414       && codeclass != tcc_binary
415       && codeclass != tcc_expression
416       && codeclass != tcc_vl_exp
417       && codeclass != tcc_comparison)
418     return NULL;
419
420   nops = TREE_OPERAND_LENGTH (expr);
421   for (i = 0; i < nops; i++)
422     {
423       aloop = outermost_invariant_loop_expr (TREE_OPERAND (expr, i), loop);
424       if (!aloop)
425         return NULL;
426
427       if (flow_loop_nested_p (max_loop, aloop))
428         max_loop = aloop;
429     }
430
431   return max_loop;
432 }
433
434 /* DATA is a structure containing information associated with a statement
435    inside LOOP.  DEF is one of the operands of this statement.
436    
437    Find the outermost loop enclosing LOOP in that value of DEF is invariant
438    and record this in DATA->max_loop field.  If DEF itself is defined inside
439    this loop as well (i.e. we need to hoist it out of the loop if we want
440    to hoist the statement represented by DATA), record the statement in that
441    DEF is defined to the DATA->depends list.  Additionally if ADD_COST is true,
442    add the cost of the computation of DEF to the DATA->cost.
443    
444    If DEF is not invariant in LOOP, return false.  Otherwise return TRUE.  */
445
446 static bool
447 add_dependency (tree def, struct lim_aux_data *data, struct loop *loop,
448                 bool add_cost)
449 {
450   tree def_stmt = SSA_NAME_DEF_STMT (def);
451   basic_block def_bb = bb_for_stmt (def_stmt);
452   struct loop *max_loop;
453   struct depend *dep;
454
455   if (!def_bb)
456     return true;
457
458   max_loop = outermost_invariant_loop (def, loop);
459   if (!max_loop)
460     return false;
461
462   if (flow_loop_nested_p (data->max_loop, max_loop))
463     data->max_loop = max_loop;
464
465   if (!LIM_DATA (def_stmt))
466     return true;
467
468   if (add_cost
469       /* Only add the cost if the statement defining DEF is inside LOOP,
470          i.e. if it is likely that by moving the invariants dependent
471          on it, we will be able to avoid creating a new register for
472          it (since it will be only used in these dependent invariants).  */
473       && def_bb->loop_father == loop)
474     data->cost += LIM_DATA (def_stmt)->cost;
475
476   dep = XNEW (struct depend);
477   dep->stmt = def_stmt;
478   dep->next = data->depends;
479   data->depends = dep;
480
481   return true;
482 }
483
484 /* Returns an estimate for a cost of statement STMT.  TODO -- the values here
485    are just ad-hoc constants.  The estimates should be based on target-specific
486    values.  */
487
488 static unsigned
489 stmt_cost (tree stmt)
490 {
491   tree rhs;
492   unsigned cost = 1;
493
494   /* Always try to create possibilities for unswitching.  */
495   if (TREE_CODE (stmt) == COND_EXPR)
496     return LIM_EXPENSIVE;
497
498   rhs = GENERIC_TREE_OPERAND (stmt, 1);
499
500   /* Hoisting memory references out should almost surely be a win.  */
501   if (stmt_references_memory_p (stmt))
502     cost += 20;
503
504   switch (TREE_CODE (rhs))
505     {
506     case CALL_EXPR:
507       /* We should be hoisting calls if possible.  */
508
509       /* Unless the call is a builtin_constant_p; this always folds to a
510          constant, so moving it is useless.  */
511       rhs = get_callee_fndecl (rhs);
512       if (DECL_BUILT_IN_CLASS (rhs) == BUILT_IN_NORMAL
513           && DECL_FUNCTION_CODE (rhs) == BUILT_IN_CONSTANT_P)
514         return 0;
515
516       cost += 20;
517       break;
518
519     case MULT_EXPR:
520     case TRUNC_DIV_EXPR:
521     case CEIL_DIV_EXPR:
522     case FLOOR_DIV_EXPR:
523     case ROUND_DIV_EXPR:
524     case EXACT_DIV_EXPR:
525     case CEIL_MOD_EXPR:
526     case FLOOR_MOD_EXPR:
527     case ROUND_MOD_EXPR:
528     case TRUNC_MOD_EXPR:
529     case RDIV_EXPR:
530       /* Division and multiplication are usually expensive.  */
531       cost += 20;
532       break;
533
534     case LSHIFT_EXPR:
535     case RSHIFT_EXPR:
536       cost += 20;
537       break;
538
539     default:
540       break;
541     }
542
543   return cost;
544 }
545
546 /* Finds the outermost loop between OUTER and LOOP in that the memory reference
547    REF is independent.  If REF is not independent in LOOP, NULL is returned
548    instead.  */
549
550 static struct loop *
551 outermost_indep_loop (struct loop *outer, struct loop *loop, mem_ref_p ref)
552 {
553   struct loop *aloop;
554
555   if (bitmap_bit_p (ref->stored, loop->num))
556     return NULL;
557
558   for (aloop = outer;
559        aloop != loop;
560        aloop = superloop_at_depth (loop, loop_depth (aloop) + 1))
561     if (!bitmap_bit_p (ref->stored, aloop->num)
562         && ref_indep_loop_p (aloop, ref))
563       return aloop;
564
565   if (ref_indep_loop_p (loop, ref))
566     return loop;
567   else
568     return NULL;
569 }
570
571 /* If there is a simple load or store to a memory reference in STMT, returns
572    the location of the memory reference, and sets IS_STORE accoring to whether
573    it is a store or load.  Otherwise, returns NULL.  */
574
575 static tree *
576 simple_mem_ref_in_stmt (tree stmt, bool *is_store)
577 {
578   tree *lhs, *rhs;
579
580   /* Recognize MEM = (SSA_NAME | invariant) and SSA_NAME = MEM patterns.  */
581   if (TREE_CODE (stmt) != GIMPLE_MODIFY_STMT)
582     return NULL;
583
584   lhs = &GIMPLE_STMT_OPERAND (stmt, 0);
585   rhs = &GIMPLE_STMT_OPERAND (stmt, 1);
586
587   if (TREE_CODE (*lhs) == SSA_NAME)
588     {
589       if (!is_gimple_addressable (*rhs))
590         return NULL;
591
592       *is_store = false;
593       return rhs;
594     }
595   else if (TREE_CODE (*rhs) == SSA_NAME
596            || is_gimple_min_invariant (*rhs))
597     {
598       *is_store = true;
599       return lhs;
600     }
601   else
602     return NULL;
603 }
604
605 /* Returns the memory reference contained in STMT.  */
606
607 static mem_ref_p
608 mem_ref_in_stmt (tree stmt)
609 {
610   bool store;
611   tree *mem = simple_mem_ref_in_stmt (stmt, &store);
612   hashval_t hash;
613   mem_ref_p ref;
614
615   if (!mem)
616     return NULL;
617   gcc_assert (!store);
618
619   hash = iterative_hash_expr (*mem, 0);
620   ref = htab_find_with_hash (memory_accesses.refs, *mem, hash);
621
622   gcc_assert (ref != NULL);
623   return ref;
624 }
625
626 /* Determine the outermost loop to that it is possible to hoist a statement
627    STMT and store it to LIM_DATA (STMT)->max_loop.  To do this we determine
628    the outermost loop in that the value computed by STMT is invariant.
629    If MUST_PRESERVE_EXEC is true, additionally choose such a loop that
630    we preserve the fact whether STMT is executed.  It also fills other related
631    information to LIM_DATA (STMT).
632    
633    The function returns false if STMT cannot be hoisted outside of the loop it
634    is defined in, and true otherwise.  */
635
636 static bool
637 determine_max_movement (tree stmt, bool must_preserve_exec)
638 {
639   basic_block bb = bb_for_stmt (stmt);
640   struct loop *loop = bb->loop_father;
641   struct loop *level;
642   struct lim_aux_data *lim_data = LIM_DATA (stmt);
643   tree val;
644   ssa_op_iter iter;
645   
646   if (must_preserve_exec)
647     level = ALWAYS_EXECUTED_IN (bb);
648   else
649     level = superloop_at_depth (loop, 1);
650   lim_data->max_loop = level;
651
652   FOR_EACH_SSA_TREE_OPERAND (val, stmt, iter, SSA_OP_USE)
653     if (!add_dependency (val, lim_data, loop, true))
654       return false;
655
656   if (!ZERO_SSA_OPERANDS (stmt, SSA_OP_VIRTUAL_USES))
657     {
658       mem_ref_p ref = mem_ref_in_stmt (stmt);
659
660       if (ref)
661         {
662           lim_data->max_loop
663                   = outermost_indep_loop (lim_data->max_loop, loop, ref);
664           if (!lim_data->max_loop)
665             return false;
666         }
667       else
668         {
669           FOR_EACH_SSA_TREE_OPERAND (val, stmt, iter, SSA_OP_VIRTUAL_USES)
670             {
671               if (!add_dependency (val, lim_data, loop, false))
672                 return false;
673             }
674         }
675     }
676
677   lim_data->cost += stmt_cost (stmt);
678
679   return true;
680 }
681
682 /* Suppose that some statement in ORIG_LOOP is hoisted to the loop LEVEL,
683    and that one of the operands of this statement is computed by STMT.
684    Ensure that STMT (together with all the statements that define its
685    operands) is hoisted at least out of the loop LEVEL.  */
686
687 static void
688 set_level (tree stmt, struct loop *orig_loop, struct loop *level)
689 {
690   struct loop *stmt_loop = bb_for_stmt (stmt)->loop_father;
691   struct depend *dep;
692
693   stmt_loop = find_common_loop (orig_loop, stmt_loop);
694   if (LIM_DATA (stmt) && LIM_DATA (stmt)->tgt_loop)
695     stmt_loop = find_common_loop (stmt_loop,
696                                   loop_outer (LIM_DATA (stmt)->tgt_loop));
697   if (flow_loop_nested_p (stmt_loop, level))
698     return;
699
700   gcc_assert (LIM_DATA (stmt));
701   gcc_assert (level == LIM_DATA (stmt)->max_loop
702               || flow_loop_nested_p (LIM_DATA (stmt)->max_loop, level));
703
704   LIM_DATA (stmt)->tgt_loop = level;
705   for (dep = LIM_DATA (stmt)->depends; dep; dep = dep->next)
706     set_level (dep->stmt, orig_loop, level);
707 }
708
709 /* Determines an outermost loop from that we want to hoist the statement STMT.
710    For now we chose the outermost possible loop.  TODO -- use profiling
711    information to set it more sanely.  */
712
713 static void
714 set_profitable_level (tree stmt)
715 {
716   set_level (stmt, bb_for_stmt (stmt)->loop_father, LIM_DATA (stmt)->max_loop);
717 }
718
719 /* Returns true if STMT is not a pure call.  */
720
721 static bool
722 nonpure_call_p (tree stmt)
723 {
724   tree call = get_call_expr_in (stmt);
725
726   if (!call)
727     return false;
728
729   return TREE_SIDE_EFFECTS (call) != 0;
730 }
731
732 /* Releases the memory occupied by DATA.  */
733
734 static void
735 free_lim_aux_data (struct lim_aux_data *data)
736 {
737   struct depend *dep, *next;
738
739   for (dep = data->depends; dep; dep = next)
740     {
741       next = dep->next;
742       free (dep);
743     }
744   free (data);
745 }
746
747 /* Rewrite a/b to a*(1/b).  Return the invariant stmt to process.  */
748
749 static tree
750 rewrite_reciprocal (block_stmt_iterator *bsi)
751 {
752   tree stmt, lhs, rhs, stmt1, stmt2, var, name, tmp;
753
754   stmt = bsi_stmt (*bsi);
755   lhs = GENERIC_TREE_OPERAND (stmt, 0);
756   rhs = GENERIC_TREE_OPERAND (stmt, 1);
757
758   /* stmt must be GIMPLE_MODIFY_STMT.  */
759   var = create_tmp_var (TREE_TYPE (rhs), "reciptmp");
760   add_referenced_var (var);
761
762   tmp = build2 (RDIV_EXPR, TREE_TYPE (rhs),
763                 build_real (TREE_TYPE (rhs), dconst1),
764                 TREE_OPERAND (rhs, 1));
765   stmt1 = build_gimple_modify_stmt (var, tmp);
766   name = make_ssa_name (var, stmt1);
767   GIMPLE_STMT_OPERAND (stmt1, 0) = name;
768   tmp = build2 (MULT_EXPR, TREE_TYPE (rhs),
769                 name, TREE_OPERAND (rhs, 0));
770   stmt2 = build_gimple_modify_stmt (lhs, tmp);
771
772   /* Replace division stmt with reciprocal and multiply stmts.
773      The multiply stmt is not invariant, so update iterator
774      and avoid rescanning.  */
775   bsi_replace (bsi, stmt1, true);
776   bsi_insert_after (bsi, stmt2, BSI_NEW_STMT);
777   SSA_NAME_DEF_STMT (lhs) = stmt2;
778
779   /* Continue processing with invariant reciprocal statement.  */
780   return stmt1;
781 }
782
783 /* Check if the pattern at *BSI is a bittest of the form
784    (A >> B) & 1 != 0 and in this case rewrite it to A & (1 << B) != 0.  */
785
786 static tree
787 rewrite_bittest (block_stmt_iterator *bsi)
788 {
789   tree stmt, lhs, rhs, var, name, use_stmt, stmt1, stmt2, t;
790   use_operand_p use;
791
792   stmt = bsi_stmt (*bsi);
793   lhs = GENERIC_TREE_OPERAND (stmt, 0);
794   rhs = GENERIC_TREE_OPERAND (stmt, 1);
795
796   /* Verify that the single use of lhs is a comparison against zero.  */
797   if (TREE_CODE (lhs) != SSA_NAME
798       || !single_imm_use (lhs, &use, &use_stmt)
799       || TREE_CODE (use_stmt) != COND_EXPR)
800     return stmt;
801   t = COND_EXPR_COND (use_stmt);
802   if (TREE_OPERAND (t, 0) != lhs
803       || (TREE_CODE (t) != NE_EXPR
804           && TREE_CODE (t) != EQ_EXPR)
805       || !integer_zerop (TREE_OPERAND (t, 1)))
806     return stmt;
807
808   /* Get at the operands of the shift.  The rhs is TMP1 & 1.  */
809   stmt1 = SSA_NAME_DEF_STMT (TREE_OPERAND (rhs, 0));
810   if (TREE_CODE (stmt1) != GIMPLE_MODIFY_STMT)
811     return stmt;
812
813   /* There is a conversion in between possibly inserted by fold.  */
814   t = GIMPLE_STMT_OPERAND (stmt1, 1);
815   if (CONVERT_EXPR_P (t))
816     {
817       t = TREE_OPERAND (t, 0);
818       if (TREE_CODE (t) != SSA_NAME
819           || !has_single_use (t))
820         return stmt;
821       stmt1 = SSA_NAME_DEF_STMT (t);
822       if (TREE_CODE (stmt1) != GIMPLE_MODIFY_STMT)
823         return stmt;
824       t = GIMPLE_STMT_OPERAND (stmt1, 1);
825     }
826
827   /* Verify that B is loop invariant but A is not.  Verify that with
828      all the stmt walking we are still in the same loop.  */
829   if (TREE_CODE (t) == RSHIFT_EXPR
830       && loop_containing_stmt (stmt1) == loop_containing_stmt (stmt)
831       && outermost_invariant_loop_expr (TREE_OPERAND (t, 1),
832                                         loop_containing_stmt (stmt1)) != NULL
833       && outermost_invariant_loop_expr (TREE_OPERAND (t, 0),
834                                         loop_containing_stmt (stmt1)) == NULL)
835     {
836       tree a = TREE_OPERAND (t, 0);
837       tree b = TREE_OPERAND (t, 1);
838
839       /* 1 << B */
840       var = create_tmp_var (TREE_TYPE (a), "shifttmp");
841       add_referenced_var (var);
842       t = fold_build2 (LSHIFT_EXPR, TREE_TYPE (a),
843                        build_int_cst (TREE_TYPE (a), 1), b);
844       stmt1 = build_gimple_modify_stmt (var, t);
845       name = make_ssa_name (var, stmt1);
846       GIMPLE_STMT_OPERAND (stmt1, 0) = name;
847
848       /* A & (1 << B) */
849       t = fold_build2 (BIT_AND_EXPR, TREE_TYPE (a), a, name);
850       stmt2 = build_gimple_modify_stmt (var, t);
851       name = make_ssa_name (var, stmt2);
852       GIMPLE_STMT_OPERAND (stmt2, 0) = name;
853
854       /* Replace the SSA_NAME we compare against zero.  Adjust
855          the type of zero accordingly.  */
856       SET_USE (use, name);
857       TREE_OPERAND (COND_EXPR_COND (use_stmt), 1)
858         = build_int_cst_type (TREE_TYPE (name), 0);
859
860       bsi_insert_before (bsi, stmt1, BSI_SAME_STMT);
861       bsi_replace (bsi, stmt2, true);
862
863       return stmt1;
864     }
865
866   return stmt;
867 }
868
869
870 /* Determine the outermost loops in that statements in basic block BB are
871    invariant, and record them to the LIM_DATA associated with the statements.
872    Callback for walk_dominator_tree.  */
873
874 static void
875 determine_invariantness_stmt (struct dom_walk_data *dw_data ATTRIBUTE_UNUSED,
876                               basic_block bb)
877 {
878   enum move_pos pos;
879   block_stmt_iterator bsi;
880   tree stmt, rhs;
881   bool maybe_never = ALWAYS_EXECUTED_IN (bb) == NULL;
882   struct loop *outermost = ALWAYS_EXECUTED_IN (bb);
883
884   if (!loop_outer (bb->loop_father))
885     return;
886
887   if (dump_file && (dump_flags & TDF_DETAILS))
888     fprintf (dump_file, "Basic block %d (loop %d -- depth %d):\n\n",
889              bb->index, bb->loop_father->num, loop_depth (bb->loop_father));
890
891   for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
892     {
893       stmt = bsi_stmt (bsi);
894
895       pos = movement_possibility (stmt);
896       if (pos == MOVE_IMPOSSIBLE)
897         {
898           if (nonpure_call_p (stmt))
899             {
900               maybe_never = true;
901               outermost = NULL;
902             }
903           continue;
904         }
905
906       if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT)
907         {
908           rhs = GIMPLE_STMT_OPERAND (stmt, 1);
909
910           /* If divisor is invariant, convert a/b to a*(1/b), allowing reciprocal
911              to be hoisted out of loop, saving expensive divide.  */
912           if (pos == MOVE_POSSIBLE
913               && TREE_CODE (rhs) == RDIV_EXPR
914               && flag_unsafe_math_optimizations
915               && !flag_trapping_math
916               && outermost_invariant_loop_expr (TREE_OPERAND (rhs, 1),
917                                                 loop_containing_stmt (stmt)) != NULL
918               && outermost_invariant_loop_expr (rhs,
919                                                 loop_containing_stmt (stmt)) == NULL)
920             stmt = rewrite_reciprocal (&bsi);
921
922           /* If the shift count is invariant, convert (A >> B) & 1 to
923              A & (1 << B) allowing the bit mask to be hoisted out of the loop
924              saving an expensive shift.  */
925           if (pos == MOVE_POSSIBLE
926               && TREE_CODE (rhs) == BIT_AND_EXPR
927               && integer_onep (TREE_OPERAND (rhs, 1))
928               && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME
929               && has_single_use (TREE_OPERAND (rhs, 0)))
930             stmt = rewrite_bittest (&bsi);
931         }
932
933       stmt_ann (stmt)->common.aux = xcalloc (1, sizeof (struct lim_aux_data));
934       LIM_DATA (stmt)->always_executed_in = outermost;
935
936       if (maybe_never && pos == MOVE_PRESERVE_EXECUTION)
937         continue;
938
939       if (!determine_max_movement (stmt, pos == MOVE_PRESERVE_EXECUTION))
940         {
941           LIM_DATA (stmt)->max_loop = NULL;
942           continue;
943         }
944
945       if (dump_file && (dump_flags & TDF_DETAILS))
946         {
947           print_generic_stmt_indented (dump_file, stmt, 0, 2);
948           fprintf (dump_file, "  invariant up to level %d, cost %d.\n\n",
949                    loop_depth (LIM_DATA (stmt)->max_loop),
950                    LIM_DATA (stmt)->cost);
951         }
952
953       if (LIM_DATA (stmt)->cost >= LIM_EXPENSIVE)
954         set_profitable_level (stmt);
955     }
956 }
957
958 /* For each statement determines the outermost loop in that it is invariant,
959    statements on whose motion it depends and the cost of the computation.
960    This information is stored to the LIM_DATA structure associated with
961    each statement.  */
962
963 static void
964 determine_invariantness (void)
965 {
966   struct dom_walk_data walk_data;
967
968   memset (&walk_data, 0, sizeof (struct dom_walk_data));
969   walk_data.dom_direction = CDI_DOMINATORS;
970   walk_data.before_dom_children_before_stmts = determine_invariantness_stmt;
971
972   init_walk_dominator_tree (&walk_data);
973   walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
974   fini_walk_dominator_tree (&walk_data);
975 }
976
977 /* Hoist the statements in basic block BB out of the loops prescribed by
978    data stored in LIM_DATA structures associated with each statement.  Callback
979    for walk_dominator_tree.  */
980
981 static void
982 move_computations_stmt (struct dom_walk_data *dw_data ATTRIBUTE_UNUSED,
983                         basic_block bb)
984 {
985   struct loop *level;
986   block_stmt_iterator bsi;
987   tree stmt;
988   unsigned cost = 0;
989
990   if (!loop_outer (bb->loop_father))
991     return;
992
993   for (bsi = bsi_start (bb); !bsi_end_p (bsi); )
994     {
995       stmt = bsi_stmt (bsi);
996
997       if (!LIM_DATA (stmt))
998         {
999           bsi_next (&bsi);
1000           continue;
1001         }
1002
1003       cost = LIM_DATA (stmt)->cost;
1004       level = LIM_DATA (stmt)->tgt_loop;
1005       free_lim_aux_data (LIM_DATA (stmt));
1006       stmt_ann (stmt)->common.aux = NULL;
1007
1008       if (!level)
1009         {
1010           bsi_next (&bsi);
1011           continue;
1012         }
1013
1014       /* We do not really want to move conditionals out of the loop; we just
1015          placed it here to force its operands to be moved if necessary.  */
1016       if (TREE_CODE (stmt) == COND_EXPR)
1017         continue;
1018
1019       if (dump_file && (dump_flags & TDF_DETAILS))
1020         {
1021           fprintf (dump_file, "Moving statement\n");
1022           print_generic_stmt (dump_file, stmt, 0);
1023           fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
1024                    cost, level->num);
1025         }
1026
1027       mark_virtual_ops_for_renaming (stmt);
1028       bsi_insert_on_edge (loop_preheader_edge (level), stmt);
1029       bsi_remove (&bsi, false);
1030     }
1031 }
1032
1033 /* Hoist the statements out of the loops prescribed by data stored in
1034    LIM_DATA structures associated with each statement.*/
1035
1036 static void
1037 move_computations (void)
1038 {
1039   struct dom_walk_data walk_data;
1040
1041   memset (&walk_data, 0, sizeof (struct dom_walk_data));
1042   walk_data.dom_direction = CDI_DOMINATORS;
1043   walk_data.before_dom_children_before_stmts = move_computations_stmt;
1044
1045   init_walk_dominator_tree (&walk_data);
1046   walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1047   fini_walk_dominator_tree (&walk_data);
1048
1049   bsi_commit_edge_inserts ();
1050   if (need_ssa_update_p ())
1051     rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
1052 }
1053
1054 /* Checks whether the statement defining variable *INDEX can be hoisted
1055    out of the loop passed in DATA.  Callback for for_each_index.  */
1056
1057 static bool
1058 may_move_till (tree ref, tree *index, void *data)
1059 {
1060   struct loop *loop = (struct loop*) data, *max_loop;
1061
1062   /* If REF is an array reference, check also that the step and the lower
1063      bound is invariant in LOOP.  */
1064   if (TREE_CODE (ref) == ARRAY_REF)
1065     {
1066       tree step = array_ref_element_size (ref);
1067       tree lbound = array_ref_low_bound (ref);
1068
1069       max_loop = outermost_invariant_loop_expr (step, loop);
1070       if (!max_loop)
1071         return false;
1072
1073       max_loop = outermost_invariant_loop_expr (lbound, loop);
1074       if (!max_loop)
1075         return false;
1076     }
1077
1078   max_loop = outermost_invariant_loop (*index, loop);
1079   if (!max_loop)
1080     return false;
1081
1082   return true;
1083 }
1084
1085 /* Forces statements defining (invariant) SSA names in expression EXPR to be
1086    moved out of the LOOP.  ORIG_LOOP is the loop in that EXPR is used.  */
1087
1088 static void
1089 force_move_till_expr (tree expr, struct loop *orig_loop, struct loop *loop)
1090 {
1091   enum tree_code_class codeclass = TREE_CODE_CLASS (TREE_CODE (expr));
1092   unsigned i, nops;
1093
1094   if (TREE_CODE (expr) == SSA_NAME)
1095     {
1096       tree stmt = SSA_NAME_DEF_STMT (expr);
1097       if (IS_EMPTY_STMT (stmt))
1098         return;
1099
1100       set_level (stmt, orig_loop, loop);
1101       return;
1102     }
1103
1104   if (codeclass != tcc_unary
1105       && codeclass != tcc_binary
1106       && codeclass != tcc_expression
1107       && codeclass != tcc_vl_exp
1108       && codeclass != tcc_comparison)
1109     return;
1110
1111   nops = TREE_OPERAND_LENGTH (expr);
1112   for (i = 0; i < nops; i++)
1113     force_move_till_expr (TREE_OPERAND (expr, i), orig_loop, loop);
1114 }
1115
1116 /* Forces statement defining invariants in REF (and *INDEX) to be moved out of
1117    the LOOP.  The reference REF is used in the loop ORIG_LOOP.  Callback for
1118    for_each_index.  */
1119
1120 struct fmt_data
1121 {
1122   struct loop *loop;
1123   struct loop *orig_loop;
1124 };
1125
1126 static bool
1127 force_move_till (tree ref, tree *index, void *data)
1128 {
1129   tree stmt;
1130   struct fmt_data *fmt_data = (struct fmt_data *) data;
1131
1132   if (TREE_CODE (ref) == ARRAY_REF)
1133     {
1134       tree step = array_ref_element_size (ref);
1135       tree lbound = array_ref_low_bound (ref);
1136
1137       force_move_till_expr (step, fmt_data->orig_loop, fmt_data->loop);
1138       force_move_till_expr (lbound, fmt_data->orig_loop, fmt_data->loop);
1139     }
1140
1141   if (TREE_CODE (*index) != SSA_NAME)
1142     return true;
1143
1144   stmt = SSA_NAME_DEF_STMT (*index);
1145   if (IS_EMPTY_STMT (stmt))
1146     return true;
1147
1148   set_level (stmt, fmt_data->orig_loop, fmt_data->loop);
1149
1150   return true;
1151 }
1152
1153 /* A hash function for struct mem_ref object OBJ.  */
1154
1155 static hashval_t
1156 memref_hash (const void *obj)
1157 {
1158   const struct mem_ref *mem = obj;
1159
1160   return mem->hash;
1161 }
1162
1163 /* An equality function for struct mem_ref object OBJ1 with
1164    memory reference OBJ2.  */
1165
1166 static int
1167 memref_eq (const void *obj1, const void *obj2)
1168 {
1169   const struct mem_ref *mem1 = obj1;
1170
1171   return operand_equal_p (mem1->mem, (tree) obj2, 0);
1172 }
1173
1174 /* Releases list of memory reference locations ACCS.  */
1175
1176 static void
1177 free_mem_ref_locs (mem_ref_locs_p accs)
1178 {
1179   unsigned i;
1180   mem_ref_loc_p loc;
1181
1182   if (!accs)
1183     return;
1184
1185   for (i = 0; VEC_iterate (mem_ref_loc_p, accs->locs, i, loc); i++)
1186     free (loc);
1187   VEC_free (mem_ref_loc_p, heap, accs->locs);
1188   free (accs);
1189 }
1190
1191 /* A function to free the mem_ref object OBJ.  */
1192
1193 static void
1194 memref_free (void *obj)
1195 {
1196   struct mem_ref *mem = obj;
1197   unsigned i;
1198   mem_ref_locs_p accs;
1199
1200   BITMAP_FREE (mem->stored);
1201   BITMAP_FREE (mem->indep_loop);
1202   BITMAP_FREE (mem->dep_loop);
1203   BITMAP_FREE (mem->indep_ref);
1204   BITMAP_FREE (mem->dep_ref);
1205
1206   for (i = 0; VEC_iterate (mem_ref_locs_p, mem->accesses_in_loop, i, accs); i++)
1207     free_mem_ref_locs (accs);
1208   VEC_free (mem_ref_locs_p, heap, mem->accesses_in_loop);
1209
1210   BITMAP_FREE (mem->vops);
1211   free (mem);
1212 }
1213
1214 /* Allocates and returns a memory reference description for MEM whose hash
1215    value is HASH and id is ID.  */
1216
1217 static mem_ref_p
1218 mem_ref_alloc (tree mem, unsigned hash, unsigned id)
1219 {
1220   mem_ref_p ref = XNEW (struct mem_ref);
1221   ref->mem = mem;
1222   ref->id = id;
1223   ref->hash = hash;
1224   ref->stored = BITMAP_ALLOC (NULL);
1225   ref->indep_loop = BITMAP_ALLOC (NULL);
1226   ref->dep_loop = BITMAP_ALLOC (NULL);
1227   ref->indep_ref = BITMAP_ALLOC (NULL);
1228   ref->dep_ref = BITMAP_ALLOC (NULL);
1229   ref->accesses_in_loop = NULL;
1230   ref->vops = BITMAP_ALLOC (NULL);
1231
1232   return ref;
1233 }
1234
1235 /* Allocates and returns the new list of locations.  */
1236
1237 static mem_ref_locs_p
1238 mem_ref_locs_alloc (void)
1239 {
1240   mem_ref_locs_p accs = XNEW (struct mem_ref_locs);
1241   accs->locs = NULL;
1242   return accs;
1243 }
1244
1245 /* Records memory reference location *LOC in LOOP to the memory reference
1246    description REF.  The reference occurs in statement STMT.  */
1247
1248 static void
1249 record_mem_ref_loc (mem_ref_p ref, struct loop *loop, tree stmt, tree *loc)
1250 {
1251   mem_ref_loc_p aref = XNEW (struct mem_ref_loc);
1252   mem_ref_locs_p accs;
1253   bitmap ril = VEC_index (bitmap, memory_accesses.refs_in_loop, loop->num);
1254
1255   if (VEC_length (mem_ref_locs_p, ref->accesses_in_loop)
1256       <= (unsigned) loop->num)
1257     VEC_safe_grow_cleared (mem_ref_locs_p, heap, ref->accesses_in_loop,
1258                            loop->num + 1);
1259   accs = VEC_index (mem_ref_locs_p, ref->accesses_in_loop, loop->num);
1260   if (!accs)
1261     {
1262       accs = mem_ref_locs_alloc ();
1263       VEC_replace (mem_ref_locs_p, ref->accesses_in_loop, loop->num, accs);
1264     }
1265
1266   aref->stmt = stmt;
1267   aref->ref = loc;
1268
1269   VEC_safe_push (mem_ref_loc_p, heap, accs->locs, aref);
1270   bitmap_set_bit (ril, ref->id);
1271 }
1272
1273 /* Marks reference REF as stored in LOOP.  */
1274
1275 static void
1276 mark_ref_stored (mem_ref_p ref, struct loop *loop)
1277 {
1278   for (;
1279        loop != current_loops->tree_root
1280        && !bitmap_bit_p (ref->stored, loop->num);
1281        loop = loop_outer (loop))
1282     bitmap_set_bit (ref->stored, loop->num);
1283 }
1284
1285 /* Gathers memory references in statement STMT in LOOP, storing the
1286    information about them in the memory_accesses structure.  Marks
1287    the vops accessed through unrecognized statements there as
1288    well.  */
1289
1290 static void
1291 gather_mem_refs_stmt (struct loop *loop, tree stmt)
1292 {
1293   tree *mem = NULL;
1294   hashval_t hash;
1295   PTR *slot;
1296   mem_ref_p ref;
1297   ssa_op_iter oi;
1298   tree vname;
1299   bool is_stored;
1300   bitmap clvops;
1301   unsigned id;
1302
1303   if (ZERO_SSA_OPERANDS (stmt, SSA_OP_ALL_VIRTUALS))
1304     return;
1305
1306   mem = simple_mem_ref_in_stmt (stmt, &is_stored);
1307   if (!mem)
1308     goto fail;
1309
1310   hash = iterative_hash_expr (*mem, 0);
1311   slot = htab_find_slot_with_hash (memory_accesses.refs, *mem, hash, INSERT);
1312
1313   if (*slot)
1314     {
1315       ref = *slot;
1316       id = ref->id;
1317     }
1318   else
1319     {
1320       id = VEC_length (mem_ref_p, memory_accesses.refs_list);
1321       ref = mem_ref_alloc (*mem, hash, id);
1322       VEC_safe_push (mem_ref_p, heap, memory_accesses.refs_list, ref);
1323       *slot = ref;
1324
1325       if (dump_file && (dump_flags & TDF_DETAILS))
1326         {
1327           fprintf (dump_file, "Memory reference %u: ", id);
1328           print_generic_expr (dump_file, ref->mem, TDF_SLIM);
1329           fprintf (dump_file, "\n");
1330         }
1331     }
1332   if (is_stored)
1333     mark_ref_stored (ref, loop);
1334
1335   FOR_EACH_SSA_TREE_OPERAND (vname, stmt, oi, SSA_OP_VIRTUAL_USES)
1336     bitmap_set_bit (ref->vops, DECL_UID (SSA_NAME_VAR (vname)));
1337   record_mem_ref_loc (ref, loop, stmt, mem);
1338   return;
1339
1340 fail:
1341   clvops = VEC_index (bitmap, memory_accesses.clobbered_vops, loop->num);
1342   FOR_EACH_SSA_TREE_OPERAND (vname, stmt, oi, SSA_OP_VIRTUAL_USES)
1343     bitmap_set_bit (clvops, DECL_UID (SSA_NAME_VAR (vname)));
1344 }
1345
1346 /* Gathers memory references in loops.  */
1347
1348 static void
1349 gather_mem_refs_in_loops (void)
1350 {
1351   block_stmt_iterator bsi;
1352   basic_block bb;
1353   struct loop *loop;
1354   loop_iterator li;
1355   bitmap clvo, clvi;
1356   bitmap lrefs, alrefs, alrefso;
1357
1358   FOR_EACH_BB (bb)
1359     {
1360       loop = bb->loop_father;
1361       if (loop == current_loops->tree_root)
1362         continue;
1363
1364       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1365         gather_mem_refs_stmt (loop, bsi_stmt (bsi));
1366     }
1367
1368   /* Propagate the information about clobbered vops and accessed memory
1369      references up the loop hierarchy.  */
1370   FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
1371     {
1372       lrefs = VEC_index (bitmap, memory_accesses.refs_in_loop, loop->num);
1373       alrefs = VEC_index (bitmap, memory_accesses.all_refs_in_loop, loop->num);
1374       bitmap_ior_into (alrefs, lrefs);
1375
1376       if (loop_outer (loop) == current_loops->tree_root)
1377         continue;
1378
1379       clvi = VEC_index (bitmap, memory_accesses.clobbered_vops, loop->num);
1380       clvo = VEC_index (bitmap, memory_accesses.clobbered_vops,
1381                         loop_outer (loop)->num);
1382       bitmap_ior_into (clvo, clvi);
1383
1384       alrefso = VEC_index (bitmap, memory_accesses.all_refs_in_loop,
1385                            loop_outer (loop)->num);
1386       bitmap_ior_into (alrefso, alrefs);
1387     }
1388 }
1389
1390 /* Element of the hash table that maps vops to memory references.  */
1391
1392 struct vop_to_refs_elt
1393 {
1394   /* DECL_UID of the vop.  */
1395   unsigned uid;
1396
1397   /* List of the all references.  */
1398   bitmap refs_all;
1399
1400   /* List of stored references.  */
1401   bitmap refs_stored;
1402 };
1403
1404 /* A hash function for struct vop_to_refs_elt object OBJ.  */
1405
1406 static hashval_t
1407 vtoe_hash (const void *obj)
1408 {
1409   const struct vop_to_refs_elt *vtoe = obj;
1410
1411   return vtoe->uid;
1412 }
1413
1414 /* An equality function for struct vop_to_refs_elt object OBJ1 with
1415    uid of a vop OBJ2.  */
1416
1417 static int
1418 vtoe_eq (const void *obj1, const void *obj2)
1419 {
1420   const struct vop_to_refs_elt *vtoe = obj1;
1421   const unsigned *uid = obj2;
1422
1423   return vtoe->uid == *uid;
1424 }
1425
1426 /* A function to free the struct vop_to_refs_elt object.  */
1427
1428 static void
1429 vtoe_free (void *obj)
1430 {
1431   struct vop_to_refs_elt *vtoe = obj;
1432
1433   BITMAP_FREE (vtoe->refs_all);
1434   BITMAP_FREE (vtoe->refs_stored);
1435   free (vtoe);
1436 }
1437
1438 /* Records REF to hashtable VOP_TO_REFS for the index VOP.  STORED is true
1439    if the reference REF is stored.  */
1440
1441 static void
1442 record_vop_access (htab_t vop_to_refs, unsigned vop, unsigned ref, bool stored)
1443 {
1444   void **slot = htab_find_slot_with_hash (vop_to_refs, &vop, vop, INSERT);
1445   struct vop_to_refs_elt *vtoe;
1446
1447   if (!*slot)
1448     {
1449       vtoe = XNEW (struct vop_to_refs_elt);
1450       vtoe->uid = vop;
1451       vtoe->refs_all = BITMAP_ALLOC (NULL);
1452       vtoe->refs_stored = BITMAP_ALLOC (NULL);
1453       *slot = vtoe;
1454     }
1455   else
1456     vtoe = *slot;
1457
1458   bitmap_set_bit (vtoe->refs_all, ref);
1459   if (stored)
1460     bitmap_set_bit (vtoe->refs_stored, ref);
1461 }
1462
1463 /* Returns the set of references that access VOP according to the table
1464    VOP_TO_REFS.  */
1465
1466 static bitmap
1467 get_vop_accesses (htab_t vop_to_refs, unsigned vop)
1468 {
1469   struct vop_to_refs_elt *vtoe = htab_find_with_hash (vop_to_refs, &vop, vop);
1470   return vtoe->refs_all;
1471 }
1472
1473 /* Returns the set of stores that access VOP according to the table
1474    VOP_TO_REFS.  */
1475
1476 static bitmap
1477 get_vop_stores (htab_t vop_to_refs, unsigned vop)
1478 {
1479   struct vop_to_refs_elt *vtoe = htab_find_with_hash (vop_to_refs, &vop, vop);
1480   return vtoe->refs_stored;
1481 }
1482
1483 /* Adds REF to mapping from virtual operands to references in LOOP.  */
1484
1485 static void
1486 add_vop_ref_mapping (struct loop *loop, mem_ref_p ref)
1487 {
1488   htab_t map = VEC_index (htab_t, memory_accesses.vop_ref_map, loop->num);
1489   bool stored = bitmap_bit_p (ref->stored, loop->num);
1490   bitmap clobbers = VEC_index (bitmap, memory_accesses.clobbered_vops,
1491                                loop->num);
1492   bitmap_iterator bi;
1493   unsigned vop;
1494
1495   EXECUTE_IF_AND_COMPL_IN_BITMAP (ref->vops, clobbers, 0, vop, bi)
1496     {
1497       record_vop_access (map, vop, ref->id, stored);
1498     }
1499 }
1500
1501 /* Create a mapping from virtual operands to references that touch them
1502    in LOOP.  */
1503
1504 static void
1505 create_vop_ref_mapping_loop (struct loop *loop)
1506 {
1507   bitmap refs = VEC_index (bitmap, memory_accesses.refs_in_loop, loop->num);
1508   struct loop *sloop;
1509   bitmap_iterator bi;
1510   unsigned i;
1511   mem_ref_p ref;
1512
1513   EXECUTE_IF_SET_IN_BITMAP (refs, 0, i, bi)
1514     {
1515       ref = VEC_index (mem_ref_p, memory_accesses.refs_list, i);
1516       for (sloop = loop; sloop != current_loops->tree_root; sloop = loop_outer (sloop))
1517         add_vop_ref_mapping (sloop, ref);
1518     }
1519 }
1520
1521 /* For each non-clobbered virtual operand and each loop, record the memory
1522    references in this loop that touch the operand.  */
1523
1524 static void
1525 create_vop_ref_mapping (void)
1526 {
1527   loop_iterator li;
1528   struct loop *loop;
1529
1530   FOR_EACH_LOOP (li, loop, 0)
1531     {
1532       create_vop_ref_mapping_loop (loop);
1533     }
1534 }
1535
1536 /* Gathers information about memory accesses in the loops.  */
1537
1538 static void
1539 analyze_memory_references (void)
1540 {
1541   unsigned i;
1542   bitmap empty;
1543   htab_t hempty;
1544
1545   memory_accesses.refs
1546           = htab_create (100, memref_hash, memref_eq, memref_free);
1547   memory_accesses.refs_list = NULL;
1548   memory_accesses.refs_in_loop = VEC_alloc (bitmap, heap,
1549                                             number_of_loops ());
1550   memory_accesses.all_refs_in_loop = VEC_alloc (bitmap, heap,
1551                                                 number_of_loops ());
1552   memory_accesses.clobbered_vops = VEC_alloc (bitmap, heap,
1553                                               number_of_loops ());
1554   memory_accesses.vop_ref_map = VEC_alloc (htab_t, heap,
1555                                            number_of_loops ());
1556
1557   for (i = 0; i < number_of_loops (); i++)
1558     {
1559       empty = BITMAP_ALLOC (NULL);
1560       VEC_quick_push (bitmap, memory_accesses.refs_in_loop, empty);
1561       empty = BITMAP_ALLOC (NULL);
1562       VEC_quick_push (bitmap, memory_accesses.all_refs_in_loop, empty);
1563       empty = BITMAP_ALLOC (NULL);
1564       VEC_quick_push (bitmap, memory_accesses.clobbered_vops, empty);
1565       hempty = htab_create (10, vtoe_hash, vtoe_eq, vtoe_free);
1566       VEC_quick_push (htab_t, memory_accesses.vop_ref_map, hempty);
1567     }
1568
1569   memory_accesses.ttae_cache = NULL;
1570
1571   gather_mem_refs_in_loops ();
1572   create_vop_ref_mapping ();
1573 }
1574
1575 /* Returns true if a region of size SIZE1 at position 0 and a region of
1576    size SIZE2 at position DIFF cannot overlap.  */
1577
1578 static bool
1579 cannot_overlap_p (aff_tree *diff, double_int size1, double_int size2)
1580 {
1581   double_int d, bound;
1582
1583   /* Unless the difference is a constant, we fail.  */
1584   if (diff->n != 0)
1585     return false;
1586
1587   d = diff->offset;
1588   if (double_int_negative_p (d))
1589     {
1590       /* The second object is before the first one, we succeed if the last
1591          element of the second object is before the start of the first one.  */
1592       bound = double_int_add (d, double_int_add (size2, double_int_minus_one));
1593       return double_int_negative_p (bound);
1594     }
1595   else
1596     {
1597       /* We succeed if the second object starts after the first one ends.  */
1598       return double_int_scmp (size1, d) <= 0;
1599     }
1600 }
1601
1602 /* Returns true if MEM1 and MEM2 may alias.  TTAE_CACHE is used as a cache in
1603    tree_to_aff_combination_expand.  */
1604
1605 static bool
1606 mem_refs_may_alias_p (tree mem1, tree mem2, struct pointer_map_t **ttae_cache)
1607 {
1608   /* Perform BASE + OFFSET analysis -- if MEM1 and MEM2 are based on the same
1609      object and their offset differ in such a way that the locations cannot
1610      overlap, then they cannot alias.  */
1611   aff_tree off1, off2;
1612   double_int size1, size2;
1613   tree base1, base2;
1614
1615   /* If MEM1 and MEM2 are based on different variables, they cannot alias.  */
1616   base1 = get_base_address (mem1);
1617   base2 = get_base_address (mem2);
1618
1619   if (base1
1620       && !INDIRECT_REF_P (base1)
1621       && base2
1622       && !INDIRECT_REF_P (base2)
1623       && !operand_equal_p (base1, base2, 0))
1624     return false;
1625
1626   /* With strict aliasing, it is impossible to access a scalar variable through
1627      anything but a pointer dereference or through a union (gcc extension).  */
1628   if (flag_strict_aliasing)
1629     {
1630       if (!INDIRECT_REF_P (mem1)
1631           && base1
1632           && TREE_CODE (TREE_TYPE (base1)) != UNION_TYPE
1633           && SSA_VAR_P (mem2)
1634           && !AGGREGATE_TYPE_P (TREE_TYPE (mem2)))
1635         return false;
1636       if (!INDIRECT_REF_P (mem2)
1637           && base2
1638           && TREE_CODE (TREE_TYPE (base2)) != UNION_TYPE
1639           && SSA_VAR_P (mem1)
1640           && !AGGREGATE_TYPE_P (TREE_TYPE (mem1)))
1641         return false;
1642       if (!alias_sets_conflict_p (get_alias_set (mem1), get_alias_set (mem2)))
1643         return false;
1644     }
1645
1646   /* The expansion of addresses may be a bit expensive, thus we only do
1647      the check at -O2 and higher optimization levels.  */
1648   if (optimize < 2)
1649     return true;
1650
1651   get_inner_reference_aff (mem1, &off1, &size1);
1652   get_inner_reference_aff (mem2, &off2, &size2);
1653   aff_combination_expand (&off1, ttae_cache);
1654   aff_combination_expand (&off2, ttae_cache);
1655   aff_combination_scale (&off1, double_int_minus_one);
1656   aff_combination_add (&off2, &off1);
1657
1658   if (cannot_overlap_p (&off2, size1, size2))
1659     return false;
1660
1661   return true;
1662 }
1663
1664 /* Rewrites location LOC by TMP_VAR.  */
1665
1666 static void
1667 rewrite_mem_ref_loc (mem_ref_loc_p loc, tree tmp_var)
1668 {
1669   mark_virtual_ops_for_renaming (loc->stmt);
1670   *loc->ref = tmp_var;
1671   update_stmt (loc->stmt);
1672 }
1673
1674 /* Adds all locations of REF in LOOP and its subloops to LOCS.  */
1675
1676 static void
1677 get_all_locs_in_loop (struct loop *loop, mem_ref_p ref,
1678                       VEC (mem_ref_loc_p, heap) **locs)
1679 {
1680   mem_ref_locs_p accs;
1681   unsigned i;
1682   mem_ref_loc_p loc;
1683   bitmap refs = VEC_index (bitmap, memory_accesses.all_refs_in_loop,
1684                            loop->num);
1685   struct loop *subloop;
1686
1687   if (!bitmap_bit_p (refs, ref->id))
1688     return;
1689
1690   if (VEC_length (mem_ref_locs_p, ref->accesses_in_loop)
1691       > (unsigned) loop->num)
1692     {
1693       accs = VEC_index (mem_ref_locs_p, ref->accesses_in_loop, loop->num);
1694       if (accs)
1695         {
1696           for (i = 0; VEC_iterate (mem_ref_loc_p, accs->locs, i, loc); i++)
1697             VEC_safe_push (mem_ref_loc_p, heap, *locs, loc);
1698         }
1699     }
1700
1701   for (subloop = loop->inner; subloop != NULL; subloop = subloop->next)
1702     get_all_locs_in_loop (subloop, ref, locs);
1703 }
1704
1705 /* Rewrites all references to REF in LOOP by variable TMP_VAR.  */
1706
1707 static void
1708 rewrite_mem_refs (struct loop *loop, mem_ref_p ref, tree tmp_var)
1709 {
1710   unsigned i;
1711   mem_ref_loc_p loc;
1712   VEC (mem_ref_loc_p, heap) *locs = NULL;
1713
1714   get_all_locs_in_loop (loop, ref, &locs);
1715   for (i = 0; VEC_iterate (mem_ref_loc_p, locs, i, loc); i++)
1716     rewrite_mem_ref_loc (loc, tmp_var);
1717   VEC_free (mem_ref_loc_p, heap, locs);
1718 }
1719
1720 /* The name and the length of the currently generated variable
1721    for lsm.  */
1722 #define MAX_LSM_NAME_LENGTH 40
1723 static char lsm_tmp_name[MAX_LSM_NAME_LENGTH + 1];
1724 static int lsm_tmp_name_length;
1725
1726 /* Adds S to lsm_tmp_name.  */
1727
1728 static void
1729 lsm_tmp_name_add (const char *s)
1730 {
1731   int l = strlen (s) + lsm_tmp_name_length;
1732   if (l > MAX_LSM_NAME_LENGTH)
1733     return;
1734
1735   strcpy (lsm_tmp_name + lsm_tmp_name_length, s);
1736   lsm_tmp_name_length = l;
1737 }
1738
1739 /* Stores the name for temporary variable that replaces REF to
1740    lsm_tmp_name.  */
1741
1742 static void
1743 gen_lsm_tmp_name (tree ref)
1744 {
1745   const char *name;
1746
1747   switch (TREE_CODE (ref))
1748     {
1749     case MISALIGNED_INDIRECT_REF:
1750     case ALIGN_INDIRECT_REF:
1751     case INDIRECT_REF:
1752       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1753       lsm_tmp_name_add ("_");
1754       break;
1755
1756     case BIT_FIELD_REF:
1757     case VIEW_CONVERT_EXPR:
1758     case ARRAY_RANGE_REF:
1759       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1760       break;
1761
1762     case REALPART_EXPR:
1763       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1764       lsm_tmp_name_add ("_RE");
1765       break;
1766       
1767     case IMAGPART_EXPR:
1768       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1769       lsm_tmp_name_add ("_IM");
1770       break;
1771
1772     case COMPONENT_REF:
1773       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1774       lsm_tmp_name_add ("_");
1775       name = get_name (TREE_OPERAND (ref, 1));
1776       if (!name)
1777         name = "F";
1778       lsm_tmp_name_add ("_");
1779       lsm_tmp_name_add (name);
1780
1781     case ARRAY_REF:
1782       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1783       lsm_tmp_name_add ("_I");
1784       break;
1785
1786     case SSA_NAME:
1787       ref = SSA_NAME_VAR (ref);
1788       /* Fallthru.  */
1789
1790     case VAR_DECL:
1791     case PARM_DECL:
1792       name = get_name (ref);
1793       if (!name)
1794         name = "D";
1795       lsm_tmp_name_add (name);
1796       break;
1797
1798     case STRING_CST:
1799       lsm_tmp_name_add ("S");
1800       break;
1801
1802     case RESULT_DECL:
1803       lsm_tmp_name_add ("R");
1804       break;
1805
1806     default:
1807       gcc_unreachable ();
1808     }
1809 }
1810
1811 /* Determines name for temporary variable that replaces REF.
1812    The name is accumulated into the lsm_tmp_name variable.
1813    N is added to the name of the temporary.  */
1814
1815 char *
1816 get_lsm_tmp_name (tree ref, unsigned n)
1817 {
1818   char ns[2];
1819
1820   lsm_tmp_name_length = 0;
1821   gen_lsm_tmp_name (ref);
1822   lsm_tmp_name_add ("_lsm");
1823   if (n < 10)
1824     {
1825       ns[0] = '0' + n;
1826       ns[1] = 0;
1827       lsm_tmp_name_add (ns);
1828     }
1829   return lsm_tmp_name;
1830 }
1831
1832 /* Executes store motion of memory reference REF from LOOP.
1833    Exits from the LOOP are stored in EXITS.  The initialization of the
1834    temporary variable is put to the preheader of the loop, and assignments
1835    to the reference from the temporary variable are emitted to exits.  */
1836
1837 static void
1838 execute_sm (struct loop *loop, VEC (edge, heap) *exits, mem_ref_p ref)
1839 {
1840   tree tmp_var;
1841   unsigned i;
1842   tree load, store;
1843   struct fmt_data fmt_data;
1844   edge ex;
1845
1846   if (dump_file && (dump_flags & TDF_DETAILS))
1847     {
1848       fprintf (dump_file, "Executing store motion of ");
1849       print_generic_expr (dump_file, ref->mem, 0);
1850       fprintf (dump_file, " from loop %d\n", loop->num);
1851     }
1852
1853   tmp_var = make_rename_temp (TREE_TYPE (ref->mem),
1854                               get_lsm_tmp_name (ref->mem, ~0));
1855
1856   fmt_data.loop = loop;
1857   fmt_data.orig_loop = loop;
1858   for_each_index (&ref->mem, force_move_till, &fmt_data);
1859
1860   rewrite_mem_refs (loop, ref, tmp_var);
1861
1862   /* Emit the load & stores.  */
1863   load = build_gimple_modify_stmt (tmp_var, unshare_expr (ref->mem));
1864   get_stmt_ann (load)->common.aux = xcalloc (1, sizeof (struct lim_aux_data));
1865   LIM_DATA (load)->max_loop = loop;
1866   LIM_DATA (load)->tgt_loop = loop;
1867
1868   /* Put this into the latch, so that we are sure it will be processed after
1869      all dependencies.  */
1870   bsi_insert_on_edge (loop_latch_edge (loop), load);
1871
1872   for (i = 0; VEC_iterate (edge, exits, i, ex); i++)
1873     {
1874       store = build_gimple_modify_stmt (unshare_expr (ref->mem), tmp_var);
1875       bsi_insert_on_edge (ex, store);
1876     }
1877 }
1878
1879 /* Hoists memory references MEM_REFS out of LOOP.  EXITS is the list of exit
1880    edges of the LOOP.  */
1881
1882 static void
1883 hoist_memory_references (struct loop *loop, bitmap mem_refs,
1884                          VEC (edge, heap) *exits)
1885 {
1886   mem_ref_p ref;
1887   unsigned  i;
1888   bitmap_iterator bi;
1889
1890   EXECUTE_IF_SET_IN_BITMAP (mem_refs, 0, i, bi)
1891     {
1892       ref = VEC_index (mem_ref_p, memory_accesses.refs_list, i);
1893       execute_sm (loop, exits, ref);
1894     }
1895 }
1896
1897 /* Returns true if REF is always accessed in LOOP.  */
1898
1899 static bool
1900 ref_always_accessed_p (struct loop *loop, mem_ref_p ref)
1901 {
1902   VEC (mem_ref_loc_p, heap) *locs = NULL;
1903   unsigned i;
1904   mem_ref_loc_p loc;
1905   bool ret = false;
1906   struct loop *must_exec;
1907
1908   get_all_locs_in_loop (loop, ref, &locs);
1909   for (i = 0; VEC_iterate (mem_ref_loc_p, locs, i, loc); i++)
1910     {
1911       if (!LIM_DATA (loc->stmt))
1912         continue;
1913
1914       must_exec = LIM_DATA (loc->stmt)->always_executed_in;
1915       if (!must_exec)
1916         continue;
1917
1918       if (must_exec == loop
1919           || flow_loop_nested_p (must_exec, loop))
1920         {
1921           ret = true;
1922           break;
1923         }
1924     }
1925   VEC_free (mem_ref_loc_p, heap, locs);
1926
1927   return ret;
1928 }
1929
1930 /* Returns true if REF1 and REF2 are independent.  */
1931
1932 static bool
1933 refs_independent_p (mem_ref_p ref1, mem_ref_p ref2)
1934 {
1935   if (ref1 == ref2
1936       || bitmap_bit_p (ref1->indep_ref, ref2->id))
1937     return true;
1938   if (bitmap_bit_p (ref1->dep_ref, ref2->id))
1939     return false;
1940
1941   if (dump_file && (dump_flags & TDF_DETAILS))
1942     fprintf (dump_file, "Querying dependency of refs %u and %u: ",
1943              ref1->id, ref2->id);
1944
1945   if (mem_refs_may_alias_p (ref1->mem, ref2->mem,
1946                             &memory_accesses.ttae_cache))
1947     {
1948       bitmap_set_bit (ref1->dep_ref, ref2->id);
1949       bitmap_set_bit (ref2->dep_ref, ref1->id);
1950       if (dump_file && (dump_flags & TDF_DETAILS))
1951         fprintf (dump_file, "dependent.\n");
1952       return false;
1953     }
1954   else
1955     {
1956       bitmap_set_bit (ref1->indep_ref, ref2->id);
1957       bitmap_set_bit (ref2->indep_ref, ref1->id);
1958       if (dump_file && (dump_flags & TDF_DETAILS))
1959         fprintf (dump_file, "independent.\n");
1960       return true;
1961     }
1962 }
1963
1964 /* Records the information whether REF is independent in LOOP (according
1965    to INDEP).  */
1966
1967 static void
1968 record_indep_loop (struct loop *loop, mem_ref_p ref, bool indep)
1969 {
1970   if (indep)
1971     bitmap_set_bit (ref->indep_loop, loop->num);
1972   else
1973     bitmap_set_bit (ref->dep_loop, loop->num);
1974 }
1975
1976 /* Returns true if REF is independent on all other memory references in
1977    LOOP.  */
1978
1979 static bool
1980 ref_indep_loop_p_1 (struct loop *loop, mem_ref_p ref)
1981 {
1982   bitmap clobbers, refs_to_check, refs;
1983   unsigned i;
1984   bitmap_iterator bi;
1985   bool ret = true, stored = bitmap_bit_p (ref->stored, loop->num);
1986   htab_t map;
1987   mem_ref_p aref;
1988
1989   /* If the reference is clobbered, it is not independent.  */
1990   clobbers = VEC_index (bitmap, memory_accesses.clobbered_vops, loop->num);
1991   if (bitmap_intersect_p (ref->vops, clobbers))
1992     return false;
1993
1994   refs_to_check = BITMAP_ALLOC (NULL);
1995
1996   map = VEC_index (htab_t, memory_accesses.vop_ref_map, loop->num);
1997   EXECUTE_IF_AND_COMPL_IN_BITMAP (ref->vops, clobbers, 0, i, bi)
1998     {
1999       if (stored)
2000         refs = get_vop_accesses (map, i);
2001       else
2002         refs = get_vop_stores (map, i);
2003
2004       bitmap_ior_into (refs_to_check, refs);
2005     }
2006
2007   EXECUTE_IF_SET_IN_BITMAP (refs_to_check, 0, i, bi)
2008     {
2009       aref = VEC_index (mem_ref_p, memory_accesses.refs_list, i);
2010       if (!refs_independent_p (ref, aref))
2011         {
2012           ret = false;
2013           record_indep_loop (loop, aref, false);
2014           break;
2015         }
2016     }
2017
2018   BITMAP_FREE (refs_to_check);
2019   return ret;
2020 }
2021
2022 /* Returns true if REF is independent on all other memory references in
2023    LOOP.  Wrapper over ref_indep_loop_p_1, caching its results.  */
2024
2025 static bool
2026 ref_indep_loop_p (struct loop *loop, mem_ref_p ref)
2027 {
2028   bool ret;
2029
2030   if (bitmap_bit_p (ref->indep_loop, loop->num))
2031     return true;
2032   if (bitmap_bit_p (ref->dep_loop, loop->num))
2033     return false;
2034
2035   ret = ref_indep_loop_p_1 (loop, ref);
2036
2037   if (dump_file && (dump_flags & TDF_DETAILS))
2038     fprintf (dump_file, "Querying dependencies of ref %u in loop %d: %s\n",
2039              ref->id, loop->num, ret ? "independent" : "dependent");
2040
2041   record_indep_loop (loop, ref, ret);
2042
2043   return ret;
2044 }
2045
2046 /* Returns true if we can perform store motion of REF from LOOP.  */
2047
2048 static bool
2049 can_sm_ref_p (struct loop *loop, mem_ref_p ref)
2050 {
2051   /* Unless the reference is stored in the loop, there is nothing to do.  */
2052   if (!bitmap_bit_p (ref->stored, loop->num))
2053     return false;
2054
2055   /* It should be movable.  */
2056   if (!is_gimple_reg_type (TREE_TYPE (ref->mem))
2057       || TREE_THIS_VOLATILE (ref->mem)
2058       || !for_each_index (&ref->mem, may_move_till, loop))
2059     return false;
2060
2061   /* If it can trap, it must be always executed in LOOP.  */
2062   if (tree_could_trap_p (ref->mem)
2063       && !ref_always_accessed_p (loop, ref))
2064     return false;
2065
2066   /* And it must be independent on all other memory references
2067      in LOOP.  */
2068   if (!ref_indep_loop_p (loop, ref))
2069     return false;
2070
2071   return true;
2072 }
2073
2074 /* Marks the references in LOOP for that store motion should be performed
2075    in REFS_TO_SM.  SM_EXECUTED is the set of references for that store
2076    motion was performed in one of the outer loops.  */
2077
2078 static void
2079 find_refs_for_sm (struct loop *loop, bitmap sm_executed, bitmap refs_to_sm)
2080 {
2081   bitmap refs = VEC_index (bitmap, memory_accesses.all_refs_in_loop,
2082                            loop->num);
2083   unsigned i;
2084   bitmap_iterator bi;
2085   mem_ref_p ref;
2086
2087   EXECUTE_IF_AND_COMPL_IN_BITMAP (refs, sm_executed, 0, i, bi)
2088     {
2089       ref = VEC_index (mem_ref_p, memory_accesses.refs_list, i);
2090       if (can_sm_ref_p (loop, ref))
2091         bitmap_set_bit (refs_to_sm, i);
2092     }
2093 }
2094
2095 /* Checks whether LOOP (with exits stored in EXITS array) is suitable
2096    for a store motion optimization (i.e. whether we can insert statement
2097    on its exits).  */
2098
2099 static bool
2100 loop_suitable_for_sm (struct loop *loop ATTRIBUTE_UNUSED,
2101                       VEC (edge, heap) *exits)
2102 {
2103   unsigned i;
2104   edge ex;
2105
2106   for (i = 0; VEC_iterate (edge, exits, i, ex); i++)
2107     if (ex->flags & EDGE_ABNORMAL)
2108       return false;
2109
2110   return true;
2111 }
2112
2113 /* Try to perform store motion for all memory references modified inside
2114    LOOP.  SM_EXECUTED is the bitmap of the memory references for that
2115    store motion was executed in one of the outer loops.  */
2116
2117 static void
2118 store_motion_loop (struct loop *loop, bitmap sm_executed)
2119 {
2120   VEC (edge, heap) *exits = get_loop_exit_edges (loop);
2121   struct loop *subloop;
2122   bitmap sm_in_loop = BITMAP_ALLOC (NULL);
2123
2124   if (loop_suitable_for_sm (loop, exits))
2125     {
2126       find_refs_for_sm (loop, sm_executed, sm_in_loop);
2127       hoist_memory_references (loop, sm_in_loop, exits);
2128     }
2129   VEC_free (edge, heap, exits);
2130
2131   bitmap_ior_into (sm_executed, sm_in_loop);
2132   for (subloop = loop->inner; subloop != NULL; subloop = subloop->next)
2133     store_motion_loop (subloop, sm_executed);
2134   bitmap_and_compl_into (sm_executed, sm_in_loop);
2135   BITMAP_FREE (sm_in_loop);
2136 }
2137
2138 /* Try to perform store motion for all memory references modified inside
2139    loops.  */
2140
2141 static void
2142 store_motion (void)
2143 {
2144   struct loop *loop;
2145   bitmap sm_executed = BITMAP_ALLOC (NULL);
2146
2147   for (loop = current_loops->tree_root->inner; loop != NULL; loop = loop->next)
2148     store_motion_loop (loop, sm_executed);
2149
2150   BITMAP_FREE (sm_executed);
2151   bsi_commit_edge_inserts ();
2152 }
2153
2154 /* Fills ALWAYS_EXECUTED_IN information for basic blocks of LOOP, i.e.
2155    for each such basic block bb records the outermost loop for that execution
2156    of its header implies execution of bb.  CONTAINS_CALL is the bitmap of
2157    blocks that contain a nonpure call.  */
2158
2159 static void
2160 fill_always_executed_in (struct loop *loop, sbitmap contains_call)
2161 {
2162   basic_block bb = NULL, *bbs, last = NULL;
2163   unsigned i;
2164   edge e;
2165   struct loop *inn_loop = loop;
2166
2167   if (!loop->header->aux)
2168     {
2169       bbs = get_loop_body_in_dom_order (loop);
2170
2171       for (i = 0; i < loop->num_nodes; i++)
2172         {
2173           edge_iterator ei;
2174           bb = bbs[i];
2175
2176           if (dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
2177             last = bb;
2178
2179           if (TEST_BIT (contains_call, bb->index))
2180             break;
2181
2182           FOR_EACH_EDGE (e, ei, bb->succs)
2183             if (!flow_bb_inside_loop_p (loop, e->dest))
2184               break;
2185           if (e)
2186             break;
2187
2188           /* A loop might be infinite (TODO use simple loop analysis
2189              to disprove this if possible).  */
2190           if (bb->flags & BB_IRREDUCIBLE_LOOP)
2191             break;
2192
2193           if (!flow_bb_inside_loop_p (inn_loop, bb))
2194             break;
2195
2196           if (bb->loop_father->header == bb)
2197             {
2198               if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
2199                 break;
2200
2201               /* In a loop that is always entered we may proceed anyway.
2202                  But record that we entered it and stop once we leave it.  */
2203               inn_loop = bb->loop_father;
2204             }
2205         }
2206
2207       while (1)
2208         {
2209           last->aux = loop;
2210           if (last == loop->header)
2211             break;
2212           last = get_immediate_dominator (CDI_DOMINATORS, last);
2213         }
2214
2215       free (bbs);
2216     }
2217
2218   for (loop = loop->inner; loop; loop = loop->next)
2219     fill_always_executed_in (loop, contains_call);
2220 }
2221
2222 /* Compute the global information needed by the loop invariant motion pass.  */
2223
2224 static void
2225 tree_ssa_lim_initialize (void)
2226 {
2227   sbitmap contains_call = sbitmap_alloc (last_basic_block);
2228   block_stmt_iterator bsi;
2229   struct loop *loop;
2230   basic_block bb;
2231
2232   sbitmap_zero (contains_call);
2233   FOR_EACH_BB (bb)
2234     {
2235       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
2236         {
2237           if (nonpure_call_p (bsi_stmt (bsi)))
2238             break;
2239         }
2240
2241       if (!bsi_end_p (bsi))
2242         SET_BIT (contains_call, bb->index);
2243     }
2244
2245   for (loop = current_loops->tree_root->inner; loop; loop = loop->next)
2246     fill_always_executed_in (loop, contains_call);
2247
2248   sbitmap_free (contains_call);
2249 }
2250
2251 /* Cleans up after the invariant motion pass.  */
2252
2253 static void
2254 tree_ssa_lim_finalize (void)
2255 {
2256   basic_block bb;
2257   unsigned i;
2258   bitmap b;
2259   htab_t h;
2260
2261   FOR_EACH_BB (bb)
2262     {
2263       bb->aux = NULL;
2264     }
2265
2266   VEC_free (mem_ref_p, heap, memory_accesses.refs_list);
2267   htab_delete (memory_accesses.refs);
2268
2269   for (i = 0; VEC_iterate (bitmap, memory_accesses.refs_in_loop, i, b); i++)
2270     BITMAP_FREE (b);
2271   VEC_free (bitmap, heap, memory_accesses.refs_in_loop);
2272
2273   for (i = 0; VEC_iterate (bitmap, memory_accesses.all_refs_in_loop, i, b); i++)
2274     BITMAP_FREE (b);
2275   VEC_free (bitmap, heap, memory_accesses.all_refs_in_loop);
2276
2277   for (i = 0; VEC_iterate (bitmap, memory_accesses.clobbered_vops, i, b); i++)
2278     BITMAP_FREE (b);
2279   VEC_free (bitmap, heap, memory_accesses.clobbered_vops);
2280
2281   for (i = 0; VEC_iterate (htab_t, memory_accesses.vop_ref_map, i, h); i++)
2282     htab_delete (h);
2283   VEC_free (htab_t, heap, memory_accesses.vop_ref_map);
2284
2285   if (memory_accesses.ttae_cache)
2286     pointer_map_destroy (memory_accesses.ttae_cache);
2287 }
2288
2289 /* Moves invariants from loops.  Only "expensive" invariants are moved out --
2290    i.e. those that are likely to be win regardless of the register pressure.  */
2291
2292 void
2293 tree_ssa_lim (void)
2294 {
2295   tree_ssa_lim_initialize ();
2296
2297   /* Gathers information about memory accesses in the loops.  */
2298   analyze_memory_references ();
2299
2300   /* For each statement determine the outermost loop in that it is
2301      invariant and cost for computing the invariant.  */
2302   determine_invariantness ();
2303
2304   /* Execute store motion.  Force the necessary invariants to be moved
2305      out of the loops as well.  */
2306   store_motion ();
2307
2308   /* Move the expressions that are expensive enough.  */
2309   move_computations ();
2310
2311   tree_ssa_lim_finalize ();
2312 }