2 * Copyright (C) 1995-2008 University of Karlsruhe. All right reserved.
4 * This file is part of libFirm.
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.
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.
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
22 * @brief Load/Store optimizations.
23 * @author Michael Beck
32 #include "iroptimize.h"
34 #include "irgraph_t.h"
42 #include "dbginfo_t.h"
43 #include "iropt_dbg.h"
49 #include "opt_polymorphy.h"
52 #include "irphase_t.h"
56 /** The debug handle. */
57 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
60 #include "cacheopt/cachesim.h"
64 #define IMAX(a,b) ((a) > (b) ? (a) : (b))
66 #define MAX_PROJ IMAX(IMAX(pn_Load_max, pn_Store_max), pn_Call_max)
69 DF_CHANGED = 1, /**< data flow changed */
70 CF_CHANGED = 2, /**< control flow changed */
76 typedef struct _walk_env_t {
77 struct obstack obst; /**< list of all stores */
78 unsigned changes; /**< a bitmask of graph changes */
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 */
90 * flags for control flow.
93 BLOCK_HAS_COND = 1, /**< Block has conditional control flow */
94 BLOCK_HAS_EXC = 2 /**< Block has exceptional control flow */
100 typedef struct _block_info_t {
101 unsigned flags; /**< flags for the block */
104 /** the master visited flag for loop detection. */
105 static unsigned master_visited = 0;
107 #define INC_MASTER() ++master_visited
108 #define MARK_NODE(info) (info)->visited = master_visited
109 #define NODE_VISITED(info) (info)->visited >= master_visited
112 * get the Load/Store info of a node
114 static ldst_info_t *get_ldst_info(ir_node *node, struct obstack *obst) {
115 ldst_info_t *info = get_irn_link(node);
118 info = obstack_alloc(obst, sizeof(*info));
119 memset(info, 0, sizeof(*info));
120 set_irn_link(node, info);
123 } /* get_ldst_info */
126 * get the Block info of a node
128 static block_info_t *get_block_info(ir_node *node, struct obstack *obst) {
129 block_info_t *info = get_irn_link(node);
132 info = obstack_alloc(obst, sizeof(*info));
133 memset(info, 0, sizeof(*info));
134 set_irn_link(node, info);
137 } /* get_block_info */
140 * update the projection info for a Load/Store
142 static unsigned update_projs(ldst_info_t *info, ir_node *proj)
144 long nr = get_Proj_proj(proj);
146 assert(0 <= nr && nr <= MAX_PROJ && "Wrong proj from LoadStore");
148 if (info->projs[nr]) {
149 /* there is already one, do CSE */
150 exchange(proj, info->projs[nr]);
154 info->projs[nr] = proj;
160 * update the exception block info for a Load/Store node.
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
166 static unsigned update_exc(ldst_info_t *info, ir_node *block, int pos)
168 assert(info->exc_block == NULL && "more than one exception block found");
170 info->exc_block = block;
175 /** Return the number of uses of an address node */
176 #define get_irn_n_uses(adr) get_irn_n_edges(adr)
179 * walker, collects all Load/Store/Proj nodes
181 * walks from Start -> End
183 static void collect_nodes(ir_node *node, void *env)
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;
190 if (opcode == iro_Proj) {
191 pred = get_Proj_pred(node);
192 opcode = get_irn_opcode(pred);
194 if (opcode == iro_Load || opcode == iro_Store || opcode == iro_Call) {
195 ldst_info = get_ldst_info(pred, &wenv->obst);
197 wenv->changes |= update_projs(ldst_info, node);
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.
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);
212 } else if (opcode == iro_Block) {
215 for (i = get_Block_n_cfgpreds(node) - 1; i >= 0; --i) {
216 ir_node *pred_block, *proj;
217 block_info_t *bl_info;
220 pred = proj = get_Block_cfgpred(node, i);
223 pred = get_Proj_pred(proj);
224 is_exc = get_Proj_proj(proj) == pn_Generic_X_except;
227 /* ignore Bad predecessors, they will be removed later */
231 pred_block = get_nodes_block(pred);
232 bl_info = get_block_info(pred_block, &wenv->obst);
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;
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);
243 wenv->changes |= update_exc(ldst_info, node, i);
247 } /* collect_nodes */
250 * Returns an entity if the address ptr points to a constant one.
252 * @param ptr the address
254 * @return an entity or NULL
256 static ir_entity *find_constant_entity(ir_node *ptr)
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))
264 } else if (is_Sel(ptr)) {
265 ir_entity *ent = get_Sel_entity(ptr);
266 ir_type *tp = get_entity_owner(ent);
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) ) )
274 if (is_Array_type(tp)) {
278 for (i = 0, n = get_Sel_n_indexs(ptr); i < n; ++i) {
280 tarval *tlower, *tupper;
281 ir_node *index = get_Sel_index(ptr, i);
282 tarval *tv = computed_value(index);
284 /* check if the index is constant */
285 if (tv == tarval_bad)
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);
293 if (tlower == tarval_bad || tupper == tarval_bad)
296 if (tarval_cmp(tv, tlower) & pn_Cmp_Lt)
298 if (tarval_cmp(tupper, tv) & pn_Cmp_Lt)
301 /* ok, bounds check finished */
305 if (variability_constant == get_entity_variability(ent))
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);
314 if (get_irn_mode(l) == get_irn_mode(ptr) && is_Const(r))
316 else if (get_irn_mode(r) == get_irn_mode(ptr) && is_Const(l))
321 /* for now, we support only one addition, reassoc should fold all others */
322 if (! is_SymConst(ptr) && !is_Sel(ptr))
324 } else if (is_Sub(ptr)) {
325 ir_node *l = get_Sub_left(ptr);
326 ir_node *r = get_Sub_right(ptr);
328 if (get_irn_mode(l) == get_irn_mode(ptr) && is_Const(r))
332 /* for now, we support only one substraction, reassoc should fold all others */
333 if (! is_SymConst(ptr) && !is_Sel(ptr))
338 } /* find_constant_entity */
341 * Return the Selection index of a Sel node from dimension n
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 */
350 * Returns the accessed component graph path for an
351 * node computing an address.
353 * @param ptr the node computing the address
354 * @param depth current depth in steps upward from the root
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;
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.
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);
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);
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));
388 } else if (is_Add(ptr)) {
389 ir_node *l = get_Add_left(ptr);
390 ir_node *r = get_Add_right(ptr);
395 tv = get_Const_tarval(r);
398 tv = get_Const_tarval(l);
401 mode = get_tarval_mode(tv);
403 /* ptr must be a Sel or a SymConst, this was checked in find_constant_entity() */
405 field = get_Sel_entity(ptr);
407 field = get_SymConst_entity(ptr);
410 for (ent = field;;) {
412 tarval *sz, *tv_index, *tlower, *tupper;
416 tp = get_entity_type(ent);
417 if (! is_Array_type(tp))
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);
423 tv_index = tarval_div(tv, sz);
424 tv = tarval_mod(tv, sz);
426 if (tv_index == tarval_bad || tv == tarval_bad)
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);
435 if (tlower == tarval_bad || tupper == tarval_bad)
438 if (tarval_cmp(tv_index, tlower) & pn_Cmp_Lt)
440 if (tarval_cmp(tupper, tv_index) & pn_Cmp_Lt)
443 /* ok, bounds check finished */
444 index = get_tarval_long(tv_index);
447 if (! tarval_is_null(tv)) {
448 /* access to some struct/union member */
452 /* should be at least ONE array */
456 res = rec_get_accessed_path(ptr, depth + idx);
460 path_len = get_compound_graph_path_length(res);
461 pos = path_len - depth - idx;
463 for (ent = field;;) {
465 tarval *sz, *tv_index;
468 tp = get_entity_type(ent);
469 if (! is_Array_type(tp))
471 ent = get_array_element_entity(tp);
472 set_compound_graph_path_node(res, pos, ent);
474 size = get_type_size_bytes(get_entity_type(ent));
475 sz = new_tarval_from_long(size, mode);
477 tv_index = tarval_div(tv, sz);
478 tv = tarval_mod(tv, sz);
480 if (tv_index == tarval_bad || tv == tarval_bad)
483 /* bounds already checked above */
484 index = get_tarval_long(tv_index);
485 set_compound_graph_path_array_index(res, pos, index);
488 if (! tarval_is_null(tv)) {
489 /* hmm, wrong access */
492 } else if (is_Sub(ptr)) {
493 ir_node *l = get_Sub_left(ptr);
494 ir_node *r = get_Sub_right(ptr);
497 tv = get_Const_tarval(r);
502 } /* rec_get_accessed_path */
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.
508 static compound_graph_path *get_accessed_path(ir_node *ptr) {
509 return rec_get_accessed_path(ptr, 0);
510 } /* get_accessed_path */
512 typedef struct path_entry {
514 struct path_entry *next;
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;
527 if (is_SymConst(ptr)) {
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)
534 n = get_initializer_compound_n_entries(initializer);
535 tp = get_entity_type(ent);
537 if (is_Array_type(tp)) {
538 ent = get_array_element_entity(tp);
543 initializer = get_initializer_compound_value(initializer, 0);
549 initializer = get_initializer_compound_value(initializer, p->index);
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);
559 n = get_initializer_compound_n_entries(initializer);
562 initializer = get_initializer_compound_value(initializer, 0);
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:
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);
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)
585 if (i >= n_members) {
586 /* not found: should NOT happen */
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);
600 tv = get_Const_tarval(r);
603 tv = get_Const_tarval(l);
606 mode = get_tarval_mode(tv);
608 /* ptr must be a Sel or a SymConst, this was checked in find_constant_entity() */
610 field = get_Sel_entity(ptr);
612 field = get_SymConst_entity(ptr);
615 /* count needed entries */
617 for (ent = field;;) {
618 tp = get_entity_type(ent);
619 if (! is_Array_type(tp))
621 ent = get_array_element_entity(tp);
624 /* should be at least ONE entry */
628 /* allocate the right number of entries */
629 NEW_ARR_A(path_entry, p, pos);
633 for (ent = field;;) {
635 tarval *sz, *tv_index, *tlower, *tupper;
639 tp = get_entity_type(ent);
640 if (! is_Array_type(tp))
642 ent = get_array_element_entity(tp);
644 p[pos].next = &p[pos + 1];
646 size = get_type_size_bytes(get_entity_type(ent));
647 sz = new_tarval_from_long(size, mode);
649 tv_index = tarval_div(tv, sz);
650 tv = tarval_mod(tv, sz);
652 if (tv_index == tarval_bad || tv == tarval_bad)
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);
661 if (tlower == tarval_bad || tupper == tarval_bad)
664 if (tarval_cmp(tv_index, tlower) & pn_Cmp_Lt)
666 if (tarval_cmp(tupper, tv_index) & pn_Cmp_Lt)
669 /* ok, bounds check finished */
670 index = get_tarval_long(tv_index);
671 p[pos].index = index;
674 if (! tarval_is_null(tv)) {
675 /* hmm, wrong access */
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);
685 tv = get_Const_tarval(r);
692 static ir_node *find_compound_ent_value(ir_node *ptr) {
693 return rec_find_compound_ent_value(ptr, NULL);
697 static void reduce_adr_usage(ir_node *ptr);
700 * Update a Load that may lost it's usage.
702 static void handle_load_update(ir_node *load) {
703 ldst_info_t *info = get_irn_link(load);
705 /* do NOT touch volatile loads for now */
706 if (get_Load_volatility(load) == volatility_is_volatile)
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);
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)));
718 reduce_adr_usage(ptr);
720 } /* handle_load_update */
723 * A Use of an address node is vanished. Check if this was a Proj
724 * node and update the counters.
726 static void reduce_adr_usage(ir_node *ptr) {
728 if (get_irn_n_edges(ptr) <= 0) {
729 /* this Proj is dead now */
730 ir_node *pred = get_Proj_pred(ptr);
733 ldst_info_t *info = get_irn_link(pred);
734 info->projs[get_Proj_proj(ptr)] = NULL;
736 /* this node lost it's result proj, handle that */
737 handle_load_update(pred);
741 } /* reduce_adr_usage */
744 * Check, if an already existing value of mode old_mode can be converted
745 * into the needed one new_mode without loss.
747 static int can_use_stored_value(ir_mode *old_mode, ir_mode *new_mode) {
748 if (old_mode == new_mode)
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)
758 } /* can_use_stored_value */
761 * Check whether a Call is at least pure, ie. does only read memory.
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);
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);
772 if (is_Global(ptr)) {
773 ir_entity *ent = get_Global_entity(ptr);
775 prop = get_entity_additional_properties(ent);
778 return (prop & (mtp_property_const|mtp_property_pure)) != 0;
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.
789 * INC_MASTER() must be called before dive into
791 static unsigned follow_Mem_chain(ir_node *load, ir_node *curr) {
793 ldst_info_t *info = get_irn_link(load);
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);
799 for (pred = curr; load != pred; ) {
800 ldst_info_t *pred_info = get_irn_link(pred);
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 ...
808 if (is_Store(pred) && get_Store_ptr(pred) == ptr &&
809 can_use_stored_value(get_irn_mode(get_Store_value(pred)), load_mode)) {
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.
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...
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);
826 DBG_OPT_RAW(load, value);
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);
833 if (info->projs[pn_Load_M])
834 exchange(info->projs[pn_Load_M], mem);
837 if (info->projs[pn_Load_X_except]) {
838 exchange( info->projs[pn_Load_X_except], new_Bad());
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)));
846 if (info->projs[pn_Load_res])
847 exchange(info->projs[pn_Load_res], value);
850 reduce_adr_usage(ptr);
851 return res | DF_CHANGED;
853 } else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
854 can_use_stored_value(get_Load_mode(pred), load_mode)) {
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.
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...
864 if (info->projs[pn_Load_X_except] == NULL || get_nodes_MacroBlock(load) == get_nodes_MacroBlock(pred)) {
867 DBG_OPT_RAR(load, pred);
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);
875 value = pred_info->projs[pn_Load_res];
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);
882 exchange(info->projs[pn_Load_res], value);
885 if (info->projs[pn_Load_M])
886 exchange(info->projs[pn_Load_M], mem);
889 if (info->projs[pn_Load_X_except]) {
890 exchange(info->projs[pn_Load_X_except], new_Bad());
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)));
899 reduce_adr_usage(ptr);
900 return res |= DF_CHANGED;
904 if (is_Store(pred)) {
905 /* check if we can pass through this store */
906 ir_alias_relation rel = get_alias_relation(
909 get_irn_mode(get_Store_value(pred)),
911 /* if the might be an alias, we cannot pass this Store */
912 if (rel != ir_no_alias)
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));
923 /* there might be Store's in the graph, stop here */
927 /* follow only Load chains */
931 /* check for cycles */
932 if (NODE_VISITED(pred_info))
934 MARK_NODE(pred_info);
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)));
949 } /* follow_Mem_chain */
954 * @param load the Load node
956 static unsigned optimize_load(ir_node *load)
958 ldst_info_t *info = get_irn_link(load);
959 ir_node *mem, *ptr, *new_node;
963 /* do NOT touch volatile loads for now */
964 if (get_Load_volatility(load) == volatility_is_volatile)
967 /* the address of the load to be optimized */
968 ptr = get_Load_ptr(load);
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.
975 * This optimizes some often used OO constructs,
976 * like x = new O; x->t;
978 if (info->projs[pn_Load_X_except]) {
980 ir_node *mem = get_Sel_mem(ptr);
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);
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 */
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;
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.
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;
1014 /* The mem of the Load. Must still be returned after optimization. */
1015 mem = get_Load_mem(load);
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);
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)));
1027 reduce_adr_usage(ptr);
1028 return res | DF_CHANGED;
1031 /* Load from a constant polymorphic field, where we can resolve
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;
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;
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;
1049 if (info->projs[pn_Load_res])
1050 exchange(info->projs[pn_Load_res], new_node);
1053 reduce_adr_usage(ptr);
1054 return res | DF_CHANGED;
1057 /* check if we can determine the entity that will be loaded */
1058 ent = find_constant_entity(ptr);
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
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;
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;
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
1088 if (info->projs[pn_Load_M]) {
1089 exchange(info->projs[pn_Load_M], mem);
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));
1097 DBG_OPT_RC(load, c);
1098 exchange(info->projs[pn_Load_res], c);
1103 reduce_adr_usage(ptr);
1107 if (ent->has_initializer) {
1108 /* new style initializer */
1109 c = find_compound_ent_value(ptr);
1111 /* old style initializer */
1112 compound_graph_path *path = get_accessed_path(ptr);
1115 assert(is_proper_compound_graph_path(path, get_compound_graph_path_length(path)-1));
1117 c = get_compound_ent_value_by_path(ent, path);
1118 free_compound_graph_path(path);
1122 if (info->projs[pn_Load_M]) {
1123 exchange(info->projs[pn_Load_M], mem);
1126 if (info->projs[pn_Load_res]) {
1127 exchange(info->projs[pn_Load_res], copy_const_value(get_irn_dbg_info(load), c));
1131 reduce_adr_usage(ptr);
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
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);
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)
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.
1161 res = follow_Mem_chain(load, skip_Proj(mem));
1163 } /* optimize_load */
1166 * Check whether a value of mode new_mode would completely overwrite a value
1167 * of mode old_mode in memory.
1169 static int is_completely_overwritten(ir_mode *old_mode, ir_mode *new_mode)
1171 return get_mode_size_bits(new_mode) >= get_mode_size_bits(old_mode);
1172 } /* is_completely_overwritten */
1175 * follow the memory chain as long as there are only Loads and alias free Stores.
1177 * INC_MASTER() must be called before dive into
1179 static unsigned follow_Mem_chain_for_Store(ir_node *store, ir_node *curr) {
1181 ldst_info_t *info = get_irn_link(store);
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);
1190 for (pred = curr; pred != store;) {
1191 ldst_info_t *pred_info = get_irn_link(pred);
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 ...
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)) {
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.
1208 * TODO: What, if both have the same exception handler ???
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));
1214 reduce_adr_usage(ptr);
1217 } else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
1218 value == pred_info->projs[pn_Load_res]) {
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
1225 if (! info->projs[pn_Store_X_except]) {
1226 DBG_OPT_WAR(store, pred);
1227 exchange(info->projs[pn_Store_M], mem);
1229 reduce_adr_usage(ptr);
1234 if (is_Store(pred)) {
1235 /* check if we can pass thru this store */
1236 ir_alias_relation rel = get_alias_relation(
1238 get_Store_ptr(pred),
1239 get_irn_mode(get_Store_value(pred)),
1241 /* if the might be an alias, we cannot pass this Store */
1242 if (rel != ir_no_alias)
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),
1249 if (rel != ir_no_alias)
1252 pred = skip_Proj(get_Load_mem(pred));
1254 /* follow only Load chains */
1258 /* check for cycles */
1259 if (NODE_VISITED(pred_info))
1261 MARK_NODE(pred_info);
1264 if (is_Sync(pred)) {
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)));
1275 } /* follow_Mem_chain_for_Store */
1280 * @param store the Store node
1282 static unsigned optimize_store(ir_node *store) {
1285 if (get_Store_volatility(store) == volatility_is_volatile)
1288 ptr = get_Store_ptr(store);
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)
1295 mem = get_Store_mem(store);
1297 /* follow the memory chain as long as there are only Loads */
1300 return follow_Mem_chain_for_Store(store, skip_Proj(mem));
1301 } /* optimize_store */
1304 * walker, optimizes Phi after Stores to identical places:
1305 * Does the following optimization:
1308 * val1 val2 val3 val1 val2 val3
1310 * Store Store Store \ | /
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.
1320 * This is only possible if the predecessor blocks have only one successor.
1322 static unsigned optimize_phi(ir_node *phi, walk_env_t *wenv)
1325 ir_node *store, *old_store, *ptr, *block, *phi_block, *phiM, *phiD, *exc, *projM;
1327 ir_node **inM, **inD, **projMs;
1329 dbg_info *db = NULL;
1331 block_info_t *bl_info;
1334 /* Must be a memory Phi */
1335 if (get_irn_mode(phi) != mode_M)
1338 n = get_Phi_n_preds(phi);
1342 /* must be only one user */
1343 projM = get_Phi_pred(phi, 0);
1344 if (get_irn_n_edges(projM) != 1)
1347 store = skip_Proj(projM);
1349 if (!is_Store(store))
1352 block = get_nodes_block(store);
1354 /* abort on dead blocks */
1355 if (is_Block_dead(block))
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)
1364 phi_block = get_nodes_block(phi);
1365 if (! block_strictly_postdominates(phi_block, block))
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;
1374 for (i = 1; i < n; ++i) {
1375 ir_node *pred = get_Phi_pred(phi, i);
1377 if (get_irn_n_edges(pred) != 1)
1380 pred = skip_Proj(pred);
1381 if (!is_Store(pred))
1384 if (ptr != get_Store_ptr(pred) || mode != get_irn_mode(get_Store_value(pred)))
1387 info = get_irn_link(pred);
1389 /* check, if all stores have the same exception flow */
1390 if (exc != info->exc_block)
1393 /* abort on dead blocks */
1394 block = get_nodes_block(pred);
1395 if (is_Block_dead(block))
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
1402 bl_info = get_irn_link(block);
1403 if (bl_info->flags & BLOCK_HAS_EXC)
1405 if (block == phi_block || ! block_postdominates(phi_block, block))
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:
1415 * val1 val2 val3 val1 val2 val3
1417 * | Str | | Str | | Str | \ | /
1423 * Is only allowed if the predecessor blocks have only one successor.
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);
1431 /* Prepare: Collect all Store nodes. We must do this
1432 first because we otherwise may loose a store when exchanging its
1435 for (i = n - 1; i >= 0; --i) {
1438 projMs[i] = get_Phi_pred(phi, i);
1439 assert(is_Proj(projMs[i]));
1441 store = get_Proj_pred(projMs[i]);
1442 info = get_irn_link(store);
1444 inM[i] = get_Store_mem(store);
1445 inD[i] = get_Store_value(store);
1446 idx[i] = info->exc_idx;
1448 block = get_nodes_block(phi);
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);
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);
1456 /* rewire memory and kill the node */
1457 for (i = n - 1; i >= 0; --i) {
1458 ir_node *proj = projMs[i];
1461 ir_node *store = get_Proj_pred(proj);
1462 exchange(proj, inM[i]);
1467 /* fourth step: create the Store */
1468 store = new_rd_Store(db, current_ir_graph, block, phiM, ptr, phiD);
1470 co_set_irn_name(store, co_get_irn_ident(old_store));
1473 projM = new_rd_Proj(NULL, current_ir_graph, block, store, mode_M, pn_Store_M);
1475 info = get_ldst_info(store, &wenv->obst);
1476 info->projs[pn_Store_M] = projM;
1478 /* fifths step: repair exception flow */
1480 ir_node *projX = new_rd_Proj(NULL, current_ir_graph, block, store, mode_X, pn_Store_X_except);
1482 info->projs[pn_Store_X_except] = projX;
1483 info->exc_block = exc;
1484 info->exc_idx = idx[0];
1486 for (i = 0; i < n; ++i) {
1487 set_Block_cfgpred(exc, idx[i], projX);
1491 /* the exception block should be optimized as some inputs are identical now */
1497 /* sixth step: replace old Phi */
1498 exchange(phi, projM);
1500 return res | DF_CHANGED;
1501 } /* optimize_phi */
1504 * walker, do the optimizations
1506 static void do_load_store_optimize(ir_node *n, void *env) {
1507 walk_env_t *wenv = env;
1509 switch (get_irn_opcode(n)) {
1512 wenv->changes |= optimize_load(n);
1516 wenv->changes |= optimize_store(n);
1520 wenv->changes |= optimize_phi(n, wenv);
1526 } /* do_load_store_optimize */
1529 typedef struct scc {
1530 ir_node *head; /**< the head of the list */
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 */
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 */
1552 unsigned changes; /**< a bitmask of graph changes */
1556 * Gets the node_entry of a node
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);
1563 e = phase_alloc(ph, sizeof(*e));
1564 memset(e, 0, sizeof(*e));
1565 phase_set_irn_data(ph, irn, e);
1571 * Push a node onto the stack.
1573 * @param env the loop environment
1574 * @param n the node to push
1576 static void push(loop_env *env, ir_node *n) {
1579 if (env->tos == ARR_LEN(env->stack)) {
1580 int nlen = ARR_LEN(env->stack) * 2;
1581 ARR_RESIZE(ir_node *, env->stack, nlen);
1583 env->stack[env->tos++] = n;
1584 e = get_irn_ne(n, env);
1589 * pop a node from the stack
1591 * @param env the loop environment
1593 * @return The topmost node
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);
1604 * Check if irn is a region constant.
1605 * The block or irn must strictly dominate the header block.
1607 * @param irn the node to check
1608 * @param header_block the header block of the induction variable
1610 static int is_rc(ir_node *irn, ir_node *header_block) {
1611 ir_node *block = get_nodes_block(irn);
1613 return (block != header_block) && block_dominates(block, header_block);
1616 typedef struct phi_entry 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 */
1625 * Move loops out of loops if possible.
1627 * @param pscc the loop described by an SCC
1628 * @param env the loop environment
1630 static void move_loads_out_of_loops(scc *pscc, loop_env *env) {
1631 ir_node *phi, *load, *next, *other, *next_other;
1634 phi_entry *phi_list = NULL;
1636 /* collect all outer memories */
1637 for (phi = pscc->head; phi != NULL; phi = next) {
1638 node_entry *ne = get_irn_ne(phi, env);
1641 /* check all memory Phi's */
1645 assert(get_irn_mode(phi) == mode_M && "DFS geturn non-memory Phi");
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);
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));
1657 pe->next = phi_list;
1662 /* no Phis no fun */
1663 assert(phi_list != NULL && "DFS found a loop without Phi");
1665 for (load = pscc->head; load; load = next) {
1667 node_entry *ne = get_irn_ne(load, env);
1670 if (is_Load(load)) {
1671 ldst_info_t *info = get_irn_link(load);
1672 ir_node *ptr = get_Load_ptr(load);
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)
1678 /* for now, we can only handle Load(Global) */
1679 if (! is_Global(ptr))
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;
1687 if (is_Store(other)) {
1688 ir_alias_relation rel = get_alias_relation(
1690 get_Store_ptr(other),
1691 get_irn_mode(get_Store_value(other)),
1693 /* if the might be an alias, we cannot pass this Store */
1694 if (rel != ir_no_alias)
1697 /* only pure Calls are allowed here, so ignore them */
1699 if (other == NULL) {
1704 /* for now, we cannot handle more than one input */
1705 if (phi_list->next != NULL)
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));
1711 db = get_irn_dbg_info(load);
1712 for (pe = phi_list; pe != NULL; pe = pe->next) {
1714 ir_node *phi = pe->phi;
1715 ir_node *blk = get_nodes_block(phi);
1716 ir_node *pred = get_Block_cfgpred_block(blk, pos);
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));
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);
1725 ninfo->projs[pn_Load_res] = new_r_Proj(current_ir_graph, pred, irn, load_mode, pn_Load_res);
1727 DB((dbg, LEVEL_1, " Created %+F in %+F\n", irn, pred));
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]);
1734 env->changes |= DF_CHANGED;
1738 } /* move_loads_out_of_loops */
1741 * Process a loop SCC.
1743 * @param pscc the SCC
1744 * @param env the loop environment
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;
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);
1758 b = get_irn_ne(block, env);
1761 if (h->POnum < b->POnum) {
1772 /* check if this scc contains only Phi, Loads or Stores nodes */
1776 for (irn = pscc->head; irn; irn = next) {
1777 node_entry *e = get_irn_ne(irn, env);
1780 switch (get_irn_opcode(irn)) {
1782 if (is_Call_pure(irn)) {
1783 /* pure calls can be treated like loads */
1787 /* non-pure calls must be handle like may-alias Stores */
1790 /* cannot handle CopyB yet */
1794 if (get_Load_volatility(irn) == volatility_is_volatile) {
1795 /* cannot handle loops with volatile Loads */
1801 if (get_Store_volatility(irn) == volatility_is_volatile) {
1802 /* cannot handle loops with volatile Stores */
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);
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 */
1824 } else if (out_rc != pred) {
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 "));
1841 for (irn = pscc->head; irn; irn = next) {
1842 node_entry *e = get_irn_ne(irn, env);
1845 exchange(irn, out_rc);
1847 env->changes |= DF_CHANGED;
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);
1856 DB((dbg, LEVEL_2, " %+F,", irn));
1858 DB((dbg, LEVEL_2, "\n"));
1860 move_loads_out_of_loops(pscc, env);
1864 } /* process_loop */
1869 * @param pscc the SCC
1870 * @param env the loop environment
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);
1876 #ifdef DEBUG_libfirm
1878 ir_node *irn, *next;
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);
1886 DB((dbg, LEVEL_4, " %+F,", irn));
1888 DB((dbg, LEVEL_4, "\n"));
1892 if (e->next != NULL) {
1893 /* this SCC has more than one member */
1894 process_loop(pscc, env);
1899 * Do Tarjan's SCC algorithm and drive load/store optimization.
1901 * @param irn start at this node
1902 * @param env the loop environment
1904 static void dfs(ir_node *irn, loop_env *env)
1907 node_entry *node = get_irn_ne(irn, env);
1909 mark_irn_visited(irn);
1911 node->DFSnum = env->nextDFSnum++;
1912 node->low = node->DFSnum;
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);
1922 if (irn_not_visited(pred)) {
1924 node->low = MIN(node->low, o->low);
1926 if (o->DFSnum < node->DFSnum && o->in_stack)
1927 node->low = MIN(o->DFSnum, node->low);
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);
1933 if (irn_not_visited(pred)) {
1935 node->low = MIN(node->low, o->low);
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);
1943 if (irn_not_visited(pred)) {
1945 node->low = MIN(node->low, o->low);
1947 if (o->DFSnum < node->DFSnum && o->in_stack)
1948 node->low = MIN(o->DFSnum, node->low);
1951 /* IGNORE predecessors */
1954 if (node->low == node->DFSnum) {
1955 scc *pscc = phase_alloc(&env->ph, sizeof(*pscc));
1963 e = get_irn_ne(x, env);
1965 e->next = pscc->head;
1969 process_scc(pscc, env);
1974 * Do the DFS on the memory edges a graph.
1976 * @param irg the graph to process
1977 * @param env the loop environment
1979 static void do_dfs(ir_graph *irg, loop_env *env) {
1980 ir_graph *rem = current_ir_graph;
1981 ir_node *endblk, *end;
1984 current_ir_graph = irg;
1985 inc_irg_visited(irg);
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);
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);
2000 assert(0 && "Unknown EndBlock predecessor");
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);
2009 if (is_Phi(ka) && irn_not_visited(ka))
2012 current_ir_graph = rem;
2016 * Initialize new phase data. We do this always explicit, so return NULL here
2018 static void *init_loop_data(ir_phase *ph, const ir_node *irn, void *data) {
2023 } /* init_loop_data */
2026 * Optimize Loads/Stores in loops.
2028 * @param irg the graph
2030 static int optimize_loops(ir_graph *irg) {
2033 env.stack = NEW_ARR_F(ir_node *, 128);
2038 phase_init(&env.ph, "ldstopt", irg, PHASE_DEFAULT_GROWTH, init_loop_data, NULL);
2040 /* calculate the SCC's and drive loop optimization. */
2043 DEL_ARR_F(env.stack);
2044 phase_free(&env.ph);
2047 } /* optimize_loops */
2050 * do the load store optimization
2052 void optimize_load_store(ir_graph *irg) {
2055 FIRM_DBG_REGISTER(dbg, "firm.opt.ldstopt");
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");
2061 /* we need landing pads */
2062 remove_critical_cf_edges(irg);
2066 /* for Phi optimization post-dominators are needed ... */
2067 assure_postdoms(irg);
2069 if (get_opt_alias_analysis()) {
2070 assure_irg_address_taken_computed(irg);
2071 assure_irp_globals_address_taken_computed();
2074 obstack_init(&env.obst);
2077 /* init the links, then collect Loads/Stores/Proj's in lists */
2079 irg_walk_graph(irg, firm_clear_link, collect_nodes, &env);
2081 /* now we have collected enough information, optimize */
2082 irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
2084 env.changes |= optimize_loops(irg);
2086 obstack_free(&env.obst, NULL);
2088 /* Handle graph state */
2090 set_irg_outs_inconsistent(irg);
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);
2098 } /* optimize_load_store */