4070a87a527439e1ef5fd1ec6317d13fa82a7144
[libfirm] / ir / opt / ldstopt.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/opt/ldstopt.c
4  * Purpose:     load store optimizations
5  * Author:
6  * Created:
7  * CVS-ID:      $Id$
8  * Copyright:   (c) 1998-2004 Universit\81ät Karlsruhe
9  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
10  */
11 #ifdef HAVE_CONFIG_H
12 # include "config.h"
13 #endif
14
15 #ifdef HAVE_ALLOCA_H
16 #include <alloca.h>
17 #endif
18 #ifdef HAVE_MALLOC_H
19 #include <malloc.h>
20 #endif
21 #ifdef HAVE_STRING_H
22 # include <string.h>
23 #endif
24
25 # include "irnode_t.h"
26 # include "irgraph_t.h"
27 # include "irmode_t.h"
28 # include "iropt_t.h"
29 # include "ircons_t.h"
30 # include "irgmod.h"
31 # include "irgwalk.h"
32 # include "irvrfy.h"
33 # include "tv_t.h"
34 # include "dbginfo_t.h"
35 # include "iropt_dbg.h"
36 # include "irflag_t.h"
37 # include "array.h"
38 # include "irhooks.h"
39 # include "opt_polymorphy.h"
40
41 #ifdef DO_CACHEOPT
42 #include "cacheopt/cachesim.h"
43 #endif
44
45 #undef IMAX
46 #define IMAX(a,b)       ((a) > (b) ? (a) : (b))
47
48 #define MAX_PROJ        IMAX(pn_Load_max, pn_Store_max)
49
50 /**
51  * walker environment
52  */
53 typedef struct _walk_env_t {
54   struct obstack obst;          /**< list of all stores */
55   int changes;
56 } walk_env_t;
57
58 /**
59  * flags for Load/Store
60  */
61 enum ldst_flags_t {
62   LDST_VISITED = 1              /**< if set, this Load/Store is already visited */
63 };
64
65 /**
66  * a Load/Store info
67  */
68 typedef struct _ldst_info_t {
69   ir_node  *projs[MAX_PROJ];    /**< list of Proj's of this node */
70   ir_node  *exc_block;          /**< the exception block if available */
71   int      exc_idx;             /**< predecessor index in the exception block */
72   unsigned flags;               /**< flags */
73 } ldst_info_t;
74
75 /**
76  * flags for control flow
77  */
78 enum block_flags_t {
79   BLOCK_HAS_COND = 1,      /**< Block has conditional control flow */
80   BLOCK_HAS_EXC  = 2       /**< Block has exceptionl control flow */
81 };
82
83 /**
84  * a Block info
85  */
86 typedef struct _block_info_t {
87   unsigned flags;               /**< flags for the block */
88 } block_info_t;
89
90 /**
91  * walker, clears all links first
92  */
93 static void init_links(ir_node *n, void *env)
94 {
95   set_irn_link(n, NULL);
96 }
97
98 /**
99  * get the Load/Store info of a node
100  */
101 static ldst_info_t *get_ldst_info(ir_node *node, walk_env_t *env)
102 {
103   ldst_info_t *info = get_irn_link(node);
104
105   if (! info) {
106     info = obstack_alloc(&env->obst, sizeof(*info));
107
108     memset(info, 0, sizeof(*info));
109
110     set_irn_link(node, info);
111   }
112   return info;
113 }
114
115 /**
116  * get the Block info of a node
117  */
118 static block_info_t *get_block_info(ir_node *node, walk_env_t *env)
119 {
120   block_info_t *info = get_irn_link(node);
121
122   if (! info) {
123     info = obstack_alloc(&env->obst, sizeof(*info));
124
125     memset(info, 0, sizeof(*info));
126
127     set_irn_link(node, info);
128   }
129   return info;
130 }
131
132 /**
133  * update the projection info for a Load/Store
134  */
135 static int update_projs(ldst_info_t *info, ir_node *proj)
136 {
137   long nr = get_Proj_proj(proj);
138
139   assert(0 <= nr && nr <= MAX_PROJ && "Wrong proj from LoadStore");
140
141   if (info->projs[nr]) {
142     /* there is already one, do CSE */
143     exchange(proj, info->projs[nr]);
144     return 1;
145   }
146   else {
147     info->projs[nr] = proj;
148     return 0;
149   }
150 }
151
152 /**
153  * update the exception block info for a Load/Store
154  */
155 static int update_exc(ldst_info_t *info, ir_node *block, int pos)
156 {
157   assert(info->exc_block == NULL && "more than one exception block found");
158
159   info->exc_block = block;
160   info->exc_idx   = pos;
161   return 0;
162 }
163
164 #define get_irn_out_n(node)     (unsigned)get_irn_link(node)
165 #define set_irn_out_n(node, n)  set_irn_link(adr, (void *)(n))
166
167 /**
168  * walker, collects all Load/Store/Proj nodes
169  *
170  * walks form Start -> End
171  */
172 static void collect_nodes(ir_node *node, void *env)
173 {
174   ir_op       *op = get_irn_op(node);
175   ir_node     *pred;
176   ldst_info_t *ldst_info;
177   walk_env_t  *wenv = env;
178
179   if (op == op_Proj) {
180     ir_node *adr;
181     ir_op *op;
182
183     pred = get_Proj_pred(node);
184     op   = get_irn_op(pred);
185
186     if (op == op_Load) {
187       ldst_info = get_ldst_info(pred, wenv);
188
189       wenv->changes |= update_projs(ldst_info, node);
190
191       if ((ldst_info->flags & LDST_VISITED) == 0) {
192         adr = get_Load_ptr(pred);
193         set_irn_out_n(adr, get_irn_out_n(adr) + 1);
194
195         ldst_info->flags |= LDST_VISITED;
196       }
197     }
198     else if (op == op_Store) {
199       ldst_info = get_ldst_info(pred, wenv);
200
201       wenv->changes |= update_projs(ldst_info, node);
202
203       if ((ldst_info->flags & LDST_VISITED) == 0) {
204         adr = get_Store_ptr(pred);
205         set_irn_out_n(adr, get_irn_out_n(adr) + 1);
206
207         ldst_info->flags |= LDST_VISITED;
208       }
209     }
210   }
211   else if (op == op_Block) { /* check, if it's an exception block */
212     int i, n;
213
214     for (i = 0, n = get_Block_n_cfgpreds(node); i < n; ++i) {
215       ir_node      *pred_block;
216       block_info_t *bl_info;
217
218       pred = skip_Proj(get_Block_cfgpred(node, i));
219
220       /* ignore Bad predecessors, they will be removed later */
221       if (is_Bad(pred))
222         continue;
223
224       pred_block = get_nodes_block(pred);
225       bl_info    = get_block_info(pred_block, wenv);
226
227       if (is_fragile_op(pred))
228         bl_info->flags |= BLOCK_HAS_EXC;
229       else if (is_forking_op(pred))
230         bl_info->flags |= BLOCK_HAS_COND;
231
232       if (get_irn_op(pred) == op_Load || get_irn_op(pred) == op_Store) {
233         ldst_info = get_ldst_info(pred, wenv);
234
235         wenv->changes |= update_exc(ldst_info, node, i);
236       }
237     }
238   }
239 }
240
241 /**
242  * Returns an entity if the address ptr points to a constant one.
243  */
244 static entity *find_constant_entity(ir_node *ptr)
245 {
246   for (;;) {
247     ir_op *op = get_irn_op(ptr);
248
249     if (op == op_SymConst && (get_SymConst_kind(ptr) == symconst_addr_ent)) {
250       return get_SymConst_entity(ptr);
251     }
252     else if (op == op_Sel) {
253       entity *ent = get_Sel_entity(ptr);
254       type *tp    = get_entity_owner(ent);
255
256       /* Do not fiddle about polymorphy. */
257       if (is_Class_type(get_entity_owner(ent)) &&
258           ((get_entity_n_overwrites(ent)    != 0) ||
259            (get_entity_n_overwrittenby(ent) != 0)   ) )
260         return NULL;
261
262       if (variability_constant == get_entity_variability(ent))
263         return ent;
264
265       if (is_Array_type(tp)) {
266         /* check bounds */
267         int i, n;
268
269         for (i = 0, n = get_Sel_n_indexs(ptr); i < n; ++i) {
270           ir_node *bound;
271           tarval *tlower, *tupper;
272           ir_node *index = get_Sel_index(ptr, i);
273           tarval *tv     = computed_value(index);
274
275           /* check if the index is constant */
276           if (tv == tarval_bad)
277             return NULL;
278
279           bound  = get_array_lower_bound(tp, i);
280           tlower = computed_value(bound);
281           bound  = get_array_upper_bound(tp, i);
282           tupper = computed_value(bound);
283
284           if (tlower == tarval_bad || tupper == tarval_bad)
285             return NULL;
286
287           if (tarval_cmp(tv, tlower) & pn_Cmp_Lt)
288             return NULL;
289           if (tarval_cmp(tupper, tv) & pn_Cmp_Lt)
290             return NULL;
291
292           /* ok, bounds check finished */
293         }
294       }
295
296       /* try next */
297       ptr = get_Sel_ptr(ptr);
298     }
299     else
300       return NULL;
301   }
302 }
303
304 static long get_Sel_array_index_long(ir_node *n, int dim) {
305   ir_node *index = get_Sel_index(n, dim);
306   assert(get_irn_op(index) == op_Const);
307   return get_tarval_long(get_Const_tarval(index));
308 }
309
310 compound_graph_path *rec_get_accessed_path(ir_node *ptr, int depth) {
311   compound_graph_path *res;
312   if (get_irn_op(ptr) == op_SymConst) {
313     assert(get_SymConst_kind(ptr) == symconst_addr_ent);
314     entity *root = get_SymConst_entity(ptr);
315     res = new_compound_graph_path(get_entity_type(root), depth);
316   } else {
317     assert(get_irn_op(ptr) == op_Sel);
318     res = rec_get_accessed_path(get_Sel_ptr(ptr), depth+1);
319     entity *field = get_Sel_entity(ptr);
320     int path_len = get_compound_graph_path_length(res);
321     int pos = path_len - depth -1;
322     set_compound_graph_path_node(res, pos, field);
323     if (is_Array_type(get_entity_owner(field))) {
324       assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
325       set_compound_graph_path_array_index(res, pos, get_Sel_array_index_long(ptr, 0));
326     }
327   }
328   return res;
329 }
330
331 compound_graph_path *get_accessed_path(ir_node *ptr) {
332   return rec_get_accessed_path(ptr, 0);
333 }
334
335
336 /**
337  * optimize a Load
338  */
339 static int optimize_load(ir_node *load)
340 {
341   ldst_info_t *info = get_irn_link(load);
342   ir_mode *load_mode = get_Load_mode(load);
343   ir_node *pred, *mem, *ptr;
344   entity *ent;
345   int res = 0;
346
347   /* the address of the load to be optimized */
348   ptr = get_Load_ptr(load);
349
350   /*
351    * Check if we can remove the exception form a Load:
352    * this can be done, if the address is from an Sel(Alloc) and
353    * the Sel type is a subtype of the alloc type.
354    *
355    * This optimizes some often used OO constructs,
356    * like x = new O; x->t;
357    */
358   if (info->projs[pn_Load_X_except]) {
359     if (get_irn_op(ptr) == op_Sel) {
360       ir_node *mem = get_Sel_mem(ptr);
361
362       if (get_irn_op(mem) == op_Alloc) {
363         /* ok, check the types */
364         entity *ent  = get_Sel_entity(ptr);
365         type *s_type = get_entity_type(ent);
366         type *a_type = get_Alloc_type(mem);
367
368         if (is_subclass_of(s_type, a_type)) {
369           /* ok, condition met: there can't be an exception because
370            * alloc guarantees that enough memory was allocated */
371
372           exchange(info->projs[pn_Load_X_except], new_Bad());
373           info->projs[pn_Load_X_except] = NULL;
374         }
375       }
376     }
377     else if (get_irn_op(ptr) == op_Alloc) {
378       /* simple case: a direct load after an Alloc. Firm Alloc throw
379        * an exception in case of out-of-memory. So, there is no way for an
380        * exception in this load.
381        * This code is constructed by the "exception lowering" in the Jack compiler.
382        */
383        exchange(info->projs[pn_Load_X_except], new_Bad());
384        info->projs[pn_Load_X_except] = NULL;
385     }
386   }
387
388   /* do NOT touch volatile loads for now */
389   if (get_Load_volatility(load) == volatility_is_volatile)
390     return 0;
391
392   if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
393     /* a Load which value is neither used nor exception checked, remove it */
394     mem  = get_Load_mem(load);
395     exchange(info->projs[pn_Load_M], mem);
396
397     return 1;
398   }
399
400   /* the mem of the Load. Must still be returned after optimization */
401   mem  = get_Load_mem(load);
402
403   /* Load from a constant polymorphic field, where we can resolve
404      polymorphy. */
405   ir_node *new_node = transform_node_Load(load);
406   if (new_node != load) {
407     if (info->projs[pn_Load_M]) {
408       exchange(info->projs[pn_Load_M], mem);
409       info->projs[pn_Load_M] = NULL;
410     }
411     if (info->projs[pn_Load_X_except]) {
412       exchange(info->projs[pn_Load_X_except], new_Bad());
413       info->projs[pn_Load_X_except] = NULL;
414     }
415     if (info->projs[pn_Load_res])
416       exchange(info->projs[pn_Load_res], new_node);
417     return 1;
418   }
419
420   /* check if we can determine the entity that will be loaded */
421   ent = find_constant_entity(ptr);
422   if (ent) {
423     if ((allocation_static == get_entity_allocation(ent)) &&
424         (visibility_external_allocated != get_entity_visibility(ent))) {
425       /* a static allocation that is not external: there should be NO exception
426        * when loading. */
427
428       /* no exception, clear the info field as it might be checked later again */
429       if (info->projs[pn_Load_X_except]) {
430         exchange(info->projs[pn_Load_X_except], new_Bad());
431         info->projs[pn_Load_X_except] = NULL;
432       }
433
434       if (variability_constant == get_entity_variability(ent)
435           && is_atomic_entity(ent)) {   /* Might not be atomic after
436                                          lowering of Sels.  In this
437                                          case we could also load, but
438                                          it's more complicated. */
439         /* more simpler case: we load the content of a constant value:
440          * replace it by the constant itself
441          */
442
443         /* no memory */
444         if (info->projs[pn_Load_M])
445           exchange(info->projs[pn_Load_M], mem);
446
447         /* no result :-) */
448         if (info->projs[pn_Load_res]) {
449           if (is_atomic_entity(ent)) {
450             ir_node *c = copy_const_value(get_atomic_ent_value(ent));
451
452             DBG_OPT_RC(load, c);
453             exchange(info->projs[pn_Load_res], c);
454
455             return 1;
456           }
457         }
458       }
459       else if (variability_constant == get_entity_variability(ent)) {
460         printf(">>>>>>>>>>>>> Found access to constant entity %s in function %s\n", get_entity_name(ent),
461                get_entity_name(get_irg_entity(current_ir_graph)));
462         printf("  load: "); DDMN(load);
463         printf("  ptr:  "); DDMN(ptr);
464
465         compound_graph_path *path = get_accessed_path(ptr);
466         assert(is_proper_compound_graph_path(path, get_compound_graph_path_length(path)-1));
467         ir_node *c = get_compound_ent_value_by_path(ent, path);
468
469         printf("  cons: "); DDMN(c);
470
471         if (info->projs[pn_Load_M])
472           exchange(info->projs[pn_Load_M], mem);
473         if (info->projs[pn_Load_res])
474           exchange(info->projs[pn_Load_res], copy_const_value(c));
475
476         {
477         int j;
478                 for (j = 0; j < get_compound_graph_path_length(path); ++j) {
479                   entity *node = get_compound_graph_path_node(path, j);
480                   fprintf(stdout, ".%s", get_entity_name(node));
481                   if (is_Array_type(get_entity_owner(node)))
482                     fprintf(stdout, "[%d]", get_compound_graph_path_array_index(path, j));
483                 }
484                 printf("\n");
485         }
486
487       }
488
489       /* we changed the irg, but try further */
490       res = 1;
491     }
492
493
494   }
495
496   /* Check, if the address of this load is used more than once.
497    * If not, this load cannot be removed in any case. */
498   if (get_irn_out_n(ptr) <= 1)
499     return 0;
500
501   /* follow the memory chain as long as there are only Loads */
502   for (pred = skip_Proj(mem); ; pred = skip_Proj(get_Load_mem(pred))) {
503
504     /*
505      * BEWARE: one might think that checking the modes is useless, because
506      * if the pointers are identical, they refer to the same object.
507      * This is only true in strong typed languages, not is C were the following
508      * is possible a = *(type1 *)p; b = *(type2 *)p ...
509      */
510
511     if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
512         get_irn_mode(get_Store_value(pred)) == load_mode) {
513       ldst_info_t *pred_info = get_irn_link(pred);
514
515       /*
516        * a Load immediately after a Store -- a read after write.
517        * We may remove the Load, if both Load & Store does not have an exception handler
518        * OR they are in the same block. In the latter case the Load cannot
519        * throw an exception when the previous Store was quiet.
520        *
521        * Why we need to check for Store Exc? If the Store cannot be executed (ROM)
522        * the exception handler might simply jump into the load block :-(
523        * We could make it a little bit better if we would know that the exception
524        * handler of the Store jumps directly to the end...
525        */
526       if ((!pred_info->projs[pn_Store_X_except] && !info->projs[pn_Load_X_except]) ||
527           get_nodes_block(load) == get_nodes_block(pred)) {
528         DBG_OPT_RAW(load, pred);
529         exchange( info->projs[pn_Load_res], get_Store_value(pred) );
530
531         if (info->projs[pn_Load_M])
532           exchange(info->projs[pn_Load_M], mem);
533
534         /* no exception */
535         if (info->projs[pn_Load_X_except])
536           exchange( info->projs[pn_Load_X_except], new_Bad());
537         return 1;
538       }
539     }
540     else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
541              get_Load_mode(pred) == load_mode) {
542       /*
543        * a Load after a Load -- a read after read.
544        * We may remove the second Load, if it does not have an exception handler
545        * OR they are in the same block. In the later case the Load cannot
546        * throw an exception when the previous Load was quiet.
547        *
548        * Here, there is no need to check if the previos Load has an exception hander because
549        * they would have exact the same exception...
550        */
551       if (! info->projs[pn_Load_X_except] || get_nodes_block(load) == get_nodes_block(pred)) {
552         ldst_info_t *pred_info = get_irn_link(pred);
553
554         DBG_OPT_RAR(load, pred);
555
556         if (pred_info->projs[pn_Load_res]) {
557           /* we need a data proj from the previous load for this optimization */
558           exchange( info->projs[pn_Load_res], pred_info->projs[pn_Load_res] );
559           if (info->projs[pn_Load_M])
560             exchange(info->projs[pn_Load_M], mem);
561         }
562         else {
563           if (info->projs[pn_Load_res]) {
564             set_Proj_pred(info->projs[pn_Load_res], pred);
565             set_nodes_block(info->projs[pn_Load_res], get_nodes_block(pred));
566           }
567           if (info->projs[pn_Load_M]) {
568             /* Actually, this if should not be necessary.  Construct the Loads
569                properly!!! */
570             exchange(info->projs[pn_Load_M], mem);
571           }
572         }
573
574         /* no exception */
575         if (info->projs[pn_Load_X_except])
576           exchange(info->projs[pn_Load_X_except], new_Bad());
577
578         return 1;
579       }
580     }
581
582     /* follow only Load chains */
583     if (get_irn_op(pred) != op_Load)
584       break;
585    }
586   return res;
587 }
588
589 /**
590  * optimize a Store
591  */
592 static int optimize_store(ir_node *store)
593 {
594   ldst_info_t *info = get_irn_link(store);
595   ir_node *pred, *mem, *ptr, *value, *block;
596   ir_mode *mode;
597   int res = 0;
598
599   if (get_Store_volatility(store) == volatility_is_volatile)
600     return 0;
601
602   /*
603    * BEWARE: one might think that checking the modes is useless, because
604    * if the pointers are identical, they refer to the same object.
605    * This is only true in strong typed languages, not is C were the following
606    * is possible *(type1 *)p = a; *(type2 *)p = b ...
607    */
608
609   ptr   = get_Store_ptr(store);
610
611   /* Check, if the address of this load is used more than once.
612    * If not, this load cannot be removed in any case. */
613   if (get_irn_out_n(ptr) <= 1)
614     return 0;
615
616   block = get_nodes_block(store);
617   mem   = get_Store_mem(store);
618   value = get_Store_value(store);
619   mode  = get_irn_mode(value);
620
621   /* follow the memory chain as long as there are only Loads */
622   for (pred = skip_Proj(mem); ; pred = skip_Proj(get_Load_mem(pred))) {
623     ldst_info_t *pred_info = get_irn_link(pred);
624
625     if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
626         get_nodes_block(pred) == block && get_irn_mode(get_Store_value(pred)) == mode) {
627       /*
628        * a Store after a Store in the same block -- a write after write.
629        * We may remove the first Store, if it does not have an exception handler.
630        *
631        * TODO: What, if both have the same exception handler ???
632        */
633       if (get_Store_volatility(pred) != volatility_is_volatile && !pred_info->projs[pn_Store_X_except]) {
634         DBG_OPT_WAW(pred, store);
635         exchange( pred_info->projs[pn_Store_M], get_Store_mem(pred) );
636         return 1;
637       }
638     }
639     else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
640              value == pred_info->projs[pn_Load_res]) {
641       /*
642        * a Store of a value after a Load -- a write after read.
643        * We may remove the second Store, if it does not have an exception handler.
644        */
645       if (! info->projs[pn_Store_X_except]) {
646         DBG_OPT_WAR(store, pred);
647         exchange( info->projs[pn_Store_M], mem );
648         return 1;
649       }
650     }
651
652     /* follow only Load chains */
653     if (get_irn_op(pred) != op_Load)
654       break;
655   }
656   return res;
657 }
658
659 /**
660  * walker, optimizes Phi after Stores:
661  * Does the following optimization:
662  *
663  *   val1   val2   val3          val1  val2  val3
664  *    |      |      |               \    |    /
665  *   Str    Str    Str               \   |   /
666  *      \    |    /                     Phi
667  *       \   |   /                       |
668  *        \  |  /                       Str
669  *          Phi
670  *
671  * This removes the number of stores and allows for predicated execution.
672  * Moves Stores back to the end of a function which may be bad
673  *
674  * Is only allowed if the predecessor blocks have only one successor.
675  */
676 static int optimize_phi(ir_node *phi, void *env)
677 {
678   walk_env_t *wenv = env;
679   int i, n;
680   ir_node *store, *old_store, *ptr, *block, *phiM, *phiD, *exc, *projM;
681   ir_mode *mode;
682   ir_node **inM, **inD;
683   int *idx;
684   dbg_info *db = NULL;
685   ldst_info_t *info;
686   block_info_t *bl_info;
687
688   /* Must be a memory Phi */
689   if (get_irn_mode(phi) != mode_M)
690     return 0;
691
692   n = get_Phi_n_preds(phi);
693   if (n <= 0)
694     return 0;
695
696   store = skip_Proj(get_Phi_pred(phi, 0));
697   old_store = store;
698   if (get_irn_op(store) != op_Store)
699     return 0;
700
701   /* abort on bad blocks */
702   if (is_Bad(get_nodes_block(store)))
703     return 0;
704
705   /* check if the block has only one output */
706   bl_info = get_irn_link(get_nodes_block(store));
707   if (bl_info->flags)
708     return 0;
709
710   /* this is the address of the store */
711   ptr  = get_Store_ptr(store);
712   mode = get_irn_mode(get_Store_value(store));
713   info = get_irn_link(store);
714   exc  = info->exc_block;
715
716   for (i = 1; i < n; ++i) {
717     ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
718
719     if (get_irn_op(pred) != op_Store)
720       return 0;
721
722     if (mode != get_irn_mode(get_Store_value(pred)) || ptr != get_Store_ptr(pred))
723       return 0;
724
725     info = get_irn_link(pred);
726
727     /* check, if all stores have the same exception flow */
728     if (exc != info->exc_block)
729       return 0;
730
731     /* abort on bad blocks */
732     if (is_Bad(get_nodes_block(store)))
733       return 0;
734
735     /* check if the block has only one output */
736     bl_info = get_irn_link(get_nodes_block(store));
737     if (bl_info->flags)
738       return 0;
739   }
740
741   /*
742    * ok, when we are here, we found all predecessors of a Phi that
743    * are Stores to the same address. That means whatever we do before
744    * we enter the block of the Phi, we do a Store.
745    * So, we can move the store to the current block:
746    *
747    *   val1    val2    val3          val1  val2  val3
748    *    |       |       |               \    |    /
749    * | Str | | Str | | Str |             \   |   /
750    *      \     |     /                     Phi
751    *       \    |    /                       |
752    *        \   |   /                       Str
753    *           Phi
754    *
755    * Is only allowed if the predecessor blocks have only one successor.
756    */
757
758   /* first step: collect all inputs */
759   NEW_ARR_A(ir_node *, inM, n);
760   NEW_ARR_A(ir_node *, inD, n);
761   NEW_ARR_A(int, idx, n);
762
763   for (i = 0; i < n; ++i) {
764     ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
765     info = get_irn_link(pred);
766
767     inM[i] = get_Store_mem(pred);
768     inD[i] = get_Store_value(pred);
769     idx[i] = info->exc_idx;
770   }
771   block = get_nodes_block(phi);
772
773   /* second step: create a new memory Phi */
774   phiM = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inM, mode_M);
775
776   /* third step: create a new data Phi */
777   phiD = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inD, mode);
778
779   /* fourth step: create the Store */
780   store = new_rd_Store(db, current_ir_graph, block, phiM, ptr, phiD);
781 #ifdef DO_CACHEOPT
782   co_set_irn_name(store, co_get_irn_ident(old_store));
783 #endif
784
785   projM = new_rd_Proj(NULL, current_ir_graph, block, store, mode_M, pn_Store_M);
786
787   info = get_ldst_info(store, wenv);
788   info->projs[pn_Store_M] = projM;
789
790   /* fifths step: repair exception flow */
791   if (exc) {
792     ir_node *projX = new_rd_Proj(NULL, current_ir_graph, block, store, mode_X, pn_Store_X_except);
793
794     info->projs[pn_Store_X_except] = projX;
795     info->exc_block                = exc;
796     info->exc_idx                  = idx[0];
797
798     for (i = 0; i < n; ++i) {
799       set_Block_cfgpred(exc, idx[i], projX);
800     }
801
802     if (n > 1) {
803       /* the exception block should be optimized as some inputs are identical now */
804     }
805   }
806
807   /* sixt step: replace old Phi */
808   exchange(phi, projM);
809
810   return 1;
811 }
812
813 /**
814  * walker, collects all Load/Store/Proj nodes
815  */
816 static void do_load_store_optimize(ir_node *n, void *env)
817 {
818   walk_env_t *wenv = env;
819
820   switch (get_irn_opcode(n)) {
821
822   case iro_Load:
823     wenv->changes |= optimize_load(n);
824     break;
825
826   case iro_Store:
827     wenv->changes |= optimize_store(n);
828     break;
829
830   case iro_Phi:
831     wenv->changes |= optimize_phi(n, env);
832
833   default:
834     ;
835   }
836 }
837
838 /*
839  * do the load store optimization
840  */
841 void optimize_load_store(ir_graph *irg)
842 {
843   walk_env_t env;
844
845   assert(get_irg_phase_state(irg) != phase_building);
846
847   if (!get_opt_redundant_LoadStore())
848     return;
849
850   obstack_init(&env.obst);
851   env.changes = 0;
852
853   /* init the links, then collect Loads/Stores/Proj's in lists */
854   irg_walk_graph(irg, init_links, collect_nodes, &env);
855
856   /* now we have collected enough information, optimize */
857   irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
858
859   obstack_free(&env.obst, NULL);
860
861   /* Handle graph state */
862   if (env.changes) {
863     if (get_irg_outs_state(current_ir_graph) == outs_consistent)
864       set_irg_outs_inconsistent(current_ir_graph);
865
866     /* is this really needed: Yes, as exception block may get bad but this might be tested */
867     if (get_irg_dom_state(current_ir_graph) == dom_consistent)
868       set_irg_dom_inconsistent(current_ir_graph);
869   }
870 }