Fixed the Phi optimize case: after fixing CSE for Phi nodes, it was broken
[libfirm] / ir / opt / ldstopt.c
1 /*
2  * Copyright (C) 1995-2007 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   Load/Store optimizations.
23  * @author  Michael Beck
24  * @version $Id$
25  */
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include <string.h>
31
32 #include "iroptimize.h"
33 #include "irnode_t.h"
34 #include "irgraph_t.h"
35 #include "irmode_t.h"
36 #include "iropt_t.h"
37 #include "ircons_t.h"
38 #include "irgmod.h"
39 #include "irgwalk.h"
40 #include "irvrfy.h"
41 #include "tv_t.h"
42 #include "dbginfo_t.h"
43 #include "iropt_dbg.h"
44 #include "irflag_t.h"
45 #include "array.h"
46 #include "irhooks.h"
47 #include "iredges.h"
48 #include "irtools.h"
49 #include "opt_polymorphy.h"
50 #include "irmemory.h"
51 #include "xmalloc.h"
52
53 #ifdef DO_CACHEOPT
54 #include "cacheopt/cachesim.h"
55 #endif
56
57 #undef IMAX
58 #define IMAX(a,b)       ((a) > (b) ? (a) : (b))
59
60 #define MAX_PROJ        IMAX(pn_Load_max, pn_Store_max)
61
62 enum changes_t {
63         DF_CHANGED = 1,       /**< data flow changed */
64         CF_CHANGED = 2,       /**< control flow changed */
65 };
66
67 /**
68  * walker environment
69  */
70 typedef struct _walk_env_t {
71         struct obstack obst;          /**< list of all stores */
72         unsigned changes;             /**< a bitmask of graph changes */
73 } walk_env_t;
74
75 /**
76  * flags for Load/Store
77  */
78 enum ldst_flags_t {
79         LDST_VISITED = 1              /**< if set, this Load/Store is already visited */
80 };
81
82 /** A Load/Store info. */
83 typedef struct _ldst_info_t {
84         ir_node  *projs[MAX_PROJ];    /**< list of Proj's of this node */
85         ir_node  *exc_block;          /**< the exception block if available */
86         int      exc_idx;             /**< predecessor index in the exception block */
87         unsigned flags;               /**< flags */
88         unsigned visited;             /**< visited counter for breaking loops */
89 } ldst_info_t;
90
91 /**
92  * flags for control flow.
93  */
94 enum block_flags_t {
95         BLOCK_HAS_COND = 1,      /**< Block has conditional control flow */
96         BLOCK_HAS_EXC  = 2       /**< Block has exceptional control flow */
97 };
98
99 /**
100  * a Block info.
101  */
102 typedef struct _block_info_t {
103         unsigned flags;               /**< flags for the block */
104 } block_info_t;
105
106 /** the master visited flag for loop detection. */
107 static unsigned master_visited = 0;
108
109 #define INC_MASTER()       ++master_visited
110 #define MARK_NODE(info)    (info)->visited = master_visited
111 #define NODE_VISITED(info) (info)->visited >= master_visited
112
113 /**
114  * get the Load/Store info of a node
115  */
116 static ldst_info_t *get_ldst_info(ir_node *node, walk_env_t *env) {
117         ldst_info_t *info = get_irn_link(node);
118
119         if (! info) {
120                 info = obstack_alloc(&env->obst, sizeof(*info));
121                 memset(info, 0, sizeof(*info));
122                 set_irn_link(node, info);
123         }
124         return info;
125 }  /* get_ldst_info */
126
127 /**
128  * get the Block info of a node
129  */
130 static block_info_t *get_block_info(ir_node *node, walk_env_t *env) {
131         block_info_t *info = get_irn_link(node);
132
133         if (! info) {
134                 info = obstack_alloc(&env->obst, sizeof(*info));
135                 memset(info, 0, sizeof(*info));
136                 set_irn_link(node, info);
137         }
138         return info;
139 }  /* get_block_info */
140
141 /**
142  * update the projection info for a Load/Store
143  */
144 static unsigned update_projs(ldst_info_t *info, ir_node *proj)
145 {
146         long nr = get_Proj_proj(proj);
147
148         assert(0 <= nr && nr <= MAX_PROJ && "Wrong proj from LoadStore");
149
150         if (info->projs[nr]) {
151                 /* there is already one, do CSE */
152                 exchange(proj, info->projs[nr]);
153                 return DF_CHANGED;
154         }
155         else {
156                 info->projs[nr] = proj;
157                 return 0;
158         }
159 }  /* update_projs */
160
161 /**
162  * update the exception block info for a Load/Store node.
163  *
164  * @param info   the load/store info struct
165  * @param block  the exception handler block for this load/store
166  * @param pos    the control flow input of the block
167  */
168 static unsigned update_exc(ldst_info_t *info, ir_node *block, int pos)
169 {
170         assert(info->exc_block == NULL && "more than one exception block found");
171
172         info->exc_block = block;
173         info->exc_idx   = pos;
174         return 0;
175 }  /* update_exc */
176
177 /** Return the number of uses of an address node */
178 #define get_irn_n_uses(adr)     get_irn_n_edges(adr)
179
180 /**
181  * walker, collects all Load/Store/Proj nodes
182  *
183  * walks from Start -> End
184  */
185 static void collect_nodes(ir_node *node, void *env)
186 {
187         ir_op       *op = get_irn_op(node);
188         ir_node     *pred, *blk, *pred_blk;
189         ldst_info_t *ldst_info;
190         walk_env_t  *wenv = env;
191
192         if (op == op_Proj) {
193                 ir_node *adr;
194                 ir_op *op;
195
196                 pred = get_Proj_pred(node);
197                 op   = get_irn_op(pred);
198
199                 if (op == op_Load) {
200                         ldst_info = get_ldst_info(pred, wenv);
201
202                         wenv->changes |= update_projs(ldst_info, node);
203
204                         if ((ldst_info->flags & LDST_VISITED) == 0) {
205                                 adr = get_Load_ptr(pred);
206                                 ldst_info->flags |= LDST_VISITED;
207                         }
208
209                         /*
210                         * Place the Proj's to the same block as the
211                         * predecessor Load. This is always ok and prevents
212                         * "non-SSA" form after optimizations if the Proj
213                         * is in a wrong block.
214                         */
215                         blk      = get_nodes_block(node);
216                         pred_blk = get_nodes_block(pred);
217                         if (blk != pred_blk) {
218                                 wenv->changes |= DF_CHANGED;
219                                 set_nodes_block(node, pred_blk);
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                                 ldst_info->flags |= LDST_VISITED;
229                         }
230
231                         /*
232                         * Place the Proj's to the same block as the
233                         * predecessor Store. This is always ok and prevents
234                         * "non-SSA" form after optimizations if the Proj
235                         * is in a wrong block.
236                         */
237                         blk      = get_nodes_block(node);
238                         pred_blk = get_nodes_block(pred);
239                         if (blk != pred_blk) {
240                                 wenv->changes |= DF_CHANGED;
241                                 set_nodes_block(node, pred_blk);
242                         }
243                 }
244         } else if (op == op_Block) {
245                 int i;
246
247                 for (i = get_Block_n_cfgpreds(node) - 1; i >= 0; --i) {
248                         ir_node      *pred_block;
249                         block_info_t *bl_info;
250
251                         pred = skip_Proj(get_Block_cfgpred(node, i));
252
253                         /* ignore Bad predecessors, they will be removed later */
254                         if (is_Bad(pred))
255                                 continue;
256
257                         pred_block = get_nodes_block(pred);
258                         bl_info    = get_block_info(pred_block, wenv);
259
260                         if (is_fragile_op(pred))
261                                 bl_info->flags |= BLOCK_HAS_EXC;
262                         else if (is_irn_forking(pred))
263                                 bl_info->flags |= BLOCK_HAS_COND;
264
265                         if (get_irn_op(pred) == op_Load || get_irn_op(pred) == op_Store) {
266                                 ldst_info = get_ldst_info(pred, wenv);
267
268                                 wenv->changes |= update_exc(ldst_info, node, i);
269                         }
270                 }
271         }
272 }  /* collect_nodes */
273
274 /**
275  * Returns an entity if the address ptr points to a constant one.
276  *
277  * @param ptr  the address
278  *
279  * @return an entity or NULL
280  */
281 static ir_entity *find_constant_entity(ir_node *ptr)
282 {
283         for (;;) {
284                 ir_op *op = get_irn_op(ptr);
285
286                 if (op == op_SymConst && (get_SymConst_kind(ptr) == symconst_addr_ent)) {
287                         ir_entity *ent = get_SymConst_entity(ptr);
288                         if (variability_constant == get_entity_variability(ent))
289                                 return ent;
290                         return NULL;
291                 } else if (op == op_Sel) {
292                         ir_entity *ent = get_Sel_entity(ptr);
293                         ir_type   *tp  = get_entity_owner(ent);
294
295                         /* Do not fiddle with polymorphism. */
296                         if (is_Class_type(get_entity_owner(ent)) &&
297                                 ((get_entity_n_overwrites(ent)    != 0) ||
298                                 (get_entity_n_overwrittenby(ent) != 0)   ) )
299                                 return NULL;
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                         if (variability_constant == get_entity_variability(ent))
333                                 return ent;
334
335                         /* try next */
336                         ptr = get_Sel_ptr(ptr);
337                 } else
338                         return NULL;
339         }
340 }  /* find_constant_entity */
341
342 /**
343  * Return the Selection index of a Sel node from dimension n
344  */
345 static long get_Sel_array_index_long(ir_node *n, int dim) {
346         ir_node *index = get_Sel_index(n, dim);
347         assert(get_irn_op(index) == op_Const);
348         return get_tarval_long(get_Const_tarval(index));
349 }  /* get_Sel_array_index_long */
350
351 /**
352  * Returns the accessed component graph path for an
353  * node computing an address.
354  *
355  * @param ptr    the node computing the address
356  * @param depth  current depth in steps upward from the root
357  *               of the address
358  */
359 static compound_graph_path *rec_get_accessed_path(ir_node *ptr, int depth) {
360         compound_graph_path *res = NULL;
361         ir_entity           *root, *field;
362         int                 path_len, pos;
363
364         if (get_irn_op(ptr) == op_SymConst) {
365                 /* a SymConst. If the depth is 0, this is an access to a global
366                  * entity and we don't need a component path, else we know
367                  * at least it's length.
368                  */
369                 assert(get_SymConst_kind(ptr) == symconst_addr_ent);
370                 root = get_SymConst_entity(ptr);
371                 res = (depth == 0) ? NULL : new_compound_graph_path(get_entity_type(root), depth);
372         } else {
373                 assert(get_irn_op(ptr) == op_Sel);
374                 /* it's a Sel, go up until we find the root */
375                 res = rec_get_accessed_path(get_Sel_ptr(ptr), depth+1);
376
377                 /* fill up the step in the path at the current position */
378                 field    = get_Sel_entity(ptr);
379                 path_len = get_compound_graph_path_length(res);
380                 pos      = path_len - depth - 1;
381                 set_compound_graph_path_node(res, pos, field);
382
383                 if (is_Array_type(get_entity_owner(field))) {
384                         assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
385                         set_compound_graph_path_array_index(res, pos, get_Sel_array_index_long(ptr, 0));
386                 }
387         }
388         return res;
389 }  /* rec_get_accessed_path */
390
391 /** Returns an access path or NULL.  The access path is only
392  *  valid, if the graph is in phase_high and _no_ address computation is used.
393  */
394 static compound_graph_path *get_accessed_path(ir_node *ptr) {
395         return rec_get_accessed_path(ptr, 0);
396 }  /* get_accessed_path */
397
398 /* forward */
399 static void reduce_adr_usage(ir_node *ptr);
400
401 /**
402  * Update a Load that may lost it's usage.
403  */
404 static void handle_load_update(ir_node *load) {
405         ldst_info_t *info = get_irn_link(load);
406
407         /* do NOT touch volatile loads for now */
408         if (get_Load_volatility(load) == volatility_is_volatile)
409                 return;
410
411         if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
412                 ir_node *ptr = get_Load_ptr(load);
413                 ir_node *mem = get_Load_mem(load);
414
415                 /* a Load which value is neither used nor exception checked, remove it */
416                 exchange(info->projs[pn_Load_M], mem);
417                 exchange(load, new_Bad());
418                 reduce_adr_usage(ptr);
419         }
420 }  /* handle_load_update */
421
422 /**
423  * A Use of an address node is vanished. Check if this was a Proj
424  * node and update the counters.
425  */
426 static void reduce_adr_usage(ir_node *ptr) {
427         if (is_Proj(ptr)) {
428                 if (get_irn_n_edges(ptr) <= 0) {
429                         /* this Proj is dead now */
430                         ir_node *pred = get_Proj_pred(ptr);
431
432                         if (is_Load(pred)) {
433                                 ldst_info_t *info = get_irn_link(pred);
434                                 info->projs[get_Proj_proj(ptr)] = NULL;
435
436                                 /* this node lost it's result proj, handle that */
437                                 handle_load_update(pred);
438                         }
439                 }
440         }
441 }  /* reduce_adr_usage */
442
443 /**
444  * Check, if an already existing value of mode old_mode can be converted
445  * into the needed one new_mode without loss.
446  */
447 static int can_use_stored_value(ir_mode *old_mode, ir_mode *new_mode) {
448         if (old_mode == new_mode)
449                 return 1;
450
451         /* if both modes are two-complement ones, we can always convert the
452            Stored value into the needed one. */
453         if (get_mode_size_bits(old_mode) >= get_mode_size_bits(new_mode) &&
454                   get_mode_arithmetic(old_mode) == irma_twos_complement &&
455                   get_mode_arithmetic(new_mode) == irma_twos_complement)
456                 return 1;
457         return 0;
458 }  /* can_use_stored_value */
459
460 /**
461  * Follow the memory chain as long as there are only Loads
462  * and alias free Stores and try to replace current Load or Store
463  * by a previous ones.
464  * Note that in unreachable loops it might happen that we reach
465  * load again, as well as we can fall into a cycle.
466  * We break such cycles using a special visited flag.
467  *
468  * INC_MASTER() must be called before dive into
469  */
470 static unsigned follow_Mem_chain(ir_node *load, ir_node *curr) {
471         unsigned res = 0;
472         ldst_info_t *info = get_irn_link(load);
473         ir_node *pred;
474         ir_node *ptr       = get_Load_ptr(load);
475         ir_node *mem       = get_Load_mem(load);
476         ir_mode *load_mode = get_Load_mode(load);
477
478         for (pred = curr; load != pred; ) {
479                 ldst_info_t *pred_info = get_irn_link(pred);
480
481                 /*
482                  * BEWARE: one might think that checking the modes is useless, because
483                  * if the pointers are identical, they refer to the same object.
484                  * This is only true in strong typed languages, not in C were the following
485                  * is possible a = *(ir_type1 *)p; b = *(ir_type2 *)p ...
486                  */
487                 if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
488                     can_use_stored_value(get_irn_mode(get_Store_value(pred)), load_mode)) {
489                         /*
490                          * a Load immediately after a Store -- a read after write.
491                          * We may remove the Load, if both Load & Store does not have an exception handler
492                          * OR they are in the same block. In the latter case the Load cannot
493                          * throw an exception when the previous Store was quiet.
494                          *
495                          * Why we need to check for Store Exception? If the Store cannot
496                          * be executed (ROM) the exception handler might simply jump into
497                          * the load block :-(
498                          * We could make it a little bit better if we would know that the exception
499                          * handler of the Store jumps directly to the end...
500                          */
501                         if ((pred_info->projs[pn_Store_X_except] == NULL && info->projs[pn_Load_X_except] == NULL) ||
502                             get_nodes_block(load) == get_nodes_block(pred)) {
503                                 ir_node *value = get_Store_value(pred);
504
505                                 DBG_OPT_RAW(load, value);
506
507                                 /* add an convert if needed */
508                                 if (get_irn_mode(get_Store_value(pred)) != load_mode) {
509                                         value = new_r_Conv(current_ir_graph, get_nodes_block(load), value, load_mode);
510                                 }
511
512                                 if (info->projs[pn_Load_M])
513                                         exchange(info->projs[pn_Load_M], mem);
514
515                                 /* no exception */
516                                 if (info->projs[pn_Load_X_except]) {
517                                         exchange( info->projs[pn_Load_X_except], new_Bad());
518                                         res |= CF_CHANGED;
519                                 }
520
521                                 if (info->projs[pn_Load_res])
522                                         exchange(info->projs[pn_Load_res], value);
523
524                                 exchange(load, new_Bad());
525                                 reduce_adr_usage(ptr);
526                                 return res | DF_CHANGED;
527                         }
528                 } else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
529                            can_use_stored_value(get_Load_mode(pred), load_mode)) {
530                         /*
531                          * a Load after a Load -- a read after read.
532                          * We may remove the second Load, if it does not have an exception handler
533                          * OR they are in the same block. In the later case the Load cannot
534                          * throw an exception when the previous Load was quiet.
535                          *
536                          * Here, there is no need to check if the previous Load has an exception
537                          * hander because they would have exact the same exception...
538                          */
539                         if (info->projs[pn_Load_X_except] == NULL || get_nodes_block(load) == get_nodes_block(pred)) {
540                                 ir_node *value;
541
542                                 DBG_OPT_RAR(load, pred);
543
544                                 /* the result is used */
545                                 if (info->projs[pn_Load_res]) {
546                                         if (pred_info->projs[pn_Load_res] == NULL) {
547                                                 /* create a new Proj again */
548                                                 pred_info->projs[pn_Load_res] = new_r_Proj(current_ir_graph, get_nodes_block(pred), pred, get_Load_mode(pred), pn_Load_res);
549                                         }
550                                         value = pred_info->projs[pn_Load_res];
551
552                                         /* add an convert if needed */
553                                         if (get_Load_mode(pred) != load_mode) {
554                                                 value = new_r_Conv(current_ir_graph, get_nodes_block(load), value, load_mode);
555                                         }
556
557                                         exchange(info->projs[pn_Load_res], value);
558                                 }
559
560                                 if (info->projs[pn_Load_M])
561                                         exchange(info->projs[pn_Load_M], mem);
562
563                                 /* no exception */
564                                 if (info->projs[pn_Load_X_except]) {
565                                         exchange(info->projs[pn_Load_X_except], new_Bad());
566                                         res |= CF_CHANGED;
567                                 }
568
569                                 exchange(load, new_Bad());
570                                 reduce_adr_usage(ptr);
571                                 return res |= DF_CHANGED;
572                         }
573                 }
574
575                 if (get_irn_op(pred) == op_Store) {
576                         /* check if we can pass through this store */
577                         ir_alias_relation rel = get_alias_relation(
578                                 current_ir_graph,
579                                 get_Store_ptr(pred),
580                                 get_irn_mode(get_Store_value(pred)),
581                                 ptr, load_mode);
582                         /* if the might be an alias, we cannot pass this Store */
583                         if (rel != no_alias)
584                                 break;
585                         pred = skip_Proj(get_Store_mem(pred));
586                 } else if (get_irn_op(pred) == op_Load) {
587                         pred = skip_Proj(get_Load_mem(pred));
588                 } else {
589                         /* follow only Load chains */
590                         break;
591                 }
592
593                 /* check for cycles */
594                 if (NODE_VISITED(pred_info))
595                         break;
596                 MARK_NODE(pred_info);
597         }
598
599         if (get_irn_op(pred) == op_Sync) {
600                 int i;
601
602                 /* handle all Sync predecessors */
603                 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
604                         res |= follow_Mem_chain(load, skip_Proj(get_Sync_pred(pred, i)));
605                         if (res)
606                                 break;
607                 }
608         }
609
610         return res;
611 }  /* follow_Mem_chain */
612
613 /**
614  * optimize a Load
615  *
616  * @param load  the Load node
617  */
618 static unsigned optimize_load(ir_node *load)
619 {
620         ldst_info_t *info = get_irn_link(load);
621         ir_node *mem, *ptr, *new_node;
622         ir_entity *ent;
623         unsigned res = 0;
624
625         /* do NOT touch volatile loads for now */
626         if (get_Load_volatility(load) == volatility_is_volatile)
627                 return 0;
628
629         /* the address of the load to be optimized */
630         ptr = get_Load_ptr(load);
631
632         /*
633          * Check if we can remove the exception from a Load:
634          * This can be done, if the address is from an Sel(Alloc) and
635          * the Sel type is a subtype of the allocated type.
636          *
637          * This optimizes some often used OO constructs,
638          * like x = new O; x->t;
639          */
640         if (info->projs[pn_Load_X_except]) {
641                 if (is_Sel(ptr)) {
642                         ir_node *mem = get_Sel_mem(ptr);
643
644                         /* FIXME: works with the current FE, but better use the base */
645                         if (get_irn_op(skip_Proj(mem)) == op_Alloc) {
646                                 /* ok, check the types */
647                                 ir_entity *ent    = get_Sel_entity(ptr);
648                                 ir_type   *s_type = get_entity_type(ent);
649                                 ir_type   *a_type = get_Alloc_type(mem);
650
651                                 if (is_SubClass_of(s_type, a_type)) {
652                                         /* ok, condition met: there can't be an exception because
653                                         * Alloc guarantees that enough memory was allocated */
654
655                                         exchange(info->projs[pn_Load_X_except], new_Bad());
656                                         info->projs[pn_Load_X_except] = NULL;
657                                         res |= CF_CHANGED;
658                                 }
659                         }
660                 } else if ((get_irn_op(skip_Proj(ptr)) == op_Alloc) ||
661                         ((get_irn_op(ptr) == op_Cast) && (get_irn_op(skip_Proj(get_Cast_op(ptr))) == op_Alloc))) {
662                                 /* simple case: a direct load after an Alloc. Firm Alloc throw
663                                  * an exception in case of out-of-memory. So, there is no way for an
664                                  * exception in this load.
665                                  * This code is constructed by the "exception lowering" in the Jack compiler.
666                                  */
667                                 exchange(info->projs[pn_Load_X_except], new_Bad());
668                                 info->projs[pn_Load_X_except] = NULL;
669                                 res |= CF_CHANGED;
670                 }
671         }
672
673         /* The mem of the Load. Must still be returned after optimization. */
674         mem  = get_Load_mem(load);
675
676         if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
677                 /* a Load which value is neither used nor exception checked, remove it */
678                 exchange(info->projs[pn_Load_M], mem);
679
680                 exchange(load, new_Bad());
681                 reduce_adr_usage(ptr);
682                 return res | DF_CHANGED;
683         }
684
685         /* Load from a constant polymorphic field, where we can resolve
686            polymorphism. */
687         new_node = transform_node_Load(load);
688         if (new_node != load) {
689                 if (info->projs[pn_Load_M]) {
690                         exchange(info->projs[pn_Load_M], mem);
691                         info->projs[pn_Load_M] = NULL;
692                 }
693                 if (info->projs[pn_Load_X_except]) {
694                         exchange(info->projs[pn_Load_X_except], new_Bad());
695                         info->projs[pn_Load_X_except] = NULL;
696                 }
697                 if (info->projs[pn_Load_res])
698                         exchange(info->projs[pn_Load_res], new_node);
699
700                 exchange(load, new_Bad());
701                 reduce_adr_usage(ptr);
702                 return res | DF_CHANGED;
703         }
704
705         /* check if we can determine the entity that will be loaded */
706         ent = find_constant_entity(ptr);
707         if (ent) {
708                 if ((allocation_static == get_entity_allocation(ent)) &&
709                         (visibility_external_allocated != get_entity_visibility(ent))) {
710                         /* a static allocation that is not external: there should be NO exception
711                          * when loading. */
712
713                         /* no exception, clear the info field as it might be checked later again */
714                         if (info->projs[pn_Load_X_except]) {
715                                 exchange(info->projs[pn_Load_X_except], new_Bad());
716                                 info->projs[pn_Load_X_except] = NULL;
717                                 res |= CF_CHANGED;
718                         }
719
720                         if (variability_constant == get_entity_variability(ent)
721                                 && is_atomic_entity(ent)) {
722                                 /* Might not be atomic after
723                                    lowering of Sels.  In this
724                                    case we could also load, but
725                                    it's more complicated. */
726                                 /* more simpler case: we load the content of a constant value:
727                                  * replace it by the constant itself
728                                  */
729
730                                 /* no memory */
731                                 if (info->projs[pn_Load_M]) {
732                                         exchange(info->projs[pn_Load_M], mem);
733                                         res |= DF_CHANGED;
734                                 }
735                                 /* no result :-) */
736                                 if (info->projs[pn_Load_res]) {
737                                         if (is_atomic_entity(ent)) {
738                                                 ir_node *c = copy_const_value(get_irn_dbg_info(load), get_atomic_ent_value(ent));
739
740                                                 DBG_OPT_RC(load, c);
741                                                 exchange(info->projs[pn_Load_res], c);
742                                                 res |= DF_CHANGED;
743                                         }
744                                 }
745                                 exchange(load, new_Bad());
746                                 reduce_adr_usage(ptr);
747                                 return res;
748                         } else if (variability_constant == get_entity_variability(ent)) {
749                                 compound_graph_path *path = get_accessed_path(ptr);
750
751                                 if (path) {
752                                         ir_node *c;
753
754                                         assert(is_proper_compound_graph_path(path, get_compound_graph_path_length(path)-1));
755                                         /*
756                                         {
757                                                 int j;
758                                                 for (j = 0; j < get_compound_graph_path_length(path); ++j) {
759                                                         ir_entity *node = get_compound_graph_path_node(path, j);
760                                                         fprintf(stdout, ".%s", get_entity_name(node));
761                                                         if (is_Array_type(get_entity_owner(node)))
762                                                                 fprintf(stdout, "[%d]", get_compound_graph_path_array_index(path, j));
763                                                 }
764                                                 printf("\n");
765                                         }
766                                         */
767
768                                         c = get_compound_ent_value_by_path(ent, path);
769                                         free_compound_graph_path(path);
770
771                                         /* printf("  cons: "); DDMN(c); */
772
773                                         if (info->projs[pn_Load_M]) {
774                                                 exchange(info->projs[pn_Load_M], mem);
775                                                 res |= DF_CHANGED;
776                                         }
777                                         if (info->projs[pn_Load_res]) {
778                                                 exchange(info->projs[pn_Load_res], copy_const_value(get_irn_dbg_info(load), c));
779                                                 res |= DF_CHANGED;
780                                         }
781                                         exchange(load, new_Bad());
782                                         reduce_adr_usage(ptr);
783                                         return res;
784                                 } else {
785                                         /*  We can not determine a correct access path.  E.g., in jack, we load
786                                         a byte from an object to generate an exception.   Happens in test program
787                                         Reflectiontest.
788                                         printf(">>>>>>>>>>>>> Found access to constant entity %s in function %s\n", get_entity_name(ent),
789                                         get_entity_name(get_irg_entity(current_ir_graph)));
790                                         printf("  load: "); DDMN(load);
791                                         printf("  ptr:  "); DDMN(ptr);
792                                         */
793                                 }
794                         }
795                 }
796         }
797
798         /* Check, if the address of this load is used more than once.
799          * If not, this load cannot be removed in any case. */
800         if (get_irn_n_uses(ptr) <= 1)
801                 return res;
802
803         /*
804          * follow the memory chain as long as there are only Loads
805          * and try to replace current Load or Store by a previous one.
806          * Note that in unreachable loops it might happen that we reach
807          * load again, as well as we can fall into a cycle.
808          * We break such cycles using a special visited flag.
809          */
810         INC_MASTER();
811         res = follow_Mem_chain(load, skip_Proj(mem));
812         return res;
813 }  /* optimize_load */
814
815 /**
816  * Check whether a value of mode new_mode would completely overwrite a value
817  * of mode old_mode in memory.
818  */
819 static int is_completely_overwritten(ir_mode *old_mode, ir_mode *new_mode)
820 {
821         return get_mode_size_bits(new_mode) >= get_mode_size_bits(old_mode);
822 }  /* is_completely_overwritten */
823
824 /**
825  * follow the memory chain as long as there are only Loads and alias free Stores.
826  *
827  * INC_MASTER() must be called before dive into
828  */
829 static unsigned follow_Mem_chain_for_Store(ir_node *store, ir_node *curr) {
830         unsigned res = 0;
831         ldst_info_t *info = get_irn_link(store);
832         ir_node *pred;
833         ir_node *ptr = get_Store_ptr(store);
834         ir_node *mem = get_Store_mem(store);
835         ir_node *value = get_Store_value(store);
836         ir_mode *mode  = get_irn_mode(value);
837         ir_node *block = get_nodes_block(store);
838
839         for (pred = curr; pred != store;) {
840                 ldst_info_t *pred_info = get_irn_link(pred);
841
842                 /*
843                  * BEWARE: one might think that checking the modes is useless, because
844                  * if the pointers are identical, they refer to the same object.
845                  * This is only true in strong typed languages, not is C were the following
846                  * is possible *(ir_type1 *)p = a; *(ir_type2 *)p = b ...
847                  * However, if the mode that is written have a bigger  or equal size the the old
848                  * one, the old value is completely overwritten and can be killed ...
849                  */
850                 if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
851                     get_nodes_block(pred) == block &&
852                     is_completely_overwritten(get_irn_mode(get_Store_value(pred)), mode)) {
853                         /*
854                          * a Store after a Store in the same block -- a write after write.
855                          * We may remove the first Store, if it does not have an exception handler.
856                          *
857                          * TODO: What, if both have the same exception handler ???
858                          */
859                         if (get_Store_volatility(pred) != volatility_is_volatile && !pred_info->projs[pn_Store_X_except]) {
860                                 DBG_OPT_WAW(pred, store);
861                                 exchange( pred_info->projs[pn_Store_M], get_Store_mem(pred) );
862                                 exchange(pred, new_Bad());
863                                 reduce_adr_usage(ptr);
864                                 return DF_CHANGED;
865                         }
866                 } else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
867                            value == pred_info->projs[pn_Load_res]) {
868                         /*
869                          * a Store of a value after a Load -- a write after read.
870                          * We may remove the second Store, if it does not have an exception handler.
871                          */
872                         if (! info->projs[pn_Store_X_except]) {
873                                 DBG_OPT_WAR(store, pred);
874                                 exchange( info->projs[pn_Store_M], mem );
875                                 exchange(store, new_Bad());
876                                 reduce_adr_usage(ptr);
877                                 return DF_CHANGED;
878                         }
879                 }
880
881                 if (get_irn_op(pred) == op_Store) {
882                         /* check if we can pass thru this store */
883                         ir_alias_relation rel = get_alias_relation(
884                                 current_ir_graph,
885                                 get_Store_ptr(pred),
886                                 get_irn_mode(get_Store_value(pred)),
887                                 ptr, mode);
888                         /* if the might be an alias, we cannot pass this Store */
889                         if (rel != no_alias)
890                                 break;
891                         pred = skip_Proj(get_Store_mem(pred));
892                 } else if (get_irn_op(pred) == op_Load) {
893                         pred = skip_Proj(get_Load_mem(pred));
894                 } else {
895                         /* follow only Load chains */
896                         break;
897                 }
898
899                 /* check for cycles */
900                 if (NODE_VISITED(pred_info))
901                         break;
902                 MARK_NODE(pred_info);
903         }
904
905         if (get_irn_op(pred) == op_Sync) {
906                 int i;
907
908                 /* handle all Sync predecessors */
909                 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
910                         res |= follow_Mem_chain_for_Store(store, skip_Proj(get_Sync_pred(pred, i)));
911                         if (res)
912                                 break;
913                 }
914         }
915         return res;
916 }  /* follow_Mem_chain_for_Store */
917
918 /**
919  * optimize a Store
920  *
921  * @param store  the Store node
922  */
923 static unsigned optimize_store(ir_node *store) {
924         ir_node *ptr, *mem;
925
926         if (get_Store_volatility(store) == volatility_is_volatile)
927                 return 0;
928
929         ptr = get_Store_ptr(store);
930
931         /* Check, if the address of this Store is used more than once.
932          * If not, this Store cannot be removed in any case. */
933         if (get_irn_n_uses(ptr) <= 1)
934                 return 0;
935
936         mem = get_Store_mem(store);
937
938         /* follow the memory chain as long as there are only Loads */
939         INC_MASTER();
940         return follow_Mem_chain_for_Store(store, skip_Proj(mem));
941 }  /* optimize_store */
942
943 /**
944  * walker, optimizes Phi after Stores to identical places:
945  * Does the following optimization:
946  * @verbatim
947  *
948  *   val1   val2   val3          val1  val2  val3
949  *    |      |      |               \    |    /
950  *  Store  Store  Store              \   |   /
951  *      \    |    /                   PhiData
952  *       \   |   /                       |
953  *        \  |  /                      Store
954  *          PhiM
955  *
956  * @endverbatim
957  * This reduces the number of stores and allows for predicated execution.
958  * Moves Stores back to the end of a function which may be bad.
959  *
960  * This is only possible if the predecessor blocks have only one successor.
961  */
962 static unsigned optimize_phi(ir_node *phi, walk_env_t *wenv)
963 {
964         int i, n;
965         ir_node *store, *old_store, *ptr, *block, *phi_block, *phiM, *phiD, *exc, *projM;
966         ir_mode *mode;
967         ir_node **inM, **inD, **stores;
968         int *idx;
969         dbg_info *db = NULL;
970         ldst_info_t *info;
971         block_info_t *bl_info;
972         unsigned res = 0;
973
974         /* Must be a memory Phi */
975         if (get_irn_mode(phi) != mode_M)
976                 return 0;
977
978         n = get_Phi_n_preds(phi);
979         if (n <= 0)
980                 return 0;
981
982         store = skip_Proj(get_Phi_pred(phi, 0));
983         old_store = store;
984         if (get_irn_op(store) != op_Store)
985                 return 0;
986
987         block = get_nodes_block(store);
988
989         /* abort on dead blocks */
990         if (is_Block_dead(block))
991                 return 0;
992
993         /* check if the block is post dominated by Phi-block
994            and has no exception exit */
995         bl_info = get_irn_link(block);
996         if (bl_info->flags & BLOCK_HAS_EXC)
997                 return 0;
998
999         phi_block = get_nodes_block(phi);
1000         if (! block_postdominates(phi_block, block))
1001                 return 0;
1002
1003         /* this is the address of the store */
1004         ptr  = get_Store_ptr(store);
1005         mode = get_irn_mode(get_Store_value(store));
1006         info = get_irn_link(store);
1007         exc  = info->exc_block;
1008
1009         for (i = 1; i < n; ++i) {
1010                 ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
1011
1012                 if (get_irn_op(pred) != op_Store)
1013                         return 0;
1014
1015                 if (ptr != get_Store_ptr(pred) || mode != get_irn_mode(get_Store_value(pred)))
1016                         return 0;
1017
1018                 info = get_irn_link(pred);
1019
1020                 /* check, if all stores have the same exception flow */
1021                 if (exc != info->exc_block)
1022                         return 0;
1023
1024                 /* abort on dead blocks */
1025                 block = get_nodes_block(pred);
1026                 if (is_Block_dead(block))
1027                         return 0;
1028
1029                 /* check if the block is post dominated by Phi-block
1030                    and has no exception exit. Note that block must be different from
1031                    Phi-block, else we would move a Store from end End of a block to its
1032                    Start... */
1033                 bl_info = get_irn_link(block);
1034                 if (bl_info->flags & BLOCK_HAS_EXC)
1035                         return 0;
1036                 if (block == phi_block || ! block_postdominates(phi_block, block))
1037                         return 0;
1038         }
1039
1040         /*
1041          * ok, when we are here, we found all predecessors of a Phi that
1042          * are Stores to the same address and size. That means whatever
1043          * we do before we enter the block of the Phi, we do a Store.
1044          * So, we can move the Store to the current block:
1045          *
1046          *   val1    val2    val3          val1  val2  val3
1047          *    |       |       |               \    |    /
1048          * | Str | | Str | | Str |             \   |   /
1049          *      \     |     /                   PhiData
1050          *       \    |    /                       |
1051          *        \   |   /                       Str
1052          *           PhiM
1053          *
1054          * Is only allowed if the predecessor blocks have only one successor.
1055          */
1056
1057         NEW_ARR_A(ir_node *, stores, n);
1058         NEW_ARR_A(ir_node *, inM, n);
1059         NEW_ARR_A(ir_node *, inD, n);
1060         NEW_ARR_A(int, idx, n);
1061
1062         /* Prepare: Collect all Store nodes.  We must do this
1063            first because we otherwise may loose a store when exchanging its
1064            memory Proj.
1065          */
1066         for (i = 0; i < n; ++i)
1067                 stores[i] = skip_Proj(get_Phi_pred(phi, i));
1068
1069         /* first step: collect all inputs */
1070         for (i = 0; i < n; ++i) {
1071                 ir_node *store = stores[i];
1072                 info = get_irn_link(store);
1073
1074                 inM[i] = get_Store_mem(store);
1075                 inD[i] = get_Store_value(store);
1076                 idx[i] = info->exc_idx;
1077
1078                 kill_node(store);
1079         }
1080         block = get_nodes_block(phi);
1081
1082         /* second step: create a new memory Phi */
1083         phiM = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inM, mode_M);
1084
1085         /* third step: create a new data Phi */
1086         phiD = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inD, mode);
1087
1088         /* fourth step: create the Store */
1089         store = new_rd_Store(db, current_ir_graph, block, phiM, ptr, phiD);
1090 #ifdef DO_CACHEOPT
1091         co_set_irn_name(store, co_get_irn_ident(old_store));
1092 #endif
1093
1094         projM = new_rd_Proj(NULL, current_ir_graph, block, store, mode_M, pn_Store_M);
1095
1096         info = get_ldst_info(store, wenv);
1097         info->projs[pn_Store_M] = projM;
1098
1099         /* fifths step: repair exception flow */
1100         if (exc) {
1101                 ir_node *projX = new_rd_Proj(NULL, current_ir_graph, block, store, mode_X, pn_Store_X_except);
1102
1103                 info->projs[pn_Store_X_except] = projX;
1104                 info->exc_block                = exc;
1105                 info->exc_idx                  = idx[0];
1106
1107                 for (i = 0; i < n; ++i) {
1108                         set_Block_cfgpred(exc, idx[i], projX);
1109                 }
1110
1111                 if (n > 1) {
1112                         /* the exception block should be optimized as some inputs are identical now */
1113                 }
1114
1115                 res |= CF_CHANGED;
1116         }
1117
1118         /* sixth step: replace old Phi */
1119         exchange(phi, projM);
1120
1121         return res | DF_CHANGED;
1122 }  /* optimize_phi */
1123
1124 /**
1125  * walker, do the optimizations
1126  */
1127 static void do_load_store_optimize(ir_node *n, void *env) {
1128         walk_env_t *wenv = env;
1129
1130         switch (get_irn_opcode(n)) {
1131
1132         case iro_Load:
1133                 wenv->changes |= optimize_load(n);
1134                 break;
1135
1136         case iro_Store:
1137                 wenv->changes |= optimize_store(n);
1138                 break;
1139
1140         case iro_Phi:
1141                 wenv->changes |= optimize_phi(n, wenv);
1142
1143         default:
1144                 ;
1145         }
1146 }  /* do_load_store_optimize */
1147
1148 /*
1149  * do the load store optimization
1150  */
1151 void optimize_load_store(ir_graph *irg) {
1152         walk_env_t env;
1153
1154         assert(get_irg_phase_state(irg) != phase_building);
1155         assert(get_irg_pinned(irg) != op_pin_state_floats &&
1156                 "LoadStore optimization needs pinned graph");
1157
1158         if (! get_opt_redundant_loadstore())
1159                 return;
1160
1161         edges_assure(irg);
1162
1163         /* for Phi optimization post-dominators are needed ... */
1164         assure_postdoms(irg);
1165
1166         if (get_opt_alias_analysis()) {
1167                 assure_irg_address_taken_computed(irg);
1168                 assure_irp_globals_address_taken_computed();
1169         }
1170
1171         obstack_init(&env.obst);
1172         env.changes = 0;
1173
1174         /* init the links, then collect Loads/Stores/Proj's in lists */
1175         master_visited = 0;
1176         irg_walk_graph(irg, firm_clear_link, collect_nodes, &env);
1177
1178         /* now we have collected enough information, optimize */
1179         irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
1180
1181         obstack_free(&env.obst, NULL);
1182
1183         /* Handle graph state */
1184         if (env.changes) {
1185                 if (get_irg_outs_state(irg) == outs_consistent)
1186                         set_irg_outs_inconsistent(irg);
1187         }
1188
1189         if (env.changes & CF_CHANGED) {
1190                 /* is this really needed: Yes, control flow changed, block might
1191                 have Bad() predecessors. */
1192                 set_irg_doms_inconsistent(irg);
1193         }
1194 }  /* optimize_load_store */