fixed DBG_OPT_RAW() call
[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 static compound_graph_path *rec_get_accessed_path(ir_node *ptr, int depth) {
311   compound_graph_path *res = NULL;
312   entity              *root, *field;
313   int                 path_len, pos;
314
315   if (get_irn_op(ptr) == op_SymConst) {
316     assert(get_SymConst_kind(ptr) == symconst_addr_ent);
317     root = get_SymConst_entity(ptr);
318     res = (depth == 0) ? NULL : new_compound_graph_path(get_entity_type(root), depth);
319   }
320   else {
321     assert(get_irn_op(ptr) == op_Sel);
322     res = rec_get_accessed_path(get_Sel_ptr(ptr), depth+1);
323     field = get_Sel_entity(ptr);
324     path_len = get_compound_graph_path_length(res);
325     pos = path_len - depth - 1;
326     set_compound_graph_path_node(res, pos, field);
327     if (is_Array_type(get_entity_owner(field))) {
328       assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
329       set_compound_graph_path_array_index(res, pos, get_Sel_array_index_long(ptr, 0));
330     }
331   }
332   return res;
333 }
334
335
336 /** Returns an access path or NULL.  The access path is only
337  *  valid, if the graph is in phase_high and _no_ address computation is used. */
338 static compound_graph_path *get_accessed_path(ir_node *ptr) {
339   return rec_get_accessed_path(ptr, 0);
340 }
341
342 /**
343  * optimize a Load
344  */
345 static int optimize_load(ir_node *load)
346 {
347   ldst_info_t *info = get_irn_link(load);
348   ir_mode *load_mode = get_Load_mode(load);
349   ir_node *pred, *mem, *ptr, *new_node;
350   entity *ent;
351   int res = 0;
352
353   /* the address of the load to be optimized */
354   ptr = get_Load_ptr(load);
355
356   /*
357    * Check if we can remove the exception form a Load:
358    * this can be done, if the address is from an Sel(Alloc) and
359    * the Sel type is a subtype of the alloc type.
360    *
361    * This optimizes some often used OO constructs,
362    * like x = new O; x->t;
363    */
364   if (info->projs[pn_Load_X_except]) {
365     if (get_irn_op(ptr) == op_Sel) {
366       ir_node *mem = get_Sel_mem(ptr);
367
368       if (get_irn_op(skip_Proj(mem)) == op_Alloc) {
369         /* ok, check the types */
370         entity *ent  = get_Sel_entity(ptr);
371         type *s_type = get_entity_type(ent);
372         type *a_type = get_Alloc_type(mem);
373
374         if (is_subclass_of(s_type, a_type)) {
375           /* ok, condition met: there can't be an exception because
376            * alloc guarantees that enough memory was allocated */
377
378           exchange(info->projs[pn_Load_X_except], new_Bad());
379           info->projs[pn_Load_X_except] = NULL;
380         }
381       }
382     }
383     else if ((get_irn_op(skip_Proj(ptr)) == op_Alloc) ||
384              ((get_irn_op(ptr) == op_Cast) && (get_irn_op(skip_Proj(get_Cast_op(ptr))) == op_Alloc))) {
385       /* simple case: a direct load after an Alloc. Firm Alloc throw
386        * an exception in case of out-of-memory. So, there is no way for an
387        * exception in this load.
388        * This code is constructed by the "exception lowering" in the Jack compiler.
389        */
390        exchange(info->projs[pn_Load_X_except], new_Bad());
391        info->projs[pn_Load_X_except] = NULL;
392     }
393   }
394
395   /* do NOT touch volatile loads for now */
396   if (get_Load_volatility(load) == volatility_is_volatile)
397     return 0;
398
399   if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
400     /* a Load which value is neither used nor exception checked, remove it */
401     mem  = get_Load_mem(load);
402     exchange(info->projs[pn_Load_M], mem);
403
404     return 1;
405   }
406
407   /* the mem of the Load. Must still be returned after optimization */
408   mem  = get_Load_mem(load);
409
410   /* Load from a constant polymorphic field, where we can resolve
411      polymorphy. */
412   new_node = transform_node_Load(load);
413   if (new_node != load) {
414     if (info->projs[pn_Load_M]) {
415       exchange(info->projs[pn_Load_M], mem);
416       info->projs[pn_Load_M] = NULL;
417     }
418     if (info->projs[pn_Load_X_except]) {
419       exchange(info->projs[pn_Load_X_except], new_Bad());
420       info->projs[pn_Load_X_except] = NULL;
421     }
422     if (info->projs[pn_Load_res])
423       exchange(info->projs[pn_Load_res], new_node);
424     return 1;
425   }
426
427   /* check if we can determine the entity that will be loaded */
428   ent = find_constant_entity(ptr);
429   if (ent) {
430     if ((allocation_static == get_entity_allocation(ent)) &&
431         (visibility_external_allocated != get_entity_visibility(ent))) {
432       /* a static allocation that is not external: there should be NO exception
433        * when loading. */
434
435       /* no exception, clear the info field as it might be checked later again */
436       if (info->projs[pn_Load_X_except]) {
437         exchange(info->projs[pn_Load_X_except], new_Bad());
438         info->projs[pn_Load_X_except] = NULL;
439       }
440
441       if (variability_constant == get_entity_variability(ent)
442                 && is_atomic_entity(ent)) {
443         /* Might not be atomic after
444            lowering of Sels.  In this
445            case we could also load, but
446            it's more complicated. */
447         /* more simpler case: we load the content of a constant value:
448          * replace it by the constant itself
449          */
450
451         /* no memory */
452         if (info->projs[pn_Load_M])
453           exchange(info->projs[pn_Load_M], mem);
454
455         /* no result :-) */
456         if (info->projs[pn_Load_res]) {
457           if (is_atomic_entity(ent)) {
458             ir_node *c = copy_const_value(get_atomic_ent_value(ent));
459
460             DBG_OPT_RC(load, c);
461             exchange(info->projs[pn_Load_res], c);
462
463             return 1;
464           }
465         }
466       }
467       else if (variability_constant == get_entity_variability(ent)) {
468         compound_graph_path *path;
469         /*
470         printf(">>>>>>>>>>>>> Found access to constant entity %s in function %s\n", get_entity_name(ent),
471         get_entity_name(get_irg_entity(current_ir_graph)));
472         printf("  load: "); DDMN(load);
473         printf("  ptr:  "); DDMN(ptr);
474         */
475         path = get_accessed_path(ptr);
476         if (path) {
477           ir_node *c;
478
479           assert(is_proper_compound_graph_path(path, get_compound_graph_path_length(path)-1));
480           c = get_compound_ent_value_by_path(ent, path);
481
482           /* printf("  cons: "); DDMN(c); */
483
484           if (info->projs[pn_Load_M])
485             exchange(info->projs[pn_Load_M], mem);
486           if (info->projs[pn_Load_res])
487             exchange(info->projs[pn_Load_res], copy_const_value(c));
488           /*
489           {
490             int j;
491             for (j = 0; j < get_compound_graph_path_length(path); ++j) {
492               entity *node = get_compound_graph_path_node(path, j);
493               fprintf(stdout, ".%s", get_entity_name(node));
494               if (is_Array_type(get_entity_owner(node)))
495                       fprintf(stdout, "[%d]", get_compound_graph_path_array_index(path, j));
496             }
497             printf("\n");
498           }
499           */
500         } else {
501           /*  We can not determine a correct access path.  E.g., in jack, we load
502               a byte from an object to generate an exception.   Happens in test program
503               Reflectiontest.
504           printf(">>>>>>>>>>>>> Found access to constant entity %s in function %s\n", get_entity_name(ent),
505                  get_entity_name(get_irg_entity(current_ir_graph)));
506           printf("  load: "); DDMN(load);
507           printf("  ptr:  "); DDMN(ptr);
508           if (get_irn_op(ptr) == op_SymConst &&
509                 get_SymConst_kind(ptr) == symconst_addr_ent) { printf("        "); DDMEO(get_SymConst_entity(ptr)); }
510           printf("cannot optimize.\n");
511           */
512         }
513       }
514
515       /* we changed the irg, but try further */
516       res = 1;
517     }
518   }
519
520   /* Check, if the address of this load is used more than once.
521    * If not, this load cannot be removed in any case. */
522   if (get_irn_out_n(ptr) <= 1)
523     return 0;
524
525   /* follow the memory chain as long as there are only Loads */
526   for (pred = skip_Proj(mem); ; pred = skip_Proj(get_Load_mem(pred))) {
527
528     /*
529      * BEWARE: one might think that checking the modes is useless, because
530      * if the pointers are identical, they refer to the same object.
531      * This is only true in strong typed languages, not is C were the following
532      * is possible a = *(type1 *)p; b = *(type2 *)p ...
533      */
534
535     if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
536         get_irn_mode(get_Store_value(pred)) == load_mode) {
537       ldst_info_t *pred_info = get_irn_link(pred);
538
539       /*
540        * a Load immediately after a Store -- a read after write.
541        * We may remove the Load, if both Load & Store does not have an exception handler
542        * OR they are in the same block. In the latter case the Load cannot
543        * throw an exception when the previous Store was quiet.
544        *
545        * Why we need to check for Store Exc? If the Store cannot be executed (ROM)
546        * the exception handler might simply jump into the load block :-(
547        * We could make it a little bit better if we would know that the exception
548        * handler of the Store jumps directly to the end...
549        */
550       if ((!pred_info->projs[pn_Store_X_except] && !info->projs[pn_Load_X_except]) ||
551           get_nodes_block(load) == get_nodes_block(pred)) {
552         ir_node *value = get_Store_value(pred);
553
554         DBG_OPT_RAW(load, value);
555         exchange(info->projs[pn_Load_res], value);
556
557         if (info->projs[pn_Load_M])
558           exchange(info->projs[pn_Load_M], mem);
559
560         /* no exception */
561         if (info->projs[pn_Load_X_except])
562           exchange( info->projs[pn_Load_X_except], new_Bad());
563         return 1;
564       }
565     }
566     else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
567              get_Load_mode(pred) == load_mode) {
568       /*
569        * a Load after a Load -- a read after read.
570        * We may remove the second Load, if it does not have an exception handler
571        * OR they are in the same block. In the later case the Load cannot
572        * throw an exception when the previous Load was quiet.
573        *
574        * Here, there is no need to check if the previos Load has an exception hander because
575        * they would have exact the same exception...
576        */
577       if (! info->projs[pn_Load_X_except] || get_nodes_block(load) == get_nodes_block(pred)) {
578         ldst_info_t *pred_info = get_irn_link(pred);
579
580         DBG_OPT_RAR(load, pred);
581
582         if (pred_info->projs[pn_Load_res]) {
583           /* we need a data proj from the previous load for this optimization */
584           exchange( info->projs[pn_Load_res], pred_info->projs[pn_Load_res] );
585           if (info->projs[pn_Load_M])
586             exchange(info->projs[pn_Load_M], mem);
587         }
588         else {
589           if (info->projs[pn_Load_res]) {
590             set_Proj_pred(info->projs[pn_Load_res], pred);
591             set_nodes_block(info->projs[pn_Load_res], get_nodes_block(pred));
592           }
593           if (info->projs[pn_Load_M]) {
594             /* Actually, this if should not be necessary.  Construct the Loads
595                properly!!! */
596             exchange(info->projs[pn_Load_M], mem);
597           }
598         }
599
600         /* no exception */
601         if (info->projs[pn_Load_X_except])
602           exchange(info->projs[pn_Load_X_except], new_Bad());
603
604         return 1;
605       }
606     }
607
608     /* follow only Load chains */
609     if (get_irn_op(pred) != op_Load)
610       break;
611    }
612   return res;
613 }
614
615 /**
616  * optimize a Store
617  */
618 static int optimize_store(ir_node *store)
619 {
620   ldst_info_t *info = get_irn_link(store);
621   ir_node *pred, *mem, *ptr, *value, *block;
622   ir_mode *mode;
623   int res = 0;
624
625   if (get_Store_volatility(store) == volatility_is_volatile)
626     return 0;
627
628   /*
629    * BEWARE: one might think that checking the modes is useless, because
630    * if the pointers are identical, they refer to the same object.
631    * This is only true in strong typed languages, not is C were the following
632    * is possible *(type1 *)p = a; *(type2 *)p = b ...
633    */
634
635   ptr   = get_Store_ptr(store);
636
637   /* Check, if the address of this load is used more than once.
638    * If not, this load cannot be removed in any case. */
639   if (get_irn_out_n(ptr) <= 1)
640     return 0;
641
642   block = get_nodes_block(store);
643   mem   = get_Store_mem(store);
644   value = get_Store_value(store);
645   mode  = get_irn_mode(value);
646
647   /* follow the memory chain as long as there are only Loads */
648   for (pred = skip_Proj(mem); ; pred = skip_Proj(get_Load_mem(pred))) {
649     ldst_info_t *pred_info = get_irn_link(pred);
650
651     if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
652         get_nodes_block(pred) == block && get_irn_mode(get_Store_value(pred)) == mode) {
653       /*
654        * a Store after a Store in the same block -- a write after write.
655        * We may remove the first Store, if it does not have an exception handler.
656        *
657        * TODO: What, if both have the same exception handler ???
658        */
659       if (get_Store_volatility(pred) != volatility_is_volatile && !pred_info->projs[pn_Store_X_except]) {
660         DBG_OPT_WAW(pred, store);
661         exchange( pred_info->projs[pn_Store_M], get_Store_mem(pred) );
662         return 1;
663       }
664     }
665     else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
666              value == pred_info->projs[pn_Load_res]) {
667       /*
668        * a Store of a value after a Load -- a write after read.
669        * We may remove the second Store, if it does not have an exception handler.
670        */
671       if (! info->projs[pn_Store_X_except]) {
672         DBG_OPT_WAR(store, pred);
673         exchange( info->projs[pn_Store_M], mem );
674         return 1;
675       }
676     }
677
678     /* follow only Load chains */
679     if (get_irn_op(pred) != op_Load)
680       break;
681   }
682   return res;
683 }
684
685 /**
686  * walker, optimizes Phi after Stores:
687  * Does the following optimization:
688  *
689  *   val1   val2   val3          val1  val2  val3
690  *    |      |      |               \    |    /
691  *   Str    Str    Str               \   |   /
692  *      \    |    /                     Phi
693  *       \   |   /                       |
694  *        \  |  /                       Str
695  *          Phi
696  *
697  * This removes the number of stores and allows for predicated execution.
698  * Moves Stores back to the end of a function which may be bad
699  *
700  * Is only allowed if the predecessor blocks have only one successor.
701  */
702 static int optimize_phi(ir_node *phi, void *env)
703 {
704   walk_env_t *wenv = env;
705   int i, n;
706   ir_node *store, *old_store, *ptr, *block, *phiM, *phiD, *exc, *projM;
707   ir_mode *mode;
708   ir_node **inM, **inD;
709   int *idx;
710   dbg_info *db = NULL;
711   ldst_info_t *info;
712   block_info_t *bl_info;
713
714   /* Must be a memory Phi */
715   if (get_irn_mode(phi) != mode_M)
716     return 0;
717
718   n = get_Phi_n_preds(phi);
719   if (n <= 0)
720     return 0;
721
722   store = skip_Proj(get_Phi_pred(phi, 0));
723   old_store = store;
724   if (get_irn_op(store) != op_Store)
725     return 0;
726
727   /* abort on bad blocks */
728   if (is_Bad(get_nodes_block(store)))
729     return 0;
730
731   /* check if the block has only one output */
732   bl_info = get_irn_link(get_nodes_block(store));
733   if (bl_info->flags)
734     return 0;
735
736   /* this is the address of the store */
737   ptr  = get_Store_ptr(store);
738   mode = get_irn_mode(get_Store_value(store));
739   info = get_irn_link(store);
740   exc  = info->exc_block;
741
742   for (i = 1; i < n; ++i) {
743     ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
744
745     if (get_irn_op(pred) != op_Store)
746       return 0;
747
748     if (mode != get_irn_mode(get_Store_value(pred)) || ptr != get_Store_ptr(pred))
749       return 0;
750
751     info = get_irn_link(pred);
752
753     /* check, if all stores have the same exception flow */
754     if (exc != info->exc_block)
755       return 0;
756
757     /* abort on bad blocks */
758     if (is_Bad(get_nodes_block(store)))
759       return 0;
760
761     /* check if the block has only one output */
762     bl_info = get_irn_link(get_nodes_block(store));
763     if (bl_info->flags)
764       return 0;
765   }
766
767   /*
768    * ok, when we are here, we found all predecessors of a Phi that
769    * are Stores to the same address. That means whatever we do before
770    * we enter the block of the Phi, we do a Store.
771    * So, we can move the store to the current block:
772    *
773    *   val1    val2    val3          val1  val2  val3
774    *    |       |       |               \    |    /
775    * | Str | | Str | | Str |             \   |   /
776    *      \     |     /                     Phi
777    *       \    |    /                       |
778    *        \   |   /                       Str
779    *           Phi
780    *
781    * Is only allowed if the predecessor blocks have only one successor.
782    */
783
784   /* first step: collect all inputs */
785   NEW_ARR_A(ir_node *, inM, n);
786   NEW_ARR_A(ir_node *, inD, n);
787   NEW_ARR_A(int, idx, n);
788
789   for (i = 0; i < n; ++i) {
790     ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
791     info = get_irn_link(pred);
792
793     inM[i] = get_Store_mem(pred);
794     inD[i] = get_Store_value(pred);
795     idx[i] = info->exc_idx;
796   }
797   block = get_nodes_block(phi);
798
799   /* second step: create a new memory Phi */
800   phiM = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inM, mode_M);
801
802   /* third step: create a new data Phi */
803   phiD = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inD, mode);
804
805   /* fourth step: create the Store */
806   store = new_rd_Store(db, current_ir_graph, block, phiM, ptr, phiD);
807 #ifdef DO_CACHEOPT
808   co_set_irn_name(store, co_get_irn_ident(old_store));
809 #endif
810
811   projM = new_rd_Proj(NULL, current_ir_graph, block, store, mode_M, pn_Store_M);
812
813   info = get_ldst_info(store, wenv);
814   info->projs[pn_Store_M] = projM;
815
816   /* fifths step: repair exception flow */
817   if (exc) {
818     ir_node *projX = new_rd_Proj(NULL, current_ir_graph, block, store, mode_X, pn_Store_X_except);
819
820     info->projs[pn_Store_X_except] = projX;
821     info->exc_block                = exc;
822     info->exc_idx                  = idx[0];
823
824     for (i = 0; i < n; ++i) {
825       set_Block_cfgpred(exc, idx[i], projX);
826     }
827
828     if (n > 1) {
829       /* the exception block should be optimized as some inputs are identical now */
830     }
831   }
832
833   /* sixt step: replace old Phi */
834   exchange(phi, projM);
835
836   return 1;
837 }
838
839 /**
840  * walker, collects all Load/Store/Proj nodes
841  */
842 static void do_load_store_optimize(ir_node *n, void *env)
843 {
844   walk_env_t *wenv = env;
845
846   switch (get_irn_opcode(n)) {
847
848   case iro_Load:
849     wenv->changes |= optimize_load(n);
850     break;
851
852   case iro_Store:
853     wenv->changes |= optimize_store(n);
854     break;
855
856   case iro_Phi:
857     wenv->changes |= optimize_phi(n, env);
858
859   default:
860     ;
861   }
862 }
863
864 /*
865  * do the load store optimization
866  */
867 void optimize_load_store(ir_graph *irg)
868 {
869   walk_env_t env;
870
871   assert(get_irg_phase_state(irg) != phase_building);
872
873   if (!get_opt_redundant_LoadStore())
874     return;
875
876   obstack_init(&env.obst);
877   env.changes = 0;
878
879   /* init the links, then collect Loads/Stores/Proj's in lists */
880   irg_walk_graph(irg, init_links, collect_nodes, &env);
881
882   /* now we have collected enough information, optimize */
883   irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
884
885   obstack_free(&env.obst, NULL);
886
887   /* Handle graph state */
888   if (env.changes) {
889     if (get_irg_outs_state(current_ir_graph) == outs_consistent)
890       set_irg_outs_inconsistent(current_ir_graph);
891
892     /* is this really needed: Yes, as exception block may get bad but this might be tested */
893     if (get_irg_dom_state(current_ir_graph) == dom_consistent)
894       set_irg_dom_inconsistent(current_ir_graph);
895   }
896 }