- improved rec_find_compound_ent_value(): handle missing [0] access
[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                 if (is_SymConst(ptr) && get_SymConst_kind(ptr) == symconst_addr_ent) {
260                         ir_entity *ent = get_SymConst_entity(ptr);
261                         if (variability_constant == get_entity_variability(ent))
262                                 return ent;
263                         return NULL;
264                 } else if (is_Sel(ptr)) {
265                         ir_entity *ent = get_Sel_entity(ptr);
266                         ir_type   *tp  = get_entity_owner(ent);
267
268                         /* Do not fiddle with polymorphism. */
269                         if (is_Class_type(get_entity_owner(ent)) &&
270                                 ((get_entity_n_overwrites(ent)    != 0) ||
271                                 (get_entity_n_overwrittenby(ent) != 0)   ) )
272                                 return NULL;
273
274                         if (is_Array_type(tp)) {
275                                 /* check bounds */
276                                 int i, n;
277
278                                 for (i = 0, n = get_Sel_n_indexs(ptr); i < n; ++i) {
279                                         ir_node *bound;
280                                         tarval *tlower, *tupper;
281                                         ir_node *index = get_Sel_index(ptr, i);
282                                         tarval *tv     = computed_value(index);
283
284                                         /* check if the index is constant */
285                                         if (tv == tarval_bad)
286                                                 return NULL;
287
288                                         bound  = get_array_lower_bound(tp, i);
289                                         tlower = computed_value(bound);
290                                         bound  = get_array_upper_bound(tp, i);
291                                         tupper = computed_value(bound);
292
293                                         if (tlower == tarval_bad || tupper == tarval_bad)
294                                                 return NULL;
295
296                                         if (tarval_cmp(tv, tlower) & pn_Cmp_Lt)
297                                                 return NULL;
298                                         if (tarval_cmp(tupper, tv) & pn_Cmp_Lt)
299                                                 return NULL;
300
301                                         /* ok, bounds check finished */
302                                 }
303                         }
304
305                         if (variability_constant == get_entity_variability(ent))
306                                 return ent;
307
308                         /* try next */
309                         ptr = get_Sel_ptr(ptr);
310                 } else if (is_Add(ptr)) {
311                         ir_node *l = get_Add_left(ptr);
312                         ir_node *r = get_Add_right(ptr);
313
314                         if (get_irn_mode(l) == get_irn_mode(ptr) && is_Const(r))
315                                 ptr = l;
316                         else if (get_irn_mode(r) == get_irn_mode(ptr) && is_Const(l))
317                                 ptr = r;
318                         else
319                                 return NULL;
320
321                         /* for now, we support only one addition, reassoc should fold all others */
322                         if (! is_SymConst(ptr) && !is_Sel(ptr))
323                                 return NULL;
324                 } else if (is_Sub(ptr)) {
325                         ir_node *l = get_Sub_left(ptr);
326                         ir_node *r = get_Sub_right(ptr);
327
328                         if (get_irn_mode(l) == get_irn_mode(ptr) &&     is_Const(r))
329                                 ptr = l;
330                         else
331                                 return NULL;
332                         /* for now, we support only one substraction, reassoc should fold all others */
333                         if (! is_SymConst(ptr) && !is_Sel(ptr))
334                                 return NULL;
335                 } else
336                         return NULL;
337         }
338 }  /* find_constant_entity */
339
340 /**
341  * Return the Selection index of a Sel node from dimension n
342  */
343 static long get_Sel_array_index_long(ir_node *n, int dim) {
344         ir_node *index = get_Sel_index(n, dim);
345         assert(is_Const(index));
346         return get_tarval_long(get_Const_tarval(index));
347 }  /* get_Sel_array_index_long */
348
349 /**
350  * Returns the accessed component graph path for an
351  * node computing an address.
352  *
353  * @param ptr    the node computing the address
354  * @param depth  current depth in steps upward from the root
355  *               of the address
356  */
357 static compound_graph_path *rec_get_accessed_path(ir_node *ptr, int depth) {
358         compound_graph_path *res = NULL;
359         ir_entity           *root, *field, *ent;
360         int                 path_len, pos, idx;
361         tarval              *tv;
362         ir_type             *tp;
363
364         if (is_SymConst(ptr)) {
365                 /* a SymConst. If the depth is 0, this is an access to a global
366                  * entity and we don't need a component path, else we know
367                  * at least it's length.
368                  */
369                 assert(get_SymConst_kind(ptr) == symconst_addr_ent);
370                 root = get_SymConst_entity(ptr);
371                 res = (depth == 0) ? NULL : new_compound_graph_path(get_entity_type(root), depth);
372         } else if (is_Sel(ptr)) {
373                 /* it's a Sel, go up until we find the root */
374                 res = rec_get_accessed_path(get_Sel_ptr(ptr), depth+1);
375                 if (res == NULL)
376                         return NULL;
377
378                 /* fill up the step in the path at the current position */
379                 field    = get_Sel_entity(ptr);
380                 path_len = get_compound_graph_path_length(res);
381                 pos      = path_len - depth - 1;
382                 set_compound_graph_path_node(res, pos, field);
383
384                 if (is_Array_type(get_entity_owner(field))) {
385                         assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
386                         set_compound_graph_path_array_index(res, pos, get_Sel_array_index_long(ptr, 0));
387                 }
388         } else if (is_Add(ptr)) {
389                 ir_node *l = get_Add_left(ptr);
390                 ir_node *r = get_Add_right(ptr);
391                 ir_mode *mode;
392
393                 if (is_Const(r)) {
394                         ptr = l;
395                         tv  = get_Const_tarval(r);
396                 } else {
397                         ptr = r;
398                         tv  = get_Const_tarval(l);
399                 }
400 ptr_arith:
401                 mode = get_tarval_mode(tv);
402
403                 /* ptr must be a Sel or a SymConst, this was checked in find_constant_entity() */
404                 if (is_Sel(ptr)) {
405                         field = get_Sel_entity(ptr);
406                 } else {
407                         field = get_SymConst_entity(ptr);
408                 }
409                 idx = 0;
410                 for (ent = field;;) {
411                         unsigned size;
412                         tarval   *sz, *tv_index, *tlower, *tupper;
413                         long     index;
414                         ir_node  *bound;
415
416                         tp = get_entity_type(ent);
417                         if (! is_Array_type(tp))
418                                 break;
419                         ent = get_array_element_entity(tp);
420                         size = get_type_size_bytes(get_entity_type(ent));
421                         sz   = new_tarval_from_long(size, mode);
422
423                         tv_index = tarval_div(tv, sz);
424                         tv       = tarval_mod(tv, sz);
425
426                         if (tv_index == tarval_bad || tv == tarval_bad)
427                                 return NULL;
428
429                         assert(get_array_n_dimensions(tp) == 1 && "multiarrays not implemented");
430                         bound  = get_array_lower_bound(tp, 0);
431                         tlower = computed_value(bound);
432                         bound  = get_array_upper_bound(tp, 0);
433                         tupper = computed_value(bound);
434
435                         if (tlower == tarval_bad || tupper == tarval_bad)
436                                 return NULL;
437
438                         if (tarval_cmp(tv_index, tlower) & pn_Cmp_Lt)
439                                 return NULL;
440                         if (tarval_cmp(tupper, tv_index) & pn_Cmp_Lt)
441                                 return NULL;
442
443                         /* ok, bounds check finished */
444                         index = get_tarval_long(tv_index);
445                         ++idx;
446                 }
447                 if (! tarval_is_null(tv)) {
448                         /* access to some struct/union member */
449                         return NULL;
450                 }
451
452                 /* should be at least ONE array */
453                 if (idx == 0)
454                         return NULL;
455
456                 res = rec_get_accessed_path(ptr, depth + idx);
457                 if (res == NULL)
458                         return NULL;
459
460                 path_len = get_compound_graph_path_length(res);
461                 pos      = path_len - depth - idx;
462
463                 for (ent = field;;) {
464                         unsigned size;
465                         tarval   *sz, *tv_index;
466                         long     index;
467
468                         tp = get_entity_type(ent);
469                         if (! is_Array_type(tp))
470                                 break;
471                         ent = get_array_element_entity(tp);
472                         set_compound_graph_path_node(res, pos, ent);
473
474                         size = get_type_size_bytes(get_entity_type(ent));
475                         sz   = new_tarval_from_long(size, mode);
476
477                         tv_index = tarval_div(tv, sz);
478                         tv       = tarval_mod(tv, sz);
479
480                         if (tv_index == tarval_bad || tv == tarval_bad)
481                                 return NULL;
482
483                         /* bounds already checked above */
484                         index = get_tarval_long(tv_index);
485                         set_compound_graph_path_array_index(res, pos, index);
486                         ++pos;
487                 }
488                 if (! tarval_is_null(tv)) {
489                         /* hmm, wrong access */
490                         return NULL;
491                 }
492         } else if (is_Sub(ptr)) {
493                 ir_node *l = get_Sub_left(ptr);
494                 ir_node *r = get_Sub_right(ptr);
495
496                 ptr = l;
497                 tv  = get_Const_tarval(r);
498                 tv  = tarval_neg(tv);
499                 goto ptr_arith;
500         }
501         return res;
502 }  /* rec_get_accessed_path */
503
504 /**
505  * Returns an access path or NULL.  The access path is only
506  * valid, if the graph is in phase_high and _no_ address computation is used.
507  */
508 static compound_graph_path *get_accessed_path(ir_node *ptr) {
509         return rec_get_accessed_path(ptr, 0);
510 }  /* get_accessed_path */
511
512 typedef struct path_entry {
513         ir_entity         *ent;
514         struct path_entry *next;
515         long              index;
516 } path_entry;
517
518 static ir_node *rec_find_compound_ent_value(ir_node *ptr, path_entry *next) {
519         path_entry       entry, *p;
520         ir_entity        *ent, *field;
521         ir_initializer_t *initializer;
522         tarval           *tv;
523         ir_type          *tp;
524         unsigned         n;
525
526         entry.next = next;
527         if (is_SymConst(ptr)) {
528                 /* found the root */
529                 ent         = get_SymConst_entity(ptr);
530                 initializer = get_entity_initializer(ent);
531                 for (p = next; p != NULL;) {
532                         if (initializer->kind != IR_INITIALIZER_COMPOUND)
533                                 return NULL;
534                         n  = get_initializer_compound_n_entries(initializer);
535                         tp = get_entity_type(ent);
536
537                         if (is_Array_type(tp)) {
538                                 ent = get_array_element_entity(tp);
539                                 if (ent != p->ent) {
540                                         /* a missing [0] */
541                                         if (0 >= n)
542                                                 return NULL;
543                                         initializer = get_initializer_compound_value(initializer, 0);
544                                         continue;
545                                 }
546                         }
547                         if (p->index >= n)
548                                 return NULL;
549                         initializer = get_initializer_compound_value(initializer, p->index);
550
551                         ent = p->ent;
552                         p   = p->next;
553                 }
554                 tp = get_entity_type(ent);
555                 while (is_Array_type(tp)) {
556                         ent = get_array_element_entity(tp);
557                         tp = get_entity_type(ent);
558                         /* a missing [0] */
559                         n  = get_initializer_compound_n_entries(initializer);
560                         if (0 >= n)
561                                 return NULL;
562                         initializer = get_initializer_compound_value(initializer, 0);
563                 }
564
565                 switch (initializer->kind) {
566                 case IR_INITIALIZER_CONST:
567                         return get_initializer_const_value(initializer);
568                 case IR_INITIALIZER_TARVAL:
569                 case IR_INITIALIZER_NULL:
570                 default:
571                         return NULL;
572                 }
573         } else if (is_Sel(ptr)) {
574                 entry.ent = field = get_Sel_entity(ptr);
575                 tp = get_entity_owner(field);
576                 if (is_Array_type(tp)) {
577                         assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
578                         entry.index = get_Sel_array_index_long(ptr, 0) - get_array_lower_bound_int(tp, 0);
579                 } else {
580                         int i, n_members = get_compound_n_members(tp);
581                         for (i = 0; i < n_members; ++i) {
582                                 if (get_compound_member(tp, i) == field)
583                                         break;
584                         }
585                         if (i >= n_members) {
586                                 /* not found: should NOT happen */
587                                 return NULL;
588                         }
589                         entry.index = i;
590                 }
591                 return rec_find_compound_ent_value(get_Sel_ptr(ptr), &entry);
592         }  else if (is_Add(ptr)) {
593                 ir_node  *l = get_Add_left(ptr);
594                 ir_node  *r = get_Add_right(ptr);
595                 ir_mode  *mode;
596                 unsigned pos;
597
598                 if (is_Const(r)) {
599                         ptr = l;
600                         tv  = get_Const_tarval(r);
601                 } else {
602                         ptr = r;
603                         tv  = get_Const_tarval(l);
604                 }
605 ptr_arith:
606                 mode = get_tarval_mode(tv);
607
608                 /* ptr must be a Sel or a SymConst, this was checked in find_constant_entity() */
609                 if (is_Sel(ptr)) {
610                         field = get_Sel_entity(ptr);
611                 } else {
612                         field = get_SymConst_entity(ptr);
613                 }
614
615                 /* count needed entries */
616                 pos = 0;
617                 for (ent = field;;) {
618                         tp = get_entity_type(ent);
619                         if (! is_Array_type(tp))
620                                 break;
621                         ent = get_array_element_entity(tp);
622                         ++pos;
623                 }
624                 /* should be at least ONE entry */
625                 if (pos == 0)
626                         return NULL;
627
628                 /* allocate the right number of entries */
629                 NEW_ARR_A(path_entry, p, pos);
630
631                 /* fill them up */
632                 pos = 0;
633                 for (ent = field;;) {
634                         unsigned size;
635                         tarval   *sz, *tv_index, *tlower, *tupper;
636                         long     index;
637                         ir_node  *bound;
638
639                         tp = get_entity_type(ent);
640                         if (! is_Array_type(tp))
641                                 break;
642                         ent = get_array_element_entity(tp);
643                         p[pos].ent  = ent;
644                         p[pos].next = &p[pos + 1];
645
646                         size = get_type_size_bytes(get_entity_type(ent));
647                         sz   = new_tarval_from_long(size, mode);
648
649                         tv_index = tarval_div(tv, sz);
650                         tv       = tarval_mod(tv, sz);
651
652                         if (tv_index == tarval_bad || tv == tarval_bad)
653                                 return NULL;
654
655                         assert(get_array_n_dimensions(tp) == 1 && "multiarrays not implemented");
656                         bound  = get_array_lower_bound(tp, 0);
657                         tlower = computed_value(bound);
658                         bound  = get_array_upper_bound(tp, 0);
659                         tupper = computed_value(bound);
660
661                         if (tlower == tarval_bad || tupper == tarval_bad)
662                                 return NULL;
663
664                         if (tarval_cmp(tv_index, tlower) & pn_Cmp_Lt)
665                                 return NULL;
666                         if (tarval_cmp(tupper, tv_index) & pn_Cmp_Lt)
667                                 return NULL;
668
669                         /* ok, bounds check finished */
670                         index = get_tarval_long(tv_index);
671                         p[pos].index = index;
672                         ++pos;
673                 }
674                 if (! tarval_is_null(tv)) {
675                         /* hmm, wrong access */
676                         return NULL;
677                 }
678                 p[pos - 1].next = next;
679                 return rec_find_compound_ent_value(ptr, p);
680         } else if (is_Sub(ptr)) {
681                 ir_node *l = get_Sub_left(ptr);
682                 ir_node *r = get_Sub_right(ptr);
683
684                 ptr = l;
685                 tv  = get_Const_tarval(r);
686                 tv  = tarval_neg(tv);
687                 goto ptr_arith;
688         }
689         return NULL;
690 }
691
692 static ir_node *find_compound_ent_value(ir_node *ptr) {
693         return rec_find_compound_ent_value(ptr, NULL);
694 }
695
696 /* forward */
697 static void reduce_adr_usage(ir_node *ptr);
698
699 /**
700  * Update a Load that may lost it's usage.
701  */
702 static void handle_load_update(ir_node *load) {
703         ldst_info_t *info = get_irn_link(load);
704
705         /* do NOT touch volatile loads for now */
706         if (get_Load_volatility(load) == volatility_is_volatile)
707                 return;
708
709         if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
710                 ir_node *ptr = get_Load_ptr(load);
711                 ir_node *mem = get_Load_mem(load);
712
713                 /* a Load which value is neither used nor exception checked, remove it */
714                 exchange(info->projs[pn_Load_M], mem);
715                 if (info->projs[pn_Load_X_regular])
716                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
717                 kill_node(load);
718                 reduce_adr_usage(ptr);
719         }
720 }  /* handle_load_update */
721
722 /**
723  * A Use of an address node is vanished. Check if this was a Proj
724  * node and update the counters.
725  */
726 static void reduce_adr_usage(ir_node *ptr) {
727         if (is_Proj(ptr)) {
728                 if (get_irn_n_edges(ptr) <= 0) {
729                         /* this Proj is dead now */
730                         ir_node *pred = get_Proj_pred(ptr);
731
732                         if (is_Load(pred)) {
733                                 ldst_info_t *info = get_irn_link(pred);
734                                 info->projs[get_Proj_proj(ptr)] = NULL;
735
736                                 /* this node lost it's result proj, handle that */
737                                 handle_load_update(pred);
738                         }
739                 }
740         }
741 }  /* reduce_adr_usage */
742
743 /**
744  * Check, if an already existing value of mode old_mode can be converted
745  * into the needed one new_mode without loss.
746  */
747 static int can_use_stored_value(ir_mode *old_mode, ir_mode *new_mode) {
748         if (old_mode == new_mode)
749                 return 1;
750
751         /* if both modes are two-complement ones, we can always convert the
752            Stored value into the needed one. */
753         if (get_mode_size_bits(old_mode) >= get_mode_size_bits(new_mode) &&
754                   get_mode_arithmetic(old_mode) == irma_twos_complement &&
755                   get_mode_arithmetic(new_mode) == irma_twos_complement)
756                 return 1;
757         return 0;
758 }  /* can_use_stored_value */
759
760 /**
761  * Check whether a Call is at least pure, ie. does only read memory.
762  */
763 static unsigned is_Call_pure(ir_node *call) {
764         ir_type *call_tp = get_Call_type(call);
765         unsigned prop = get_method_additional_properties(call_tp);
766
767         /* check first the call type */
768         if ((prop & (mtp_property_const|mtp_property_pure)) == 0) {
769                 /* try the called entity */
770                 ir_node *ptr = get_Call_ptr(call);
771
772                 if (is_Global(ptr)) {
773                         ir_entity *ent = get_Global_entity(ptr);
774
775                         prop = get_entity_additional_properties(ent);
776                 }
777         }
778         return (prop & (mtp_property_const|mtp_property_pure)) != 0;
779 }  /* is_Call_pure */
780
781 /**
782  * Follow the memory chain as long as there are only Loads,
783  * alias free Stores, and constant Calls and try to replace the
784  * current Load by a previous ones.
785  * Note that in unreachable loops it might happen that we reach
786  * load again, as well as we can fall into a cycle.
787  * We break such cycles using a special visited flag.
788  *
789  * INC_MASTER() must be called before dive into
790  */
791 static unsigned follow_Mem_chain(ir_node *load, ir_node *curr) {
792         unsigned res = 0;
793         ldst_info_t *info = get_irn_link(load);
794         ir_node *pred;
795         ir_node *ptr       = get_Load_ptr(load);
796         ir_node *mem       = get_Load_mem(load);
797         ir_mode *load_mode = get_Load_mode(load);
798
799         for (pred = curr; load != pred; ) {
800                 ldst_info_t *pred_info = get_irn_link(pred);
801
802                 /*
803                  * BEWARE: one might think that checking the modes is useless, because
804                  * if the pointers are identical, they refer to the same object.
805                  * This is only true in strong typed languages, not in C were the following
806                  * is possible a = *(ir_type1 *)p; b = *(ir_type2 *)p ...
807                  */
808                 if (is_Store(pred) && get_Store_ptr(pred) == ptr &&
809                     can_use_stored_value(get_irn_mode(get_Store_value(pred)), load_mode)) {
810                         /*
811                          * a Load immediately after a Store -- a read after write.
812                          * We may remove the Load, if both Load & Store does not have an exception handler
813                          * OR they are in the same MacroBlock. In the latter case the Load cannot
814                          * throw an exception when the previous Store was quiet.
815                          *
816                          * Why we need to check for Store Exception? If the Store cannot
817                          * be executed (ROM) the exception handler might simply jump into
818                          * the load MacroBlock :-(
819                          * We could make it a little bit better if we would know that the exception
820                          * handler of the Store jumps directly to the end...
821                          */
822                         if ((pred_info->projs[pn_Store_X_except] == NULL && info->projs[pn_Load_X_except] == NULL) ||
823                             get_nodes_MacroBlock(load) == get_nodes_MacroBlock(pred)) {
824                                 ir_node *value = get_Store_value(pred);
825
826                                 DBG_OPT_RAW(load, value);
827
828                                 /* add an convert if needed */
829                                 if (get_irn_mode(get_Store_value(pred)) != load_mode) {
830                                         value = new_r_Conv(current_ir_graph, get_nodes_block(load), value, load_mode);
831                                 }
832
833                                 if (info->projs[pn_Load_M])
834                                         exchange(info->projs[pn_Load_M], mem);
835
836                                 /* no exception */
837                                 if (info->projs[pn_Load_X_except]) {
838                                         exchange( info->projs[pn_Load_X_except], new_Bad());
839                                         res |= CF_CHANGED;
840                                 }
841                                 if (info->projs[pn_Load_X_regular]) {
842                                         exchange( info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
843                                         res |= CF_CHANGED;
844                                 }
845
846                                 if (info->projs[pn_Load_res])
847                                         exchange(info->projs[pn_Load_res], value);
848
849                                 kill_node(load);
850                                 reduce_adr_usage(ptr);
851                                 return res | DF_CHANGED;
852                         }
853                 } else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
854                            can_use_stored_value(get_Load_mode(pred), load_mode)) {
855                         /*
856                          * a Load after a Load -- a read after read.
857                          * We may remove the second Load, if it does not have an exception handler
858                          * OR they are in the same MacroBlock. In the later case the Load cannot
859                          * throw an exception when the previous Load was quiet.
860                          *
861                          * Here, there is no need to check if the previous Load has an exception
862                          * hander because they would have exact the same exception...
863                          */
864                         if (info->projs[pn_Load_X_except] == NULL || get_nodes_MacroBlock(load) == get_nodes_MacroBlock(pred)) {
865                                 ir_node *value;
866
867                                 DBG_OPT_RAR(load, pred);
868
869                                 /* the result is used */
870                                 if (info->projs[pn_Load_res]) {
871                                         if (pred_info->projs[pn_Load_res] == NULL) {
872                                                 /* create a new Proj again */
873                                                 pred_info->projs[pn_Load_res] = new_r_Proj(current_ir_graph, get_nodes_block(pred), pred, get_Load_mode(pred), pn_Load_res);
874                                         }
875                                         value = pred_info->projs[pn_Load_res];
876
877                                         /* add an convert if needed */
878                                         if (get_Load_mode(pred) != load_mode) {
879                                                 value = new_r_Conv(current_ir_graph, get_nodes_block(load), value, load_mode);
880                                         }
881
882                                         exchange(info->projs[pn_Load_res], value);
883                                 }
884
885                                 if (info->projs[pn_Load_M])
886                                         exchange(info->projs[pn_Load_M], mem);
887
888                                 /* no exception */
889                                 if (info->projs[pn_Load_X_except]) {
890                                         exchange(info->projs[pn_Load_X_except], new_Bad());
891                                         res |= CF_CHANGED;
892                                 }
893                                 if (info->projs[pn_Load_X_regular]) {
894                                         exchange( info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
895                                         res |= CF_CHANGED;
896                                 }
897
898                                 kill_node(load);
899                                 reduce_adr_usage(ptr);
900                                 return res |= DF_CHANGED;
901                         }
902                 }
903
904                 if (is_Store(pred)) {
905                         /* check if we can pass through this store */
906                         ir_alias_relation rel = get_alias_relation(
907                                 current_ir_graph,
908                                 get_Store_ptr(pred),
909                                 get_irn_mode(get_Store_value(pred)),
910                                 ptr, load_mode);
911                         /* if the might be an alias, we cannot pass this Store */
912                         if (rel != ir_no_alias)
913                                 break;
914                         pred = skip_Proj(get_Store_mem(pred));
915                 } else if (is_Load(pred)) {
916                         pred = skip_Proj(get_Load_mem(pred));
917                 } else if (is_Call(pred)) {
918                         if (is_Call_pure(pred)) {
919                                 /* The called graph is at least pure, so there are no Store's
920                                    in it. We can handle it like a Load and skip it. */
921                                 pred = skip_Proj(get_Call_mem(pred));
922                         } else {
923                                 /* there might be Store's in the graph, stop here */
924                                 break;
925                         }
926                 } else {
927                         /* follow only Load chains */
928                         break;
929                 }
930
931                 /* check for cycles */
932                 if (NODE_VISITED(pred_info))
933                         break;
934                 MARK_NODE(pred_info);
935         }
936
937         if (is_Sync(pred)) {
938                 int i;
939
940                 /* handle all Sync predecessors */
941                 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
942                         res |= follow_Mem_chain(load, skip_Proj(get_Sync_pred(pred, i)));
943                         if (res)
944                                 return res;
945                 }
946         }
947
948         return res;
949 }  /* follow_Mem_chain */
950
951 /**
952  * optimize a Load
953  *
954  * @param load  the Load node
955  */
956 static unsigned optimize_load(ir_node *load)
957 {
958         ldst_info_t *info = get_irn_link(load);
959         ir_node *mem, *ptr, *new_node;
960         ir_entity *ent;
961         unsigned res = 0;
962
963         /* do NOT touch volatile loads for now */
964         if (get_Load_volatility(load) == volatility_is_volatile)
965                 return 0;
966
967         /* the address of the load to be optimized */
968         ptr = get_Load_ptr(load);
969
970         /*
971          * Check if we can remove the exception from a Load:
972          * This can be done, if the address is from an Sel(Alloc) and
973          * the Sel type is a subtype of the allocated type.
974          *
975          * This optimizes some often used OO constructs,
976          * like x = new O; x->t;
977          */
978         if (info->projs[pn_Load_X_except]) {
979                 if (is_Sel(ptr)) {
980                         ir_node *mem = get_Sel_mem(ptr);
981
982                         /* FIXME: works with the current FE, but better use the base */
983                         if (is_Alloc(skip_Proj(mem))) {
984                                 /* ok, check the types */
985                                 ir_entity *ent    = get_Sel_entity(ptr);
986                                 ir_type   *s_type = get_entity_type(ent);
987                                 ir_type   *a_type = get_Alloc_type(mem);
988
989                                 if (is_SubClass_of(s_type, a_type)) {
990                                         /* ok, condition met: there can't be an exception because
991                                         * Alloc guarantees that enough memory was allocated */
992
993                                         exchange(info->projs[pn_Load_X_except], new_Bad());
994                                         info->projs[pn_Load_X_except] = NULL;
995                                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
996                                         info->projs[pn_Load_X_regular] = NULL;
997                                         res |= CF_CHANGED;
998                                 }
999                         }
1000                 } else if (is_Alloc(skip_Proj(skip_Cast(ptr)))) {
1001                                 /* simple case: a direct load after an Alloc. Firm Alloc throw
1002                                  * an exception in case of out-of-memory. So, there is no way for an
1003                                  * exception in this load.
1004                                  * This code is constructed by the "exception lowering" in the Jack compiler.
1005                                  */
1006                                 exchange(info->projs[pn_Load_X_except], new_Bad());
1007                                 info->projs[pn_Load_X_except] = NULL;
1008                                 exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
1009                                 info->projs[pn_Load_X_regular] = NULL;
1010                                 res |= CF_CHANGED;
1011                 }
1012         }
1013
1014         /* The mem of the Load. Must still be returned after optimization. */
1015         mem  = get_Load_mem(load);
1016
1017         if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
1018                 /* a Load which value is neither used nor exception checked, remove it */
1019                 exchange(info->projs[pn_Load_M], mem);
1020
1021                 if (info->projs[pn_Load_X_regular]) {
1022                         /* should not happen, but if it does, remove it */
1023                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
1024                         res |= CF_CHANGED;
1025                 }
1026                 kill_node(load);
1027                 reduce_adr_usage(ptr);
1028                 return res | DF_CHANGED;
1029         }
1030
1031         /* Load from a constant polymorphic field, where we can resolve
1032            polymorphism. */
1033         new_node = transform_node_Load(load);
1034         if (new_node != load) {
1035                 if (info->projs[pn_Load_M]) {
1036                         exchange(info->projs[pn_Load_M], mem);
1037                         info->projs[pn_Load_M] = NULL;
1038                 }
1039                 if (info->projs[pn_Load_X_except]) {
1040                         exchange(info->projs[pn_Load_X_except], new_Bad());
1041                         info->projs[pn_Load_X_except] = NULL;
1042                         res |= CF_CHANGED;
1043                 }
1044                 if (info->projs[pn_Load_X_regular]) {
1045                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
1046                         info->projs[pn_Load_X_regular] = NULL;
1047                         res |= CF_CHANGED;
1048                 }
1049                 if (info->projs[pn_Load_res])
1050                         exchange(info->projs[pn_Load_res], new_node);
1051
1052                 kill_node(load);
1053                 reduce_adr_usage(ptr);
1054                 return res | DF_CHANGED;
1055         }
1056
1057         /* check if we can determine the entity that will be loaded */
1058         ent = find_constant_entity(ptr);
1059         if (ent) {
1060                 if ((allocation_static == get_entity_allocation(ent)) &&
1061                         (visibility_external_allocated != get_entity_visibility(ent))) {
1062                         /* a static allocation that is not external: there should be NO exception
1063                          * when loading. */
1064
1065                         /* no exception, clear the info field as it might be checked later again */
1066                         if (info->projs[pn_Load_X_except]) {
1067                                 exchange(info->projs[pn_Load_X_except], new_Bad());
1068                                 info->projs[pn_Load_X_except] = NULL;
1069                                 res |= CF_CHANGED;
1070                         }
1071                         if (info->projs[pn_Load_X_regular]) {
1072                                 exchange(info->projs[pn_Load_X_regular], new_r_Jmp(current_ir_graph, get_nodes_block(load)));
1073                                 info->projs[pn_Load_X_regular] = NULL;
1074                                 res |= CF_CHANGED;
1075                         }
1076
1077                         if (variability_constant == get_entity_variability(ent)) {
1078                                 if (is_atomic_entity(ent)) {
1079                                         /* Might not be atomic after
1080                                            lowering of Sels.  In this
1081                                            case we could also load, but
1082                                            it's more complicated. */
1083                                         /* more simpler case: we load the content of a constant value:
1084                                          * replace it by the constant itself
1085                                          */
1086
1087                                         /* no memory */
1088                                         if (info->projs[pn_Load_M]) {
1089                                                 exchange(info->projs[pn_Load_M], mem);
1090                                                 res |= DF_CHANGED;
1091                                         }
1092                                         /* no result :-) */
1093                                         if (info->projs[pn_Load_res]) {
1094                                                 if (is_atomic_entity(ent)) {
1095                                                         ir_node *c = copy_const_value(get_irn_dbg_info(load), get_atomic_ent_value(ent));
1096
1097                                                         DBG_OPT_RC(load, c);
1098                                                         exchange(info->projs[pn_Load_res], c);
1099                                                         res |= DF_CHANGED;
1100                                                 }
1101                                         }
1102                                         kill_node(load);
1103                                         reduce_adr_usage(ptr);
1104                                         return res;
1105                                 } else {
1106                                         ir_node *c = NULL;
1107                                         if (ent->has_initializer) {
1108                                                 /* new style initializer */
1109                                                 c = find_compound_ent_value(ptr);
1110                                         } else {
1111                                                 /* old style initializer */
1112                                                 compound_graph_path *path = get_accessed_path(ptr);
1113
1114                                                 if (path) {
1115                                                         assert(is_proper_compound_graph_path(path, get_compound_graph_path_length(path)-1));
1116
1117                                                         c = get_compound_ent_value_by_path(ent, path);
1118                                                         free_compound_graph_path(path);
1119                                                 }
1120                                         }
1121                                         if (c != NULL) {
1122                                                 if (info->projs[pn_Load_M]) {
1123                                                         exchange(info->projs[pn_Load_M], mem);
1124                                                         res |= DF_CHANGED;
1125                                                 }
1126                                                 if (info->projs[pn_Load_res]) {
1127                                                         exchange(info->projs[pn_Load_res], copy_const_value(get_irn_dbg_info(load), c));
1128                                                         res |= DF_CHANGED;
1129                                                 }
1130                                                 kill_node(load);
1131                                                 reduce_adr_usage(ptr);
1132                                                 return res;
1133                                         } else {
1134                                                 /*  We can not determine a correct access path.  E.g., in jack, we load
1135                                                 a byte from an object to generate an exception.   Happens in test program
1136                                                 Reflectiontest.
1137                                                 printf(">>>>>>>>>>>>> Found access to constant entity %s in function %s\n", get_entity_name(ent),
1138                                                 get_entity_name(get_irg_entity(current_ir_graph)));
1139                                                 ir_printf("  load: %+F\n", load);
1140                                                 ir_printf("  ptr:  %+F\n", ptr);
1141                                                 */
1142                                         }
1143                                 }
1144                         }
1145                 }
1146         }
1147
1148         /* Check, if the address of this load is used more than once.
1149          * If not, this load cannot be removed in any case. */
1150         if (get_irn_n_uses(ptr) <= 1)
1151                 return res;
1152
1153         /*
1154          * follow the memory chain as long as there are only Loads
1155          * and try to replace current Load or Store by a previous one.
1156          * Note that in unreachable loops it might happen that we reach
1157          * load again, as well as we can fall into a cycle.
1158          * We break such cycles using a special visited flag.
1159          */
1160         INC_MASTER();
1161         res = follow_Mem_chain(load, skip_Proj(mem));
1162         return res;
1163 }  /* optimize_load */
1164
1165 /**
1166  * Check whether a value of mode new_mode would completely overwrite a value
1167  * of mode old_mode in memory.
1168  */
1169 static int is_completely_overwritten(ir_mode *old_mode, ir_mode *new_mode)
1170 {
1171         return get_mode_size_bits(new_mode) >= get_mode_size_bits(old_mode);
1172 }  /* is_completely_overwritten */
1173
1174 /**
1175  * follow the memory chain as long as there are only Loads and alias free Stores.
1176  *
1177  * INC_MASTER() must be called before dive into
1178  */
1179 static unsigned follow_Mem_chain_for_Store(ir_node *store, ir_node *curr) {
1180         unsigned res = 0;
1181         ldst_info_t *info = get_irn_link(store);
1182         ir_node *pred;
1183         ir_node *ptr = get_Store_ptr(store);
1184         ir_node *mem = get_Store_mem(store);
1185         ir_node *value = get_Store_value(store);
1186         ir_mode *mode  = get_irn_mode(value);
1187         ir_node *block = get_nodes_block(store);
1188         ir_node *mblk  = get_Block_MacroBlock(block);
1189
1190         for (pred = curr; pred != store;) {
1191                 ldst_info_t *pred_info = get_irn_link(pred);
1192
1193                 /*
1194                  * BEWARE: one might think that checking the modes is useless, because
1195                  * if the pointers are identical, they refer to the same object.
1196                  * This is only true in strong typed languages, not is C were the following
1197                  * is possible *(ir_type1 *)p = a; *(ir_type2 *)p = b ...
1198                  * However, if the mode that is written have a bigger  or equal size the the old
1199                  * one, the old value is completely overwritten and can be killed ...
1200                  */
1201                 if (is_Store(pred) && get_Store_ptr(pred) == ptr &&
1202                     get_nodes_MacroBlock(pred) == mblk &&
1203                     is_completely_overwritten(get_irn_mode(get_Store_value(pred)), mode)) {
1204                         /*
1205                          * a Store after a Store in the same MacroBlock -- a write after write.
1206                          * We may remove the first Store, if it does not have an exception handler.
1207                          *
1208                          * TODO: What, if both have the same exception handler ???
1209                          */
1210                         if (get_Store_volatility(pred) != volatility_is_volatile && !pred_info->projs[pn_Store_X_except]) {
1211                                 DBG_OPT_WAW(pred, store);
1212                                 exchange(pred_info->projs[pn_Store_M], get_Store_mem(pred));
1213                                 kill_node(pred);
1214                                 reduce_adr_usage(ptr);
1215                                 return DF_CHANGED;
1216                         }
1217                 } else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
1218                            value == pred_info->projs[pn_Load_res]) {
1219                         /*
1220                          * a Store of a value just loaded from the same address
1221                          * -- a write after read.
1222                          * We may remove the Store, if it does not have an exception
1223                          * handler.
1224                          */
1225                         if (! info->projs[pn_Store_X_except]) {
1226                                 DBG_OPT_WAR(store, pred);
1227                                 exchange(info->projs[pn_Store_M], mem);
1228                                 kill_node(store);
1229                                 reduce_adr_usage(ptr);
1230                                 return DF_CHANGED;
1231                         }
1232                 }
1233
1234                 if (is_Store(pred)) {
1235                         /* check if we can pass thru this store */
1236                         ir_alias_relation rel = get_alias_relation(
1237                                 current_ir_graph,
1238                                 get_Store_ptr(pred),
1239                                 get_irn_mode(get_Store_value(pred)),
1240                                 ptr, mode);
1241                         /* if the might be an alias, we cannot pass this Store */
1242                         if (rel != ir_no_alias)
1243                                 break;
1244                         pred = skip_Proj(get_Store_mem(pred));
1245                 } else if (is_Load(pred)) {
1246                         ir_alias_relation rel = get_alias_relation(
1247                                 current_ir_graph, get_Load_ptr(pred), get_Load_mode(pred),
1248                                 ptr, mode);
1249                         if (rel != ir_no_alias)
1250                                 break;
1251
1252                         pred = skip_Proj(get_Load_mem(pred));
1253                 } else {
1254                         /* follow only Load chains */
1255                         break;
1256                 }
1257
1258                 /* check for cycles */
1259                 if (NODE_VISITED(pred_info))
1260                         break;
1261                 MARK_NODE(pred_info);
1262         }
1263
1264         if (is_Sync(pred)) {
1265                 int i;
1266
1267                 /* handle all Sync predecessors */
1268                 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
1269                         res |= follow_Mem_chain_for_Store(store, skip_Proj(get_Sync_pred(pred, i)));
1270                         if (res)
1271                                 break;
1272                 }
1273         }
1274         return res;
1275 }  /* follow_Mem_chain_for_Store */
1276
1277 /**
1278  * optimize a Store
1279  *
1280  * @param store  the Store node
1281  */
1282 static unsigned optimize_store(ir_node *store) {
1283         ir_node *ptr, *mem;
1284
1285         if (get_Store_volatility(store) == volatility_is_volatile)
1286                 return 0;
1287
1288         ptr = get_Store_ptr(store);
1289
1290         /* Check, if the address of this Store is used more than once.
1291          * If not, this Store cannot be removed in any case. */
1292         if (get_irn_n_uses(ptr) <= 1)
1293                 return 0;
1294
1295         mem = get_Store_mem(store);
1296
1297         /* follow the memory chain as long as there are only Loads */
1298         INC_MASTER();
1299
1300         return follow_Mem_chain_for_Store(store, skip_Proj(mem));
1301 }  /* optimize_store */
1302
1303 /**
1304  * walker, optimizes Phi after Stores to identical places:
1305  * Does the following optimization:
1306  * @verbatim
1307  *
1308  *   val1   val2   val3          val1  val2  val3
1309  *    |      |      |               \    |    /
1310  *  Store  Store  Store              \   |   /
1311  *      \    |    /                   PhiData
1312  *       \   |   /                       |
1313  *        \  |  /                      Store
1314  *          PhiM
1315  *
1316  * @endverbatim
1317  * This reduces the number of stores and allows for predicated execution.
1318  * Moves Stores back to the end of a function which may be bad.
1319  *
1320  * This is only possible if the predecessor blocks have only one successor.
1321  */
1322 static unsigned optimize_phi(ir_node *phi, walk_env_t *wenv)
1323 {
1324         int i, n;
1325         ir_node *store, *old_store, *ptr, *block, *phi_block, *phiM, *phiD, *exc, *projM;
1326         ir_mode *mode;
1327         ir_node **inM, **inD, **projMs;
1328         int *idx;
1329         dbg_info *db = NULL;
1330         ldst_info_t *info;
1331         block_info_t *bl_info;
1332         unsigned res = 0;
1333
1334         /* Must be a memory Phi */
1335         if (get_irn_mode(phi) != mode_M)
1336                 return 0;
1337
1338         n = get_Phi_n_preds(phi);
1339         if (n <= 0)
1340                 return 0;
1341
1342         /* must be only one user */
1343         projM = get_Phi_pred(phi, 0);
1344         if (get_irn_n_edges(projM) != 1)
1345                 return 0;
1346
1347         store = skip_Proj(projM);
1348         old_store = store;
1349         if (!is_Store(store))
1350                 return 0;
1351
1352         block = get_nodes_block(store);
1353
1354         /* abort on dead blocks */
1355         if (is_Block_dead(block))
1356                 return 0;
1357
1358         /* check if the block is post dominated by Phi-block
1359            and has no exception exit */
1360         bl_info = get_irn_link(block);
1361         if (bl_info->flags & BLOCK_HAS_EXC)
1362                 return 0;
1363
1364         phi_block = get_nodes_block(phi);
1365         if (! block_strictly_postdominates(phi_block, block))
1366                 return 0;
1367
1368         /* this is the address of the store */
1369         ptr  = get_Store_ptr(store);
1370         mode = get_irn_mode(get_Store_value(store));
1371         info = get_irn_link(store);
1372         exc  = info->exc_block;
1373
1374         for (i = 1; i < n; ++i) {
1375                 ir_node *pred = get_Phi_pred(phi, i);
1376
1377                 if (get_irn_n_edges(pred) != 1)
1378                         return 0;
1379
1380                 pred = skip_Proj(pred);
1381                 if (!is_Store(pred))
1382                         return 0;
1383
1384                 if (ptr != get_Store_ptr(pred) || mode != get_irn_mode(get_Store_value(pred)))
1385                         return 0;
1386
1387                 info = get_irn_link(pred);
1388
1389                 /* check, if all stores have the same exception flow */
1390                 if (exc != info->exc_block)
1391                         return 0;
1392
1393                 /* abort on dead blocks */
1394                 block = get_nodes_block(pred);
1395                 if (is_Block_dead(block))
1396                         return 0;
1397
1398                 /* check if the block is post dominated by Phi-block
1399                    and has no exception exit. Note that block must be different from
1400                    Phi-block, else we would move a Store from end End of a block to its
1401                    Start... */
1402                 bl_info = get_irn_link(block);
1403                 if (bl_info->flags & BLOCK_HAS_EXC)
1404                         return 0;
1405                 if (block == phi_block || ! block_postdominates(phi_block, block))
1406                         return 0;
1407         }
1408
1409         /*
1410          * ok, when we are here, we found all predecessors of a Phi that
1411          * are Stores to the same address and size. That means whatever
1412          * we do before we enter the block of the Phi, we do a Store.
1413          * So, we can move the Store to the current block:
1414          *
1415          *   val1    val2    val3          val1  val2  val3
1416          *    |       |       |               \    |    /
1417          * | Str | | Str | | Str |             \   |   /
1418          *      \     |     /                   PhiData
1419          *       \    |    /                       |
1420          *        \   |   /                       Str
1421          *           PhiM
1422          *
1423          * Is only allowed if the predecessor blocks have only one successor.
1424          */
1425
1426         NEW_ARR_A(ir_node *, projMs, n);
1427         NEW_ARR_A(ir_node *, inM, n);
1428         NEW_ARR_A(ir_node *, inD, n);
1429         NEW_ARR_A(int, idx, n);
1430
1431         /* Prepare: Collect all Store nodes.  We must do this
1432            first because we otherwise may loose a store when exchanging its
1433            memory Proj.
1434          */
1435         for (i = n - 1; i >= 0; --i) {
1436                 ir_node *store;
1437
1438                 projMs[i] = get_Phi_pred(phi, i);
1439                 assert(is_Proj(projMs[i]));
1440
1441                 store = get_Proj_pred(projMs[i]);
1442                 info  = get_irn_link(store);
1443
1444                 inM[i] = get_Store_mem(store);
1445                 inD[i] = get_Store_value(store);
1446                 idx[i] = info->exc_idx;
1447         }
1448         block = get_nodes_block(phi);
1449
1450         /* second step: create a new memory Phi */
1451         phiM = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inM, mode_M);
1452
1453         /* third step: create a new data Phi */
1454         phiD = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inD, mode);
1455
1456         /* rewire memory and kill the node */
1457         for (i = n - 1; i >= 0; --i) {
1458                 ir_node *proj  = projMs[i];
1459
1460                 if(is_Proj(proj)) {
1461                         ir_node *store = get_Proj_pred(proj);
1462                         exchange(proj, inM[i]);
1463                         kill_node(store);
1464                 }
1465         }
1466
1467         /* fourth step: create the Store */
1468         store = new_rd_Store(db, current_ir_graph, block, phiM, ptr, phiD);
1469 #ifdef DO_CACHEOPT
1470         co_set_irn_name(store, co_get_irn_ident(old_store));
1471 #endif
1472
1473         projM = new_rd_Proj(NULL, current_ir_graph, block, store, mode_M, pn_Store_M);
1474
1475         info = get_ldst_info(store, &wenv->obst);
1476         info->projs[pn_Store_M] = projM;
1477
1478         /* fifths step: repair exception flow */
1479         if (exc) {
1480                 ir_node *projX = new_rd_Proj(NULL, current_ir_graph, block, store, mode_X, pn_Store_X_except);
1481
1482                 info->projs[pn_Store_X_except] = projX;
1483                 info->exc_block                = exc;
1484                 info->exc_idx                  = idx[0];
1485
1486                 for (i = 0; i < n; ++i) {
1487                         set_Block_cfgpred(exc, idx[i], projX);
1488                 }
1489
1490                 if (n > 1) {
1491                         /* the exception block should be optimized as some inputs are identical now */
1492                 }
1493
1494                 res |= CF_CHANGED;
1495         }
1496
1497         /* sixth step: replace old Phi */
1498         exchange(phi, projM);
1499
1500         return res | DF_CHANGED;
1501 }  /* optimize_phi */
1502
1503 /**
1504  * walker, do the optimizations
1505  */
1506 static void do_load_store_optimize(ir_node *n, void *env) {
1507         walk_env_t *wenv = env;
1508
1509         switch (get_irn_opcode(n)) {
1510
1511         case iro_Load:
1512                 wenv->changes |= optimize_load(n);
1513                 break;
1514
1515         case iro_Store:
1516                 wenv->changes |= optimize_store(n);
1517                 break;
1518
1519         case iro_Phi:
1520                 wenv->changes |= optimize_phi(n, wenv);
1521                 break;
1522
1523         default:
1524                 ;
1525         }
1526 }  /* do_load_store_optimize */
1527
1528 /** A scc. */
1529 typedef struct scc {
1530         ir_node *head;          /**< the head of the list */
1531 } scc;
1532
1533 /** A node entry. */
1534 typedef struct node_entry {
1535         unsigned DFSnum;    /**< the DFS number of this node */
1536         unsigned low;       /**< the low number of this node */
1537         ir_node  *header;   /**< the header of this node */
1538         int      in_stack;  /**< flag, set if the node is on the stack */
1539         ir_node  *next;     /**< link to the next node the the same scc */
1540         scc      *pscc;     /**< the scc of this node */
1541         unsigned POnum;     /**< the post order number for blocks */
1542 } node_entry;
1543
1544 /** A loop entry. */
1545 typedef struct loop_env {
1546         ir_phase ph;           /**< the phase object */
1547         ir_node  **stack;      /**< the node stack */
1548         int      tos;          /**< tos index */
1549         unsigned nextDFSnum;   /**< the current DFS number */
1550         unsigned POnum;        /**< current post order number */
1551
1552         unsigned changes;      /**< a bitmask of graph changes */
1553 } loop_env;
1554
1555 /**
1556 * Gets the node_entry of a node
1557 */
1558 static node_entry *get_irn_ne(ir_node *irn, loop_env *env) {
1559         ir_phase   *ph = &env->ph;
1560         node_entry *e  = phase_get_irn_data(&env->ph, irn);
1561
1562         if (! e) {
1563                 e = phase_alloc(ph, sizeof(*e));
1564                 memset(e, 0, sizeof(*e));
1565                 phase_set_irn_data(ph, irn, e);
1566         }
1567         return e;
1568 }  /* get_irn_ne */
1569
1570 /**
1571  * Push a node onto the stack.
1572  *
1573  * @param env   the loop environment
1574  * @param n     the node to push
1575  */
1576 static void push(loop_env *env, ir_node *n) {
1577         node_entry *e;
1578
1579         if (env->tos == ARR_LEN(env->stack)) {
1580                 int nlen = ARR_LEN(env->stack) * 2;
1581                 ARR_RESIZE(ir_node *, env->stack, nlen);
1582         }
1583         env->stack[env->tos++] = n;
1584         e = get_irn_ne(n, env);
1585         e->in_stack = 1;
1586 }  /* push */
1587
1588 /**
1589  * pop a node from the stack
1590  *
1591  * @param env   the loop environment
1592  *
1593  * @return  The topmost node
1594  */
1595 static ir_node *pop(loop_env *env) {
1596         ir_node *n = env->stack[--env->tos];
1597         node_entry *e = get_irn_ne(n, env);
1598
1599         e->in_stack = 0;
1600         return n;
1601 }  /* pop */
1602
1603 /**
1604  * Check if irn is a region constant.
1605  * The block or irn must strictly dominate the header block.
1606  *
1607  * @param irn           the node to check
1608  * @param header_block  the header block of the induction variable
1609  */
1610 static int is_rc(ir_node *irn, ir_node *header_block) {
1611         ir_node *block = get_nodes_block(irn);
1612
1613         return (block != header_block) && block_dominates(block, header_block);
1614 }  /* is_rc */
1615
1616 typedef struct phi_entry phi_entry;
1617 struct phi_entry {
1618         ir_node   *phi;    /**< A phi with a region const memory. */
1619         int       pos;     /**< The position of the region const memory */
1620         ir_node   *load;   /**< the newly created load for this phi */
1621         phi_entry *next;
1622 };
1623
1624 /**
1625  * Move loops out of loops if possible.
1626  *
1627  * @param pscc   the loop described by an SCC
1628  * @param env    the loop environment
1629  */
1630 static void move_loads_out_of_loops(scc *pscc, loop_env *env) {
1631         ir_node   *phi, *load, *next, *other, *next_other;
1632         ir_entity *ent;
1633         int       j;
1634         phi_entry *phi_list = NULL;
1635
1636         /* collect all outer memories */
1637         for (phi = pscc->head; phi != NULL; phi = next) {
1638                 node_entry *ne = get_irn_ne(phi, env);
1639                 next = ne->next;
1640
1641                 /* check all memory Phi's */
1642                 if (! is_Phi(phi))
1643                         continue;
1644
1645                 assert(get_irn_mode(phi) == mode_M && "DFS geturn non-memory Phi");
1646
1647                 for (j = get_irn_arity(phi) - 1; j >= 0; --j) {
1648                         ir_node    *pred = get_irn_n(phi, j);
1649                         node_entry *pe   = get_irn_ne(pred, env);
1650
1651                         if (pe->pscc != ne->pscc) {
1652                                 /* not in the same SCC, is region const */
1653                                 phi_entry *pe = phase_alloc(&env->ph, sizeof(*pe));
1654
1655                                 pe->phi  = phi;
1656                                 pe->pos  = j;
1657                                 pe->next = phi_list;
1658                                 phi_list = pe;
1659                         }
1660                 }
1661         }
1662         /* no Phis no fun */
1663         assert(phi_list != NULL && "DFS found a loop without Phi");
1664
1665         for (load = pscc->head; load; load = next) {
1666                 ir_mode *load_mode;
1667                 node_entry *ne = get_irn_ne(load, env);
1668                 next = ne->next;
1669
1670                 if (is_Load(load)) {
1671                         ldst_info_t *info = get_irn_link(load);
1672                         ir_node     *ptr = get_Load_ptr(load);
1673
1674                         /* for now, we cannot handle Loads with exceptions */
1675                         if (info->projs[pn_Load_res] == NULL || info->projs[pn_Load_X_regular] != NULL || info->projs[pn_Load_X_except] != NULL)
1676                                 continue;
1677
1678                         /* for now, we can only handle Load(Global) */
1679                         if (! is_Global(ptr))
1680                                 continue;
1681                         ent = get_Global_entity(ptr);
1682                         load_mode = get_Load_mode(load);
1683                         for (other = pscc->head; other != NULL; other = next_other) {
1684                                 node_entry *ne = get_irn_ne(other, env);
1685                                 next_other = ne->next;
1686
1687                                 if (is_Store(other)) {
1688                                         ir_alias_relation rel = get_alias_relation(
1689                                                 current_ir_graph,
1690                                                 get_Store_ptr(other),
1691                                                 get_irn_mode(get_Store_value(other)),
1692                                                 ptr, load_mode);
1693                                         /* if the might be an alias, we cannot pass this Store */
1694                                         if (rel != ir_no_alias)
1695                                                 break;
1696                                 }
1697                                 /* only pure Calls are allowed here, so ignore them */
1698                         }
1699                         if (other == NULL) {
1700                                 ldst_info_t *ninfo;
1701                                 phi_entry   *pe;
1702                                 dbg_info    *db;
1703
1704                                 /* for now, we cannot handle more than one input */
1705                                 if (phi_list->next != NULL)
1706                                         return;
1707
1708                                 /* yep, no aliasing Store found, Load can be moved */
1709                                 DB((dbg, LEVEL_1, "  Found a Load that could be moved: %+F\n", load));
1710
1711                                 db   = get_irn_dbg_info(load);
1712                                 for (pe = phi_list; pe != NULL; pe = pe->next) {
1713                                         int     pos   = pe->pos;
1714                                         ir_node *phi  = pe->phi;
1715                                         ir_node *blk  = get_nodes_block(phi);
1716                                         ir_node *pred = get_Block_cfgpred_block(blk, pos);
1717                                         ir_node *irn, *mem;
1718
1719                                         pe->load = irn = new_rd_Load(db, current_ir_graph, pred, get_Phi_pred(phi, pos), ptr, load_mode);
1720                                         ninfo = get_ldst_info(irn, phase_obst(&env->ph));
1721
1722                                         ninfo->projs[pn_Load_M] = mem = new_r_Proj(current_ir_graph, pred, irn, mode_M, pn_Load_M);
1723                                         set_Phi_pred(phi, pos, mem);
1724
1725                                         ninfo->projs[pn_Load_res] = new_r_Proj(current_ir_graph, pred, irn, load_mode, pn_Load_res);
1726
1727                                         DB((dbg, LEVEL_1, "  Created %+F in %+F\n", irn, pred));
1728                                 }
1729
1730                                 /* now kill the old Load */
1731                                 exchange(info->projs[pn_Load_M], get_Load_mem(load));
1732                                 exchange(info->projs[pn_Load_res], ninfo->projs[pn_Load_res]);
1733
1734                                 env->changes |= DF_CHANGED;
1735                         }
1736                 }
1737         }
1738 }  /* move_loads_out_of_loops */
1739
1740 /**
1741  * Process a loop SCC.
1742  *
1743  * @param pscc  the SCC
1744  * @param env   the loop environment
1745  */
1746 static void process_loop(scc *pscc, loop_env *env) {
1747         ir_node *irn, *next, *header = NULL;
1748         node_entry *b, *h = NULL;
1749         int j, only_phi, num_outside, process = 0;
1750         ir_node *out_rc;
1751
1752         /* find the header block for this scc */
1753         for (irn = pscc->head; irn; irn = next) {
1754                 node_entry *e = get_irn_ne(irn, env);
1755                 ir_node *block = get_nodes_block(irn);
1756
1757                 next = e->next;
1758                 b = get_irn_ne(block, env);
1759
1760                 if (header) {
1761                         if (h->POnum < b->POnum) {
1762                                 header = block;
1763                                 h      = b;
1764                         }
1765                 }
1766                 else {
1767                         header = block;
1768                         h      = b;
1769                 }
1770         }
1771
1772         /* check if this scc contains only Phi, Loads or Stores nodes */
1773         only_phi    = 1;
1774         num_outside = 0;
1775         out_rc      = NULL;
1776         for (irn = pscc->head; irn; irn = next) {
1777                 node_entry *e = get_irn_ne(irn, env);
1778
1779                 next = e->next;
1780                 switch (get_irn_opcode(irn)) {
1781                 case iro_Call:
1782                         if (is_Call_pure(irn)) {
1783                                 /* pure calls can be treated like loads */
1784                                 only_phi = 0;
1785                                 break;
1786                         }
1787                         /* non-pure calls must be handle like may-alias Stores */
1788                         goto fail;
1789                 case iro_CopyB:
1790                         /* cannot handle CopyB yet */
1791                         goto fail;
1792                 case iro_Load:
1793                         process = 1;
1794                         if (get_Load_volatility(irn) == volatility_is_volatile) {
1795                                 /* cannot handle loops with volatile Loads */
1796                                 goto fail;
1797                         }
1798                         only_phi = 0;
1799                         break;
1800                 case iro_Store:
1801                         if (get_Store_volatility(irn) == volatility_is_volatile) {
1802                                 /* cannot handle loops with volatile Stores */
1803                                 goto fail;
1804                         }
1805                         only_phi = 0;
1806                         break;
1807                 default:
1808                         only_phi = 0;
1809                         break;
1810                 case iro_Phi:
1811                         for (j = get_irn_arity(irn) - 1; j >= 0; --j) {
1812                                 ir_node *pred  = get_irn_n(irn, j);
1813                                 node_entry *pe = get_irn_ne(pred, env);
1814
1815                                 if (pe->pscc != e->pscc) {
1816                                         /* not in the same SCC, must be a region const */
1817                                         if (! is_rc(pred, header)) {
1818                                                 /* not a memory loop */
1819                                                 goto fail;
1820                                         }
1821                                         if (! out_rc) {
1822                                                 out_rc = pred;
1823                                                 ++num_outside;
1824                                         } else if (out_rc != pred) {
1825                                                 ++num_outside;
1826                                         }
1827                                 }
1828                         }
1829                         break;
1830                 }
1831         }
1832         if (! process)
1833                 goto fail;
1834
1835         /* found a memory loop */
1836         DB((dbg, LEVEL_2, "  Found a memory loop:\n  "));
1837         if (only_phi && num_outside == 1) {
1838                 /* a phi cycle with only one real predecessor can be collapsed */
1839                 DB((dbg, LEVEL_2, "  Found an USELESS Phi cycle:\n  "));
1840
1841                 for (irn = pscc->head; irn; irn = next) {
1842                         node_entry *e = get_irn_ne(irn, env);
1843                         next = e->next;
1844                         e->header = NULL;
1845                         exchange(irn, out_rc);
1846                 }
1847                 env->changes |= DF_CHANGED;
1848                 return;
1849         }
1850
1851         /* set the header for every node in this scc */
1852         for (irn = pscc->head; irn; irn = next) {
1853                 node_entry *e = get_irn_ne(irn, env);
1854                 e->header = header;
1855                 next = e->next;
1856                 DB((dbg, LEVEL_2, " %+F,", irn));
1857         }
1858         DB((dbg, LEVEL_2, "\n"));
1859
1860         move_loads_out_of_loops(pscc, env);
1861
1862 fail:
1863         ;
1864 }  /* process_loop */
1865
1866 /**
1867  * Process a SCC.
1868  *
1869  * @param pscc  the SCC
1870  * @param env   the loop environment
1871  */
1872 static void process_scc(scc *pscc, loop_env *env) {
1873         ir_node *head = pscc->head;
1874         node_entry *e = get_irn_ne(head, env);
1875
1876 #ifdef DEBUG_libfirm
1877         {
1878                 ir_node *irn, *next;
1879
1880                 DB((dbg, LEVEL_4, " SCC at %p:\n ", pscc));
1881                 for (irn = pscc->head; irn; irn = next) {
1882                         node_entry *e = get_irn_ne(irn, env);
1883
1884                         next = e->next;
1885
1886                         DB((dbg, LEVEL_4, " %+F,", irn));
1887                 }
1888                 DB((dbg, LEVEL_4, "\n"));
1889         }
1890 #endif
1891
1892         if (e->next != NULL) {
1893                 /* this SCC has more than one member */
1894                 process_loop(pscc, env);
1895         }
1896 }  /* process_scc */
1897
1898 /**
1899  * Do Tarjan's SCC algorithm and drive load/store optimization.
1900  *
1901  * @param irn  start at this node
1902  * @param env  the loop environment
1903  */
1904 static void dfs(ir_node *irn, loop_env *env)
1905 {
1906         int i, n;
1907         node_entry *node = get_irn_ne(irn, env);
1908
1909         mark_irn_visited(irn);
1910
1911         node->DFSnum = env->nextDFSnum++;
1912         node->low    = node->DFSnum;
1913         push(env, irn);
1914
1915         /* handle preds */
1916         if (is_Phi(irn) || is_Sync(irn)) {
1917                 n = get_irn_arity(irn);
1918                 for (i = 0; i < n; ++i) {
1919                         ir_node *pred = get_irn_n(irn, i);
1920                         node_entry *o = get_irn_ne(pred, env);
1921
1922                         if (irn_not_visited(pred)) {
1923                                 dfs(pred, env);
1924                                 node->low = MIN(node->low, o->low);
1925                         }
1926                         if (o->DFSnum < node->DFSnum && o->in_stack)
1927                                 node->low = MIN(o->DFSnum, node->low);
1928                 }
1929         } else if (is_fragile_op(irn)) {
1930                 ir_node *pred = get_fragile_op_mem(irn);
1931                 node_entry *o = get_irn_ne(pred, env);
1932
1933                 if (irn_not_visited(pred)) {
1934                         dfs(pred, env);
1935                         node->low = MIN(node->low, o->low);
1936                 }
1937                 if (o->DFSnum < node->DFSnum && o->in_stack)
1938                         node->low = MIN(o->DFSnum, node->low);
1939         } else if (is_Proj(irn)) {
1940                 ir_node *pred = get_Proj_pred(irn);
1941                 node_entry *o = get_irn_ne(pred, env);
1942
1943                 if (irn_not_visited(pred)) {
1944                         dfs(pred, env);
1945                         node->low = MIN(node->low, o->low);
1946                 }
1947                 if (o->DFSnum < node->DFSnum && o->in_stack)
1948                         node->low = MIN(o->DFSnum, node->low);
1949         }
1950         else {
1951                  /* IGNORE predecessors */
1952         }
1953
1954         if (node->low == node->DFSnum) {
1955                 scc *pscc = phase_alloc(&env->ph, sizeof(*pscc));
1956                 ir_node *x;
1957
1958                 pscc->head = NULL;
1959                 do {
1960                         node_entry *e;
1961
1962                         x = pop(env);
1963                         e = get_irn_ne(x, env);
1964                         e->pscc    = pscc;
1965                         e->next    = pscc->head;
1966                         pscc->head = x;
1967                 } while (x != irn);
1968
1969                 process_scc(pscc, env);
1970         }
1971 }  /* dfs */
1972
1973 /**
1974  * Do the DFS on the memory edges a graph.
1975  *
1976  * @param irg  the graph to process
1977  * @param env  the loop environment
1978  */
1979 static void do_dfs(ir_graph *irg, loop_env *env) {
1980         ir_graph *rem = current_ir_graph;
1981         ir_node  *endblk, *end;
1982         int      i;
1983
1984         current_ir_graph = irg;
1985         inc_irg_visited(irg);
1986
1987         /* visit all memory nodes */
1988         endblk = get_irg_end_block(irg);
1989         for (i = get_Block_n_cfgpreds(endblk) - 1; i >= 0; --i) {
1990                 ir_node *pred = get_Block_cfgpred(endblk, i);
1991
1992                 pred = skip_Proj(pred);
1993                 if (is_Return(pred))
1994                         dfs(get_Return_mem(pred), env);
1995                 else if (is_Raise(pred))
1996                         dfs(get_Raise_mem(pred), env);
1997                 else if (is_fragile_op(pred))
1998                         dfs(get_fragile_op_mem(pred), env);
1999                 else {
2000                         assert(0 && "Unknown EndBlock predecessor");
2001                 }
2002         }
2003
2004         /* visit the keep-alives */
2005         end = get_irg_end(irg);
2006         for (i = get_End_n_keepalives(end) - 1; i >= 0; --i) {
2007                 ir_node *ka = get_End_keepalive(end, i);
2008
2009                 if (is_Phi(ka) && irn_not_visited(ka))
2010                         dfs(ka, env);
2011         }
2012         current_ir_graph = rem;
2013 }  /* do_dfs */
2014
2015 /**
2016  * Initialize new phase data. We do this always explicit, so return NULL here
2017  */
2018 static void *init_loop_data(ir_phase *ph, const ir_node *irn, void *data) {
2019         (void)ph;
2020         (void)irn;
2021         (void)data;
2022         return NULL;
2023 }  /* init_loop_data */
2024
2025 /**
2026  * Optimize Loads/Stores in loops.
2027  *
2028  * @param irg  the graph
2029  */
2030 static int optimize_loops(ir_graph *irg) {
2031         loop_env env;
2032
2033         env.stack         = NEW_ARR_F(ir_node *, 128);
2034         env.tos           = 0;
2035         env.nextDFSnum    = 0;
2036         env.POnum         = 0;
2037         env.changes       = 0;
2038         phase_init(&env.ph, "ldstopt", irg, PHASE_DEFAULT_GROWTH, init_loop_data, NULL);
2039
2040         /* calculate the SCC's and drive loop optimization. */
2041         do_dfs(irg, &env);
2042
2043         DEL_ARR_F(env.stack);
2044         phase_free(&env.ph);
2045
2046         return env.changes;
2047 }  /* optimize_loops */
2048
2049 /*
2050  * do the load store optimization
2051  */
2052 void optimize_load_store(ir_graph *irg) {
2053         walk_env_t env;
2054
2055         FIRM_DBG_REGISTER(dbg, "firm.opt.ldstopt");
2056
2057         assert(get_irg_phase_state(irg) != phase_building);
2058         assert(get_irg_pinned(irg) != op_pin_state_floats &&
2059                 "LoadStore optimization needs pinned graph");
2060
2061         /* we need landing pads */
2062         remove_critical_cf_edges(irg);
2063
2064         edges_assure(irg);
2065
2066         /* for Phi optimization post-dominators are needed ... */
2067         assure_postdoms(irg);
2068
2069         if (get_opt_alias_analysis()) {
2070                 assure_irg_address_taken_computed(irg);
2071                 assure_irp_globals_address_taken_computed();
2072         }
2073
2074         obstack_init(&env.obst);
2075         env.changes = 0;
2076
2077         /* init the links, then collect Loads/Stores/Proj's in lists */
2078         master_visited = 0;
2079         irg_walk_graph(irg, firm_clear_link, collect_nodes, &env);
2080
2081         /* now we have collected enough information, optimize */
2082         irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
2083
2084         env.changes |= optimize_loops(irg);
2085
2086         obstack_free(&env.obst, NULL);
2087
2088         /* Handle graph state */
2089         if (env.changes) {
2090                 set_irg_outs_inconsistent(irg);
2091         }
2092
2093         if (env.changes & CF_CHANGED) {
2094                 /* is this really needed: Yes, control flow changed, block might
2095                 have Bad() predecessors. */
2096                 set_irg_doms_inconsistent(irg);
2097         }
2098 }  /* optimize_load_store */