c1f214c08a6cab551cfb6a51a5ba374463b55540
[libfirm] / ir / opt / ldstopt.c
1 /*
2  * Copyright (C) 1995-2008 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 #include "irphase_t.h"
53 #include "irgopt.h"
54 #include "debug.h"
55
56 /** The debug handle. */
57 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
58
59 #ifdef DO_CACHEOPT
60 #include "cacheopt/cachesim.h"
61 #endif
62
63 #undef IMAX
64 #define IMAX(a,b)       ((a) > (b) ? (a) : (b))
65
66 #define MAX_PROJ        IMAX(IMAX(pn_Load_max, pn_Store_max), pn_Call_max)
67
68 enum changes_t {
69         DF_CHANGED = 1,       /**< data flow changed */
70         CF_CHANGED = 2,       /**< control flow changed */
71 };
72
73 /**
74  * walker environment
75  */
76 typedef struct _walk_env_t {
77         struct obstack obst;          /**< list of all stores */
78         unsigned changes;             /**< a bitmask of graph changes */
79 } walk_env_t;
80
81 /** A Load/Store info. */
82 typedef struct _ldst_info_t {
83         ir_node  *projs[MAX_PROJ];    /**< list of Proj's of this node */
84         ir_node  *exc_block;          /**< the exception block if available */
85         int      exc_idx;             /**< predecessor index in the exception block */
86         unsigned visited;             /**< visited counter for breaking loops */
87 } ldst_info_t;
88
89 /**
90  * flags for control flow.
91  */
92 enum block_flags_t {
93         BLOCK_HAS_COND = 1,      /**< Block has conditional control flow */
94         BLOCK_HAS_EXC  = 2       /**< Block has exceptional control flow */
95 };
96
97 /**
98  * a Block info.
99  */
100 typedef struct _block_info_t {
101         unsigned flags;               /**< flags for the block */
102 } block_info_t;
103
104 /** the master visited flag for loop detection. */
105 static unsigned master_visited = 0;
106
107 #define INC_MASTER()       ++master_visited
108 #define MARK_NODE(info)    (info)->visited = master_visited
109 #define NODE_VISITED(info) (info)->visited >= master_visited
110
111 /**
112  * get the Load/Store info of a node
113  */
114 static ldst_info_t *get_ldst_info(ir_node *node, struct obstack *obst) {
115         ldst_info_t *info = get_irn_link(node);
116
117         if (! info) {
118                 info = obstack_alloc(obst, sizeof(*info));
119                 memset(info, 0, sizeof(*info));
120                 set_irn_link(node, info);
121         }
122         return info;
123 }  /* get_ldst_info */
124
125 /**
126  * get the Block info of a node
127  */
128 static block_info_t *get_block_info(ir_node *node, struct obstack *obst) {
129         block_info_t *info = get_irn_link(node);
130
131         if (! info) {
132                 info = obstack_alloc(obst, sizeof(*info));
133                 memset(info, 0, sizeof(*info));
134                 set_irn_link(node, info);
135         }
136         return info;
137 }  /* get_block_info */
138
139 /**
140  * update the projection info for a Load/Store
141  */
142 static unsigned update_projs(ldst_info_t *info, ir_node *proj)
143 {
144         long nr = get_Proj_proj(proj);
145
146         assert(0 <= nr && nr <= MAX_PROJ && "Wrong proj from LoadStore");
147
148         if (info->projs[nr]) {
149                 /* there is already one, do CSE */
150                 exchange(proj, info->projs[nr]);
151                 return DF_CHANGED;
152         }
153         else {
154                 info->projs[nr] = proj;
155                 return 0;
156         }
157 }  /* update_projs */
158
159 /**
160  * update the exception block info for a Load/Store node.
161  *
162  * @param info   the load/store info struct
163  * @param block  the exception handler block for this load/store
164  * @param pos    the control flow input of the block
165  */
166 static unsigned update_exc(ldst_info_t *info, ir_node *block, int pos)
167 {
168         assert(info->exc_block == NULL && "more than one exception block found");
169
170         info->exc_block = block;
171         info->exc_idx   = pos;
172         return 0;
173 }  /* update_exc */
174
175 /** Return the number of uses of an address node */
176 #define get_irn_n_uses(adr)     get_irn_n_edges(adr)
177
178 /**
179  * walker, collects all Load/Store/Proj nodes
180  *
181  * walks from Start -> End
182  */
183 static void collect_nodes(ir_node *node, void *env)
184 {
185         ir_opcode   opcode = get_irn_opcode(node);
186         ir_node     *pred, *blk, *pred_blk;
187         ldst_info_t *ldst_info;
188         walk_env_t  *wenv = env;
189
190         if (opcode == iro_Proj) {
191                 pred   = get_Proj_pred(node);
192                 opcode = get_irn_opcode(pred);
193
194                 if (opcode == iro_Load || opcode == iro_Store || opcode == iro_Call) {
195                         ldst_info = get_ldst_info(pred, &wenv->obst);
196
197                         wenv->changes |= update_projs(ldst_info, node);
198
199                         /*
200                          * Place the Proj's to the same block as the
201                          * predecessor Load. This is always ok and prevents
202                          * "non-SSA" form after optimizations if the Proj
203                          * is in a wrong block.
204                          */
205                         blk      = get_nodes_block(node);
206                         pred_blk = get_nodes_block(pred);
207                         if (blk != pred_blk) {
208                                 wenv->changes |= DF_CHANGED;
209                                 set_nodes_block(node, pred_blk);
210                         }
211                 }
212         } else if (opcode == iro_Block) {
213                 int i;
214
215                 for (i = get_Block_n_cfgpreds(node) - 1; i >= 0; --i) {
216                         ir_node      *pred_block, *proj;
217                         block_info_t *bl_info;
218                         int          is_exc = 0;
219
220                         pred = proj = get_Block_cfgpred(node, i);
221
222                         if (is_Proj(proj)) {
223                                 pred   = get_Proj_pred(proj);
224                                 is_exc = get_Proj_proj(proj) == pn_Generic_X_except;
225                         }
226
227                         /* ignore Bad predecessors, they will be removed later */
228                         if (is_Bad(pred))
229                                 continue;
230
231                         pred_block = get_nodes_block(pred);
232                         bl_info    = get_block_info(pred_block, &wenv->obst);
233
234                         if (is_fragile_op(pred) && is_exc)
235                                 bl_info->flags |= BLOCK_HAS_EXC;
236                         else if (is_irn_forking(pred))
237                                 bl_info->flags |= BLOCK_HAS_COND;
238
239                         opcode = get_irn_opcode(pred);
240                         if (is_exc && (opcode == iro_Load || opcode == iro_Store || opcode == iro_Call)) {
241                                 ldst_info = get_ldst_info(pred, &wenv->obst);
242
243                                 wenv->changes |= update_exc(ldst_info, node, i);
244                         }
245                 }
246         }
247 }  /* collect_nodes */
248
249 /**
250  * Returns an entity if the address ptr points to a constant one.
251  *
252  * @param ptr  the address
253  *
254  * @return an entity or NULL
255  */
256 static ir_entity *find_constant_entity(ir_node *ptr)
257 {
258         for (;;) {
259                 ir_op *op = get_irn_op(ptr);
260
261                 if (op == op_SymConst && (get_SymConst_kind(ptr) == symconst_addr_ent)) {
262                         ir_entity *ent = get_SymConst_entity(ptr);
263                         if (variability_constant == get_entity_variability(ent))
264                                 return ent;
265                         return NULL;
266                 } else if (op == op_Sel) {
267                         ir_entity *ent = get_Sel_entity(ptr);
268                         ir_type   *tp  = get_entity_owner(ent);
269
270                         /* Do not fiddle with polymorphism. */
271                         if (is_Class_type(get_entity_owner(ent)) &&
272                                 ((get_entity_n_overwrites(ent)    != 0) ||
273                                 (get_entity_n_overwrittenby(ent) != 0)   ) )
274                                 return NULL;
275
276                         if (is_Array_type(tp)) {
277                                 /* check bounds */
278                                 int i, n;
279
280                                 for (i = 0, n = get_Sel_n_indexs(ptr); i < n; ++i) {
281                                         ir_node *bound;
282                                         tarval *tlower, *tupper;
283                                         ir_node *index = get_Sel_index(ptr, i);
284                                         tarval *tv     = computed_value(index);
285
286                                         /* check if the index is constant */
287                                         if (tv == tarval_bad)
288                                                 return NULL;
289
290                                         bound  = get_array_lower_bound(tp, i);
291                                         tlower = computed_value(bound);
292                                         bound  = get_array_upper_bound(tp, i);
293                                         tupper = computed_value(bound);
294
295                                         if (tlower == tarval_bad || tupper == tarval_bad)
296                                                 return NULL;
297
298                                         if (tarval_cmp(tv, tlower) & pn_Cmp_Lt)
299                                                 return NULL;
300                                         if (tarval_cmp(tupper, tv) & pn_Cmp_Lt)
301                                                 return NULL;
302
303                                         /* ok, bounds check finished */
304                                 }
305                         }
306
307                         if (variability_constant == get_entity_variability(ent))
308                                 return ent;
309
310                         /* try next */
311                         ptr = get_Sel_ptr(ptr);
312                 } else
313                         return NULL;
314         }
315 }  /* find_constant_entity */
316
317 /**
318  * Return the Selection index of a Sel node from dimension n
319  */
320 static long get_Sel_array_index_long(ir_node *n, int dim) {
321         ir_node *index = get_Sel_index(n, dim);
322         assert(is_Const(index));
323         return get_tarval_long(get_Const_tarval(index));
324 }  /* get_Sel_array_index_long */
325
326 /**
327  * Returns the accessed component graph path for an
328  * node computing an address.
329  *
330  * @param ptr    the node computing the address
331  * @param depth  current depth in steps upward from the root
332  *               of the address
333  */
334 static compound_graph_path *rec_get_accessed_path(ir_node *ptr, int depth) {
335         compound_graph_path *res = NULL;
336         ir_entity           *root, *field;
337         int                 path_len, pos;
338
339         if (get_irn_op(ptr) == op_SymConst) {
340                 /* a SymConst. If the depth is 0, this is an access to a global
341                  * entity and we don't need a component path, else we know
342                  * at least it's length.
343                  */
344                 assert(get_SymConst_kind(ptr) == symconst_addr_ent);
345                 root = get_SymConst_entity(ptr);
346                 res = (depth == 0) ? NULL : new_compound_graph_path(get_entity_type(root), depth);
347         } else {
348                 assert(get_irn_op(ptr) == op_Sel);
349                 /* it's a Sel, go up until we find the root */
350                 res = rec_get_accessed_path(get_Sel_ptr(ptr), depth+1);
351
352                 /* fill up the step in the path at the current position */
353                 field    = get_Sel_entity(ptr);
354                 path_len = get_compound_graph_path_length(res);
355                 pos      = path_len - depth - 1;
356                 set_compound_graph_path_node(res, pos, field);
357
358                 if (is_Array_type(get_entity_owner(field))) {
359                         assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
360                         set_compound_graph_path_array_index(res, pos, get_Sel_array_index_long(ptr, 0));
361                 }
362         }
363         return res;
364 }  /* rec_get_accessed_path */
365
366 /** Returns an access path or NULL.  The access path is only
367  *  valid, if the graph is in phase_high and _no_ address computation is used.
368  */
369 static compound_graph_path *get_accessed_path(ir_node *ptr) {
370         return rec_get_accessed_path(ptr, 0);
371 }  /* get_accessed_path */
372
373 /* forward */
374 static void reduce_adr_usage(ir_node *ptr);
375
376 /**
377  * Update a Load that may lost it's usage.
378  */
379 static void handle_load_update(ir_node *load) {
380         ldst_info_t *info = get_irn_link(load);
381
382         /* do NOT touch volatile loads for now */
383         if (get_Load_volatility(load) == volatility_is_volatile)
384                 return;
385
386         if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
387                 ir_node *ptr = get_Load_ptr(load);
388                 ir_node *mem = get_Load_mem(load);
389
390                 /* a Load which value is neither used nor exception checked, remove it */
391                 exchange(info->projs[pn_Load_M], mem);
392                 if (info->projs[pn_Load_X_regular])
393                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
394                 kill_node(load);
395                 reduce_adr_usage(ptr);
396         }
397 }  /* handle_load_update */
398
399 /**
400  * A Use of an address node is vanished. Check if this was a Proj
401  * node and update the counters.
402  */
403 static void reduce_adr_usage(ir_node *ptr) {
404         if (is_Proj(ptr)) {
405                 if (get_irn_n_edges(ptr) <= 0) {
406                         /* this Proj is dead now */
407                         ir_node *pred = get_Proj_pred(ptr);
408
409                         if (is_Load(pred)) {
410                                 ldst_info_t *info = get_irn_link(pred);
411                                 info->projs[get_Proj_proj(ptr)] = NULL;
412
413                                 /* this node lost it's result proj, handle that */
414                                 handle_load_update(pred);
415                         }
416                 }
417         }
418 }  /* reduce_adr_usage */
419
420 /**
421  * Check, if an already existing value of mode old_mode can be converted
422  * into the needed one new_mode without loss.
423  */
424 static int can_use_stored_value(ir_mode *old_mode, ir_mode *new_mode) {
425         if (old_mode == new_mode)
426                 return 1;
427
428         /* if both modes are two-complement ones, we can always convert the
429            Stored value into the needed one. */
430         if (get_mode_size_bits(old_mode) >= get_mode_size_bits(new_mode) &&
431                   get_mode_arithmetic(old_mode) == irma_twos_complement &&
432                   get_mode_arithmetic(new_mode) == irma_twos_complement)
433                 return 1;
434         return 0;
435 }  /* can_use_stored_value */
436
437 /**
438  * Check whether a Call is at least pure, ie. does only read memory.
439  */
440 static unsigned is_Call_pure(ir_node *call) {
441         ir_type *call_tp = get_Call_type(call);
442         unsigned prop = get_method_additional_properties(call_tp);
443
444         /* check first the call type */
445         if ((prop & (mtp_property_const|mtp_property_pure)) == 0) {
446                 /* try the called entity */
447                 ir_node *ptr = get_Call_ptr(call);
448
449                 if (is_Global(ptr)) {
450                         ir_entity *ent = get_Global_entity(ptr);
451
452                         prop = get_entity_additional_properties(ent);
453                 }
454         }
455         return (prop & (mtp_property_const|mtp_property_pure)) != 0;
456 }  /* is_Call_pure */
457
458 /**
459  * Follow the memory chain as long as there are only Loads,
460  * alias free Stores, and constant Calls and try to replace the
461  * current Load by a previous ones.
462  * Note that in unreachable loops it might happen that we reach
463  * load again, as well as we can fall into a cycle.
464  * We break such cycles using a special visited flag.
465  *
466  * INC_MASTER() must be called before dive into
467  */
468 static unsigned follow_Mem_chain(ir_node *load, ir_node *curr) {
469         unsigned res = 0;
470         ldst_info_t *info = get_irn_link(load);
471         ir_node *pred;
472         ir_node *ptr       = get_Load_ptr(load);
473         ir_node *mem       = get_Load_mem(load);
474         ir_mode *load_mode = get_Load_mode(load);
475
476         for (pred = curr; load != pred; ) {
477                 ldst_info_t *pred_info = get_irn_link(pred);
478
479                 /*
480                  * BEWARE: one might think that checking the modes is useless, because
481                  * if the pointers are identical, they refer to the same object.
482                  * This is only true in strong typed languages, not in C were the following
483                  * is possible a = *(ir_type1 *)p; b = *(ir_type2 *)p ...
484                  */
485                 if (is_Store(pred) && get_Store_ptr(pred) == ptr &&
486                     can_use_stored_value(get_irn_mode(get_Store_value(pred)), load_mode)) {
487                         /*
488                          * a Load immediately after a Store -- a read after write.
489                          * We may remove the Load, if both Load & Store does not have an exception handler
490                          * OR they are in the same MacroBlock. In the latter case the Load cannot
491                          * throw an exception when the previous Store was quiet.
492                          *
493                          * Why we need to check for Store Exception? If the Store cannot
494                          * be executed (ROM) the exception handler might simply jump into
495                          * the load MacroBlock :-(
496                          * We could make it a little bit better if we would know that the exception
497                          * handler of the Store jumps directly to the end...
498                          */
499                         if ((pred_info->projs[pn_Store_X_except] == NULL && info->projs[pn_Load_X_except] == NULL) ||
500                             get_nodes_MacroBlock(load) == get_nodes_MacroBlock(pred)) {
501                                 ir_node *value = get_Store_value(pred);
502
503                                 DBG_OPT_RAW(load, value);
504
505                                 /* add an convert if needed */
506                                 if (get_irn_mode(get_Store_value(pred)) != load_mode) {
507                                         value = new_r_Conv(current_ir_graph, get_nodes_block(load), value, load_mode);
508                                 }
509
510                                 if (info->projs[pn_Load_M])
511                                         exchange(info->projs[pn_Load_M], mem);
512
513                                 /* no exception */
514                                 if (info->projs[pn_Load_X_except]) {
515                                         exchange( info->projs[pn_Load_X_except], new_Bad());
516                                         res |= CF_CHANGED;
517                                 }
518                                 if (info->projs[pn_Load_X_regular]) {
519                                         exchange( info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
520                                         res |= CF_CHANGED;
521                                 }
522
523                                 if (info->projs[pn_Load_res])
524                                         exchange(info->projs[pn_Load_res], value);
525
526                                 kill_node(load);
527                                 reduce_adr_usage(ptr);
528                                 return res | DF_CHANGED;
529                         }
530                 } else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
531                            can_use_stored_value(get_Load_mode(pred), load_mode)) {
532                         /*
533                          * a Load after a Load -- a read after read.
534                          * We may remove the second Load, if it does not have an exception handler
535                          * OR they are in the same MacroBlock. In the later case the Load cannot
536                          * throw an exception when the previous Load was quiet.
537                          *
538                          * Here, there is no need to check if the previous Load has an exception
539                          * hander because they would have exact the same exception...
540                          */
541                         if (info->projs[pn_Load_X_except] == NULL || get_nodes_MacroBlock(load) == get_nodes_MacroBlock(pred)) {
542                                 ir_node *value;
543
544                                 DBG_OPT_RAR(load, pred);
545
546                                 /* the result is used */
547                                 if (info->projs[pn_Load_res]) {
548                                         if (pred_info->projs[pn_Load_res] == NULL) {
549                                                 /* create a new Proj again */
550                                                 pred_info->projs[pn_Load_res] = new_r_Proj(current_ir_graph, get_nodes_block(pred), pred, get_Load_mode(pred), pn_Load_res);
551                                         }
552                                         value = pred_info->projs[pn_Load_res];
553
554                                         /* add an convert if needed */
555                                         if (get_Load_mode(pred) != load_mode) {
556                                                 value = new_r_Conv(current_ir_graph, get_nodes_block(load), value, load_mode);
557                                         }
558
559                                         exchange(info->projs[pn_Load_res], value);
560                                 }
561
562                                 if (info->projs[pn_Load_M])
563                                         exchange(info->projs[pn_Load_M], mem);
564
565                                 /* no exception */
566                                 if (info->projs[pn_Load_X_except]) {
567                                         exchange(info->projs[pn_Load_X_except], new_Bad());
568                                         res |= CF_CHANGED;
569                                 }
570                                 if (info->projs[pn_Load_X_regular]) {
571                                         exchange( info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
572                                         res |= CF_CHANGED;
573                                 }
574
575                                 kill_node(load);
576                                 reduce_adr_usage(ptr);
577                                 return res |= DF_CHANGED;
578                         }
579                 }
580
581                 if (is_Store(pred)) {
582                         /* check if we can pass through this store */
583                         ir_alias_relation rel = get_alias_relation(
584                                 current_ir_graph,
585                                 get_Store_ptr(pred),
586                                 get_irn_mode(get_Store_value(pred)),
587                                 ptr, load_mode);
588                         /* if the might be an alias, we cannot pass this Store */
589                         if (rel != no_alias)
590                                 break;
591                         pred = skip_Proj(get_Store_mem(pred));
592                 } else if (is_Load(pred)) {
593                         pred = skip_Proj(get_Load_mem(pred));
594                 } else if (is_Call(pred)) {
595                         if (is_Call_pure(pred)) {
596                                 /* The called graph is at least pure, so there are no Store's
597                                    in it. We can handle it like a Load and skip it. */
598                                 pred = skip_Proj(get_Call_mem(pred));
599                         } else {
600                                 /* there might be Store's in the graph, stop here */
601                                 break;
602                         }
603                 } else {
604                         /* follow only Load chains */
605                         break;
606                 }
607
608                 /* check for cycles */
609                 if (NODE_VISITED(pred_info))
610                         break;
611                 MARK_NODE(pred_info);
612         }
613
614         if (is_Sync(pred)) {
615                 int i;
616
617                 /* handle all Sync predecessors */
618                 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
619                         res |= follow_Mem_chain(load, skip_Proj(get_Sync_pred(pred, i)));
620                         if (res)
621                                 return res;
622                 }
623         }
624
625         return res;
626 }  /* follow_Mem_chain */
627
628 /**
629  * optimize a Load
630  *
631  * @param load  the Load node
632  */
633 static unsigned optimize_load(ir_node *load)
634 {
635         ldst_info_t *info = get_irn_link(load);
636         ir_node *mem, *ptr, *new_node;
637         ir_entity *ent;
638         unsigned res = 0;
639
640         /* do NOT touch volatile loads for now */
641         if (get_Load_volatility(load) == volatility_is_volatile)
642                 return 0;
643
644         /* the address of the load to be optimized */
645         ptr = get_Load_ptr(load);
646
647         /*
648          * Check if we can remove the exception from a Load:
649          * This can be done, if the address is from an Sel(Alloc) and
650          * the Sel type is a subtype of the allocated type.
651          *
652          * This optimizes some often used OO constructs,
653          * like x = new O; x->t;
654          */
655         if (info->projs[pn_Load_X_except]) {
656                 if (is_Sel(ptr)) {
657                         ir_node *mem = get_Sel_mem(ptr);
658
659                         /* FIXME: works with the current FE, but better use the base */
660                         if (is_Alloc(skip_Proj(mem))) {
661                                 /* ok, check the types */
662                                 ir_entity *ent    = get_Sel_entity(ptr);
663                                 ir_type   *s_type = get_entity_type(ent);
664                                 ir_type   *a_type = get_Alloc_type(mem);
665
666                                 if (is_SubClass_of(s_type, a_type)) {
667                                         /* ok, condition met: there can't be an exception because
668                                         * Alloc guarantees that enough memory was allocated */
669
670                                         exchange(info->projs[pn_Load_X_except], new_Bad());
671                                         info->projs[pn_Load_X_except] = NULL;
672                                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
673                                         info->projs[pn_Load_X_regular] = NULL;
674                                         res |= CF_CHANGED;
675                                 }
676                         }
677                 } else if (is_Alloc(skip_Proj(skip_Cast(ptr)))) {
678                                 /* simple case: a direct load after an Alloc. Firm Alloc throw
679                                  * an exception in case of out-of-memory. So, there is no way for an
680                                  * exception in this load.
681                                  * This code is constructed by the "exception lowering" in the Jack compiler.
682                                  */
683                                 exchange(info->projs[pn_Load_X_except], new_Bad());
684                                 info->projs[pn_Load_X_except] = NULL;
685                                 exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
686                                 info->projs[pn_Load_X_regular] = NULL;
687                                 res |= CF_CHANGED;
688                 }
689         }
690
691         /* The mem of the Load. Must still be returned after optimization. */
692         mem  = get_Load_mem(load);
693
694         if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
695                 /* a Load which value is neither used nor exception checked, remove it */
696                 exchange(info->projs[pn_Load_M], mem);
697
698                 if (info->projs[pn_Load_X_regular]) {
699                         /* should not happen, but if it does, remove it */
700                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
701                         res |= CF_CHANGED;
702                 }
703                 kill_node(load);
704                 reduce_adr_usage(ptr);
705                 return res | DF_CHANGED;
706         }
707
708         /* Load from a constant polymorphic field, where we can resolve
709            polymorphism. */
710         new_node = transform_node_Load(load);
711         if (new_node != load) {
712                 if (info->projs[pn_Load_M]) {
713                         exchange(info->projs[pn_Load_M], mem);
714                         info->projs[pn_Load_M] = NULL;
715                 }
716                 if (info->projs[pn_Load_X_except]) {
717                         exchange(info->projs[pn_Load_X_except], new_Bad());
718                         info->projs[pn_Load_X_except] = NULL;
719                         res |= CF_CHANGED;
720                 }
721                 if (info->projs[pn_Load_X_regular]) {
722                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
723                         info->projs[pn_Load_X_regular] = NULL;
724                         res |= CF_CHANGED;
725                 }
726                 if (info->projs[pn_Load_res])
727                         exchange(info->projs[pn_Load_res], new_node);
728
729                 kill_node(load);
730                 reduce_adr_usage(ptr);
731                 return res | DF_CHANGED;
732         }
733
734         /* check if we can determine the entity that will be loaded */
735         ent = find_constant_entity(ptr);
736         if (ent) {
737                 if ((allocation_static == get_entity_allocation(ent)) &&
738                         (visibility_external_allocated != get_entity_visibility(ent))) {
739                         /* a static allocation that is not external: there should be NO exception
740                          * when loading. */
741
742                         /* no exception, clear the info field as it might be checked later again */
743                         if (info->projs[pn_Load_X_except]) {
744                                 exchange(info->projs[pn_Load_X_except], new_Bad());
745                                 info->projs[pn_Load_X_except] = NULL;
746                                 res |= CF_CHANGED;
747                         }
748                         if (info->projs[pn_Load_X_regular]) {
749                                 exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
750                                 info->projs[pn_Load_X_regular] = NULL;
751                                 res |= CF_CHANGED;
752                         }
753
754                         if (variability_constant == get_entity_variability(ent)) {
755                                 if (is_atomic_entity(ent)) {
756                                         /* Might not be atomic after
757                                            lowering of Sels.  In this
758                                            case we could also load, but
759                                            it's more complicated. */
760                                         /* more simpler case: we load the content of a constant value:
761                                          * replace it by the constant itself
762                                          */
763
764                                         /* no memory */
765                                         if (info->projs[pn_Load_M]) {
766                                                 exchange(info->projs[pn_Load_M], mem);
767                                                 res |= DF_CHANGED;
768                                         }
769                                         /* no result :-) */
770                                         if (info->projs[pn_Load_res]) {
771                                                 if (is_atomic_entity(ent)) {
772                                                         ir_node *c = copy_const_value(get_irn_dbg_info(load), get_atomic_ent_value(ent));
773
774                                                         DBG_OPT_RC(load, c);
775                                                         exchange(info->projs[pn_Load_res], c);
776                                                         res |= DF_CHANGED;
777                                                 }
778                                         }
779                                         kill_node(load);
780                                         reduce_adr_usage(ptr);
781                                         return res;
782                                 } else {
783                                         compound_graph_path *path = get_accessed_path(ptr);
784
785                                         if (path) {
786                                                 ir_node *c;
787
788                                                 assert(is_proper_compound_graph_path(path, get_compound_graph_path_length(path)-1));
789                                                 /*
790                                                 {
791                                                         int j;
792                                                         for (j = 0; j < get_compound_graph_path_length(path); ++j) {
793                                                                 ir_entity *node = get_compound_graph_path_node(path, j);
794                                                                 fprintf(stdout, ".%s", get_entity_name(node));
795                                                                 if (is_Array_type(get_entity_owner(node)))
796                                                                         fprintf(stdout, "[%d]", get_compound_graph_path_array_index(path, j));
797                                                         }
798                                                         printf("\n");
799                                                 }
800                                                 */
801
802                                                 c = get_compound_ent_value_by_path(ent, path);
803                                                 free_compound_graph_path(path);
804
805                                                 /* printf("  cons: "); DDMN(c); */
806
807                                                 if (info->projs[pn_Load_M]) {
808                                                         exchange(info->projs[pn_Load_M], mem);
809                                                         res |= DF_CHANGED;
810                                                 }
811                                                 if (info->projs[pn_Load_res]) {
812                                                         exchange(info->projs[pn_Load_res], copy_const_value(get_irn_dbg_info(load), c));
813                                                         res |= DF_CHANGED;
814                                                 }
815                                                 kill_node(load);
816                                                 reduce_adr_usage(ptr);
817                                                 return res;
818                                         } else {
819                                                 /*  We can not determine a correct access path.  E.g., in jack, we load
820                                                 a byte from an object to generate an exception.   Happens in test program
821                                                 Reflectiontest.
822                                                 printf(">>>>>>>>>>>>> Found access to constant entity %s in function %s\n", get_entity_name(ent),
823                                                 get_entity_name(get_irg_entity(current_ir_graph)));
824                                                 printf("  load: "); DDMN(load);
825                                                 printf("  ptr:  "); DDMN(ptr);
826                                                 */
827                                         }
828                                 }
829                         }
830                 }
831         }
832
833         /* Check, if the address of this load is used more than once.
834          * If not, this load cannot be removed in any case. */
835         if (get_irn_n_uses(ptr) <= 1)
836                 return res;
837
838         /*
839          * follow the memory chain as long as there are only Loads
840          * and try to replace current Load or Store by a previous one.
841          * Note that in unreachable loops it might happen that we reach
842          * load again, as well as we can fall into a cycle.
843          * We break such cycles using a special visited flag.
844          */
845         INC_MASTER();
846         res = follow_Mem_chain(load, skip_Proj(mem));
847         return res;
848 }  /* optimize_load */
849
850 /**
851  * Check whether a value of mode new_mode would completely overwrite a value
852  * of mode old_mode in memory.
853  */
854 static int is_completely_overwritten(ir_mode *old_mode, ir_mode *new_mode)
855 {
856         return get_mode_size_bits(new_mode) >= get_mode_size_bits(old_mode);
857 }  /* is_completely_overwritten */
858
859 /**
860  * follow the memory chain as long as there are only Loads and alias free Stores.
861  *
862  * INC_MASTER() must be called before dive into
863  */
864 static unsigned follow_Mem_chain_for_Store(ir_node *store, ir_node *curr) {
865         unsigned res = 0;
866         ldst_info_t *info = get_irn_link(store);
867         ir_node *pred;
868         ir_node *ptr = get_Store_ptr(store);
869         ir_node *mem = get_Store_mem(store);
870         ir_node *value = get_Store_value(store);
871         ir_mode *mode  = get_irn_mode(value);
872         ir_node *block = get_nodes_block(store);
873         ir_node *mblk  = get_Block_MacroBlock(block);
874
875         for (pred = curr; pred != store;) {
876                 ldst_info_t *pred_info = get_irn_link(pred);
877
878                 /*
879                  * BEWARE: one might think that checking the modes is useless, because
880                  * if the pointers are identical, they refer to the same object.
881                  * This is only true in strong typed languages, not is C were the following
882                  * is possible *(ir_type1 *)p = a; *(ir_type2 *)p = b ...
883                  * However, if the mode that is written have a bigger  or equal size the the old
884                  * one, the old value is completely overwritten and can be killed ...
885                  */
886                 if (is_Store(pred) && get_Store_ptr(pred) == ptr &&
887                     get_nodes_MacroBlock(pred) == mblk &&
888                     is_completely_overwritten(get_irn_mode(get_Store_value(pred)), mode)) {
889                         /*
890                          * a Store after a Store in the same block -- a write after write.
891                          * We may remove the first Store, if it does not have an exception handler.
892                          *
893                          * TODO: What, if both have the same exception handler ???
894                          */
895                         if (get_Store_volatility(pred) != volatility_is_volatile && !pred_info->projs[pn_Store_X_except]) {
896                                 DBG_OPT_WAW(pred, store);
897                                 exchange(pred_info->projs[pn_Store_M], get_Store_mem(pred));
898                                 kill_node(pred);
899                                 reduce_adr_usage(ptr);
900                                 return DF_CHANGED;
901                         }
902                 } else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
903                            value == pred_info->projs[pn_Load_res]) {
904                         /*
905                          * a Store of a value after a Load -- a write after read.
906                          * We may remove the second Store, if it does not have an exception handler.
907                          */
908                         if (! info->projs[pn_Store_X_except]) {
909                                 DBG_OPT_WAR(store, pred);
910                                 exchange(info->projs[pn_Store_M], mem);
911                                 kill_node(store);
912                                 reduce_adr_usage(ptr);
913                                 return DF_CHANGED;
914                         }
915                 }
916
917                 if (is_Store(pred)) {
918                         /* check if we can pass thru this store */
919                         ir_alias_relation rel = get_alias_relation(
920                                 current_ir_graph,
921                                 get_Store_ptr(pred),
922                                 get_irn_mode(get_Store_value(pred)),
923                                 ptr, mode);
924                         /* if the might be an alias, we cannot pass this Store */
925                         if (rel != no_alias)
926                                 break;
927                         pred = skip_Proj(get_Store_mem(pred));
928                 } else if (get_irn_op(pred) == op_Load) {
929                         pred = skip_Proj(get_Load_mem(pred));
930                 } else {
931                         /* follow only Load chains */
932                         break;
933                 }
934
935                 /* check for cycles */
936                 if (NODE_VISITED(pred_info))
937                         break;
938                 MARK_NODE(pred_info);
939         }
940
941         if (is_Sync(pred)) {
942                 int i;
943
944                 /* handle all Sync predecessors */
945                 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
946                         res |= follow_Mem_chain_for_Store(store, skip_Proj(get_Sync_pred(pred, i)));
947                         if (res)
948                                 break;
949                 }
950         }
951         return res;
952 }  /* follow_Mem_chain_for_Store */
953
954 /**
955  * optimize a Store
956  *
957  * @param store  the Store node
958  */
959 static unsigned optimize_store(ir_node *store) {
960         ir_node *ptr, *mem;
961
962         if (get_Store_volatility(store) == volatility_is_volatile)
963                 return 0;
964
965         ptr = get_Store_ptr(store);
966
967         /* Check, if the address of this Store is used more than once.
968          * If not, this Store cannot be removed in any case. */
969         if (get_irn_n_uses(ptr) <= 1)
970                 return 0;
971
972         mem = get_Store_mem(store);
973
974         /* follow the memory chain as long as there are only Loads */
975         INC_MASTER();
976         return follow_Mem_chain_for_Store(store, skip_Proj(mem));
977 }  /* optimize_store */
978
979 /**
980  * walker, optimizes Phi after Stores to identical places:
981  * Does the following optimization:
982  * @verbatim
983  *
984  *   val1   val2   val3          val1  val2  val3
985  *    |      |      |               \    |    /
986  *  Store  Store  Store              \   |   /
987  *      \    |    /                   PhiData
988  *       \   |   /                       |
989  *        \  |  /                      Store
990  *          PhiM
991  *
992  * @endverbatim
993  * This reduces the number of stores and allows for predicated execution.
994  * Moves Stores back to the end of a function which may be bad.
995  *
996  * This is only possible if the predecessor blocks have only one successor.
997  */
998 static unsigned optimize_phi(ir_node *phi, walk_env_t *wenv)
999 {
1000         int i, n;
1001         ir_node *store, *old_store, *ptr, *block, *phi_block, *phiM, *phiD, *exc, *projM;
1002         ir_mode *mode;
1003         ir_node **inM, **inD, **projMs;
1004         int *idx;
1005         dbg_info *db = NULL;
1006         ldst_info_t *info;
1007         block_info_t *bl_info;
1008         unsigned res = 0;
1009
1010         /* Must be a memory Phi */
1011         if (get_irn_mode(phi) != mode_M)
1012                 return 0;
1013
1014         n = get_Phi_n_preds(phi);
1015         if (n <= 0)
1016                 return 0;
1017
1018         /* must be only one user */
1019         projM = get_Phi_pred(phi, 0);
1020         if (get_irn_n_edges(projM) != 1)
1021                 return 0;
1022
1023         store = skip_Proj(projM);
1024         old_store = store;
1025         if (get_irn_op(store) != op_Store)
1026                 return 0;
1027
1028         block = get_nodes_block(store);
1029
1030         /* abort on dead blocks */
1031         if (is_Block_dead(block))
1032                 return 0;
1033
1034         /* check if the block is post dominated by Phi-block
1035            and has no exception exit */
1036         bl_info = get_irn_link(block);
1037         if (bl_info->flags & BLOCK_HAS_EXC)
1038                 return 0;
1039
1040         phi_block = get_nodes_block(phi);
1041         if (! block_strictly_postdominates(phi_block, block))
1042                 return 0;
1043
1044         /* this is the address of the store */
1045         ptr  = get_Store_ptr(store);
1046         mode = get_irn_mode(get_Store_value(store));
1047         info = get_irn_link(store);
1048         exc  = info->exc_block;
1049
1050         for (i = 1; i < n; ++i) {
1051                 ir_node *pred = get_Phi_pred(phi, i);
1052
1053                 if (get_irn_n_edges(pred) != 1)
1054                         return 0;
1055
1056                 pred = skip_Proj(pred);
1057                 if (!is_Store(pred))
1058                         return 0;
1059
1060                 if (ptr != get_Store_ptr(pred) || mode != get_irn_mode(get_Store_value(pred)))
1061                         return 0;
1062
1063                 info = get_irn_link(pred);
1064
1065                 /* check, if all stores have the same exception flow */
1066                 if (exc != info->exc_block)
1067                         return 0;
1068
1069                 /* abort on dead blocks */
1070                 block = get_nodes_block(pred);
1071                 if (is_Block_dead(block))
1072                         return 0;
1073
1074                 /* check if the block is post dominated by Phi-block
1075                    and has no exception exit. Note that block must be different from
1076                    Phi-block, else we would move a Store from end End of a block to its
1077                    Start... */
1078                 bl_info = get_irn_link(block);
1079                 if (bl_info->flags & BLOCK_HAS_EXC)
1080                         return 0;
1081                 if (block == phi_block || ! block_postdominates(phi_block, block))
1082                         return 0;
1083         }
1084
1085         /*
1086          * ok, when we are here, we found all predecessors of a Phi that
1087          * are Stores to the same address and size. That means whatever
1088          * we do before we enter the block of the Phi, we do a Store.
1089          * So, we can move the Store to the current block:
1090          *
1091          *   val1    val2    val3          val1  val2  val3
1092          *    |       |       |               \    |    /
1093          * | Str | | Str | | Str |             \   |   /
1094          *      \     |     /                   PhiData
1095          *       \    |    /                       |
1096          *        \   |   /                       Str
1097          *           PhiM
1098          *
1099          * Is only allowed if the predecessor blocks have only one successor.
1100          */
1101
1102         NEW_ARR_A(ir_node *, projMs, n);
1103         NEW_ARR_A(ir_node *, inM, n);
1104         NEW_ARR_A(ir_node *, inD, n);
1105         NEW_ARR_A(int, idx, n);
1106
1107         /* Prepare: Collect all Store nodes.  We must do this
1108            first because we otherwise may loose a store when exchanging its
1109            memory Proj.
1110          */
1111         for (i = n - 1; i >= 0; --i) {
1112                 ir_node *store;
1113
1114                 projMs[i] = get_Phi_pred(phi, i);
1115                 assert(is_Proj(projMs[i]));
1116
1117                 store = get_Proj_pred(projMs[i]);
1118                 info  = get_irn_link(store);
1119
1120                 inM[i] = get_Store_mem(store);
1121                 inD[i] = get_Store_value(store);
1122                 idx[i] = info->exc_idx;
1123         }
1124         block = get_nodes_block(phi);
1125
1126         /* second step: create a new memory Phi */
1127         phiM = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inM, mode_M);
1128
1129         /* third step: create a new data Phi */
1130         phiD = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inD, mode);
1131
1132         /* rewire memory and kill the node */
1133         for (i = n - 1; i >= 0; --i) {
1134                 ir_node *proj  = projMs[i];
1135
1136                 if(is_Proj(proj)) {
1137                         ir_node *store = get_Proj_pred(proj);
1138                         exchange(proj, inM[i]);
1139                         kill_node(store);
1140                 }
1141         }
1142
1143         /* fourth step: create the Store */
1144         store = new_rd_Store(db, current_ir_graph, block, phiM, ptr, phiD);
1145 #ifdef DO_CACHEOPT
1146         co_set_irn_name(store, co_get_irn_ident(old_store));
1147 #endif
1148
1149         projM = new_rd_Proj(NULL, current_ir_graph, block, store, mode_M, pn_Store_M);
1150
1151         info = get_ldst_info(store, &wenv->obst);
1152         info->projs[pn_Store_M] = projM;
1153
1154         /* fifths step: repair exception flow */
1155         if (exc) {
1156                 ir_node *projX = new_rd_Proj(NULL, current_ir_graph, block, store, mode_X, pn_Store_X_except);
1157
1158                 info->projs[pn_Store_X_except] = projX;
1159                 info->exc_block                = exc;
1160                 info->exc_idx                  = idx[0];
1161
1162                 for (i = 0; i < n; ++i) {
1163                         set_Block_cfgpred(exc, idx[i], projX);
1164                 }
1165
1166                 if (n > 1) {
1167                         /* the exception block should be optimized as some inputs are identical now */
1168                 }
1169
1170                 res |= CF_CHANGED;
1171         }
1172
1173         /* sixth step: replace old Phi */
1174         exchange(phi, projM);
1175
1176         return res | DF_CHANGED;
1177 }  /* optimize_phi */
1178
1179 /**
1180  * walker, do the optimizations
1181  */
1182 static void do_load_store_optimize(ir_node *n, void *env) {
1183         walk_env_t *wenv = env;
1184
1185         switch (get_irn_opcode(n)) {
1186
1187         case iro_Load:
1188                 wenv->changes |= optimize_load(n);
1189                 break;
1190
1191         case iro_Store:
1192                 wenv->changes |= optimize_store(n);
1193                 break;
1194
1195         case iro_Phi:
1196                 wenv->changes |= optimize_phi(n, wenv);
1197                 break;
1198
1199         default:
1200                 ;
1201         }
1202 }  /* do_load_store_optimize */
1203
1204 /** A scc. */
1205 typedef struct scc {
1206         ir_node *head;          /**< the head of the list */
1207 } scc;
1208
1209 /** A node entry. */
1210 typedef struct node_entry {
1211         unsigned DFSnum;    /**< the DFS number of this node */
1212         unsigned low;       /**< the low number of this node */
1213         ir_node  *header;   /**< the header of this node */
1214         int      in_stack;  /**< flag, set if the node is on the stack */
1215         ir_node  *next;     /**< link to the next node the the same scc */
1216         scc      *pscc;     /**< the scc of this node */
1217         unsigned POnum;     /**< the post order number for blocks */
1218 } node_entry;
1219
1220 /** A loop entry. */
1221 typedef struct loop_env {
1222         ir_phase ph;           /**< the phase object */
1223         ir_node  **stack;      /**< the node stack */
1224         int      tos;          /**< tos index */
1225         unsigned nextDFSnum;   /**< the current DFS number */
1226         unsigned POnum;        /**< current post order number */
1227
1228         unsigned changes;      /**< a bitmask of graph changes */
1229 } loop_env;
1230
1231 /**
1232 * Gets the node_entry of a node
1233 */
1234 static node_entry *get_irn_ne(ir_node *irn, loop_env *env) {
1235         ir_phase   *ph = &env->ph;
1236         node_entry *e  = phase_get_irn_data(&env->ph, irn);
1237
1238         if (! e) {
1239                 e = phase_alloc(ph, sizeof(*e));
1240                 memset(e, 0, sizeof(*e));
1241                 phase_set_irn_data(ph, irn, e);
1242         }
1243         return e;
1244 }  /* get_irn_ne */
1245
1246 /**
1247  * Push a node onto the stack.
1248  *
1249  * @param env   the loop environment
1250  * @param n     the node to push
1251  */
1252 static void push(loop_env *env, ir_node *n) {
1253         node_entry *e;
1254
1255         if (env->tos == ARR_LEN(env->stack)) {
1256                 int nlen = ARR_LEN(env->stack) * 2;
1257                 ARR_RESIZE(ir_node *, env->stack, nlen);
1258         }
1259         env->stack[env->tos++] = n;
1260         e = get_irn_ne(n, env);
1261         e->in_stack = 1;
1262 }  /* push */
1263
1264 /**
1265  * pop a node from the stack
1266  *
1267  * @param env   the loop environment
1268  *
1269  * @return  The topmost node
1270  */
1271 static ir_node *pop(loop_env *env) {
1272         ir_node *n = env->stack[--env->tos];
1273         node_entry *e = get_irn_ne(n, env);
1274
1275         e->in_stack = 0;
1276         return n;
1277 }  /* pop */
1278
1279 /**
1280  * Check if irn is a region constant.
1281  * The block or irn must strictly dominate the header block.
1282  *
1283  * @param irn           the node to check
1284  * @param header_block  the header block of the induction variable
1285  */
1286 static int is_rc(ir_node *irn, ir_node *header_block) {
1287         ir_node *block = get_nodes_block(irn);
1288
1289         return (block != header_block) && block_dominates(block, header_block);
1290 }  /* is_rc */
1291
1292 typedef struct phi_entry phi_entry;
1293 struct phi_entry {
1294         ir_node   *phi;    /**< A phi with a region const memory. */
1295         int       pos;     /**< The position of the region const memory */
1296         ir_node   *load;   /**< the newly created load for this phi */
1297         phi_entry *next;
1298 };
1299
1300 /**
1301  * Move loops out of loops if possible.
1302  *
1303  * @param pscc   the loop described by an SCC
1304  * @param env    the loop environment
1305  */
1306 static void move_loads_out_of_loops(scc *pscc, loop_env *env) {
1307         ir_node   *phi, *load, *next, *other, *next_other;
1308         ir_entity *ent;
1309         int       j;
1310         phi_entry *phi_list = NULL;
1311
1312         /* collect all outer memories */
1313         for (phi = pscc->head; phi != NULL; phi = next) {
1314                 node_entry *ne = get_irn_ne(phi, env);
1315                 next = ne->next;
1316
1317                 /* check all memory Phi's */
1318                 if (! is_Phi(phi))
1319                         continue;
1320
1321                 assert(get_irn_mode(phi) == mode_M && "DFS geturn non-memory Phi");
1322
1323                 for (j = get_irn_arity(phi) - 1; j >= 0; --j) {
1324                         ir_node    *pred = get_irn_n(phi, j);
1325                         node_entry *pe   = get_irn_ne(pred, env);
1326
1327                         if (pe->pscc != ne->pscc) {
1328                                 /* not in the same SCC, is region const */
1329                                 phi_entry *pe = phase_alloc(&env->ph, sizeof(*pe));
1330
1331                                 pe->phi  = phi;
1332                                 pe->pos  = j;
1333                                 pe->next = phi_list;
1334                                 phi_list = pe;
1335                         }
1336                 }
1337         }
1338         /* no Phis no fun */
1339         assert(phi_list != NULL && "DFS found a loop without Phi");
1340
1341         for (load = pscc->head; load; load = next) {
1342                 ir_mode *load_mode;
1343                 node_entry *ne = get_irn_ne(load, env);
1344                 next = ne->next;
1345
1346                 if (is_Load(load)) {
1347                         ldst_info_t *info = get_irn_link(load);
1348                         ir_node     *ptr = get_Load_ptr(load);
1349
1350                         /* for now, we cannot handle Loads with exceptions */
1351                         if (info->projs[pn_Load_res] == NULL || info->projs[pn_Load_X_regular] != NULL || info->projs[pn_Load_X_except] != NULL)
1352                                 continue;
1353
1354                         /* for now, we can only handle Load(Global) */
1355                         if (! is_Global(ptr))
1356                                 continue;
1357                         ent = get_Global_entity(ptr);
1358                         load_mode = get_Load_mode(load);
1359                         for (other = pscc->head; other != NULL; other = next_other) {
1360                                 node_entry *ne = get_irn_ne(other, env);
1361                                 next_other = ne->next;
1362
1363                                 if (is_Store(other)) {
1364                                         ir_alias_relation rel = get_alias_relation(
1365                                                 current_ir_graph,
1366                                                 get_Store_ptr(other),
1367                                                 get_irn_mode(get_Store_value(other)),
1368                                                 ptr, load_mode);
1369                                         /* if the might be an alias, we cannot pass this Store */
1370                                         if (rel != no_alias)
1371                                                 break;
1372                                 }
1373                                 /* only pure Calls are allowed here, so ignore them */
1374                         }
1375                         if (other == NULL) {
1376                                 ldst_info_t *ninfo;
1377                                 phi_entry   *pe;
1378                                 dbg_info    *db;
1379
1380                                 /* for now, we cannot handle more than one input */
1381                                 if (phi_list->next != NULL)
1382                                         return;
1383
1384                                 /* yep, no aliasing Store found, Load can be moved */
1385                                 DB((dbg, LEVEL_1, "  Found a Load that could be moved: %+F\n", load));
1386
1387                                 db   = get_irn_dbg_info(load);
1388                                 for (pe = phi_list; pe != NULL; pe = pe->next) {
1389                                         int     pos   = pe->pos;
1390                                         ir_node *phi  = pe->phi;
1391                                         ir_node *blk  = get_nodes_block(phi);
1392                                         ir_node *pred = get_Block_cfgpred_block(blk, pos);
1393                                         ir_node *irn, *mem;
1394
1395                                         pe->load = irn = new_rd_Load(db, current_ir_graph, pred, get_Phi_pred(phi, pos), ptr, load_mode);
1396                                         ninfo = get_ldst_info(irn, phase_obst(&env->ph));
1397
1398                                         ninfo->projs[pn_Load_M] = mem = new_r_Proj(current_ir_graph, pred, irn, mode_M, pn_Load_M);
1399                                         set_Phi_pred(phi, pos, mem);
1400
1401                                         ninfo->projs[pn_Load_res] = new_r_Proj(current_ir_graph, pred, irn, load_mode, pn_Load_res);
1402
1403                                         DB((dbg, LEVEL_1, "  Created %+F in %+F\n", irn, pred));
1404                                 }
1405
1406                                 /* now kill the old Load */
1407                                 exchange(info->projs[pn_Load_M], get_Load_mem(load));
1408                                 exchange(info->projs[pn_Load_res], ninfo->projs[pn_Load_res]);
1409
1410                                 env->changes |= DF_CHANGED;
1411                         }
1412                 }
1413         }
1414 }  /* move_loads_out_of_loops */
1415
1416 /**
1417  * Process a loop SCC.
1418  *
1419  * @param pscc  the SCC
1420  * @param env   the loop environment
1421  */
1422 static void process_loop(scc *pscc, loop_env *env) {
1423         ir_node *irn, *next, *header = NULL;
1424         node_entry *b, *h = NULL;
1425         int j, only_phi, num_outside, process = 0;
1426         ir_node *out_rc;
1427
1428         /* find the header block for this scc */
1429         for (irn = pscc->head; irn; irn = next) {
1430                 node_entry *e = get_irn_ne(irn, env);
1431                 ir_node *block = get_nodes_block(irn);
1432
1433                 next = e->next;
1434                 b = get_irn_ne(block, env);
1435
1436                 if (header) {
1437                         if (h->POnum < b->POnum) {
1438                                 header = block;
1439                                 h      = b;
1440                         }
1441                 }
1442                 else {
1443                         header = block;
1444                         h      = b;
1445                 }
1446         }
1447
1448         /* check if this scc contains only Phi, Loads or Stores nodes */
1449         only_phi    = 1;
1450         num_outside = 0;
1451         out_rc      = NULL;
1452         for (irn = pscc->head; irn; irn = next) {
1453                 node_entry *e = get_irn_ne(irn, env);
1454
1455                 next = e->next;
1456                 switch (get_irn_opcode(irn)) {
1457                 case iro_Call:
1458                         if (is_Call_pure(irn)) {
1459                                 /* pure calls can be treated like loads */
1460                                 only_phi = 0;
1461                                 break;
1462                         }
1463                         /* non-pure calls must be handle like may-alias Stores */
1464                         goto fail;
1465                 case iro_CopyB:
1466                         /* cannot handle CopyB yet */
1467                         goto fail;
1468                 case iro_Load:
1469                         process = 1;
1470                         if (get_Load_volatility(irn) == volatility_is_volatile) {
1471                                 /* cannot handle loops with volatile Loads */
1472                                 goto fail;
1473                         }
1474                         only_phi = 0;
1475                         break;
1476                 case iro_Store:
1477                         if (get_Store_volatility(irn) == volatility_is_volatile) {
1478                                 /* cannot handle loops with volatile Stores */
1479                                 goto fail;
1480                         }
1481                         only_phi = 0;
1482                         break;
1483                 default:
1484                         only_phi = 0;
1485                         break;
1486                 case iro_Phi:
1487                         for (j = get_irn_arity(irn) - 1; j >= 0; --j) {
1488                                 ir_node *pred  = get_irn_n(irn, j);
1489                                 node_entry *pe = get_irn_ne(pred, env);
1490
1491                                 if (pe->pscc != e->pscc) {
1492                                         /* not in the same SCC, must be a region const */
1493                                         if (! is_rc(pred, header)) {
1494                                                 /* not a memory loop */
1495                                                 goto fail;
1496                                         }
1497                                         if (! out_rc) {
1498                                                 out_rc = pred;
1499                                                 ++num_outside;
1500                                         } else if (out_rc != pred) {
1501                                                 ++num_outside;
1502                                         }
1503                                 }
1504                         }
1505                         break;
1506                 }
1507         }
1508         if (! process)
1509                 goto fail;
1510
1511         /* found a memory loop */
1512         DB((dbg, LEVEL_2, "  Found a memory loop:\n  "));
1513         if (only_phi && num_outside == 1) {
1514                 /* a phi cycle with only one real predecessor can be collapsed */
1515                 DB((dbg, LEVEL_2, "  Found an USELESS Phi cycle:\n  "));
1516
1517                 for (irn = pscc->head; irn; irn = next) {
1518                         node_entry *e = get_irn_ne(irn, env);
1519                         next = e->next;
1520                         e->header = NULL;
1521                         exchange(irn, out_rc);
1522                 }
1523                 env->changes |= DF_CHANGED;
1524                 return;
1525         }
1526
1527         /* set the header for every node in this scc */
1528         for (irn = pscc->head; irn; irn = next) {
1529                 node_entry *e = get_irn_ne(irn, env);
1530                 e->header = header;
1531                 next = e->next;
1532                 DB((dbg, LEVEL_2, " %+F,", irn));
1533         }
1534         DB((dbg, LEVEL_2, "\n"));
1535
1536         move_loads_out_of_loops(pscc, env);
1537
1538 fail:
1539         ;
1540 }  /* process_loop */
1541
1542 /**
1543  * Process a SCC.
1544  *
1545  * @param pscc  the SCC
1546  * @param env   the loop environment
1547  */
1548 static void process_scc(scc *pscc, loop_env *env) {
1549         ir_node *head = pscc->head;
1550         node_entry *e = get_irn_ne(head, env);
1551
1552 #ifdef DEBUG_libfirm
1553         {
1554                 ir_node *irn, *next;
1555
1556                 DB((dbg, LEVEL_4, " SCC at %p:\n ", pscc));
1557                 for (irn = pscc->head; irn; irn = next) {
1558                         node_entry *e = get_irn_ne(irn, env);
1559
1560                         next = e->next;
1561
1562                         DB((dbg, LEVEL_4, " %+F,", irn));
1563                 }
1564                 DB((dbg, LEVEL_4, "\n"));
1565         }
1566 #endif
1567
1568         if (e->next != NULL) {
1569                 /* this SCC has more than one member */
1570                 process_loop(pscc, env);
1571         }
1572 }  /* process_scc */
1573
1574 /**
1575  * Do Tarjan's SCC algorithm and drive load/store optimization.
1576  *
1577  * @param irn  start at this node
1578  * @param env  the loop environment
1579  */
1580 static void dfs(ir_node *irn, loop_env *env)
1581 {
1582         int i, n;
1583         node_entry *node = get_irn_ne(irn, env);
1584
1585         mark_irn_visited(irn);
1586
1587         node->DFSnum = env->nextDFSnum++;
1588         node->low    = node->DFSnum;
1589         push(env, irn);
1590
1591         /* handle preds */
1592         if (is_Phi(irn) || is_Sync(irn)) {
1593                 n = get_irn_arity(irn);
1594                 for (i = 0; i < n; ++i) {
1595                         ir_node *pred = get_irn_n(irn, i);
1596                         node_entry *o = get_irn_ne(pred, env);
1597
1598                         if (irn_not_visited(pred)) {
1599                                 dfs(pred, env);
1600                                 node->low = MIN(node->low, o->low);
1601                         }
1602                         if (o->DFSnum < node->DFSnum && o->in_stack)
1603                                 node->low = MIN(o->DFSnum, node->low);
1604                 }
1605         } else if (is_fragile_op(irn)) {
1606                 ir_node *pred = get_fragile_op_mem(irn);
1607                 node_entry *o = get_irn_ne(pred, env);
1608
1609                 if (irn_not_visited(pred)) {
1610                         dfs(pred, env);
1611                         node->low = MIN(node->low, o->low);
1612                 }
1613                 if (o->DFSnum < node->DFSnum && o->in_stack)
1614                         node->low = MIN(o->DFSnum, node->low);
1615         } else if (is_Proj(irn)) {
1616                 ir_node *pred = get_Proj_pred(irn);
1617                 node_entry *o = get_irn_ne(pred, env);
1618
1619                 if (irn_not_visited(pred)) {
1620                         dfs(pred, env);
1621                         node->low = MIN(node->low, o->low);
1622                 }
1623                 if (o->DFSnum < node->DFSnum && o->in_stack)
1624                         node->low = MIN(o->DFSnum, node->low);
1625         }
1626         else {
1627                  /* IGNORE predecessors */
1628         }
1629
1630         if (node->low == node->DFSnum) {
1631                 scc *pscc = phase_alloc(&env->ph, sizeof(*pscc));
1632                 ir_node *x;
1633
1634                 pscc->head = NULL;
1635                 do {
1636                         node_entry *e;
1637
1638                         x = pop(env);
1639                         e = get_irn_ne(x, env);
1640                         e->pscc    = pscc;
1641                         e->next    = pscc->head;
1642                         pscc->head = x;
1643                 } while (x != irn);
1644
1645                 process_scc(pscc, env);
1646         }
1647 }  /* dfs */
1648
1649 /**
1650  * Do the DFS on the memory edges a graph.
1651  *
1652  * @param irg  the graph to process
1653  * @param env  the loop environment
1654  */
1655 static void do_dfs(ir_graph *irg, loop_env *env) {
1656         ir_graph *rem = current_ir_graph;
1657         ir_node  *endblk, *end;
1658         int      i;
1659
1660         current_ir_graph = irg;
1661         inc_irg_visited(irg);
1662
1663         /* visit all memory nodes */
1664         endblk = get_irg_end_block(irg);
1665         for (i = get_Block_n_cfgpreds(endblk) - 1; i >= 0; --i) {
1666                 ir_node *pred = get_Block_cfgpred(endblk, i);
1667
1668                 pred = skip_Proj(pred);
1669                 if (is_Return(pred))
1670                         dfs(get_Return_mem(pred), env);
1671                 else if (is_Raise(pred))
1672                         dfs(get_Raise_mem(pred), env);
1673                 else if (is_fragile_op(pred))
1674                         dfs(get_fragile_op_mem(pred), env);
1675                 else {
1676                         assert(0 && "Unknown EndBlock predecessor");
1677                 }
1678         }
1679
1680         /* visit the keep-alives */
1681         end = get_irg_end(irg);
1682         for (i = get_End_n_keepalives(end) - 1; i >= 0; --i) {
1683                 ir_node *ka = get_End_keepalive(end, i);
1684
1685                 if (is_Phi(ka) && irn_not_visited(ka))
1686                         dfs(ka, env);
1687         }
1688         current_ir_graph = rem;
1689 }  /* do_dfs */
1690
1691 /**
1692  * Initialize new phase data. We do this always explicit, so return NULL here
1693  */
1694 static void *init_loop_data(ir_phase *ph, const ir_node *irn, void *data) {
1695         (void)ph;
1696         (void)irn;
1697         (void)data;
1698         return NULL;
1699 }  /* init_loop_data */
1700
1701 /**
1702  * Optimize Loads/Stores in loops.
1703  *
1704  * @param irg  the graph
1705  */
1706 static int optimize_loops(ir_graph *irg) {
1707         loop_env env;
1708
1709         env.stack         = NEW_ARR_F(ir_node *, 128);
1710         env.tos           = 0;
1711         env.nextDFSnum    = 0;
1712         env.POnum         = 0;
1713         env.changes       = 0;
1714         phase_init(&env.ph, "ldstopt", irg, PHASE_DEFAULT_GROWTH, init_loop_data, NULL);
1715
1716         /* calculate the SCC's and drive loop optimization. */
1717         do_dfs(irg, &env);
1718
1719         DEL_ARR_F(env.stack);
1720         phase_free(&env.ph);
1721
1722         return env.changes;
1723 }  /* optimize_loops */
1724
1725 /*
1726  * do the load store optimization
1727  */
1728 void optimize_load_store(ir_graph *irg) {
1729         walk_env_t env;
1730
1731         FIRM_DBG_REGISTER(dbg, "firm.opt.ldstopt");
1732
1733         assert(get_irg_phase_state(irg) != phase_building);
1734         assert(get_irg_pinned(irg) != op_pin_state_floats &&
1735                 "LoadStore optimization needs pinned graph");
1736
1737         /* we need landing pads */
1738         remove_critical_cf_edges(irg);
1739
1740         edges_assure(irg);
1741
1742         /* for Phi optimization post-dominators are needed ... */
1743         assure_postdoms(irg);
1744
1745         if (get_opt_alias_analysis()) {
1746                 assure_irg_address_taken_computed(irg);
1747                 assure_irp_globals_address_taken_computed();
1748         }
1749
1750         obstack_init(&env.obst);
1751         env.changes = 0;
1752
1753         /* init the links, then collect Loads/Stores/Proj's in lists */
1754         master_visited = 0;
1755         irg_walk_graph(irg, firm_clear_link, collect_nodes, &env);
1756
1757         /* now we have collected enough information, optimize */
1758         irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
1759
1760         env.changes |= optimize_loops(irg);
1761
1762         obstack_free(&env.obst, NULL);
1763
1764         /* Handle graph state */
1765         if (env.changes) {
1766                 set_irg_outs_inconsistent(irg);
1767         }
1768
1769         if (env.changes & CF_CHANGED) {
1770                 /* is this really needed: Yes, control flow changed, block might
1771                 have Bad() predecessors. */
1772                 set_irg_doms_inconsistent(irg);
1773         }
1774 }  /* optimize_load_store */