3 * File name: ir/opt/ldstopt.c
4 * Purpose: load store optimizations
8 * Copyright: (c) 1998-2007 Universität Karlsruhe
9 * Licence: This file protected by GPL - GNU GENERAL PUBLIC LICENSE.
26 #include "irgraph_t.h"
34 #include "dbginfo_t.h"
35 #include "iropt_dbg.h"
41 #include "opt_polymorphy.h"
45 #include "cacheopt/cachesim.h"
49 #define IMAX(a,b) ((a) > (b) ? (a) : (b))
51 #define MAX_PROJ IMAX(pn_Load_max, pn_Store_max)
54 DF_CHANGED = 1, /**< data flow changed */
55 CF_CHANGED = 2, /**< control flow changed */
61 typedef struct _walk_env_t {
62 struct obstack obst; /**< list of all stores */
63 unsigned changes; /**< a bitmask of graph changes */
67 * flags for Load/Store
70 LDST_VISITED = 1 /**< if set, this Load/Store is already visited */
73 /** A Load/Store info. */
74 typedef struct _ldst_info_t {
75 ir_node *projs[MAX_PROJ]; /**< list of Proj's of this node */
76 ir_node *exc_block; /**< the exception block if available */
77 int exc_idx; /**< predecessor index in the exception block */
78 unsigned flags; /**< flags */
79 unsigned visited; /**< visited counter for breaking loops */
83 * flags for control flow.
86 BLOCK_HAS_COND = 1, /**< Block has conditional control flow */
87 BLOCK_HAS_EXC = 2 /**< Block has exceptional control flow */
93 typedef struct _block_info_t {
94 unsigned flags; /**< flags for the block */
97 /** the master visited flag for loop detection. */
98 static unsigned master_visited = 0;
100 #define INC_MASTER() ++master_visited
101 #define MARK_NODE(info) (info)->visited = master_visited
102 #define NODE_VISITED(info) (info)->visited >= master_visited
105 * get the Load/Store info of a node
107 static ldst_info_t *get_ldst_info(ir_node *node, walk_env_t *env) {
108 ldst_info_t *info = get_irn_link(node);
111 info = obstack_alloc(&env->obst, sizeof(*info));
112 memset(info, 0, sizeof(*info));
113 set_irn_link(node, info);
116 } /* get_ldst_info */
119 * get the Block info of a node
121 static block_info_t *get_block_info(ir_node *node, walk_env_t *env) {
122 block_info_t *info = get_irn_link(node);
125 info = obstack_alloc(&env->obst, sizeof(*info));
126 memset(info, 0, sizeof(*info));
127 set_irn_link(node, info);
130 } /* get_block_info */
133 * update the projection info for a Load/Store
135 static unsigned update_projs(ldst_info_t *info, ir_node *proj)
137 long nr = get_Proj_proj(proj);
139 assert(0 <= nr && nr <= MAX_PROJ && "Wrong proj from LoadStore");
141 if (info->projs[nr]) {
142 /* there is already one, do CSE */
143 exchange(proj, info->projs[nr]);
147 info->projs[nr] = proj;
153 * update the exception block info for a Load/Store node.
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
159 static unsigned update_exc(ldst_info_t *info, ir_node *block, int pos)
161 assert(info->exc_block == NULL && "more than one exception block found");
163 info->exc_block = block;
168 /** Return the number of uses of an address node */
169 #define get_irn_n_uses(adr) get_irn_n_edges(adr)
172 * walker, collects all Load/Store/Proj nodes
174 * walks from Start -> End
176 static void collect_nodes(ir_node *node, void *env)
178 ir_op *op = get_irn_op(node);
179 ir_node *pred, *blk, *pred_blk;
180 ldst_info_t *ldst_info;
181 walk_env_t *wenv = env;
187 pred = get_Proj_pred(node);
188 op = get_irn_op(pred);
191 ldst_info = get_ldst_info(pred, wenv);
193 wenv->changes |= update_projs(ldst_info, node);
195 if ((ldst_info->flags & LDST_VISITED) == 0) {
196 adr = get_Load_ptr(pred);
197 ldst_info->flags |= LDST_VISITED;
201 * Place the Proj's to the same block as the
202 * predecessor Load. This is always ok and prevents
203 * "non-SSA" form after optimizations if the Proj
204 * is in a wrong block.
206 blk = get_nodes_block(node);
207 pred_blk = get_nodes_block(pred);
208 if (blk != pred_blk) {
209 wenv->changes |= DF_CHANGED;
210 set_nodes_block(node, pred_blk);
212 } else if (op == op_Store) {
213 ldst_info = get_ldst_info(pred, wenv);
215 wenv->changes |= update_projs(ldst_info, node);
217 if ((ldst_info->flags & LDST_VISITED) == 0) {
218 adr = get_Store_ptr(pred);
219 ldst_info->flags |= LDST_VISITED;
223 * Place the Proj's to the same block as the
224 * predecessor Store. This is always ok and prevents
225 * "non-SSA" form after optimizations if the Proj
226 * is in a wrong block.
228 blk = get_nodes_block(node);
229 pred_blk = get_nodes_block(pred);
230 if (blk != pred_blk) {
231 wenv->changes |= DF_CHANGED;
232 set_nodes_block(node, pred_blk);
235 } else if (op == op_Block) {
238 for (i = get_Block_n_cfgpreds(node) - 1; i >= 0; --i) {
240 block_info_t *bl_info;
242 pred = skip_Proj(get_Block_cfgpred(node, i));
244 /* ignore Bad predecessors, they will be removed later */
248 pred_block = get_nodes_block(pred);
249 bl_info = get_block_info(pred_block, wenv);
251 if (is_fragile_op(pred))
252 bl_info->flags |= BLOCK_HAS_EXC;
253 else if (is_irn_forking(pred))
254 bl_info->flags |= BLOCK_HAS_COND;
256 if (get_irn_op(pred) == op_Load || get_irn_op(pred) == op_Store) {
257 ldst_info = get_ldst_info(pred, wenv);
259 wenv->changes |= update_exc(ldst_info, node, i);
263 } /* collect_nodes */
266 * Returns an entity if the address ptr points to a constant one.
268 * @param ptr the address
270 * @return an entity or NULL
272 static ir_entity *find_constant_entity(ir_node *ptr)
275 ir_op *op = get_irn_op(ptr);
277 if (op == op_SymConst && (get_SymConst_kind(ptr) == symconst_addr_ent)) {
278 ir_entity *ent = get_SymConst_entity(ptr);
279 if (variability_constant == get_entity_variability(ent))
282 } else if (op == op_Sel) {
283 ir_entity *ent = get_Sel_entity(ptr);
284 ir_type *tp = get_entity_owner(ent);
286 /* Do not fiddle with polymorphism. */
287 if (is_Class_type(get_entity_owner(ent)) &&
288 ((get_entity_n_overwrites(ent) != 0) ||
289 (get_entity_n_overwrittenby(ent) != 0) ) )
292 if (is_Array_type(tp)) {
296 for (i = 0, n = get_Sel_n_indexs(ptr); i < n; ++i) {
298 tarval *tlower, *tupper;
299 ir_node *index = get_Sel_index(ptr, i);
300 tarval *tv = computed_value(index);
302 /* check if the index is constant */
303 if (tv == tarval_bad)
306 bound = get_array_lower_bound(tp, i);
307 tlower = computed_value(bound);
308 bound = get_array_upper_bound(tp, i);
309 tupper = computed_value(bound);
311 if (tlower == tarval_bad || tupper == tarval_bad)
314 if (tarval_cmp(tv, tlower) & pn_Cmp_Lt)
316 if (tarval_cmp(tupper, tv) & pn_Cmp_Lt)
319 /* ok, bounds check finished */
323 if (variability_constant == get_entity_variability(ent))
327 ptr = get_Sel_ptr(ptr);
331 } /* find_constant_entity */
334 * Return the Selection index of a Sel node from dimension n
336 static long get_Sel_array_index_long(ir_node *n, int dim) {
337 ir_node *index = get_Sel_index(n, dim);
338 assert(get_irn_op(index) == op_Const);
339 return get_tarval_long(get_Const_tarval(index));
340 } /* get_Sel_array_index_long */
343 * Returns the accessed component graph path for an
344 * node computing an address.
346 * @param ptr the node computing the address
347 * @param depth current depth in steps upward from the root
350 static compound_graph_path *rec_get_accessed_path(ir_node *ptr, int depth) {
351 compound_graph_path *res = NULL;
352 ir_entity *root, *field;
355 if (get_irn_op(ptr) == op_SymConst) {
356 /* a SymConst. If the depth is 0, this is an access to a global
357 * entity and we don't need a component path, else we know
358 * at least it's length.
360 assert(get_SymConst_kind(ptr) == symconst_addr_ent);
361 root = get_SymConst_entity(ptr);
362 res = (depth == 0) ? NULL : new_compound_graph_path(get_entity_type(root), depth);
364 assert(get_irn_op(ptr) == op_Sel);
365 /* it's a Sel, go up until we find the root */
366 res = rec_get_accessed_path(get_Sel_ptr(ptr), depth+1);
368 /* fill up the step in the path at the current position */
369 field = get_Sel_entity(ptr);
370 path_len = get_compound_graph_path_length(res);
371 pos = path_len - depth - 1;
372 set_compound_graph_path_node(res, pos, field);
374 if (is_Array_type(get_entity_owner(field))) {
375 assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
376 set_compound_graph_path_array_index(res, pos, get_Sel_array_index_long(ptr, 0));
380 } /* rec_get_accessed_path */
382 /** Returns an access path or NULL. The access path is only
383 * valid, if the graph is in phase_high and _no_ address computation is used.
385 static compound_graph_path *get_accessed_path(ir_node *ptr) {
386 return rec_get_accessed_path(ptr, 0);
387 } /* get_accessed_path */
390 static void reduce_adr_usage(ir_node *ptr);
393 * Update a Load that may lost it's usage.
395 static void handle_load_update(ir_node *load) {
396 ldst_info_t *info = get_irn_link(load);
398 /* do NOT touch volatile loads for now */
399 if (get_Load_volatility(load) == volatility_is_volatile)
402 if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
403 ir_node *ptr = get_Load_ptr(load);
404 ir_node *mem = get_Load_mem(load);
406 /* a Load which value is neither used nor exception checked, remove it */
407 exchange(info->projs[pn_Load_M], mem);
408 exchange(load, new_Bad());
409 reduce_adr_usage(ptr);
411 } /* handle_load_update */
414 * A Use of an address node is vanished. Check if this was a Proj
415 * node and update the counters.
417 static void reduce_adr_usage(ir_node *ptr) {
419 if (get_irn_n_edges(ptr) <= 0) {
420 /* this Proj is dead now */
421 ir_node *pred = get_Proj_pred(ptr);
424 ldst_info_t *info = get_irn_link(pred);
425 info->projs[get_Proj_proj(ptr)] = NULL;
427 /* this node lost it's result proj, handle that */
428 handle_load_update(pred);
432 } /* reduce_adr_usage */
435 * Check, if an already existing value of mode old_mode can be converted
436 * into the needed one new_mode without loss.
438 static int can_use_stored_value(ir_mode *old_mode, ir_mode *new_mode) {
439 if (old_mode == new_mode)
442 /* if both modes are two-complement ones, we can always convert the
443 Stored value into the needed one. */
444 if (get_mode_size_bits(old_mode) >= get_mode_size_bits(new_mode) &&
445 get_mode_arithmetic(old_mode) == irma_twos_complement &&
446 get_mode_arithmetic(new_mode) == irma_twos_complement)
449 } /* can_use_stored_value */
452 * Follow the memory chain as long as there are only Loads
453 * and alias free Stores and try to replace current Load or Store
454 * by a previous ones.
455 * Note that in unreachable loops it might happen that we reach
456 * load again, as well as we can fall into a cycle.
457 * We break such cycles using a special visited flag.
459 * INC_MASTER() must be called before dive into
461 static unsigned follow_Mem_chain(ir_node *load, ir_node *curr) {
463 ldst_info_t *info = get_irn_link(load);
465 ir_node *ptr = get_Load_ptr(load);
466 ir_node *mem = get_Load_mem(load);
467 ir_mode *load_mode = get_Load_mode(load);
469 for (pred = curr; load != pred; ) {
470 ldst_info_t *pred_info = get_irn_link(pred);
473 * BEWARE: one might think that checking the modes is useless, because
474 * if the pointers are identical, they refer to the same object.
475 * This is only true in strong typed languages, not in C were the following
476 * is possible a = *(ir_type1 *)p; b = *(ir_type2 *)p ...
478 if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
479 can_use_stored_value(get_irn_mode(get_Store_value(pred)), load_mode)) {
481 * a Load immediately after a Store -- a read after write.
482 * We may remove the Load, if both Load & Store does not have an exception handler
483 * OR they are in the same block. In the latter case the Load cannot
484 * throw an exception when the previous Store was quiet.
486 * Why we need to check for Store Exception? If the Store cannot
487 * be executed (ROM) the exception handler might simply jump into
489 * We could make it a little bit better if we would know that the exception
490 * handler of the Store jumps directly to the end...
492 if ((pred_info->projs[pn_Store_X_except] == NULL && info->projs[pn_Load_X_except] == NULL) ||
493 get_nodes_block(load) == get_nodes_block(pred)) {
494 ir_node *value = get_Store_value(pred);
496 DBG_OPT_RAW(load, value);
498 /* add an convert if needed */
499 if (get_irn_mode(get_Store_value(pred)) != load_mode) {
500 value = new_r_Conv(current_ir_graph, get_nodes_block(load), value, load_mode);
503 if (info->projs[pn_Load_M])
504 exchange(info->projs[pn_Load_M], mem);
507 if (info->projs[pn_Load_X_except]) {
508 exchange( info->projs[pn_Load_X_except], new_Bad());
512 if (info->projs[pn_Load_res])
513 exchange(info->projs[pn_Load_res], value);
515 exchange(load, new_Bad());
516 reduce_adr_usage(ptr);
517 return res | DF_CHANGED;
519 } else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
520 can_use_stored_value(get_Load_mode(pred), load_mode)) {
522 * a Load after a Load -- a read after read.
523 * We may remove the second Load, if it does not have an exception handler
524 * OR they are in the same block. In the later case the Load cannot
525 * throw an exception when the previous Load was quiet.
527 * Here, there is no need to check if the previous Load has an exception
528 * hander because they would have exact the same exception...
530 if (info->projs[pn_Load_X_except] == NULL || get_nodes_block(load) == get_nodes_block(pred)) {
533 DBG_OPT_RAR(load, pred);
535 /* the result is used */
536 if (info->projs[pn_Load_res]) {
537 if (pred_info->projs[pn_Load_res] == NULL) {
538 /* create a new Proj again */
539 pred_info->projs[pn_Load_res] = new_r_Proj(current_ir_graph, get_nodes_block(pred), pred, get_Load_mode(pred), pn_Load_res);
541 value = pred_info->projs[pn_Load_res];
543 /* add an convert if needed */
544 if (get_Load_mode(pred) != load_mode) {
545 value = new_r_Conv(current_ir_graph, get_nodes_block(load), value, load_mode);
548 exchange(info->projs[pn_Load_res], value);
551 if (info->projs[pn_Load_M])
552 exchange(info->projs[pn_Load_M], mem);
555 if (info->projs[pn_Load_X_except]) {
556 exchange(info->projs[pn_Load_X_except], new_Bad());
560 exchange(load, new_Bad());
561 reduce_adr_usage(ptr);
562 return res |= DF_CHANGED;
566 if (get_irn_op(pred) == op_Store) {
567 /* check if we can pass through this store */
568 ir_alias_relation rel = get_alias_relation(
571 get_irn_mode(get_Store_value(pred)),
573 /* if the might be an alias, we cannot pass this Store */
576 pred = skip_Proj(get_Store_mem(pred));
577 } else if (get_irn_op(pred) == op_Load) {
578 pred = skip_Proj(get_Load_mem(pred));
580 /* follow only Load chains */
584 /* check for cycles */
585 if (NODE_VISITED(pred_info))
587 MARK_NODE(pred_info);
590 if (get_irn_op(pred) == op_Sync) {
593 /* handle all Sync predecessors */
594 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
595 res |= follow_Mem_chain(load, skip_Proj(get_Sync_pred(pred, i)));
602 } /* follow_Mem_chain */
607 * @param load the Load node
609 static unsigned optimize_load(ir_node *load)
611 ldst_info_t *info = get_irn_link(load);
612 ir_node *mem, *ptr, *new_node;
616 /* do NOT touch volatile loads for now */
617 if (get_Load_volatility(load) == volatility_is_volatile)
620 /* the address of the load to be optimized */
621 ptr = get_Load_ptr(load);
624 * Check if we can remove the exception from a Load:
625 * This can be done, if the address is from an Sel(Alloc) and
626 * the Sel type is a subtype of the allocated type.
628 * This optimizes some often used OO constructs,
629 * like x = new O; x->t;
631 if (info->projs[pn_Load_X_except]) {
633 ir_node *mem = get_Sel_mem(ptr);
635 /* FIXME: works with the current FE, but better use the base */
636 if (get_irn_op(skip_Proj(mem)) == op_Alloc) {
637 /* ok, check the types */
638 ir_entity *ent = get_Sel_entity(ptr);
639 ir_type *s_type = get_entity_type(ent);
640 ir_type *a_type = get_Alloc_type(mem);
642 if (is_SubClass_of(s_type, a_type)) {
643 /* ok, condition met: there can't be an exception because
644 * Alloc guarantees that enough memory was allocated */
646 exchange(info->projs[pn_Load_X_except], new_Bad());
647 info->projs[pn_Load_X_except] = NULL;
651 } else if ((get_irn_op(skip_Proj(ptr)) == op_Alloc) ||
652 ((get_irn_op(ptr) == op_Cast) && (get_irn_op(skip_Proj(get_Cast_op(ptr))) == op_Alloc))) {
653 /* simple case: a direct load after an Alloc. Firm Alloc throw
654 * an exception in case of out-of-memory. So, there is no way for an
655 * exception in this load.
656 * This code is constructed by the "exception lowering" in the Jack compiler.
658 exchange(info->projs[pn_Load_X_except], new_Bad());
659 info->projs[pn_Load_X_except] = NULL;
664 /* The mem of the Load. Must still be returned after optimization. */
665 mem = get_Load_mem(load);
667 if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
668 /* a Load which value is neither used nor exception checked, remove it */
669 exchange(info->projs[pn_Load_M], mem);
671 exchange(load, new_Bad());
672 reduce_adr_usage(ptr);
673 return res | DF_CHANGED;
676 /* Load from a constant polymorphic field, where we can resolve
678 new_node = transform_node_Load(load);
679 if (new_node != load) {
680 if (info->projs[pn_Load_M]) {
681 exchange(info->projs[pn_Load_M], mem);
682 info->projs[pn_Load_M] = NULL;
684 if (info->projs[pn_Load_X_except]) {
685 exchange(info->projs[pn_Load_X_except], new_Bad());
686 info->projs[pn_Load_X_except] = NULL;
688 if (info->projs[pn_Load_res])
689 exchange(info->projs[pn_Load_res], new_node);
691 exchange(load, new_Bad());
692 reduce_adr_usage(ptr);
693 return res | DF_CHANGED;
696 /* check if we can determine the entity that will be loaded */
697 ent = find_constant_entity(ptr);
699 if ((allocation_static == get_entity_allocation(ent)) &&
700 (visibility_external_allocated != get_entity_visibility(ent))) {
701 /* a static allocation that is not external: there should be NO exception
704 /* no exception, clear the info field as it might be checked later again */
705 if (info->projs[pn_Load_X_except]) {
706 exchange(info->projs[pn_Load_X_except], new_Bad());
707 info->projs[pn_Load_X_except] = NULL;
711 if (variability_constant == get_entity_variability(ent)
712 && is_atomic_entity(ent)) {
713 /* Might not be atomic after
714 lowering of Sels. In this
715 case we could also load, but
716 it's more complicated. */
717 /* more simpler case: we load the content of a constant value:
718 * replace it by the constant itself
722 if (info->projs[pn_Load_M]) {
723 exchange(info->projs[pn_Load_M], mem);
727 if (info->projs[pn_Load_res]) {
728 if (is_atomic_entity(ent)) {
729 ir_node *c = copy_const_value(get_irn_dbg_info(load), get_atomic_ent_value(ent));
732 exchange(info->projs[pn_Load_res], c);
736 exchange(load, new_Bad());
737 reduce_adr_usage(ptr);
739 } else if (variability_constant == get_entity_variability(ent)) {
740 compound_graph_path *path = get_accessed_path(ptr);
745 assert(is_proper_compound_graph_path(path, get_compound_graph_path_length(path)-1));
749 for (j = 0; j < get_compound_graph_path_length(path); ++j) {
750 ir_entity *node = get_compound_graph_path_node(path, j);
751 fprintf(stdout, ".%s", get_entity_name(node));
752 if (is_Array_type(get_entity_owner(node)))
753 fprintf(stdout, "[%d]", get_compound_graph_path_array_index(path, j));
759 c = get_compound_ent_value_by_path(ent, path);
760 free_compound_graph_path(path);
762 /* printf(" cons: "); DDMN(c); */
764 if (info->projs[pn_Load_M]) {
765 exchange(info->projs[pn_Load_M], mem);
768 if (info->projs[pn_Load_res]) {
769 exchange(info->projs[pn_Load_res], copy_const_value(get_irn_dbg_info(load), c));
772 exchange(load, new_Bad());
773 reduce_adr_usage(ptr);
776 /* We can not determine a correct access path. E.g., in jack, we load
777 a byte from an object to generate an exception. Happens in test program
779 printf(">>>>>>>>>>>>> Found access to constant entity %s in function %s\n", get_entity_name(ent),
780 get_entity_name(get_irg_entity(current_ir_graph)));
781 printf(" load: "); DDMN(load);
782 printf(" ptr: "); DDMN(ptr);
789 /* Check, if the address of this load is used more than once.
790 * If not, this load cannot be removed in any case. */
791 if (get_irn_n_uses(ptr) <= 1)
795 * follow the memory chain as long as there are only Loads
796 * and try to replace current Load or Store by a previous one.
797 * Note that in unreachable loops it might happen that we reach
798 * load again, as well as we can fall into a cycle.
799 * We break such cycles using a special visited flag.
802 res = follow_Mem_chain(load, skip_Proj(mem));
804 } /* optimize_load */
807 * Check whether a value of mode new_mode would completely overwrite a value
808 * of mode old_mode in memory.
810 static int is_completely_overwritten(ir_mode *old_mode, ir_mode *new_mode)
812 return get_mode_size_bits(new_mode) >= get_mode_size_bits(old_mode);
813 } /* is_completely_overwritten */
816 * follow the memory chain as long as there are only Loads and alias free Stores.
818 * INC_MASTER() must be called before dive into
820 static unsigned follow_Mem_chain_for_Store(ir_node *store, ir_node *curr) {
822 ldst_info_t *info = get_irn_link(store);
824 ir_node *ptr = get_Store_ptr(store);
825 ir_node *mem = get_Store_mem(store);
826 ir_node *value = get_Store_value(store);
827 ir_mode *mode = get_irn_mode(value);
828 ir_node *block = get_nodes_block(store);
830 for (pred = curr; pred != store;) {
831 ldst_info_t *pred_info = get_irn_link(pred);
834 * BEWARE: one might think that checking the modes is useless, because
835 * if the pointers are identical, they refer to the same object.
836 * This is only true in strong typed languages, not is C were the following
837 * is possible *(ir_type1 *)p = a; *(ir_type2 *)p = b ...
838 * However, if the mode that is written have a bigger or equal size the the old
839 * one, the old value is completely overwritten and can be killed ...
841 if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
842 get_nodes_block(pred) == block &&
843 is_completely_overwritten(get_irn_mode(get_Store_value(pred)), mode)) {
845 * a Store after a Store in the same block -- a write after write.
846 * We may remove the first Store, if it does not have an exception handler.
848 * TODO: What, if both have the same exception handler ???
850 if (get_Store_volatility(pred) != volatility_is_volatile && !pred_info->projs[pn_Store_X_except]) {
851 DBG_OPT_WAW(pred, store);
852 exchange( pred_info->projs[pn_Store_M], get_Store_mem(pred) );
853 exchange(pred, new_Bad());
854 reduce_adr_usage(ptr);
857 } else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
858 value == pred_info->projs[pn_Load_res]) {
860 * a Store of a value after a Load -- a write after read.
861 * We may remove the second Store, if it does not have an exception handler.
863 if (! info->projs[pn_Store_X_except]) {
864 DBG_OPT_WAR(store, pred);
865 exchange( info->projs[pn_Store_M], mem );
866 exchange(store, new_Bad());
867 reduce_adr_usage(ptr);
872 if (get_irn_op(pred) == op_Store) {
873 /* check if we can pass thru this store */
874 ir_alias_relation rel = get_alias_relation(
877 get_irn_mode(get_Store_value(pred)),
879 /* if the might be an alias, we cannot pass this Store */
882 pred = skip_Proj(get_Store_mem(pred));
883 } else if (get_irn_op(pred) == op_Load) {
884 pred = skip_Proj(get_Load_mem(pred));
886 /* follow only Load chains */
890 /* check for cycles */
891 if (NODE_VISITED(pred_info))
893 MARK_NODE(pred_info);
896 if (get_irn_op(pred) == op_Sync) {
899 /* handle all Sync predecessors */
900 for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
901 res |= follow_Mem_chain_for_Store(store, skip_Proj(get_Sync_pred(pred, i)));
907 } /* follow_Mem_chain_for_Store */
912 * @param store the Store node
914 static unsigned optimize_store(ir_node *store) {
917 if (get_Store_volatility(store) == volatility_is_volatile)
920 ptr = get_Store_ptr(store);
922 /* Check, if the address of this Store is used more than once.
923 * If not, this Store cannot be removed in any case. */
924 if (get_irn_n_uses(ptr) <= 1)
927 mem = get_Store_mem(store);
929 /* follow the memory chain as long as there are only Loads */
931 return follow_Mem_chain_for_Store(store, skip_Proj(mem));
932 } /* optimize_store */
935 * walker, optimizes Phi after Stores to identical places:
936 * Does the following optimization:
939 * val1 val2 val3 val1 val2 val3
941 * Store Store Store \ | /
948 * This reduces the number of stores and allows for predicated execution.
949 * Moves Stores back to the end of a function which may be bad.
951 * This is only possible if the predecessor blocks have only one successor.
953 static unsigned optimize_phi(ir_node *phi, walk_env_t *wenv)
956 ir_node *store, *old_store, *ptr, *block, *phi_block, *phiM, *phiD, *exc, *projM;
958 ir_node **inM, **inD, **stores;
962 block_info_t *bl_info;
965 /* Must be a memory Phi */
966 if (get_irn_mode(phi) != mode_M)
969 n = get_Phi_n_preds(phi);
973 store = skip_Proj(get_Phi_pred(phi, 0));
975 if (get_irn_op(store) != op_Store)
978 block = get_nodes_block(store);
980 /* abort on dead blocks */
981 if (is_Block_dead(block))
984 /* check if the block is post dominated by Phi-block
985 and has no exception exit */
986 bl_info = get_irn_link(block);
987 if (bl_info->flags & BLOCK_HAS_EXC)
990 phi_block = get_nodes_block(phi);
991 if (! block_postdominates(phi_block, block))
994 /* this is the address of the store */
995 ptr = get_Store_ptr(store);
996 mode = get_irn_mode(get_Store_value(store));
997 info = get_irn_link(store);
998 exc = info->exc_block;
1000 for (i = 1; i < n; ++i) {
1001 ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
1003 if (get_irn_op(pred) != op_Store)
1006 if (ptr != get_Store_ptr(pred) || mode != get_irn_mode(get_Store_value(pred)))
1009 info = get_irn_link(pred);
1011 /* check, if all stores have the same exception flow */
1012 if (exc != info->exc_block)
1015 /* abort on dead blocks */
1016 block = get_nodes_block(pred);
1017 if (is_Block_dead(block))
1020 /* check if the block is post dominated by Phi-block
1021 and has no exception exit. Note that block must be different from
1022 Phi-block, else we would move a Store from end End of a block to its
1024 bl_info = get_irn_link(block);
1025 if (bl_info->flags & BLOCK_HAS_EXC)
1027 if (block == phi_block || ! block_postdominates(phi_block, block))
1032 * ok, when we are here, we found all predecessors of a Phi that
1033 * are Stores to the same address and size. That means whatever
1034 * we do before we enter the block of the Phi, we do a Store.
1035 * So, we can move the Store to the current block:
1037 * val1 val2 val3 val1 val2 val3
1039 * | Str | | Str | | Str | \ | /
1045 * Is only allowed if the predecessor blocks have only one successor.
1048 NEW_ARR_A(ir_node *, stores, n);
1049 NEW_ARR_A(ir_node *, inM, n);
1050 NEW_ARR_A(ir_node *, inD, n);
1051 NEW_ARR_A(int, idx, n);
1053 /* Prepare: Collect all Store nodes. We must do this
1054 first because we otherwise may loose a store when exchanging its
1057 for (i = 0; i < n; ++i)
1058 stores[i] = skip_Proj(get_Phi_pred(phi, i));
1060 /* Prepare: Skip the memory Proj: we need this in the case some stores
1062 Beware: One Store might be included more than once in the stores[]
1063 list, so we must prevent to do the exchange more than once.
1065 for (i = 0; i < n; ++i) {
1066 ir_node *store = stores[i];
1069 info = get_irn_link(store);
1070 proj_m = info->projs[pn_Store_M];
1072 if (is_Proj(proj_m) && get_Proj_pred(proj_m) == store)
1073 exchange(proj_m, get_Store_mem(store));
1076 /* first step: collect all inputs */
1077 for (i = 0; i < n; ++i) {
1078 ir_node *store = stores[i];
1079 info = get_irn_link(store);
1081 inM[i] = get_Store_mem(store);
1082 inD[i] = get_Store_value(store);
1083 idx[i] = info->exc_idx;
1085 block = get_nodes_block(phi);
1087 /* second step: create a new memory Phi */
1088 phiM = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inM, mode_M);
1090 /* third step: create a new data Phi */
1091 phiD = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inD, mode);
1093 /* fourth step: create the Store */
1094 store = new_rd_Store(db, current_ir_graph, block, phiM, ptr, phiD);
1096 co_set_irn_name(store, co_get_irn_ident(old_store));
1099 projM = new_rd_Proj(NULL, current_ir_graph, block, store, mode_M, pn_Store_M);
1101 info = get_ldst_info(store, wenv);
1102 info->projs[pn_Store_M] = projM;
1104 /* fifths step: repair exception flow */
1106 ir_node *projX = new_rd_Proj(NULL, current_ir_graph, block, store, mode_X, pn_Store_X_except);
1108 info->projs[pn_Store_X_except] = projX;
1109 info->exc_block = exc;
1110 info->exc_idx = idx[0];
1112 for (i = 0; i < n; ++i) {
1113 set_Block_cfgpred(exc, idx[i], projX);
1117 /* the exception block should be optimized as some inputs are identical now */
1123 /* sixth step: replace old Phi */
1124 exchange(phi, projM);
1126 return res | DF_CHANGED;
1127 } /* optimize_phi */
1130 * walker, do the optimizations
1132 static void do_load_store_optimize(ir_node *n, void *env) {
1133 walk_env_t *wenv = env;
1135 switch (get_irn_opcode(n)) {
1138 wenv->changes |= optimize_load(n);
1142 wenv->changes |= optimize_store(n);
1146 wenv->changes |= optimize_phi(n, wenv);
1151 } /* do_load_store_optimize */
1154 * do the load store optimization
1156 void optimize_load_store(ir_graph *irg) {
1159 assert(get_irg_phase_state(irg) != phase_building);
1160 assert(get_irg_pinned(irg) != op_pin_state_floats &&
1161 "LoadStore optimization needs pinned graph");
1163 if (! get_opt_redundant_loadstore())
1168 /* for Phi optimization post-dominators are needed ... */
1169 assure_postdoms(irg);
1171 if (get_opt_alias_analysis()) {
1172 assure_irg_address_taken_computed(irg);
1173 assure_irp_globals_address_taken_computed();
1176 obstack_init(&env.obst);
1179 /* init the links, then collect Loads/Stores/Proj's in lists */
1181 irg_walk_graph(irg, firm_clear_link, collect_nodes, &env);
1183 /* now we have collected enough information, optimize */
1184 irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
1186 obstack_free(&env.obst, NULL);
1188 /* Handle graph state */
1190 if (get_irg_outs_state(irg) == outs_consistent)
1191 set_irg_outs_inconsistent(irg);
1194 if (env.changes & CF_CHANGED) {
1195 /* is this really needed: Yes, control flow changed, block might
1196 have Bad() predecessors. */
1197 set_irg_doms_inconsistent(irg);
1199 } /* optimize_load_store */