4ff2aebe0d46dc2c53b4a3f1ee3463451d1f73db
[libfirm] / ir / opt / ldstopt.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/opt/ldstopt.c
4  * Purpose:     load store optimizations
5  * Author:      Michael Beck
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 "irtools.h"
40 # include "opt_polymorphy.h"
41
42 #ifdef DO_CACHEOPT
43 #include "cacheopt/cachesim.h"
44 #endif
45
46 #undef IMAX
47 #define IMAX(a,b)       ((a) > (b) ? (a) : (b))
48
49 #define MAX_PROJ        IMAX(pn_Load_max, pn_Store_max)
50
51 enum changes_t {
52   DF_CHANGED = 1,       /**< data flow changed */
53   CF_CHANGED = 2,       /**< control flow changed */
54 };
55
56 /**
57  * walker environment
58  */
59 typedef struct _walk_env_t {
60   struct obstack obst;          /**< list of all stores */
61   unsigned changes;             /**< a bitmask of graph changes */
62 } walk_env_t;
63
64 /**
65  * flags for Load/Store
66  */
67 enum ldst_flags_t {
68   LDST_VISITED = 1              /**< if set, this Load/Store is already visited */
69 };
70
71 /**
72  * a Load/Store info
73  */
74 typedef struct _ldst_info_t {
75   ir_node  *projs[MAX_PROJ];    /**< list of Proj's of this node */
76   ir_node  *exc_block;          /**< the exception block if available */
77   int      exc_idx;             /**< predecessor index in the exception block */
78   unsigned flags;               /**< flags */
79   unsigned visited;             /**< visited counter for breaking loops */
80 } ldst_info_t;
81
82 /**
83  * flags for control flow
84  */
85 enum block_flags_t {
86   BLOCK_HAS_COND = 1,      /**< Block has conditional control flow */
87   BLOCK_HAS_EXC  = 2       /**< Block has exceptional control flow */
88 };
89
90 /**
91  * a Block info
92  */
93 typedef struct _block_info_t {
94   unsigned flags;               /**< flags for the block */
95 } block_info_t;
96
97 /** the master visited flag for loop detection. */
98 static unsigned master_visited = 0;
99
100 #define INC_MASTER()       ++master_visited
101 #define MARK_NODE(info)    (info)->visited = master_visited
102 #define NODE_VISITED(info) (info)->visited >= master_visited
103
104 /**
105  * get the Load/Store info of a node
106  */
107 static ldst_info_t *get_ldst_info(ir_node *node, walk_env_t *env)
108 {
109   ldst_info_t *info = get_irn_link(node);
110
111   if (! info) {
112     info = obstack_alloc(&env->obst, sizeof(*info));
113
114     memset(info, 0, sizeof(*info));
115
116     set_irn_link(node, info);
117   }
118   return info;
119 }
120
121 /**
122  * get the Block info of a node
123  */
124 static block_info_t *get_block_info(ir_node *node, walk_env_t *env)
125 {
126   block_info_t *info = get_irn_link(node);
127
128   if (! info) {
129     info = obstack_alloc(&env->obst, sizeof(*info));
130
131     memset(info, 0, sizeof(*info));
132
133     set_irn_link(node, info);
134   }
135   return info;
136 }
137
138 /**
139  * update the projection info for a Load/Store
140  */
141 static unsigned update_projs(ldst_info_t *info, ir_node *proj)
142 {
143   long nr = get_Proj_proj(proj);
144
145   assert(0 <= nr && nr <= MAX_PROJ && "Wrong proj from LoadStore");
146
147   if (info->projs[nr]) {
148     /* there is already one, do CSE */
149     exchange(proj, info->projs[nr]);
150     return DF_CHANGED;
151   }
152   else {
153     info->projs[nr] = proj;
154     return 0;
155   }
156 }
157
158 /**
159  * update the exception block info for a Load/Store node.
160  *
161  * @param info   the load/store info struct
162  * @param block  the exception handler block for this load/store
163  * @param pos    the control flow input of the block
164  */
165 static unsigned update_exc(ldst_info_t *info, ir_node *block, int pos)
166 {
167   assert(info->exc_block == NULL && "more than one exception block found");
168
169   info->exc_block = block;
170   info->exc_idx   = pos;
171   return 0;
172 }
173
174 #define get_irn_out_n(node)     (unsigned)PTR_TO_INT(get_irn_link(node))
175 #define set_irn_out_n(node, n)  set_irn_link(adr, INT_TO_PTR(n))
176
177 /**
178  * walker, collects all Load/Store/Proj nodes
179  *
180  * walks from Start -> End
181  */
182 static void collect_nodes(ir_node *node, void *env)
183 {
184   ir_op       *op = get_irn_op(node);
185   ir_node     *pred, *blk, *pred_blk;
186   ldst_info_t *ldst_info;
187   walk_env_t  *wenv = env;
188
189   if (op == op_Proj) {
190     ir_node *adr;
191     ir_op *op;
192
193     pred = get_Proj_pred(node);
194     op   = get_irn_op(pred);
195
196     if (op == op_Load) {
197       ldst_info = get_ldst_info(pred, wenv);
198
199       wenv->changes |= update_projs(ldst_info, node);
200
201       if ((ldst_info->flags & LDST_VISITED) == 0) {
202         adr = get_Load_ptr(pred);
203         set_irn_out_n(adr, get_irn_out_n(adr) + 1);
204
205         ldst_info->flags |= LDST_VISITED;
206       }
207
208       /*
209        * Place the Proj's to the same block as the
210        * predecessor Load. This is always ok and prevents
211        * "non-SSA" form after optimizations if the Proj
212        * is in a wrong block.
213        */
214       blk      = get_nodes_block(node);
215       pred_blk = get_nodes_block(pred);
216       if (blk != pred_blk) {
217         wenv->changes |= DF_CHANGED;
218         set_nodes_block(node, pred_blk);
219       }
220     }
221     else if (op == op_Store) {
222       ldst_info = get_ldst_info(pred, wenv);
223
224       wenv->changes |= update_projs(ldst_info, node);
225
226       if ((ldst_info->flags & LDST_VISITED) == 0) {
227         adr = get_Store_ptr(pred);
228         set_irn_out_n(adr, get_irn_out_n(adr) + 1);
229
230         ldst_info->flags |= LDST_VISITED;
231       }
232
233       /*
234        * Place the Proj's to the same block as the
235        * predecessor Store. This is always ok and prevents
236        * "non-SSA" form after optimizations if the Proj
237        * is in a wrong block.
238        */
239       blk      = get_nodes_block(node);
240       pred_blk = get_nodes_block(pred);
241       if (blk != pred_blk) {
242         wenv->changes |= DF_CHANGED;
243         set_nodes_block(node, pred_blk);
244       }
245     }
246   }
247   else if (op == op_Block) { /* check, if it's an exception block */
248     int i;
249
250     for (i = get_Block_n_cfgpreds(node) - 1; i >= 0; --i) {
251       ir_node      *pred_block;
252       block_info_t *bl_info;
253
254       pred = skip_Proj(get_Block_cfgpred(node, i));
255
256       /* ignore Bad predecessors, they will be removed later */
257       if (is_Bad(pred))
258         continue;
259
260       pred_block = get_nodes_block(pred);
261       bl_info    = get_block_info(pred_block, wenv);
262
263       if (is_fragile_op(pred))
264               bl_info->flags |= BLOCK_HAS_EXC;
265       else if (is_irn_forking(pred))
266         bl_info->flags |= BLOCK_HAS_COND;
267
268       if (get_irn_op(pred) == op_Load || get_irn_op(pred) == op_Store) {
269         ldst_info = get_ldst_info(pred, wenv);
270
271         wenv->changes |= update_exc(ldst_info, node, i);
272       }
273     }
274   }
275 }
276
277 /**
278  * Returns an entity if the address ptr points to a constant one.
279  */
280 static entity *find_constant_entity(ir_node *ptr)
281 {
282   for (;;) {
283     ir_op *op = get_irn_op(ptr);
284
285     if (op == op_SymConst && (get_SymConst_kind(ptr) == symconst_addr_ent)) {
286       return get_SymConst_entity(ptr);
287     }
288     else if (op == op_Sel) {
289       entity  *ent = get_Sel_entity(ptr);
290       ir_type *tp  = get_entity_owner(ent);
291
292       /* Do not fiddle with polymorphism. */
293       if (is_Class_type(get_entity_owner(ent)) &&
294           ((get_entity_n_overwrites(ent)    != 0) ||
295            (get_entity_n_overwrittenby(ent) != 0)   ) )
296         return NULL;
297
298       if (variability_constant == get_entity_variability(ent))
299         return ent;
300
301       if (is_Array_type(tp)) {
302         /* check bounds */
303         int i, n;
304
305         for (i = 0, n = get_Sel_n_indexs(ptr); i < n; ++i) {
306           ir_node *bound;
307           tarval *tlower, *tupper;
308           ir_node *index = get_Sel_index(ptr, i);
309           tarval *tv     = computed_value(index);
310
311           /* check if the index is constant */
312           if (tv == tarval_bad)
313             return NULL;
314
315           bound  = get_array_lower_bound(tp, i);
316           tlower = computed_value(bound);
317           bound  = get_array_upper_bound(tp, i);
318           tupper = computed_value(bound);
319
320           if (tlower == tarval_bad || tupper == tarval_bad)
321             return NULL;
322
323           if (tarval_cmp(tv, tlower) & pn_Cmp_Lt)
324             return NULL;
325           if (tarval_cmp(tupper, tv) & pn_Cmp_Lt)
326             return NULL;
327
328           /* ok, bounds check finished */
329         }
330       }
331
332       /* try next */
333       ptr = get_Sel_ptr(ptr);
334     }
335     else
336       return NULL;
337   }
338 }
339
340 /**
341  * Return the Selection index of a Sel node from dimension n
342  */
343 static long get_Sel_array_index_long(ir_node *n, int dim) {
344   ir_node *index = get_Sel_index(n, dim);
345   assert(get_irn_op(index) == op_Const);
346   return get_tarval_long(get_Const_tarval(index));
347 }
348
349 /**
350  * Returns the accessed component graph path for an
351  * node computing an address.
352  *
353  * @param ptr    the node computing the address
354  * @param depth  current depth in steps upward from the root
355  *               of the address
356  */
357 static compound_graph_path *rec_get_accessed_path(ir_node *ptr, int depth) {
358   compound_graph_path *res = NULL;
359   entity              *root, *field;
360   int                 path_len, pos;
361
362   if (get_irn_op(ptr) == op_SymConst) {
363     /* a SymConst. If the depth is 0, this is an access to a global
364      * entity and we don't need a component path, else we know
365      * at least it's length.
366      */
367     assert(get_SymConst_kind(ptr) == symconst_addr_ent);
368     root = get_SymConst_entity(ptr);
369     res = (depth == 0) ? NULL : new_compound_graph_path(get_entity_type(root), depth);
370   }
371   else {
372     assert(get_irn_op(ptr) == op_Sel);
373     /* it's a Sel, go up until we find the root */
374     res = rec_get_accessed_path(get_Sel_ptr(ptr), depth+1);
375
376     /* fill up the step in the path at the current position */
377     field    = get_Sel_entity(ptr);
378     path_len = get_compound_graph_path_length(res);
379     pos      = path_len - depth - 1;
380     set_compound_graph_path_node(res, pos, field);
381
382     if (is_Array_type(get_entity_owner(field))) {
383       assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
384       set_compound_graph_path_array_index(res, pos, get_Sel_array_index_long(ptr, 0));
385     }
386   }
387   return res;
388 }
389
390 /** Returns an access path or NULL.  The access path is only
391  *  valid, if the graph is in phase_high and _no_ address computation is used.
392  */
393 static compound_graph_path *get_accessed_path(ir_node *ptr) {
394   return rec_get_accessed_path(ptr, 0);
395 }
396
397 /**
398  * Follow the memory chain as long as there are only Loads
399  * and try to replace current Load or Store by a previous one.
400  * Note that in unreachable loops it might happen that we reach
401  * load again, as well as we can fall into a cycle.
402  * We break such cycles using a special visited flag.
403  *
404  * INC_MASTER() must be called before dive into
405  */
406 static unsigned follow_Load_chain(ir_node *load, ir_node *curr) {
407   unsigned res = 0;
408   ldst_info_t *info = get_irn_link(load);
409   ir_node *pred;
410   ir_node *ptr       = get_Load_ptr(load);
411   ir_node *mem       = get_Load_mem(load);
412   ir_mode *load_mode = get_Load_mode(load);
413
414   for (pred = curr; load != pred; pred = skip_Proj(get_Load_mem(pred))) {
415     ldst_info_t *pred_info = get_irn_link(pred);
416
417     /*
418      * BEWARE: one might think that checking the modes is useless, because
419      * if the pointers are identical, they refer to the same object.
420      * This is only true in strong typed languages, not in C were the following
421      * is possible a = *(ir_type1 *)p; b = *(ir_type2 *)p ...
422      */
423
424     if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
425         get_irn_mode(get_Store_value(pred)) == load_mode) {
426       /*
427        * a Load immediately after a Store -- a read after write.
428        * We may remove the Load, if both Load & Store does not have an exception handler
429        * OR they are in the same block. In the latter case the Load cannot
430        * throw an exception when the previous Store was quiet.
431        *
432        * Why we need to check for Store Exception? If the Store cannot
433        * be executed (ROM) the exception handler might simply jump into
434        * the load block :-(
435        * We could make it a little bit better if we would know that the exception
436        * handler of the Store jumps directly to the end...
437        */
438       if ((!pred_info->projs[pn_Store_X_except] && !info->projs[pn_Load_X_except]) ||
439           get_nodes_block(load) == get_nodes_block(pred)) {
440         ir_node *value = get_Store_value(pred);
441
442         DBG_OPT_RAW(load, value);
443         if (info->projs[pn_Load_M])
444           exchange(info->projs[pn_Load_M], mem);
445
446         /* no exception */
447         if (info->projs[pn_Load_X_except]) {
448           exchange( info->projs[pn_Load_X_except], new_Bad());
449           res |= CF_CHANGED;
450         }
451
452         if (info->projs[pn_Load_res])
453           exchange(info->projs[pn_Load_res], value);
454
455         return res | DF_CHANGED;
456       }
457     }
458     else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
459              get_Load_mode(pred) == load_mode) {
460       /*
461        * a Load after a Load -- a read after read.
462        * We may remove the second Load, if it does not have an exception handler
463        * OR they are in the same block. In the later case the Load cannot
464        * throw an exception when the previous Load was quiet.
465        *
466        * Here, there is no need to check if the previous Load has an exception
467        * hander because they would have exact the same exception...
468        */
469       if (! info->projs[pn_Load_X_except] || get_nodes_block(load) == get_nodes_block(pred)) {
470         DBG_OPT_RAR(load, pred);
471
472         if (pred_info->projs[pn_Load_res]) {
473           /* we need a data proj from the previous load for this optimization */
474           if (info->projs[pn_Load_res])
475             exchange(info->projs[pn_Load_res], pred_info->projs[pn_Load_res]);
476
477           if (info->projs[pn_Load_M])
478             exchange(info->projs[pn_Load_M], mem);
479         }
480         else {
481           if (info->projs[pn_Load_res]) {
482             set_Proj_pred(info->projs[pn_Load_res], pred);
483             set_nodes_block(info->projs[pn_Load_res], get_nodes_block(pred));
484             pred_info->projs[pn_Load_res] = info->projs[pn_Load_res];
485           }
486           if (info->projs[pn_Load_M]) {
487             /* Actually, this if should not be necessary.  Construct the Loads
488                properly!!! */
489             exchange(info->projs[pn_Load_M], mem);
490           }
491         }
492
493         /* no exception */
494         if (info->projs[pn_Load_X_except]) {
495           exchange(info->projs[pn_Load_X_except], new_Bad());
496           res |= CF_CHANGED;
497         }
498
499         return res |= DF_CHANGED;
500       }
501     }
502
503     /* follow only Load chains */
504     if (get_irn_op(pred) != op_Load)
505       break;
506
507     /* check for cycles */
508     if (NODE_VISITED(pred_info))
509       break;
510     MARK_NODE(pred_info);
511   }
512
513   if (get_irn_op(pred) == op_Sync) {
514     int i;
515
516     /* handle all Sync predecessors */
517     for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
518       res |= follow_Load_chain(load, skip_Proj(get_Sync_pred(pred, i)));
519       if (res)
520         break;
521     }
522   }
523
524   return res;
525 }
526
527 /**
528  * optimize a Load
529  */
530 static unsigned optimize_load(ir_node *load)
531 {
532   ldst_info_t *info = get_irn_link(load);
533   ir_mode *load_mode = get_Load_mode(load);
534   ir_node *mem, *ptr, *new_node;
535   entity *ent;
536   unsigned res = 0;
537
538   /* do NOT touch volatile loads for now */
539   if (get_Load_volatility(load) == volatility_is_volatile)
540     return 0;
541
542   /* the address of the load to be optimized */
543   ptr = get_Load_ptr(load);
544
545   /*
546    * Check if we can remove the exception from a Load:
547    * This can be done, if the address is from an Sel(Alloc) and
548    * the Sel type is a subtype of the allocated type.
549    *
550    * This optimizes some often used OO constructs,
551    * like x = new O; x->t;
552    */
553   if (info->projs[pn_Load_X_except]) {
554     if (is_Sel(ptr)) {
555       ir_node *mem = get_Sel_mem(ptr);
556
557       if (get_irn_op(skip_Proj(mem)) == op_Alloc) {
558         /* ok, check the types */
559         entity  *ent    = get_Sel_entity(ptr);
560         ir_type *s_type = get_entity_type(ent);
561         ir_type *a_type = get_Alloc_type(mem);
562
563         if (is_SubClass_of(s_type, a_type)) {
564           /* ok, condition met: there can't be an exception because
565            * Alloc guarantees that enough memory was allocated */
566
567           exchange(info->projs[pn_Load_X_except], new_Bad());
568           info->projs[pn_Load_X_except] = NULL;
569           res |= CF_CHANGED;
570         }
571       }
572     }
573     else if ((get_irn_op(skip_Proj(ptr)) == op_Alloc) ||
574              ((get_irn_op(ptr) == op_Cast) && (get_irn_op(skip_Proj(get_Cast_op(ptr))) == op_Alloc))) {
575       /* simple case: a direct load after an Alloc. Firm Alloc throw
576        * an exception in case of out-of-memory. So, there is no way for an
577        * exception in this load.
578        * This code is constructed by the "exception lowering" in the Jack compiler.
579        */
580        exchange(info->projs[pn_Load_X_except], new_Bad());
581        info->projs[pn_Load_X_except] = NULL;
582        res |= CF_CHANGED;
583     }
584   }
585
586   /* the mem of the Load. Must still be returned after optimization */
587   mem  = get_Load_mem(load);
588
589   if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
590     /* a Load which value is neither used nor exception checked, remove it */
591     exchange(info->projs[pn_Load_M], mem);
592
593     return res | DF_CHANGED;
594   }
595
596   /* Load from a constant polymorphic field, where we can resolve
597      polymorphism. */
598   new_node = transform_node_Load(load);
599   if (new_node != load) {
600     if (info->projs[pn_Load_M]) {
601       exchange(info->projs[pn_Load_M], mem);
602       info->projs[pn_Load_M] = NULL;
603     }
604     if (info->projs[pn_Load_X_except]) {
605       exchange(info->projs[pn_Load_X_except], new_Bad());
606       info->projs[pn_Load_X_except] = NULL;
607     }
608     if (info->projs[pn_Load_res])
609       exchange(info->projs[pn_Load_res], new_node);
610     return res | DF_CHANGED;
611   }
612
613   /* check if we can determine the entity that will be loaded */
614   ent = find_constant_entity(ptr);
615   if (ent) {
616     if ((allocation_static == get_entity_allocation(ent)) &&
617         (visibility_external_allocated != get_entity_visibility(ent))) {
618       /* a static allocation that is not external: there should be NO exception
619        * when loading. */
620
621       /* no exception, clear the info field as it might be checked later again */
622       if (info->projs[pn_Load_X_except]) {
623         exchange(info->projs[pn_Load_X_except], new_Bad());
624         info->projs[pn_Load_X_except] = NULL;
625         res |= CF_CHANGED;
626       }
627
628       if (variability_constant == get_entity_variability(ent)
629                 && is_atomic_entity(ent)) {
630         /* Might not be atomic after
631            lowering of Sels.  In this
632            case we could also load, but
633            it's more complicated. */
634         /* more simpler case: we load the content of a constant value:
635          * replace it by the constant itself
636          */
637
638         /* no memory */
639         if (info->projs[pn_Load_M]) {
640           exchange(info->projs[pn_Load_M], mem);
641           res |= DF_CHANGED;
642         }
643
644         /* no result :-) */
645         if (info->projs[pn_Load_res]) {
646           if (is_atomic_entity(ent)) {
647             ir_node *c = copy_const_value(get_irn_dbg_info(load), get_atomic_ent_value(ent));
648
649             DBG_OPT_RC(load, c);
650             exchange(info->projs[pn_Load_res], c);
651             return DF_CHANGED | res;
652           }
653         }
654       }
655       else if (variability_constant == get_entity_variability(ent)) {
656         compound_graph_path *path = get_accessed_path(ptr);
657
658         if (path) {
659           ir_node *c;
660
661           assert(is_proper_compound_graph_path(path, get_compound_graph_path_length(path)-1));
662           /*
663           {
664             int j;
665             for (j = 0; j < get_compound_graph_path_length(path); ++j) {
666               entity *node = get_compound_graph_path_node(path, j);
667               fprintf(stdout, ".%s", get_entity_name(node));
668               if (is_Array_type(get_entity_owner(node)))
669                       fprintf(stdout, "[%d]", get_compound_graph_path_array_index(path, j));
670             }
671             printf("\n");
672           }
673           */
674
675           c = get_compound_ent_value_by_path(ent, path);
676           free_compound_graph_path(path);
677
678           /* printf("  cons: "); DDMN(c); */
679
680           if (info->projs[pn_Load_M]) {
681             exchange(info->projs[pn_Load_M], mem);
682             res |= DF_CHANGED;
683           }
684           if (info->projs[pn_Load_res]) {
685             exchange(info->projs[pn_Load_res], copy_const_value(get_irn_dbg_info(load), c));
686             return res | DF_CHANGED;
687           }
688         }
689         else {
690           /*  We can not determine a correct access path.  E.g., in jack, we load
691                     a byte from an object to generate an exception.   Happens in test program
692                     Reflectiontest.
693           printf(">>>>>>>>>>>>> Found access to constant entity %s in function %s\n", get_entity_name(ent),
694            get_entity_name(get_irg_entity(current_ir_graph)));
695           printf("  load: "); DDMN(load);
696           printf("  ptr:  "); DDMN(ptr);
697           */
698         }
699       }
700     }
701   }
702
703   /* Check, if the address of this load is used more than once.
704    * If not, this load cannot be removed in any case. */
705   if (get_irn_out_n(ptr) <= 1)
706     return res;
707
708   /*
709    * follow the memory chain as long as there are only Loads
710    * and try to replace current Load or Store by a previous one.
711    * Note that in unreachable loops it might happen that we reach
712    * load again, as well as we can fall into a cycle.
713    * We break such cycles using a special visited flag.
714    */
715   INC_MASTER();
716   res = follow_Load_chain(load, skip_Proj(mem));
717   return res;
718 }
719
720 /**
721  * follow the memory chain as long as there are only Loads.
722  *
723  * INC_MASTER() must be called before dive into
724  */
725 static unsigned follow_Load_chain_for_Store(ir_node *store, ir_node *curr) {
726   unsigned res = 0;
727   ldst_info_t *info = get_irn_link(store);
728   ir_node *pred;
729   ir_node *ptr = get_Store_ptr(store);
730   ir_node *mem = get_Store_mem(store);
731   ir_node *value = get_Store_value(store);
732   ir_mode *mode  = get_irn_mode(value);
733   ir_node *block = get_nodes_block(store);
734
735   for (pred = curr; pred != store; pred = skip_Proj(get_Load_mem(pred))) {
736     ldst_info_t *pred_info = get_irn_link(pred);
737
738     /*
739      * BEWARE: one might think that checking the modes is useless, because
740      * if the pointers are identical, they refer to the same object.
741      * This is only true in strong typed languages, not is C were the following
742      * is possible *(ir_type1 *)p = a; *(ir_type2 *)p = b ...
743      */
744     if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
745         get_nodes_block(pred) == block && get_irn_mode(get_Store_value(pred)) == mode) {
746       /*
747        * a Store after a Store in the same block -- a write after write.
748        * We may remove the first Store, if it does not have an exception handler.
749        *
750        * TODO: What, if both have the same exception handler ???
751        */
752       if (get_Store_volatility(pred) != volatility_is_volatile && !pred_info->projs[pn_Store_X_except]) {
753         DBG_OPT_WAW(pred, store);
754         exchange( pred_info->projs[pn_Store_M], get_Store_mem(pred) );
755         return DF_CHANGED;
756       }
757     }
758     else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
759              value == pred_info->projs[pn_Load_res]) {
760       /*
761        * a Store of a value after a Load -- a write after read.
762        * We may remove the second Store, if it does not have an exception handler.
763        */
764       if (! info->projs[pn_Store_X_except]) {
765         DBG_OPT_WAR(store, pred);
766         exchange( info->projs[pn_Store_M], mem );
767         return DF_CHANGED;
768       }
769     }
770
771     /* follow only Load chains */
772     if (get_irn_op(pred) != op_Load)
773       break;
774
775     /* check for cycles */
776     if (NODE_VISITED(pred_info))
777       break;
778     MARK_NODE(pred_info);
779   }
780
781   if (get_irn_op(pred) == op_Sync) {
782     int i;
783
784     /* handle all Sync predecessors */
785     for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
786       res |= follow_Load_chain_for_Store(store, skip_Proj(get_Sync_pred(pred, i)));
787       if (res)
788         break;
789     }
790   }
791   return res;
792 }
793
794 /**
795  * optimize a Store
796  */
797 static unsigned optimize_store(ir_node *store)
798 {
799   ldst_info_t *info = get_irn_link(store);
800   ir_node *ptr, *mem;
801
802   if (get_Store_volatility(store) == volatility_is_volatile)
803     return 0;
804
805   ptr = get_Store_ptr(store);
806
807   /* Check, if the address of this load is used more than once.
808    * If not, this load cannot be removed in any case. */
809   if (get_irn_out_n(ptr) <= 1)
810     return 0;
811
812   mem = get_Store_mem(store);
813
814   /* follow the memory chain as long as there are only Loads */
815   INC_MASTER();
816   return follow_Load_chain_for_Store(store, skip_Proj(mem));
817 }
818
819 /**
820  * walker, optimizes Phi after Stores to identical places:
821  * Does the following optimization:
822  * @verbatim
823  *
824  *   val1   val2   val3          val1  val2  val3
825  *    |      |      |               \    |    /
826  *   Str    Str    Str               \   |   /
827  *      \    |    /                   PhiData
828  *       \   |   /                       |
829  *        \  |  /                       Str
830  *          PhiM
831  *
832  * @endverbatim
833  * This reduces the number of stores and allows for predicated execution.
834  * Moves Stores back to the end of a function which may be bad.
835  *
836  * This is only possible if the predecessor blocks have only one successor.
837  */
838 static unsigned optimize_phi(ir_node *phi, void *env)
839 {
840   walk_env_t *wenv = env;
841   int i, n;
842   ir_node *store, *old_store, *ptr, *block, *phiM, *phiD, *exc, *projM;
843   ir_mode *mode;
844   ir_node **inM, **inD;
845   int *idx;
846   dbg_info *db = NULL;
847   ldst_info_t *info;
848   block_info_t *bl_info;
849   unsigned res = 0;
850
851   /* Must be a memory Phi */
852   if (get_irn_mode(phi) != mode_M)
853     return 0;
854
855   n = get_Phi_n_preds(phi);
856   if (n <= 0)
857     return 0;
858
859   store = skip_Proj(get_Phi_pred(phi, 0));
860   old_store = store;
861   if (get_irn_op(store) != op_Store)
862     return 0;
863
864   /* abort on dead blocks */
865   if (is_Block_dead(get_nodes_block(store)))
866     return 0;
867
868   /* check if the block has only one successor */
869   bl_info = get_irn_link(get_nodes_block(store));
870   if (bl_info->flags)
871     return 0;
872
873   /* this is the address of the store */
874   ptr  = get_Store_ptr(store);
875   mode = get_irn_mode(get_Store_value(store));
876   info = get_irn_link(store);
877   exc  = info->exc_block;
878
879   for (i = 1; i < n; ++i) {
880     ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
881
882     if (get_irn_op(pred) != op_Store)
883       return 0;
884
885     if (ptr != get_Store_ptr(pred) || mode != get_irn_mode(get_Store_value(pred)))
886       return 0;
887
888     info = get_irn_link(pred);
889
890     /* check, if all stores have the same exception flow */
891     if (exc != info->exc_block)
892       return 0;
893
894     /* abort on dead blocks */
895     if (is_Block_dead(get_nodes_block(store)))
896       return 0;
897
898     /* check if the block has only one successor */
899     bl_info = get_irn_link(get_nodes_block(store));
900     if (bl_info->flags)
901       return 0;
902   }
903
904   /*
905    * ok, when we are here, we found all predecessors of a Phi that
906    * are Stores to the same address and size. That means whatever
907    * we do before we enter the block of the Phi, we do a Store.
908    * So, we can move the Store to the current block:
909    *
910    *   val1    val2    val3          val1  val2  val3
911    *    |       |       |               \    |    /
912    * | Str | | Str | | Str |             \   |   /
913    *      \     |     /                   PhiData
914    *       \    |    /                       |
915    *        \   |   /                       Str
916    *           PhiM
917    *
918    * Is only allowed if the predecessor blocks have only one successor.
919    */
920
921   /* first step: collect all inputs */
922   NEW_ARR_A(ir_node *, inM, n);
923   NEW_ARR_A(ir_node *, inD, n);
924   NEW_ARR_A(int, idx, n);
925
926   for (i = 0; i < n; ++i) {
927     ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
928     info = get_irn_link(pred);
929
930     inM[i] = get_Store_mem(pred);
931     inD[i] = get_Store_value(pred);
932     idx[i] = info->exc_idx;
933   }
934   block = get_nodes_block(phi);
935
936   /* second step: create a new memory Phi */
937   phiM = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inM, mode_M);
938
939   /* third step: create a new data Phi */
940   phiD = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inD, mode);
941
942   /* fourth step: create the Store */
943   store = new_rd_Store(db, current_ir_graph, block, phiM, ptr, phiD);
944 #ifdef DO_CACHEOPT
945   co_set_irn_name(store, co_get_irn_ident(old_store));
946 #endif
947
948   projM = new_rd_Proj(NULL, current_ir_graph, block, store, mode_M, pn_Store_M);
949
950   info = get_ldst_info(store, wenv);
951   info->projs[pn_Store_M] = projM;
952
953   /* fifths step: repair exception flow */
954   if (exc) {
955     ir_node *projX = new_rd_Proj(NULL, current_ir_graph, block, store, mode_X, pn_Store_X_except);
956
957     info->projs[pn_Store_X_except] = projX;
958     info->exc_block                = exc;
959     info->exc_idx                  = idx[0];
960
961     for (i = 0; i < n; ++i) {
962       set_Block_cfgpred(exc, idx[i], projX);
963     }
964
965     if (n > 1) {
966       /* the exception block should be optimized as some inputs are identical now */
967     }
968
969     res |= CF_CHANGED;
970   }
971
972   /* sixth step: replace old Phi */
973   exchange(phi, projM);
974
975   return res | DF_CHANGED;
976 }
977
978 /**
979  * walker, do the optimizations
980  */
981 static void do_load_store_optimize(ir_node *n, void *env)
982 {
983   walk_env_t *wenv = env;
984
985   switch (get_irn_opcode(n)) {
986
987   case iro_Load:
988     wenv->changes |= optimize_load(n);
989     break;
990
991   case iro_Store:
992     wenv->changes |= optimize_store(n);
993     break;
994
995   case iro_Phi:
996     wenv->changes |= optimize_phi(n, env);
997
998   default:
999     ;
1000   }
1001 }
1002
1003 /*
1004  * do the load store optimization
1005  */
1006 void optimize_load_store(ir_graph *irg)
1007 {
1008   walk_env_t env;
1009
1010   assert(get_irg_phase_state(irg) != phase_building);
1011   assert(get_irg_pinned(irg) != op_pin_state_floats &&
1012     "LoadStore optimization needs pinned graph");
1013
1014   if (! get_opt_redundant_loadstore())
1015     return;
1016
1017   obstack_init(&env.obst);
1018   env.changes = 0;
1019
1020   /* init the links, then collect Loads/Stores/Proj's in lists */
1021   master_visited = 0;
1022   irg_walk_graph(irg, firm_clear_link, collect_nodes, &env);
1023
1024   /* now we have collected enough information, optimize */
1025   irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
1026
1027   obstack_free(&env.obst, NULL);
1028
1029   /* Handle graph state */
1030   if (env.changes) {
1031     if (get_irg_outs_state(current_ir_graph) == outs_consistent)
1032       set_irg_outs_inconsistent(current_ir_graph);
1033   }
1034
1035   if (env.changes & CF_CHANGED) {
1036     /* is this really needed: Yes, control flow changed, block might get Bad. */
1037     set_irg_doms_inconsistent(current_ir_graph);
1038   }
1039 }