cleanup: Remove pointless assert(is_${NODE}(x)) just before get_${NODE}_${FOO}(x...
[libfirm] / ir / opt / ldstopt.c
1 /*
2  * Copyright (C) 1995-2011 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  */
25 #include "config.h"
26
27 #include <string.h>
28
29 #include "iroptimize.h"
30 #include "irnode_t.h"
31 #include "irgraph_t.h"
32 #include "irmode_t.h"
33 #include "iropt_t.h"
34 #include "ircons_t.h"
35 #include "irgmod.h"
36 #include "irgwalk.h"
37 #include "irtools.h"
38 #include "tv_t.h"
39 #include "dbginfo_t.h"
40 #include "iropt_dbg.h"
41 #include "irflag_t.h"
42 #include "array_t.h"
43 #include "irhooks.h"
44 #include "iredges.h"
45 #include "irpass.h"
46 #include "irmemory.h"
47 #include "irnodehashmap.h"
48 #include "irgopt.h"
49 #include "set.h"
50 #include "be.h"
51 #include "debug.h"
52
53 /** The debug handle. */
54 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
55
56 #undef IMAX
57 #define IMAX(a,b)   ((a) > (b) ? (a) : (b))
58
59 #define MAX_PROJ    IMAX(IMAX((long)pn_Load_max, (long)pn_Store_max), (long)pn_Call_max)
60
61 enum changes_t {
62         DF_CHANGED = 1,       /**< data flow changed */
63         CF_CHANGED = 2,       /**< control flow changed */
64 };
65
66 /**
67  * walker environment
68  */
69 typedef struct walk_env_t {
70         struct obstack obst;          /**< list of all stores */
71         unsigned changes;             /**< a bitmask of graph changes */
72 } walk_env_t;
73
74 /** A Load/Store info. */
75 typedef struct ldst_info_t {
76         ir_node  *projs[MAX_PROJ+1];  /**< list of Proj's of this node */
77         ir_node  *exc_block;          /**< the exception block if available */
78         int      exc_idx;             /**< predecessor index in the exception block */
79         unsigned visited;             /**< visited counter for breaking loops */
80 } ldst_info_t;
81
82 /**
83  * flags for control flow.
84  */
85 enum block_flags_t {
86         BLOCK_HAS_COND = 1,      /**< Block has conditional control flow */
87         BLOCK_HAS_EXC  = 2       /**< Block has exceptional control flow */
88 };
89
90 /**
91  * a Block info.
92  */
93 typedef struct block_info_t {
94         unsigned flags;               /**< flags for the block */
95 } block_info_t;
96
97 /** the master visited flag for loop detection. */
98 static unsigned master_visited = 0;
99
100 #define INC_MASTER()       ++master_visited
101 #define MARK_NODE(info)    (info)->visited = master_visited
102 #define NODE_VISITED(info) (info)->visited >= master_visited
103
104 /**
105  * get the Load/Store info of a node
106  */
107 static ldst_info_t *get_ldst_info(ir_node *node, struct obstack *obst)
108 {
109         ldst_info_t *info = (ldst_info_t*)get_irn_link(node);
110
111         if (! info) {
112                 info = OALLOCZ(obst, ldst_info_t);
113                 set_irn_link(node, info);
114         }
115         return info;
116 }
117
118 /**
119  * get the Block info of a node
120  */
121 static block_info_t *get_block_info(ir_node *node, struct obstack *obst)
122 {
123         block_info_t *info = (block_info_t*)get_irn_link(node);
124
125         if (! info) {
126                 info = OALLOCZ(obst, block_info_t);
127                 set_irn_link(node, info);
128         }
129         return info;
130 }
131
132 /**
133  * update the projection info for a Load/Store
134  */
135 static unsigned update_projs(ldst_info_t *info, ir_node *proj)
136 {
137         long nr = get_Proj_proj(proj);
138
139         assert(0 <= nr && nr <= MAX_PROJ && "Wrong proj from LoadStore");
140
141         if (info->projs[nr]) {
142                 /* there is already one, do CSE */
143                 exchange(proj, info->projs[nr]);
144                 return DF_CHANGED;
145         }
146         else {
147                 info->projs[nr] = proj;
148                 return 0;
149         }
150 }
151
152 /**
153  * update the exception block info for a Load/Store node.
154  *
155  * @param info   the load/store info struct
156  * @param block  the exception handler block for this load/store
157  * @param pos    the control flow input of the block
158  */
159 static unsigned update_exc(ldst_info_t *info, ir_node *block, int pos)
160 {
161         assert(info->exc_block == NULL && "more than one exception block found");
162
163         info->exc_block = block;
164         info->exc_idx   = pos;
165         return 0;
166 }
167
168 /**
169  * walker, collects all Load/Store/Proj nodes
170  *
171  * walks from Start -> End
172  */
173 static void collect_nodes(ir_node *node, void *env)
174 {
175         walk_env_t  *wenv   = (walk_env_t *)env;
176         unsigned     opcode = get_irn_opcode(node);
177         ir_node     *pred, *blk, *pred_blk;
178         ldst_info_t *ldst_info;
179
180         if (opcode == iro_Proj) {
181                 pred   = get_Proj_pred(node);
182                 opcode = get_irn_opcode(pred);
183
184                 if (opcode == iro_Load || opcode == iro_Store || opcode == iro_Call) {
185                         ldst_info = get_ldst_info(pred, &wenv->obst);
186
187                         wenv->changes |= update_projs(ldst_info, node);
188
189                         /*
190                          * Place the Proj's to the same block as the
191                          * predecessor Load. This is always ok and prevents
192                          * "non-SSA" form after optimizations if the Proj
193                          * is in a wrong block.
194                          */
195                         blk      = get_nodes_block(node);
196                         pred_blk = get_nodes_block(pred);
197                         if (blk != pred_blk) {
198                                 wenv->changes |= DF_CHANGED;
199                                 set_nodes_block(node, pred_blk);
200                         }
201                 }
202         } else if (opcode == iro_Block) {
203                 int i;
204
205                 for (i = get_Block_n_cfgpreds(node) - 1; i >= 0; --i) {
206                         ir_node      *pred_block, *proj;
207                         block_info_t *bl_info;
208                         int          is_exc = 0;
209
210                         pred = proj = get_Block_cfgpred(node, i);
211
212                         if (is_Proj(proj)) {
213                                 pred   = get_Proj_pred(proj);
214                                 is_exc = is_x_except_Proj(proj);
215                         }
216
217                         /* ignore Bad predecessors, they will be removed later */
218                         if (is_Bad(pred))
219                                 continue;
220
221                         pred_block = get_nodes_block(pred);
222                         bl_info    = get_block_info(pred_block, &wenv->obst);
223
224                         if (is_fragile_op(pred) && is_exc)
225                                 bl_info->flags |= BLOCK_HAS_EXC;
226                         else if (is_irn_forking(pred))
227                                 bl_info->flags |= BLOCK_HAS_COND;
228
229                         opcode = get_irn_opcode(pred);
230                         if (is_exc && (opcode == iro_Load || opcode == iro_Store || opcode == iro_Call)) {
231                                 ldst_info = get_ldst_info(pred, &wenv->obst);
232
233                                 wenv->changes |= update_exc(ldst_info, node, i);
234                         }
235                 }
236         }
237 }
238
239 /**
240  * Returns an entity if the address ptr points to a constant one.
241  *
242  * @param ptr  the address
243  *
244  * @return an entity or NULL
245  */
246 static ir_entity *find_constant_entity(ir_node *ptr)
247 {
248         for (;;) {
249                 if (is_SymConst(ptr) && get_SymConst_kind(ptr) == symconst_addr_ent) {
250                         return get_SymConst_entity(ptr);
251                 } else if (is_Sel(ptr)) {
252                         ir_entity *ent = get_Sel_entity(ptr);
253                         ir_type   *tp  = get_entity_owner(ent);
254
255                         /* Do not fiddle with polymorphism. */
256                         if (is_Class_type(get_entity_owner(ent)) &&
257                                 ((get_entity_n_overwrites(ent)    != 0) ||
258                                 (get_entity_n_overwrittenby(ent) != 0)   ) )
259                                 return NULL;
260
261                         if (is_Array_type(tp)) {
262                                 /* check bounds */
263                                 int i, n;
264
265                                 for (i = 0, n = get_Sel_n_indexs(ptr); i < n; ++i) {
266                                         ir_node   *bound;
267                                         ir_tarval *tlower, *tupper;
268                                         ir_node   *index = get_Sel_index(ptr, i);
269                                         ir_tarval *tv    = computed_value(index);
270
271                                         /* check if the index is constant */
272                                         if (tv == tarval_bad)
273                                                 return NULL;
274
275                                         bound  = get_array_lower_bound(tp, i);
276                                         tlower = computed_value(bound);
277                                         bound  = get_array_upper_bound(tp, i);
278                                         tupper = computed_value(bound);
279
280                                         if (tlower == tarval_bad || tupper == tarval_bad)
281                                                 return NULL;
282
283                                         if (tarval_cmp(tv, tlower) == ir_relation_less)
284                                                 return NULL;
285                                         if (tarval_cmp(tupper, tv) == ir_relation_less)
286                                                 return NULL;
287
288                                         /* ok, bounds check finished */
289                                 }
290                         }
291
292                         if (get_entity_linkage(ent) & IR_LINKAGE_CONSTANT)
293                                 return ent;
294
295                         /* try next */
296                         ptr = get_Sel_ptr(ptr);
297                 } else if (is_Add(ptr)) {
298                         ir_node *l = get_Add_left(ptr);
299                         ir_node *r = get_Add_right(ptr);
300
301                         if (get_irn_mode(l) == get_irn_mode(ptr) && is_Const(r))
302                                 ptr = l;
303                         else if (get_irn_mode(r) == get_irn_mode(ptr) && is_Const(l))
304                                 ptr = r;
305                         else
306                                 return NULL;
307
308                         /* for now, we support only one addition, reassoc should fold all others */
309                         if (! is_SymConst(ptr) && !is_Sel(ptr))
310                                 return NULL;
311                 } else if (is_Sub(ptr)) {
312                         ir_node *l = get_Sub_left(ptr);
313                         ir_node *r = get_Sub_right(ptr);
314
315                         if (get_irn_mode(l) == get_irn_mode(ptr) && is_Const(r))
316                                 ptr = l;
317                         else
318                                 return NULL;
319                         /* for now, we support only one substraction, reassoc should fold all others */
320                         if (! is_SymConst(ptr) && !is_Sel(ptr))
321                                 return NULL;
322                 } else
323                         return NULL;
324         }
325 }
326
327 /**
328  * Return the Selection index of a Sel node from dimension n
329  */
330 static long get_Sel_array_index_long(ir_node *n, int dim)
331 {
332         ir_node *index = get_Sel_index(n, dim);
333         return get_tarval_long(get_Const_tarval(index));
334 }
335
336 typedef struct path_entry {
337         ir_entity         *ent;
338         struct path_entry *next;
339         size_t            index;
340 } path_entry;
341
342 static ir_node *rec_find_compound_ent_value(ir_node *ptr, path_entry *next)
343 {
344         path_entry       entry, *p;
345         ir_entity        *ent, *field;
346         ir_initializer_t *initializer;
347         ir_tarval        *tv;
348         ir_type          *tp;
349         size_t           n;
350
351         entry.next = next;
352         if (is_SymConst(ptr)) {
353                 /* found the root */
354                 ent         = get_SymConst_entity(ptr);
355                 initializer = get_entity_initializer(ent);
356                 for (p = next; p != NULL;) {
357                         if (initializer->kind != IR_INITIALIZER_COMPOUND)
358                                 return NULL;
359                         n  = get_initializer_compound_n_entries(initializer);
360                         tp = get_entity_type(ent);
361
362                         if (is_Array_type(tp)) {
363                                 ent = get_array_element_entity(tp);
364                                 if (ent != p->ent) {
365                                         /* a missing [0] */
366                                         if (0 >= n)
367                                                 return NULL;
368                                         initializer = get_initializer_compound_value(initializer, 0);
369                                         continue;
370                                 }
371                         }
372                         if (p->index >= n)
373                                 return NULL;
374                         initializer = get_initializer_compound_value(initializer, p->index);
375
376                         ent = p->ent;
377                         p   = p->next;
378                 }
379                 tp = get_entity_type(ent);
380                 while (is_Array_type(tp)) {
381                         ent = get_array_element_entity(tp);
382                         tp = get_entity_type(ent);
383                         /* a missing [0] */
384                         n  = get_initializer_compound_n_entries(initializer);
385                         if (0 >= n)
386                                 return NULL;
387                         initializer = get_initializer_compound_value(initializer, 0);
388                 }
389
390                 switch (initializer->kind) {
391                 case IR_INITIALIZER_CONST:
392                         return get_initializer_const_value(initializer);
393                 case IR_INITIALIZER_TARVAL:
394                 case IR_INITIALIZER_NULL:
395                 default:
396                         return NULL;
397                 }
398         } else if (is_Sel(ptr)) {
399                 entry.ent = field = get_Sel_entity(ptr);
400                 tp = get_entity_owner(field);
401                 if (is_Array_type(tp)) {
402                         assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
403                         entry.index = get_Sel_array_index_long(ptr, 0) - get_array_lower_bound_int(tp, 0);
404                 } else {
405                         size_t i, n_members = get_compound_n_members(tp);
406                         for (i = 0; i < n_members; ++i) {
407                                 if (get_compound_member(tp, i) == field)
408                                         break;
409                         }
410                         if (i >= n_members) {
411                                 /* not found: should NOT happen */
412                                 return NULL;
413                         }
414                         entry.index = i;
415                 }
416                 return rec_find_compound_ent_value(get_Sel_ptr(ptr), &entry);
417         }  else if (is_Add(ptr)) {
418                 ir_mode  *mode;
419                 unsigned pos;
420
421                 {
422                         ir_node *l = get_Add_left(ptr);
423                         ir_node *r = get_Add_right(ptr);
424                         if (is_Const(r)) {
425                                 ptr = l;
426                                 tv  = get_Const_tarval(r);
427                         } else {
428                                 ptr = r;
429                                 tv  = get_Const_tarval(l);
430                         }
431                 }
432 ptr_arith:
433                 mode = get_tarval_mode(tv);
434
435                 /* ptr must be a Sel or a SymConst, this was checked in find_constant_entity() */
436                 if (is_Sel(ptr)) {
437                         field = get_Sel_entity(ptr);
438                 } else {
439                         field = get_SymConst_entity(ptr);
440                 }
441
442                 /* count needed entries */
443                 pos = 0;
444                 for (ent = field;;) {
445                         tp = get_entity_type(ent);
446                         if (! is_Array_type(tp))
447                                 break;
448                         ent = get_array_element_entity(tp);
449                         ++pos;
450                 }
451                 /* should be at least ONE entry */
452                 if (pos == 0)
453                         return NULL;
454
455                 /* allocate the right number of entries */
456                 NEW_ARR_A(path_entry, p, pos);
457
458                 /* fill them up */
459                 pos = 0;
460                 for (ent = field;;) {
461                         unsigned   size;
462                         ir_tarval *sz, *tv_index, *tlower, *tupper;
463                         long       index;
464                         ir_node   *bound;
465
466                         tp = get_entity_type(ent);
467                         if (! is_Array_type(tp))
468                                 break;
469                         ent = get_array_element_entity(tp);
470                         p[pos].ent  = ent;
471                         p[pos].next = &p[pos + 1];
472
473                         size = get_type_size_bytes(get_entity_type(ent));
474                         sz   = new_tarval_from_long(size, mode);
475
476                         tv_index = tarval_div(tv, sz);
477                         tv       = tarval_mod(tv, sz);
478
479                         if (tv_index == tarval_bad || tv == tarval_bad)
480                                 return NULL;
481
482                         assert(get_array_n_dimensions(tp) == 1 && "multiarrays not implemented");
483                         bound  = get_array_lower_bound(tp, 0);
484                         tlower = computed_value(bound);
485                         bound  = get_array_upper_bound(tp, 0);
486                         tupper = computed_value(bound);
487
488                         if (tlower == tarval_bad || tupper == tarval_bad)
489                                 return NULL;
490
491                         if (tarval_cmp(tv_index, tlower) == ir_relation_less)
492                                 return NULL;
493                         if (tarval_cmp(tupper, tv_index) == ir_relation_less)
494                                 return NULL;
495
496                         /* ok, bounds check finished */
497                         index = get_tarval_long(tv_index);
498                         p[pos].index = index;
499                         ++pos;
500                 }
501                 if (! tarval_is_null(tv)) {
502                         /* hmm, wrong access */
503                         return NULL;
504                 }
505                 p[pos - 1].next = next;
506                 return rec_find_compound_ent_value(ptr, p);
507         } else if (is_Sub(ptr)) {
508                 ir_node *l = get_Sub_left(ptr);
509                 ir_node *r = get_Sub_right(ptr);
510
511                 ptr = l;
512                 tv  = get_Const_tarval(r);
513                 tv  = tarval_neg(tv);
514                 goto ptr_arith;
515         }
516         return NULL;
517 }
518
519 static ir_node *find_compound_ent_value(ir_node *ptr)
520 {
521         return rec_find_compound_ent_value(ptr, NULL);
522 }
523
524 /* forward */
525 static void reduce_adr_usage(ir_node *ptr);
526
527 /**
528  * Update a Load that may have lost its users.
529  */
530 static void handle_load_update(ir_node *load)
531 {
532         ldst_info_t *info = (ldst_info_t*)get_irn_link(load);
533
534         /* do NOT touch volatile loads for now */
535         if (get_Load_volatility(load) == volatility_is_volatile)
536                 return;
537
538         if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
539                 ir_node *ptr = get_Load_ptr(load);
540                 ir_node *mem = get_Load_mem(load);
541
542                 /* a Load whose value is neither used nor exception checked, remove it */
543                 exchange(info->projs[pn_Load_M], mem);
544                 if (info->projs[pn_Load_X_regular])
545                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
546                 kill_node(load);
547                 reduce_adr_usage(ptr);
548         }
549 }
550
551 /**
552  * A use of an address node has vanished. Check if this was a Proj
553  * node and update the counters.
554  */
555 static void reduce_adr_usage(ir_node *ptr)
556 {
557         ir_node *pred;
558         if (!is_Proj(ptr))
559                 return;
560         if (get_irn_n_edges(ptr) > 0)
561                 return;
562
563         /* this Proj is dead now */
564         pred = get_Proj_pred(ptr);
565         if (is_Load(pred)) {
566                 ldst_info_t *info = (ldst_info_t*)get_irn_link(pred);
567                 info->projs[get_Proj_proj(ptr)] = NULL;
568
569                 /* this node lost its result proj, handle that */
570                 handle_load_update(pred);
571         }
572 }
573
574 /**
575  * Check, if an already existing value of mode old_mode can be converted
576  * into the needed one new_mode without loss.
577  */
578 static int can_use_stored_value(ir_mode *old_mode, ir_mode *new_mode)
579 {
580         unsigned old_size;
581         unsigned new_size;
582         if (old_mode == new_mode)
583                 return true;
584
585         old_size = get_mode_size_bits(old_mode);
586         new_size = get_mode_size_bits(new_mode);
587
588         /* if both modes are two-complement ones, we can always convert the
589            Stored value into the needed one. (on big endian machines we currently
590            only support this for modes of same size) */
591         if (old_size >= new_size &&
592                   get_mode_arithmetic(old_mode) == irma_twos_complement &&
593                   get_mode_arithmetic(new_mode) == irma_twos_complement &&
594                   (!be_get_backend_param()->byte_order_big_endian
595                 || old_size == new_size)) {
596                 return true;
597         }
598         return false;
599 }
600
601 /**
602  * Check whether a Call is at least pure, i.e. does only read memory.
603  */
604 static unsigned is_Call_pure(ir_node *call)
605 {
606         ir_type *call_tp = get_Call_type(call);
607         unsigned prop = get_method_additional_properties(call_tp);
608
609         /* check first the call type */
610         if ((prop & (mtp_property_const|mtp_property_pure)) == 0) {
611                 /* try the called entity */
612                 ir_node *ptr = get_Call_ptr(call);
613
614                 if (is_SymConst_addr_ent(ptr)) {
615                         ir_entity *ent = get_SymConst_entity(ptr);
616
617                         prop = get_entity_additional_properties(ent);
618                 }
619         }
620         return (prop & (mtp_property_const|mtp_property_pure)) != 0;
621 }
622
623 static ir_node *get_base_and_offset(ir_node *ptr, long *pOffset)
624 {
625         ir_mode *mode  = get_irn_mode(ptr);
626         long    offset = 0;
627
628         /* TODO: long might not be enough, we should probably use some tarval thingy... */
629         for (;;) {
630                 if (is_Add(ptr)) {
631                         ir_node *l = get_Add_left(ptr);
632                         ir_node *r = get_Add_right(ptr);
633
634                         if (get_irn_mode(l) != mode || !is_Const(r))
635                                 break;
636
637                         offset += get_tarval_long(get_Const_tarval(r));
638                         ptr     = l;
639                 } else if (is_Sub(ptr)) {
640                         ir_node *l = get_Sub_left(ptr);
641                         ir_node *r = get_Sub_right(ptr);
642
643                         if (get_irn_mode(l) != mode || !is_Const(r))
644                                 break;
645
646                         offset -= get_tarval_long(get_Const_tarval(r));
647                         ptr     = l;
648                 } else if (is_Sel(ptr)) {
649                         ir_entity *ent = get_Sel_entity(ptr);
650                         ir_type   *tp  = get_entity_owner(ent);
651
652                         if (is_Array_type(tp)) {
653                                 int     size;
654                                 ir_node *index;
655
656                                 /* only one dimensional arrays yet */
657                                 if (get_Sel_n_indexs(ptr) != 1)
658                                         break;
659                                 index = get_Sel_index(ptr, 0);
660                                 if (! is_Const(index))
661                                         break;
662
663                                 tp = get_entity_type(ent);
664                                 if (get_type_state(tp) != layout_fixed)
665                                         break;
666
667                                 size    = get_type_size_bytes(tp);
668                                 offset += size * get_tarval_long(get_Const_tarval(index));
669                         } else {
670                                 if (get_type_state(tp) != layout_fixed)
671                                         break;
672                                 offset += get_entity_offset(ent);
673                         }
674                         ptr = get_Sel_ptr(ptr);
675                 } else
676                         break;
677         }
678
679         *pOffset = offset;
680         return ptr;
681 }
682
683 static int try_load_after_store(ir_node *load,
684                 ir_node *load_base_ptr, long load_offset, ir_node *store)
685 {
686         ldst_info_t *info;
687         ir_node *store_ptr      = get_Store_ptr(store);
688         long     store_offset;
689         ir_node *store_base_ptr = get_base_and_offset(store_ptr, &store_offset);
690         ir_node *store_value;
691         ir_mode *store_mode;
692         ir_node *load_ptr;
693         ir_mode *load_mode;
694         long     load_mode_len;
695         long     store_mode_len;
696         long     delta;
697         int      res;
698
699         if (load_base_ptr != store_base_ptr)
700                 return 0;
701
702         load_mode      = get_Load_mode(load);
703         load_mode_len  = get_mode_size_bytes(load_mode);
704         store_mode     = get_irn_mode(get_Store_value(store));
705         store_mode_len = get_mode_size_bytes(store_mode);
706         delta          = load_offset - store_offset;
707         store_value    = get_Store_value(store);
708
709         if (delta < 0 || delta+load_mode_len > store_mode_len)
710                 return 0;
711
712         if (store_mode != load_mode &&
713             get_mode_arithmetic(store_mode) == irma_twos_complement &&
714             get_mode_arithmetic(load_mode)  == irma_twos_complement) {
715
716                 /* produce a shift to adjust offset delta */
717                 unsigned const shift = be_get_backend_param()->byte_order_big_endian
718                         ? store_mode_len - load_mode_len - delta
719                         : delta;
720                 if (shift != 0) {
721                         ir_graph *const irg  = get_irn_irg(load);
722                         ir_node  *const cnst = new_r_Const_long(irg, mode_Iu, shift * 8);
723                         store_value = new_r_Shr(get_nodes_block(load),
724                                                                         store_value, cnst, store_mode);
725                 }
726
727                 store_value = new_r_Conv(get_nodes_block(load), store_value, load_mode);
728         } else {
729                 /* we would need some kind of bitcast node here */
730                 return 0;
731         }
732
733         DBG_OPT_RAW(load, store_value);
734
735         info = (ldst_info_t*)get_irn_link(load);
736         if (info->projs[pn_Load_M])
737                 exchange(info->projs[pn_Load_M], get_Load_mem(load));
738
739         res = 0;
740         /* no exception */
741         if (info->projs[pn_Load_X_except]) {
742                 ir_graph *irg = get_irn_irg(load);
743                 exchange( info->projs[pn_Load_X_except], new_r_Bad(irg, mode_X));
744                 res |= CF_CHANGED;
745         }
746         if (info->projs[pn_Load_X_regular]) {
747                 exchange( info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
748                 res |= CF_CHANGED;
749         }
750
751         if (info->projs[pn_Load_res])
752                 exchange(info->projs[pn_Load_res], store_value);
753
754         load_ptr = get_Load_ptr(load);
755         kill_node(load);
756         reduce_adr_usage(load_ptr);
757         return res | DF_CHANGED;
758 }
759
760 /**
761  * Follow the memory chain as long as there are only Loads,
762  * alias free Stores, and constant Calls and try to replace the
763  * current Load by a previous ones.
764  * Note that in unreachable loops it might happen that we reach
765  * load again, as well as we can fall into a cycle.
766  * We break such cycles using a special visited flag.
767  *
768  * INC_MASTER() must be called before dive into
769  */
770 static unsigned follow_Mem_chain(ir_node *load, ir_node *curr)
771 {
772         unsigned    res = 0;
773         ldst_info_t *info = (ldst_info_t*)get_irn_link(load);
774         ir_node     *pred;
775         ir_node     *ptr       = get_Load_ptr(load);
776         ir_node     *mem       = get_Load_mem(load);
777         ir_mode     *load_mode = get_Load_mode(load);
778
779         for (pred = curr; load != pred; ) {
780                 ldst_info_t *pred_info = (ldst_info_t*)get_irn_link(pred);
781
782                 /*
783                  * a Load immediately after a Store -- a read after write.
784                  * We may remove the Load, if both Load & Store does not have an
785                  * exception handler OR they are in the same Block. In the latter
786                  * case the Load cannot throw an exception when the previous Store was
787                  * quiet.
788                  *
789                  * Why we need to check for Store Exception? If the Store cannot
790                  * be executed (ROM) the exception handler might simply jump into
791                  * the load Block :-(
792                  * We could make it a little bit better if we would know that the
793                  * exception handler of the Store jumps directly to the end...
794                  */
795                 if (is_Store(pred) && ((pred_info->projs[pn_Store_X_except] == NULL
796                                 && info->projs[pn_Load_X_except] == NULL)
797                                 || get_nodes_block(load) == get_nodes_block(pred)))
798                 {
799                         long    load_offset;
800                         ir_node *base_ptr = get_base_and_offset(ptr, &load_offset);
801                         int     changes   = try_load_after_store(load, base_ptr, load_offset, pred);
802
803                         if (changes != 0)
804                                 return res | changes;
805                 } else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
806                            can_use_stored_value(get_Load_mode(pred), load_mode)) {
807                         /*
808                          * a Load after a Load -- a read after read.
809                          * We may remove the second Load, if it does not have an exception
810                          * handler OR they are in the same Block. In the later case
811                          * the Load cannot throw an exception when the previous Load was
812                          * quiet.
813                          *
814                          * Here, there is no need to check if the previous Load has an
815                          * exception hander because they would have exact the same
816                          * exception...
817                          *
818                          * TODO: implement load-after-load with different mode for big
819                          *       endian
820                          */
821                         if (info->projs[pn_Load_X_except] == NULL
822                                         || get_nodes_block(load) == get_nodes_block(pred)) {
823                                 ir_node *value;
824
825                                 DBG_OPT_RAR(load, pred);
826
827                                 /* the result is used */
828                                 if (info->projs[pn_Load_res]) {
829                                         if (pred_info->projs[pn_Load_res] == NULL) {
830                                                 /* create a new Proj again */
831                                                 pred_info->projs[pn_Load_res] = new_r_Proj(pred, get_Load_mode(pred), pn_Load_res);
832                                         }
833                                         value = pred_info->projs[pn_Load_res];
834
835                                         /* add an convert if needed */
836                                         if (get_Load_mode(pred) != load_mode) {
837                                                 value = new_r_Conv(get_nodes_block(load), value, load_mode);
838                                         }
839
840                                         exchange(info->projs[pn_Load_res], value);
841                                 }
842
843                                 if (info->projs[pn_Load_M])
844                                         exchange(info->projs[pn_Load_M], mem);
845
846                                 /* no exception */
847                                 if (info->projs[pn_Load_X_except]) {
848                                         ir_graph *irg = get_irn_irg(load);
849                                         exchange(info->projs[pn_Load_X_except], new_r_Bad(irg, mode_X));
850                                         res |= CF_CHANGED;
851                                 }
852                                 if (info->projs[pn_Load_X_regular]) {
853                                         exchange( info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
854                                         res |= CF_CHANGED;
855                                 }
856
857                                 kill_node(load);
858                                 reduce_adr_usage(ptr);
859                                 return res |= DF_CHANGED;
860                         }
861                 }
862
863                 if (is_Store(pred)) {
864                         /* check if we can pass through this store */
865                         ir_alias_relation rel = get_alias_relation(
866                                 get_Store_ptr(pred),
867                                 get_irn_mode(get_Store_value(pred)),
868                                 ptr, load_mode);
869                         /* if the might be an alias, we cannot pass this Store */
870                         if (rel != ir_no_alias)
871                                 break;
872                         pred = skip_Proj(get_Store_mem(pred));
873                 } else if (is_Load(pred)) {
874                         pred = skip_Proj(get_Load_mem(pred));
875                 } else if (is_Call(pred)) {
876                         if (is_Call_pure(pred)) {
877                                 /* The called graph is at least pure, so there are no Store's
878                                    in it. We can handle it like a Load and skip it. */
879                                 pred = skip_Proj(get_Call_mem(pred));
880                         } else {
881                                 /* there might be Store's in the graph, stop here */
882                                 break;
883                         }
884                 } else {
885                         /* follow only Load chains */
886                         break;
887                 }
888
889                 /* check for cycles */
890                 if (NODE_VISITED(pred_info))
891                         break;
892                 MARK_NODE(pred_info);
893         }
894
895         if (is_Sync(pred)) {
896                 int i;
897
898                 /* handle all Sync predecessors */
899                 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
900                         res |= follow_Mem_chain(load, skip_Proj(get_Sync_pred(pred, i)));
901                         if (res)
902                                 return res;
903                 }
904         }
905
906         return res;
907 }
908
909 ir_node *can_replace_load_by_const(const ir_node *load, ir_node *c)
910 {
911         ir_mode  *c_mode = get_irn_mode(c);
912         ir_mode  *l_mode = get_Load_mode(load);
913         ir_node  *block  = get_nodes_block(load);
914         dbg_info *dbgi   = get_irn_dbg_info(load);
915         ir_node  *res    = copy_const_value(dbgi, c, block);
916
917         if (c_mode != l_mode) {
918                 /* check, if the mode matches OR can be easily converted info */
919                 if (is_reinterpret_cast(c_mode, l_mode)) {
920                         /* copy the value from the const code irg and cast it */
921                         res = new_rd_Conv(dbgi, block, res, l_mode);
922                 } else {
923                         return NULL;
924                 }
925         }
926         return res;
927 }
928
929 /**
930  * optimize a Load
931  *
932  * @param load  the Load node
933  */
934 static unsigned optimize_load(ir_node *load)
935 {
936         ldst_info_t *info = (ldst_info_t*)get_irn_link(load);
937         ir_node     *mem, *ptr, *value;
938         ir_entity   *ent;
939         long        dummy;
940         unsigned    res = 0;
941
942         /* do NOT touch volatile loads for now */
943         if (get_Load_volatility(load) == volatility_is_volatile)
944                 return 0;
945
946         /* the address of the load to be optimized */
947         ptr = get_Load_ptr(load);
948
949         /* The mem of the Load. Must still be returned after optimization. */
950         mem = get_Load_mem(load);
951
952         if (info->projs[pn_Load_res] == NULL
953                         && info->projs[pn_Load_X_except] == NULL) {
954                 /* the value is never used and we don't care about exceptions, remove */
955                 exchange(info->projs[pn_Load_M], mem);
956
957                 if (info->projs[pn_Load_X_regular]) {
958                         /* should not happen, but if it does, remove it */
959                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
960                         res |= CF_CHANGED;
961                 }
962                 kill_node(load);
963                 reduce_adr_usage(ptr);
964                 return res | DF_CHANGED;
965         }
966
967         value = NULL;
968         /* check if we can determine the entity that will be loaded */
969         ent = find_constant_entity(ptr);
970         if (ent != NULL
971                         && get_entity_visibility(ent) != ir_visibility_external) {
972                 /* a static allocation that is not external: there should be NO
973                  * exception when loading even if we cannot replace the load itself.
974                  */
975
976                 /* no exception, clear the info field as it might be checked later again */
977                 if (info->projs[pn_Load_X_except]) {
978                         ir_graph *irg = get_irn_irg(load);
979                         exchange(info->projs[pn_Load_X_except], new_r_Bad(irg, mode_X));
980                         info->projs[pn_Load_X_except] = NULL;
981                         res |= CF_CHANGED;
982                 }
983                 if (info->projs[pn_Load_X_regular]) {
984                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
985                         info->projs[pn_Load_X_regular] = NULL;
986                         res |= CF_CHANGED;
987                 }
988
989                 if (get_entity_linkage(ent) & IR_LINKAGE_CONSTANT) {
990                         if (has_entity_initializer(ent)) {
991                                 /* new style initializer */
992                                 value = find_compound_ent_value(ptr);
993                         }
994                         if (value != NULL) {
995                                 ir_graph *irg = get_irn_irg(load);
996                                 value = can_replace_load_by_const(load, value);
997                                 if (value != NULL && is_Sel(ptr)) {
998                                         /* frontend has inserted masking operations after bitfield accesses,
999                                          * so we might have to shift the const. */
1000                                         unsigned char bit_offset = get_entity_offset_bits_remainder(get_Sel_entity(ptr));
1001                                         if (bit_offset != 0) {
1002                                                 if (is_Const(value)) {
1003                                                         ir_tarval *tv_old = get_Const_tarval(value);
1004                                                         ir_tarval *tv_offset = new_tarval_from_long(bit_offset, mode_Bu);
1005                                                         ir_tarval *tv_new = tarval_shl(tv_old, tv_offset);
1006                                                         value = new_r_Const(irg, tv_new);
1007                                                 } else {
1008                                                         value = NULL;
1009                                                 }
1010                                         }
1011                                 }
1012                         }
1013                 }
1014         }
1015         if (value != NULL) {
1016                 /* we completely replace the load by this value */
1017                 if (info->projs[pn_Load_X_except]) {
1018                         ir_graph *irg = get_irn_irg(load);
1019                         exchange(info->projs[pn_Load_X_except], new_r_Bad(irg, mode_X));
1020                         info->projs[pn_Load_X_except] = NULL;
1021                         res |= CF_CHANGED;
1022                 }
1023                 if (info->projs[pn_Load_X_regular]) {
1024                         exchange(info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
1025                         info->projs[pn_Load_X_regular] = NULL;
1026                         res |= CF_CHANGED;
1027                 }
1028                 if (info->projs[pn_Load_M]) {
1029                         exchange(info->projs[pn_Load_M], mem);
1030                         res |= DF_CHANGED;
1031                 }
1032                 if (info->projs[pn_Load_res]) {
1033                         exchange(info->projs[pn_Load_res], value);
1034                         res |= DF_CHANGED;
1035                 }
1036                 kill_node(load);
1037                 reduce_adr_usage(ptr);
1038                 return res;
1039         }
1040
1041         /* Check, if the address of this load is used more than once.
1042          * If not, more load cannot be removed in any case. */
1043         if (get_irn_n_edges(ptr) <= 1 && get_irn_n_edges(get_base_and_offset(ptr, &dummy)) <= 1)
1044                 return res;
1045
1046         /*
1047          * follow the memory chain as long as there are only Loads
1048          * and try to replace current Load or Store by a previous one.
1049          * Note that in unreachable loops it might happen that we reach
1050          * load again, as well as we can fall into a cycle.
1051          * We break such cycles using a special visited flag.
1052          */
1053         INC_MASTER();
1054         res = follow_Mem_chain(load, skip_Proj(mem));
1055         return res;
1056 }
1057
1058 /**
1059  * Check whether a value of mode new_mode would completely overwrite a value
1060  * of mode old_mode in memory.
1061  */
1062 static int is_completely_overwritten(ir_mode *old_mode, ir_mode *new_mode)
1063 {
1064         return get_mode_size_bits(new_mode) >= get_mode_size_bits(old_mode);
1065 }
1066
1067 /**
1068  * Check whether small is a part of large (starting at same address).
1069  */
1070 static int is_partially_same(ir_node *small, ir_node *large)
1071 {
1072         ir_mode *sm = get_irn_mode(small);
1073         ir_mode *lm = get_irn_mode(large);
1074
1075         /* FIXME: Check endianness */
1076         return is_Conv(small) && get_Conv_op(small) == large
1077             && get_mode_size_bytes(sm) < get_mode_size_bytes(lm)
1078             && get_mode_arithmetic(sm) == irma_twos_complement
1079             && get_mode_arithmetic(lm) == irma_twos_complement;
1080 }
1081
1082 /**
1083  * follow the memory chain as long as there are only Loads and alias free Stores.
1084  *
1085  * INC_MASTER() must be called before dive into
1086  */
1087 static unsigned follow_Mem_chain_for_Store(ir_node *store, ir_node *curr)
1088 {
1089         unsigned res = 0;
1090         ldst_info_t *info = (ldst_info_t*)get_irn_link(store);
1091         ir_node *pred;
1092         ir_node *ptr = get_Store_ptr(store);
1093         ir_node *mem = get_Store_mem(store);
1094         ir_node *value = get_Store_value(store);
1095         ir_mode *mode  = get_irn_mode(value);
1096         ir_node *block = get_nodes_block(store);
1097
1098         for (pred = curr; pred != store;) {
1099                 ldst_info_t *pred_info = (ldst_info_t*)get_irn_link(pred);
1100
1101                 /*
1102                  * BEWARE: one might think that checking the modes is useless, because
1103                  * if the pointers are identical, they refer to the same object.
1104                  * This is only true in strong typed languages, not is C were the following
1105                  * is possible *(ir_type1 *)p = a; *(ir_type2 *)p = b ...
1106                  * However, if the size of the mode that is written is bigger or equal the
1107                  * size of the old one, the old value is completely overwritten and can be
1108                  * killed ...
1109                  */
1110                 if (is_Store(pred) && get_Store_ptr(pred) == ptr &&
1111             get_nodes_block(pred) == block) {
1112                         /*
1113                          * a Store after a Store in the same Block -- a write after write.
1114                          */
1115
1116                         /*
1117                          * We may remove the first Store, if the old value is completely
1118                          * overwritten or the old value is a part of the new value,
1119                          * and if it does not have an exception handler.
1120                          *
1121                          * TODO: What, if both have the same exception handler ???
1122                          */
1123                         if (get_Store_volatility(pred) != volatility_is_volatile
1124                                 && !pred_info->projs[pn_Store_X_except]) {
1125                                 ir_node *predvalue = get_Store_value(pred);
1126                                 ir_mode *predmode  = get_irn_mode(predvalue);
1127
1128                                 if (is_completely_overwritten(predmode, mode)
1129                                         || is_partially_same(predvalue, value)) {
1130                                         DBG_OPT_WAW(pred, store);
1131                                         exchange(pred_info->projs[pn_Store_M], get_Store_mem(pred));
1132                                         kill_node(pred);
1133                                         reduce_adr_usage(ptr);
1134                                         return DF_CHANGED;
1135                                 }
1136                         }
1137
1138                         /*
1139                          * We may remove the Store, if the old value already contains
1140                          * the new value, and if it does not have an exception handler.
1141                          *
1142                          * TODO: What, if both have the same exception handler ???
1143                          */
1144                         if (get_Store_volatility(store) != volatility_is_volatile
1145                                 && !info->projs[pn_Store_X_except]) {
1146                                 ir_node *predvalue = get_Store_value(pred);
1147
1148                                 if (is_partially_same(value, predvalue)) {
1149                                         DBG_OPT_WAW(pred, store);
1150                                         exchange(info->projs[pn_Store_M], mem);
1151                                         kill_node(store);
1152                                         reduce_adr_usage(ptr);
1153                                         return DF_CHANGED;
1154                                 }
1155                         }
1156                 } else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
1157                            value == pred_info->projs[pn_Load_res]) {
1158                         /*
1159                          * a Store of a value just loaded from the same address
1160                          * -- a write after read.
1161                          * We may remove the Store, if it does not have an exception
1162                          * handler.
1163                          */
1164                         if (! info->projs[pn_Store_X_except]) {
1165                                 DBG_OPT_WAR(store, pred);
1166                                 exchange(info->projs[pn_Store_M], mem);
1167                                 kill_node(store);
1168                                 reduce_adr_usage(ptr);
1169                                 return DF_CHANGED;
1170                         }
1171                 }
1172
1173                 if (is_Store(pred)) {
1174                         /* check if we can pass through this store */
1175                         ir_alias_relation rel = get_alias_relation(
1176                                 get_Store_ptr(pred),
1177                                 get_irn_mode(get_Store_value(pred)),
1178                                 ptr, mode);
1179                         /* if the might be an alias, we cannot pass this Store */
1180                         if (rel != ir_no_alias)
1181                                 break;
1182                         pred = skip_Proj(get_Store_mem(pred));
1183                 } else if (is_Load(pred)) {
1184                         ir_alias_relation rel = get_alias_relation(
1185                                 get_Load_ptr(pred), get_Load_mode(pred),
1186                                 ptr, mode);
1187                         if (rel != ir_no_alias)
1188                                 break;
1189
1190                         pred = skip_Proj(get_Load_mem(pred));
1191                 } else {
1192                         /* follow only Load chains */
1193                         break;
1194                 }
1195
1196                 /* check for cycles */
1197                 if (NODE_VISITED(pred_info))
1198                         break;
1199                 MARK_NODE(pred_info);
1200         }
1201
1202         if (is_Sync(pred)) {
1203                 int i;
1204
1205                 /* handle all Sync predecessors */
1206                 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
1207                         res |= follow_Mem_chain_for_Store(store, skip_Proj(get_Sync_pred(pred, i)));
1208                         if (res)
1209                                 break;
1210                 }
1211         }
1212         return res;
1213 }
1214
1215 /** find entity used as base for an address calculation */
1216 static ir_entity *find_entity(ir_node *ptr)
1217 {
1218         switch (get_irn_opcode(ptr)) {
1219         case iro_SymConst:
1220                 return get_SymConst_entity(ptr);
1221         case iro_Sel: {
1222                 ir_node *pred = get_Sel_ptr(ptr);
1223                 if (get_irg_frame(get_irn_irg(ptr)) == pred)
1224                         return get_Sel_entity(ptr);
1225
1226                 return find_entity(pred);
1227         }
1228         case iro_Sub:
1229         case iro_Add: {
1230                 ir_node *left = get_binop_left(ptr);
1231                 ir_node *right;
1232                 if (mode_is_reference(get_irn_mode(left)))
1233                         return find_entity(left);
1234                 right = get_binop_right(ptr);
1235                 if (mode_is_reference(get_irn_mode(right)))
1236                         return find_entity(right);
1237                 return NULL;
1238         }
1239         default:
1240                 return NULL;
1241         }
1242 }
1243
1244 /**
1245  * optimize a Store
1246  *
1247  * @param store  the Store node
1248  */
1249 static unsigned optimize_store(ir_node *store)
1250 {
1251         ir_node   *ptr;
1252         ir_node   *mem;
1253         ir_entity *entity;
1254
1255         if (get_Store_volatility(store) == volatility_is_volatile)
1256                 return 0;
1257
1258         ptr    = get_Store_ptr(store);
1259         entity = find_entity(ptr);
1260
1261         /* a store to an entity which is never read is unnecessary */
1262         if (entity != NULL && !(get_entity_usage(entity) & ir_usage_read)) {
1263                 ldst_info_t *info = (ldst_info_t*)get_irn_link(store);
1264                 if (info->projs[pn_Store_X_except] == NULL) {
1265                         DB((dbg, LEVEL_1, "  Killing useless %+F to never read entity %+F\n", store, entity));
1266                         exchange(info->projs[pn_Store_M], get_Store_mem(store));
1267                         kill_node(store);
1268                         reduce_adr_usage(ptr);
1269                         return DF_CHANGED;
1270                 }
1271         }
1272
1273         /* Check, if the address of this Store is used more than once.
1274          * If not, this Store cannot be removed in any case. */
1275         if (get_irn_n_edges(ptr) <= 1)
1276                 return 0;
1277
1278         mem = get_Store_mem(store);
1279
1280         /* follow the memory chain as long as there are only Loads */
1281         INC_MASTER();
1282
1283         return follow_Mem_chain_for_Store(store, skip_Proj(mem));
1284 }
1285
1286 /* check if a node has more than one real user. Keepalive edges do not count as
1287  * real users */
1288 static bool has_multiple_users(const ir_node *node)
1289 {
1290         unsigned real_users = 0;
1291         foreach_out_edge(node, edge) {
1292                 ir_node *user = get_edge_src_irn(edge);
1293                 if (is_End(user))
1294                         continue;
1295                 ++real_users;
1296                 if (real_users > 1)
1297                         return true;
1298         }
1299         return false;
1300 }
1301
1302 /**
1303  * walker, optimizes Phi after Stores to identical places:
1304  * Does the following optimization:
1305  * @verbatim
1306  *
1307  *   val1   val2   val3          val1  val2  val3
1308  *    |      |      |               \    |    /
1309  *  Store  Store  Store              \   |   /
1310  *      \    |    /                   PhiData
1311  *       \   |   /                       |
1312  *        \  |  /                      Store
1313  *          PhiM
1314  *
1315  * @endverbatim
1316  * This reduces the number of stores and allows for predicated execution.
1317  * Moves Stores back to the end of a function which may be bad.
1318  *
1319  * This is only possible if the predecessor blocks have only one successor.
1320  */
1321 static unsigned optimize_phi(ir_node *phi, walk_env_t *wenv)
1322 {
1323         int i, n;
1324         ir_node *store, *ptr, *block, *phi_block, *phiM, *phiD, *exc, *projM;
1325 #ifdef DO_CACHEOPT
1326         ir_node *old_store;
1327 #endif
1328         ir_mode *mode;
1329         ir_node **inM, **inD, **projMs;
1330         int *idx;
1331         dbg_info *db = NULL;
1332         ldst_info_t *info;
1333         block_info_t *bl_info;
1334         unsigned res = 0;
1335
1336         /* Must be a memory Phi */
1337         if (get_irn_mode(phi) != mode_M)
1338                 return 0;
1339
1340         n = get_Phi_n_preds(phi);
1341         if (n <= 0)
1342                 return 0;
1343
1344         /* must be only one user */
1345         projM = get_Phi_pred(phi, 0);
1346         if (has_multiple_users(projM))
1347                 return 0;
1348
1349         store = skip_Proj(projM);
1350 #ifdef DO_CACHEOPT
1351         old_store = store;
1352 #endif
1353         if (!is_Store(store))
1354                 return 0;
1355
1356         block = get_nodes_block(store);
1357
1358         /* check if the block is post dominated by Phi-block
1359            and has no exception exit */
1360         bl_info = (block_info_t*)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 = (ldst_info_t*)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 (has_multiple_users(pred))
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 = (ldst_info_t*)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                 block = get_nodes_block(pred);
1394
1395                 /* check if the block is post dominated by Phi-block
1396                    and has no exception exit. Note that block must be different from
1397                    Phi-block, else we would move a Store from end End of a block to its
1398                    Start... */
1399                 bl_info = (block_info_t*)get_irn_link(block);
1400                 if (bl_info->flags & BLOCK_HAS_EXC)
1401                         return 0;
1402                 if (block == phi_block || ! block_postdominates(phi_block, block))
1403                         return 0;
1404         }
1405
1406         /*
1407          * ok, when we are here, we found all predecessors of a Phi that
1408          * are Stores to the same address and size. That means whatever
1409          * we do before we enter the block of the Phi, we do a Store.
1410          * So, we can move the Store to the current block:
1411          *
1412          *   val1    val2    val3          val1  val2  val3
1413          *    |       |       |               \    |    /
1414          * | Str | | Str | | Str |             \   |   /
1415          *      \     |     /                   PhiData
1416          *       \    |    /                       |
1417          *        \   |   /                       Str
1418          *           PhiM
1419          *
1420          * Is only allowed if the predecessor blocks have only one successor.
1421          */
1422
1423         NEW_ARR_A(ir_node *, projMs, n);
1424         NEW_ARR_A(ir_node *, inM, n);
1425         NEW_ARR_A(ir_node *, inD, n);
1426         NEW_ARR_A(int, idx, n);
1427
1428         /* Prepare: Collect all Store nodes.  We must do this
1429            first because we otherwise may loose a store when exchanging its
1430            memory Proj.
1431          */
1432         for (i = n - 1; i >= 0; --i) {
1433                 projMs[i] = get_Phi_pred(phi, i);
1434
1435                 ir_node *const store = get_Proj_pred(projMs[i]);
1436                 info  = (ldst_info_t*)get_irn_link(store);
1437
1438                 inM[i] = get_Store_mem(store);
1439                 inD[i] = get_Store_value(store);
1440                 idx[i] = info->exc_idx;
1441         }
1442         block = get_nodes_block(phi);
1443
1444         /* second step: create a new memory Phi */
1445         phiM = new_rd_Phi(get_irn_dbg_info(phi), block, n, inM, mode_M);
1446
1447         /* third step: create a new data Phi */
1448         phiD = new_rd_Phi(get_irn_dbg_info(phi), block, n, inD, mode);
1449
1450         /* rewire memory and kill the node */
1451         for (i = n - 1; i >= 0; --i) {
1452                 ir_node *proj  = projMs[i];
1453
1454                 if (is_Proj(proj)) {
1455                         ir_node *store = get_Proj_pred(proj);
1456                         exchange(proj, inM[i]);
1457                         kill_node(store);
1458                 }
1459         }
1460
1461         /* fourth step: create the Store */
1462         store = new_rd_Store(db, block, phiM, ptr, phiD, cons_none);
1463 #ifdef DO_CACHEOPT
1464         co_set_irn_name(store, co_get_irn_ident(old_store));
1465 #endif
1466
1467         projM = new_rd_Proj(NULL, store, mode_M, pn_Store_M);
1468
1469         info = get_ldst_info(store, &wenv->obst);
1470         info->projs[pn_Store_M] = projM;
1471
1472         /* fifths step: repair exception flow */
1473         if (exc) {
1474                 ir_node *projX = new_rd_Proj(NULL, store, mode_X, pn_Store_X_except);
1475
1476                 info->projs[pn_Store_X_except] = projX;
1477                 info->exc_block                = exc;
1478                 info->exc_idx                  = idx[0];
1479
1480                 for (i = 0; i < n; ++i) {
1481                         set_Block_cfgpred(exc, idx[i], projX);
1482                 }
1483
1484                 if (n > 1) {
1485                         /* the exception block should be optimized as some inputs are identical now */
1486                 }
1487
1488                 res |= CF_CHANGED;
1489         }
1490
1491         /* sixth step: replace old Phi */
1492         exchange(phi, projM);
1493
1494         return res | DF_CHANGED;
1495 }
1496
1497 static int optimize_conv_load(ir_node *conv)
1498 {
1499         ir_node *op = get_Conv_op(conv);
1500         if (!is_Proj(op))
1501                 return 0;
1502         if (has_multiple_users(op))
1503                 return 0;
1504         /* shrink mode of load if possible. */
1505         ir_node *load = get_Proj_pred(op);
1506         if (!is_Load(load))
1507                 return 0;
1508
1509         /* only do it if we are the only user (otherwise the risk is too
1510          * great that we end up with 2 loads instead of one). */
1511         ir_mode *mode      = get_irn_mode(conv);
1512         ir_mode *load_mode = get_Load_mode(load);
1513         int      bits_diff
1514                 = get_mode_size_bits(load_mode) - get_mode_size_bits(mode);
1515         if (mode_is_float(load_mode) || mode_is_float(mode) || bits_diff < 0)
1516             return 0;
1517
1518         if (be_get_backend_param()->byte_order_big_endian) {
1519                 if (bits_diff % 8 != 0)
1520                         return 0;
1521                 ir_graph *irg   = get_irn_irg(conv);
1522                 ir_node  *ptr   = get_Load_ptr(load);
1523                 ir_mode  *mode  = get_irn_mode(ptr);
1524                 ir_node  *delta = new_r_Const_long(irg, mode, bits_diff/8);
1525                 ir_node  *block = get_nodes_block(load);
1526                 ir_node  *add   = new_r_Add(block, ptr, delta, mode);
1527                 set_Load_ptr(load, add);
1528         }
1529         set_Load_mode(load, mode);
1530         set_irn_mode(op, mode);
1531         exchange(conv, op);
1532         return DF_CHANGED;
1533 }
1534
1535 /**
1536  * walker, do the optimizations
1537  */
1538 static void do_load_store_optimize(ir_node *n, void *env)
1539 {
1540         walk_env_t *wenv = (walk_env_t*)env;
1541
1542         switch (get_irn_opcode(n)) {
1543
1544         case iro_Load:
1545                 wenv->changes |= optimize_load(n);
1546                 break;
1547
1548         case iro_Store:
1549                 wenv->changes |= optimize_store(n);
1550                 break;
1551
1552         case iro_Phi:
1553                 wenv->changes |= optimize_phi(n, wenv);
1554                 break;
1555
1556         case iro_Conv:
1557                 wenv->changes |= optimize_conv_load(n);
1558                 break;
1559
1560         default:
1561                 break;
1562         }
1563 }
1564
1565 /** A scc. */
1566 typedef struct scc {
1567         ir_node *head;      /**< the head of the list */
1568 } scc;
1569
1570 /** A node entry. */
1571 typedef struct node_entry {
1572         unsigned DFSnum;    /**< the DFS number of this node */
1573         unsigned low;       /**< the low number of this node */
1574         int      in_stack;  /**< flag, set if the node is on the stack */
1575         ir_node  *next;     /**< link to the next node the the same scc */
1576         scc      *pscc;     /**< the scc of this node */
1577         unsigned POnum;     /**< the post order number for blocks */
1578 } node_entry;
1579
1580 /** A loop entry. */
1581 typedef struct loop_env {
1582         ir_nodehashmap_t map;
1583         struct obstack   obst;
1584         ir_node          **stack;      /**< the node stack */
1585         size_t           tos;          /**< tos index */
1586         unsigned         nextDFSnum;   /**< the current DFS number */
1587         unsigned         POnum;        /**< current post order number */
1588
1589         unsigned         changes;      /**< a bitmask of graph changes */
1590 } loop_env;
1591
1592 /**
1593 * Gets the node_entry of a node
1594 */
1595 static node_entry *get_irn_ne(ir_node *irn, loop_env *env)
1596 {
1597         node_entry *e = ir_nodehashmap_get(node_entry, &env->map, irn);
1598
1599         if (e == NULL) {
1600                 e = OALLOC(&env->obst, node_entry);
1601                 memset(e, 0, sizeof(*e));
1602                 ir_nodehashmap_insert(&env->map, irn, e);
1603         }
1604         return e;
1605 }
1606
1607 /**
1608  * Push a node onto the stack.
1609  *
1610  * @param env   the loop environment
1611  * @param n     the node to push
1612  */
1613 static void push(loop_env *env, ir_node *n)
1614 {
1615         node_entry *e;
1616
1617         if (env->tos == ARR_LEN(env->stack)) {
1618                 size_t nlen = ARR_LEN(env->stack) * 2;
1619                 ARR_RESIZE(ir_node *, env->stack, nlen);
1620         }
1621         env->stack[env->tos++] = n;
1622         e = get_irn_ne(n, env);
1623         e->in_stack = 1;
1624 }
1625
1626 /**
1627  * pop a node from the stack
1628  *
1629  * @param env   the loop environment
1630  *
1631  * @return  The topmost node
1632  */
1633 static ir_node *pop(loop_env *env)
1634 {
1635         ir_node *n = env->stack[--env->tos];
1636         node_entry *e = get_irn_ne(n, env);
1637
1638         e->in_stack = 0;
1639         return n;
1640 }
1641
1642 /**
1643  * Check if irn is a region constant.
1644  * The block or irn must strictly dominate the header block.
1645  *
1646  * @param irn           the node to check
1647  * @param header_block  the header block of the induction variable
1648  */
1649 static int is_rc(ir_node *irn, ir_node *header_block)
1650 {
1651         ir_node *block = get_nodes_block(irn);
1652
1653         return (block != header_block) && block_dominates(block, header_block);
1654 }
1655
1656 typedef struct phi_entry phi_entry;
1657 struct phi_entry {
1658         ir_node   *phi;    /**< A phi with a region const memory. */
1659         int       pos;     /**< The position of the region const memory */
1660         ir_node   *load;   /**< the newly created load for this phi */
1661         phi_entry *next;
1662 };
1663
1664 /**
1665  * An entry in the avail set.
1666  */
1667 typedef struct avail_entry_t {
1668         ir_node *ptr;   /**< the address pointer */
1669         ir_mode *mode;  /**< the load mode */
1670         ir_node *load;  /**< the associated Load */
1671 } avail_entry_t;
1672
1673 /**
1674  * Compare two avail entries.
1675  */
1676 static int cmp_avail_entry(const void *elt, const void *key, size_t size)
1677 {
1678         const avail_entry_t *a = (const avail_entry_t*)elt;
1679         const avail_entry_t *b = (const avail_entry_t*)key;
1680         (void) size;
1681
1682         return a->ptr != b->ptr || a->mode != b->mode;
1683 }
1684
1685 /**
1686  * Calculate the hash value of an avail entry.
1687  */
1688 static unsigned hash_cache_entry(const avail_entry_t *entry)
1689 {
1690         return get_irn_idx(entry->ptr) * 9 + hash_ptr(entry->mode);
1691 }
1692
1693 /**
1694  * Move loops out of loops if possible.
1695  *
1696  * @param pscc   the loop described by an SCC
1697  * @param env    the loop environment
1698  */
1699 static void move_loads_out_of_loops(scc *pscc, loop_env *env)
1700 {
1701         ir_node   *phi, *load, *next, *other, *next_other;
1702         int       j;
1703         phi_entry *phi_list = NULL;
1704         set       *avail;
1705
1706         /* collect all outer memories */
1707         for (phi = pscc->head; phi != NULL; phi = next) {
1708                 node_entry *ne = get_irn_ne(phi, env);
1709                 next = ne->next;
1710
1711                 /* check all memory Phi's */
1712                 if (! is_Phi(phi))
1713                         continue;
1714
1715                 assert(get_irn_mode(phi) == mode_M && "DFS return non-memory Phi");
1716
1717                 for (j = get_irn_arity(phi) - 1; j >= 0; --j) {
1718                         ir_node    *pred = get_irn_n(phi, j);
1719                         node_entry *pe   = get_irn_ne(pred, env);
1720
1721                         if (pe->pscc != ne->pscc) {
1722                                 /* not in the same SCC, is region const */
1723                                 phi_entry *pe = OALLOC(&env->obst, phi_entry);
1724
1725                                 pe->phi  = phi;
1726                                 pe->pos  = j;
1727                                 pe->next = phi_list;
1728                                 phi_list = pe;
1729                         }
1730                 }
1731         }
1732         /* no Phis no fun */
1733         assert(phi_list != NULL && "DFS found a loop without Phi");
1734
1735         /* for now, we cannot handle more than one input (only reducible cf) */
1736         if (phi_list->next != NULL)
1737                 return;
1738
1739         avail = new_set(cmp_avail_entry, 8);
1740
1741         for (load = pscc->head; load; load = next) {
1742                 ir_mode *load_mode;
1743                 node_entry *ne = get_irn_ne(load, env);
1744                 next = ne->next;
1745
1746                 if (is_Load(load)) {
1747                         ldst_info_t *info = (ldst_info_t*)get_irn_link(load);
1748                         ir_node     *ptr = get_Load_ptr(load);
1749
1750                         /* for now, we cannot handle Loads with exceptions */
1751                         if (info->projs[pn_Load_res] == NULL || info->projs[pn_Load_X_regular] != NULL || info->projs[pn_Load_X_except] != NULL)
1752                                 continue;
1753
1754                         /* for now, we can only move Load(Global) */
1755                         if (! is_SymConst_addr_ent(ptr))
1756                                 continue;
1757                         load_mode = get_Load_mode(load);
1758                         for (other = pscc->head; other != NULL; other = next_other) {
1759                                 node_entry *ne = get_irn_ne(other, env);
1760                                 next_other = ne->next;
1761
1762                                 if (is_Store(other)) {
1763                                         ir_alias_relation rel = get_alias_relation(
1764                                                 get_Store_ptr(other),
1765                                                 get_irn_mode(get_Store_value(other)),
1766                                                 ptr, load_mode);
1767                                         /* if the might be an alias, we cannot pass this Store */
1768                                         if (rel != ir_no_alias)
1769                                                 break;
1770                                 }
1771                                 /* only Phis and pure Calls are allowed here, so ignore them */
1772                         }
1773                         if (other == NULL) {
1774                                 ldst_info_t *ninfo = NULL;
1775                                 phi_entry   *pe;
1776                                 dbg_info    *db;
1777
1778                                 /* yep, no aliasing Store found, Load can be moved */
1779                                 DB((dbg, LEVEL_1, "  Found a Load that could be moved: %+F\n", load));
1780
1781                                 db   = get_irn_dbg_info(load);
1782                                 for (pe = phi_list; pe != NULL; pe = pe->next) {
1783                                         int     pos   = pe->pos;
1784                                         ir_node *phi  = pe->phi;
1785                                         ir_node *blk  = get_nodes_block(phi);
1786                                         ir_node *pred = get_Block_cfgpred_block(blk, pos);
1787                                         ir_node *irn, *mem;
1788                                         avail_entry_t entry, *res;
1789
1790                                         entry.ptr  = ptr;
1791                                         entry.mode = load_mode;
1792                                         res = set_find(avail_entry_t, avail, &entry, sizeof(entry), hash_cache_entry(&entry));
1793                                         if (res != NULL) {
1794                                                 irn = res->load;
1795                                         } else {
1796                                                 irn = new_rd_Load(db, pred, get_Phi_pred(phi, pos), ptr, load_mode, cons_none);
1797                                                 entry.load = irn;
1798                                                 (void)set_insert(avail_entry_t, avail, &entry, sizeof(entry), hash_cache_entry(&entry));
1799                                                 DB((dbg, LEVEL_1, "  Created %+F in %+F\n", irn, pred));
1800                                         }
1801                                         pe->load = irn;
1802                                         ninfo = get_ldst_info(irn, &env->obst);
1803
1804                                         ninfo->projs[pn_Load_M] = mem = new_r_Proj(irn, mode_M, pn_Load_M);
1805                                         if (res == NULL) {
1806                                                 /* irn is from cache, so do not set phi pred again.
1807                                                  * There might be other Loads between phi and irn already.
1808                                                  */
1809                                                 set_Phi_pred(phi, pos, mem);
1810                                         }
1811
1812                                         ninfo->projs[pn_Load_res] = new_r_Proj(irn, load_mode, pn_Load_res);
1813                                 }
1814
1815                                 /* now kill the old Load */
1816                                 exchange(info->projs[pn_Load_M], get_Load_mem(load));
1817                                 exchange(info->projs[pn_Load_res], ninfo->projs[pn_Load_res]);
1818
1819                                 env->changes |= DF_CHANGED;
1820                         }
1821                 }
1822         }
1823         del_set(avail);
1824 }
1825
1826 /**
1827  * Process a loop SCC.
1828  *
1829  * @param pscc  the SCC
1830  * @param env   the loop environment
1831  */
1832 static void process_loop(scc *pscc, loop_env *env)
1833 {
1834         ir_node *irn, *next, *header = NULL;
1835         node_entry *b, *h = NULL;
1836         int j, only_phi, num_outside, process = 0;
1837         ir_node *out_rc;
1838
1839         /* find the header block for this scc */
1840         for (irn = pscc->head; irn; irn = next) {
1841                 node_entry *e = get_irn_ne(irn, env);
1842                 ir_node *block = get_nodes_block(irn);
1843
1844                 next = e->next;
1845                 b = get_irn_ne(block, env);
1846
1847                 if (header != NULL) {
1848                         if (h->POnum < b->POnum) {
1849                                 header = block;
1850                                 h      = b;
1851                         }
1852                 } else {
1853                         header = block;
1854                         h      = b;
1855                 }
1856         }
1857
1858         /* check if this scc contains only Phi, Loads or Stores nodes */
1859         only_phi    = 1;
1860         num_outside = 0;
1861         out_rc      = NULL;
1862         for (irn = pscc->head; irn; irn = next) {
1863                 node_entry *e = get_irn_ne(irn, env);
1864
1865                 next = e->next;
1866                 switch (get_irn_opcode(irn)) {
1867                 case iro_Call:
1868                         if (is_Call_pure(irn)) {
1869                                 /* pure calls can be treated like loads */
1870                                 only_phi = 0;
1871                                 break;
1872                         }
1873                         /* non-pure calls must be handle like may-alias Stores */
1874                         goto fail;
1875                 case iro_CopyB:
1876                         /* cannot handle CopyB yet */
1877                         goto fail;
1878                 case iro_Load:
1879                         process = 1;
1880                         if (get_Load_volatility(irn) == volatility_is_volatile) {
1881                                 /* cannot handle loops with volatile Loads */
1882                                 goto fail;
1883                         }
1884                         only_phi = 0;
1885                         break;
1886                 case iro_Store:
1887                         if (get_Store_volatility(irn) == volatility_is_volatile) {
1888                                 /* cannot handle loops with volatile Stores */
1889                                 goto fail;
1890                         }
1891                         only_phi = 0;
1892                         break;
1893                 default:
1894                         only_phi = 0;
1895                         break;
1896                 case iro_Phi:
1897                         for (j = get_irn_arity(irn) - 1; j >= 0; --j) {
1898                                 ir_node *pred  = get_irn_n(irn, j);
1899                                 node_entry *pe = get_irn_ne(pred, env);
1900
1901                                 if (pe->pscc != e->pscc) {
1902                                         /* not in the same SCC, must be a region const */
1903                                         if (! is_rc(pred, header)) {
1904                                                 /* not a memory loop */
1905                                                 goto fail;
1906                                         }
1907                                         if (out_rc == NULL) {
1908                                                 /* first region constant */
1909                                                 out_rc = pred;
1910                                                 ++num_outside;
1911                                         } else if (out_rc != pred) {
1912                                                 /* another region constant */
1913                                                 ++num_outside;
1914                                         }
1915                                 }
1916                         }
1917                         break;
1918                 }
1919         }
1920         if (! process)
1921                 goto fail;
1922
1923         /* found a memory loop */
1924         DB((dbg, LEVEL_2, "  Found a memory loop:\n  "));
1925         if (only_phi && num_outside == 1) {
1926                 /* a phi cycle with only one real predecessor can be collapsed */
1927                 DB((dbg, LEVEL_2, "  Found an USELESS Phi cycle:\n  "));
1928
1929                 for (irn = pscc->head; irn; irn = next) {
1930                         node_entry *e = get_irn_ne(irn, env);
1931                         next = e->next;
1932                         exchange(irn, out_rc);
1933                 }
1934                 env->changes |= DF_CHANGED;
1935                 return;
1936         }
1937
1938 #ifdef DEBUG_libfirm
1939         for (irn = pscc->head; irn; irn = next) {
1940                 node_entry *e = get_irn_ne(irn, env);
1941                 next = e->next;
1942                 DB((dbg, LEVEL_2, " %+F,", irn));
1943         }
1944         DB((dbg, LEVEL_2, "\n"));
1945 #endif
1946         move_loads_out_of_loops(pscc, env);
1947
1948 fail:
1949         ;
1950 }
1951
1952 /**
1953  * Process a SCC.
1954  *
1955  * @param pscc  the SCC
1956  * @param env   the loop environment
1957  */
1958 static void process_scc(scc *pscc, loop_env *env)
1959 {
1960         ir_node *head = pscc->head;
1961         node_entry *e = get_irn_ne(head, env);
1962
1963 #ifdef DEBUG_libfirm
1964         {
1965                 ir_node *irn, *next;
1966
1967                 DB((dbg, LEVEL_4, " SCC at %p:\n ", pscc));
1968                 for (irn = pscc->head; irn; irn = next) {
1969                         node_entry *e = get_irn_ne(irn, env);
1970
1971                         next = e->next;
1972
1973                         DB((dbg, LEVEL_4, " %+F,", irn));
1974                 }
1975                 DB((dbg, LEVEL_4, "\n"));
1976         }
1977 #endif
1978
1979         if (e->next != NULL) {
1980                 /* this SCC has more than one member */
1981                 process_loop(pscc, env);
1982         }
1983 }
1984
1985 /**
1986  * Do Tarjan's SCC algorithm and drive load/store optimization.
1987  *
1988  * @param irn  start at this node
1989  * @param env  the loop environment
1990  */
1991 static void dfs(ir_node *irn, loop_env *env)
1992 {
1993         int i, n;
1994         node_entry *node = get_irn_ne(irn, env);
1995
1996         mark_irn_visited(irn);
1997
1998         node->DFSnum = env->nextDFSnum++;
1999         node->low    = node->DFSnum;
2000         push(env, irn);
2001
2002         /* handle preds */
2003         if (is_Phi(irn) || is_Sync(irn)) {
2004                 n = get_irn_arity(irn);
2005                 for (i = 0; i < n; ++i) {
2006                         ir_node *pred = get_irn_n(irn, i);
2007                         node_entry *o = get_irn_ne(pred, env);
2008
2009                         if (!irn_visited(pred)) {
2010                                 dfs(pred, env);
2011                                 node->low = MIN(node->low, o->low);
2012                         }
2013                         if (o->DFSnum < node->DFSnum && o->in_stack)
2014                                 node->low = MIN(o->DFSnum, node->low);
2015                 }
2016         } else if (is_fragile_op(irn)) {
2017                 ir_node *pred = get_memop_mem(irn);
2018                 node_entry *o = get_irn_ne(pred, env);
2019
2020                 if (!irn_visited(pred)) {
2021                         dfs(pred, env);
2022                         node->low = MIN(node->low, o->low);
2023                 }
2024                 if (o->DFSnum < node->DFSnum && o->in_stack)
2025                         node->low = MIN(o->DFSnum, node->low);
2026         } else if (is_Proj(irn)) {
2027                 ir_node *pred = get_Proj_pred(irn);
2028                 node_entry *o = get_irn_ne(pred, env);
2029
2030                 if (!irn_visited(pred)) {
2031                         dfs(pred, env);
2032                         node->low = MIN(node->low, o->low);
2033                 }
2034                 if (o->DFSnum < node->DFSnum && o->in_stack)
2035                         node->low = MIN(o->DFSnum, node->low);
2036         }
2037         else {
2038                  /* IGNORE predecessors */
2039         }
2040
2041         if (node->low == node->DFSnum) {
2042                 scc *pscc = OALLOC(&env->obst, scc);
2043                 ir_node *x;
2044
2045                 pscc->head = NULL;
2046                 do {
2047                         node_entry *e;
2048
2049                         x = pop(env);
2050                         e = get_irn_ne(x, env);
2051                         e->pscc    = pscc;
2052                         e->next    = pscc->head;
2053                         pscc->head = x;
2054                 } while (x != irn);
2055
2056                 process_scc(pscc, env);
2057         }
2058 }
2059
2060 /**
2061  * Do the DFS on the memory edges a graph.
2062  *
2063  * @param irg  the graph to process
2064  * @param env  the loop environment
2065  */
2066 static void do_dfs(ir_graph *irg, loop_env *env)
2067 {
2068         ir_node  *endblk, *end;
2069         int      i;
2070
2071         inc_irg_visited(irg);
2072
2073         /* visit all memory nodes */
2074         endblk = get_irg_end_block(irg);
2075         for (i = get_Block_n_cfgpreds(endblk) - 1; i >= 0; --i) {
2076                 ir_node *pred = get_Block_cfgpred(endblk, i);
2077
2078                 pred = skip_Proj(pred);
2079                 if (is_Return(pred)) {
2080                         dfs(get_Return_mem(pred), env);
2081                 } else if (is_Raise(pred)) {
2082                         dfs(get_Raise_mem(pred), env);
2083                 } else if (is_fragile_op(pred)) {
2084                         dfs(get_memop_mem(pred), env);
2085                 } else if (is_Bad(pred)) {
2086                         /* ignore non-optimized block predecessor */
2087                 } else {
2088                         assert(0 && "Unknown EndBlock predecessor");
2089                 }
2090         }
2091
2092         /* visit the keep-alives */
2093         end = get_irg_end(irg);
2094         for (i = get_End_n_keepalives(end) - 1; i >= 0; --i) {
2095                 ir_node *ka = get_End_keepalive(end, i);
2096
2097                 if (is_Phi(ka) && !irn_visited(ka))
2098                         dfs(ka, env);
2099         }
2100 }
2101
2102 /**
2103  * Optimize Loads/Stores in loops.
2104  *
2105  * @param irg  the graph
2106  */
2107 static int optimize_loops(ir_graph *irg)
2108 {
2109         loop_env env;
2110
2111         env.stack         = NEW_ARR_F(ir_node *, 128);
2112         env.tos           = 0;
2113         env.nextDFSnum    = 0;
2114         env.POnum         = 0;
2115         env.changes       = 0;
2116         ir_nodehashmap_init(&env.map);
2117         obstack_init(&env.obst);
2118
2119         /* calculate the SCC's and drive loop optimization. */
2120         do_dfs(irg, &env);
2121
2122         DEL_ARR_F(env.stack);
2123         obstack_free(&env.obst, NULL);
2124         ir_nodehashmap_destroy(&env.map);
2125
2126         return env.changes;
2127 }
2128
2129 void optimize_load_store(ir_graph *irg)
2130 {
2131         walk_env_t env;
2132
2133         assure_irg_properties(irg,
2134                 IR_GRAPH_PROPERTY_NO_UNREACHABLE_CODE
2135                 | IR_GRAPH_PROPERTY_CONSISTENT_OUT_EDGES
2136                 | IR_GRAPH_PROPERTY_NO_CRITICAL_EDGES
2137                 | IR_GRAPH_PROPERTY_CONSISTENT_DOMINANCE
2138                 | IR_GRAPH_PROPERTY_CONSISTENT_ENTITY_USAGE);
2139
2140         FIRM_DBG_REGISTER(dbg, "firm.opt.ldstopt");
2141
2142         assert(get_irg_pinned(irg) != op_pin_state_floats &&
2143                 "LoadStore optimization needs pinned graph");
2144
2145         if (get_opt_alias_analysis()) {
2146                 assure_irp_globals_entity_usage_computed();
2147         }
2148
2149         obstack_init(&env.obst);
2150         env.changes = 0;
2151
2152         /* init the links, then collect Loads/Stores/Proj's in lists */
2153         master_visited = 0;
2154         irg_walk_graph(irg, firm_clear_link, collect_nodes, &env);
2155
2156         /* now we have collected enough information, optimize */
2157         irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
2158
2159         env.changes |= optimize_loops(irg);
2160
2161         obstack_free(&env.obst, NULL);
2162
2163         confirm_irg_properties(irg,
2164                 env.changes
2165                 ? env.changes & CF_CHANGED
2166                         ? IR_GRAPH_PROPERTIES_NONE
2167                         : IR_GRAPH_PROPERTIES_CONTROL_FLOW
2168                 : IR_GRAPH_PROPERTIES_ALL);
2169 }
2170
2171 ir_graph_pass_t *optimize_load_store_pass(const char *name)
2172 {
2173         return def_graph_pass(name ? name : "ldst", optimize_load_store);
2174 }