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