3 * File name: ir/opt/scalar_replace.c
4 * Purpose: scalar replacement of arrays and compounds
5 * Author: Beyhan Veliev
6 * Modified by: Michael Beck
9 * Copyright: (c) 1998-2005 Universität Karlsruhe
10 * Licence: This file protected by GPL - GNU GENERAL PUBLIC LICENSE.
28 #include "scalar_replace.h"
42 #define SET_VNUM(node, vnum) set_irn_link(node, INT_TO_PTR(vnum))
43 #define GET_VNUM(node) (unsigned)PTR_TO_INT(get_irn_link(node))
46 * A path element entry: it is either an entity
47 * or a tarval, because we evaluate only constant array
48 * accesses like a.b.c[8].d
56 * An access path, used to assign value numbers
57 * to variables that will be scalar replaced.
59 typedef struct _path_t {
60 unsigned vnum; /**< The value number. */
61 unsigned path_len; /**< The length of the access path. */
62 path_elem_t path[1]; /**< The path. */
65 /** The size of a path in bytes. */
66 #define PATH_SIZE(p) (sizeof(*(p)) + sizeof((p)->path[0]) * ((p)->path_len - 1))
68 typedef struct _scalars_t {
69 ir_entity *ent; /**< A entity for scalar replacement. */
70 ir_type *ent_owner; /**< The owner of this entity. */
77 * @return 0 if they are identically
79 static int path_cmp(const void *elt, const void *key, size_t size)
81 const path_t *p1 = elt;
82 const path_t *p2 = key;
84 /* we can use memcmp here, because identical tarvals should have identical addresses */
85 return memcmp(p1->path, p2->path, p1->path_len * sizeof(p1->path[0]));
89 * Compare two elements of the scalars_t set.
91 * @return 0 if they are identically
93 static int ent_cmp(const void *elt, const void *key, size_t size)
95 const scalars_t *c1 = elt;
96 const scalars_t *c2 = key;
98 return c1->ent != c2->ent;
102 * Calculate a hash value for a path.
104 static unsigned path_hash(const path_t *path)
109 for (i = 0; i < path->path_len; ++i)
110 hash ^= (unsigned)PTR_TO_INT(path->path[i].ent);
116 * Returns non-zero, if all indeces of a Sel node are constants.
118 * @param sel the Sel node that will be checked
120 static int is_const_sel(ir_node *sel) {
121 int i, n = get_Sel_n_indexs(sel);
123 for (i = 0; i < n; ++i) {
124 ir_node *idx = get_Sel_index(sel, i);
126 if (get_irn_op(idx) != op_Const)
133 * Check the mode of a Load/Store with the mode of the entity
135 * If the mode of the entity and the Load/Store mode do not match, we
136 * have the bad reinterpret case:
139 * char b = *(char *)&i;
141 * We do NOT count this as one value and return address_taken
143 * However, we support an often used case. If the mode is two-complement
144 * we allow casts between signed/unsigned.
146 * @param mode the mode of the Load/Store
147 * @param ent_mode the mode of the accessed entity
149 static int check_load_store_mode(ir_mode *mode, ir_mode *ent_mode) {
150 if (ent_mode != mode) {
151 if (ent_mode == NULL ||
152 get_mode_size_bits(ent_mode) != get_mode_size_bits(mode) ||
153 get_mode_sort(ent_mode) != get_mode_sort(mode) ||
154 get_mode_arithmetic(ent_mode) != irma_twos_complement ||
155 get_mode_arithmetic(mode) != irma_twos_complement)
162 * Returns non-zero, if the address of an entity
163 * represented by a Sel node (or it's successor Sels) is taken.
165 int is_address_taken(ir_node *sel)
168 ir_mode *emode, *mode;
172 if (! is_const_sel(sel))
175 for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
176 ir_node *succ = get_irn_out(sel, i);
178 switch (get_irn_opcode(succ)) {
180 /* check if this load is not a hidden conversion */
181 mode = get_Load_mode(succ);
182 ent = get_Sel_entity(sel);
183 emode = get_type_mode(get_entity_type(ent));
184 if (! check_load_store_mode(mode, emode))
189 /* check that Sel is not the Store's value */
190 value = get_Store_value(succ);
193 /* check if this Store is not a hidden conversion */
194 mode = get_irn_mode(value);
195 ent = get_Sel_entity(sel);
196 emode = get_type_mode(get_entity_type(ent));
197 if (! check_load_store_mode(mode, emode))
202 /* Check the Sel successor of Sel */
203 int res = is_address_taken(succ);
211 /* The address of an entity is given as a parameter.
212 * As long as we do not have analyses that can tell what
213 * is done with parameters, think is taken.
218 /* another op, the address is taken */
226 * Link all leave Sels with the entity.
228 * @param ent the entity that will be scalar replaced
229 * @param sel a Sel node that selects some fields of this entity
231 static void link_all_leave_sels(ir_entity *ent, ir_node *sel)
235 n = get_irn_n_outs(sel);
236 for (i = 0; i < n; ++i) {
237 ir_node *succ = get_irn_out(sel, i);
240 link_all_leave_sels(ent, succ);
246 /* if Sel nodes with memory inputs are used, a entity can be
247 * visited more than once causing a ring here, so we use the
248 * node flag to mark linked nodes
250 if (irn_visited(sel))
253 /* we know we are at a leave, because this function is only
254 * called if the address is NOT taken, so succ must be a Load
257 set_irn_link(sel, get_entity_link(ent));
258 set_entity_link(ent, sel);
260 mark_irn_visited(sel);
264 /* we need a special address that serves as an address taken marker */
266 static void *ADDRESS_TAKEN = &_x;
269 * Find possible scalar replacements.
271 * @param irg an IR graph
273 * This function finds variables on the (members of the) frame type
274 * that can be scalar replaced, because their address is never taken.
275 * If such a variable is found, it's entity link will hold a list of all
276 * Sel nodes, that selects the atomic fields of this entity.
277 * Otherwise, the link will be ADDRESS_TAKEN or NULL.
279 * @return non-zero if at least one entity could be replaced
282 static int find_possible_replacements(ir_graph *irg)
284 ir_node *irg_frame = get_irg_frame(irg);
288 inc_irg_visited(irg);
290 n = get_irn_n_outs(irg_frame);
293 * First, clear the link field of all interesting entities.
294 * Note that we did not rely on the fact that there is only
295 * one Sel node per entity, so we might access one entity
296 * more than once here.
297 * That's why we have need two loops.
299 for (i = 0; i < n; ++i) {
300 ir_node *succ = get_irn_out(irg_frame, i);
303 ir_entity *ent = get_Sel_entity(succ);
304 set_entity_link(ent, NULL);
309 * Check the ir_graph for Sel nodes. If the entity of Sel
310 * isn't a scalar replacement set the link of this entity
311 * equal ADDRESS_TAKEN.
313 for (i = 0; i < n; ++i) {
314 ir_node *succ = get_irn_out(irg_frame, i);
317 ir_entity *ent = get_Sel_entity(succ);
320 if (get_entity_link(ent) == ADDRESS_TAKEN)
324 * Beware: in rare cases even entities on the frame might be
325 * volatile. This might happen if the entity serves as a store
326 * to a value that must survive a exception. Do not optimize
327 * such entities away.
329 if (get_entity_volatility(ent) == volatility_is_volatile) {
330 set_entity_link(ent, ADDRESS_TAKEN);
334 ent_type = get_entity_type(ent);
336 /* we can handle arrays, structs and atomic types yet */
337 if (is_Array_type(ent_type) || is_Struct_type(ent_type) || is_atomic_type(ent_type)) {
338 if (is_address_taken(succ)) {
339 if (get_entity_link(ent)) /* killing one */
341 set_entity_link(ent, ADDRESS_TAKEN);
344 /* possible found one */
345 if (get_entity_link(ent) == NULL)
347 link_all_leave_sels(ent, succ);
357 * Return a path from the Sel node sel to it's root.
359 * @param sel the Sel node
360 * @param len the length of the path so far
362 static path_t *find_path(ir_node *sel, unsigned len)
366 ir_node *pred = get_Sel_ptr(sel);
368 /* the current Sel node will add some path elements */
369 n = get_Sel_n_indexs(sel);
372 if (! is_Sel(pred)) {
373 /* we found the root */
375 res = xmalloc(sizeof(*res) + (len - 1) * sizeof(res->path));
379 res = find_path(pred, len);
381 pos = res->path_len - len;
383 res->path[pos++].ent = get_Sel_entity(sel);
384 for (i = 0; i < n; ++i) {
385 ir_node *index = get_Sel_index(sel, i);
387 res->path[pos++].tv = get_Const_tarval(index);
394 * Allocate value numbers for the leaves
395 * in our found entities.
397 * @param sels a set that will contain all Sels that have a value number
398 * @param ent the entity that will be scalar replaced
399 * @param vnum the first value number we can assign
400 * @param modes a flexible array, containing all the modes of
403 * @return the next free value number
405 static unsigned allocate_value_numbers(pset *sels, ir_entity *ent, unsigned vnum, ir_mode ***modes)
409 set *pathes = new_set(path_cmp, 8);
411 /* visit all Sel nodes in the chain of the entity */
412 for (sel = get_entity_link(ent); sel; sel = next) {
413 next = get_irn_link(sel);
415 /* we must mark this sel for later */
416 pset_insert_ptr(sels, sel);
418 key = find_path(sel, 0);
419 path = set_find(pathes, key, PATH_SIZE(key), path_hash(key));
422 SET_VNUM(sel, path->vnum);
426 set_insert(pathes, key, PATH_SIZE(key), path_hash(key));
428 SET_VNUM(sel, key->vnum);
429 ARR_EXTO(ir_mode *, *modes, (key->vnum + 15) & ~15);
431 (*modes)[key->vnum] = get_type_mode(get_entity_type(get_Sel_entity(sel)));
433 assert((*modes)[key->vnum] && "Value is not atomic");
437 if (get_opt_scalar_replacement_verbose() && get_firm_verbosity() > 1) {
439 printf(" %s", get_entity_name(key->path[0].ent));
440 for (i = 1; i < key->path_len; ++i) {
441 if (is_entity(key->path[i].ent))
442 printf(".%s", get_entity_name(key->path[i].ent));
444 printf("[%ld]", get_tarval_long(key->path[i].tv));
446 printf(" = %u (%s)\n", PTR_TO_INT(get_irn_link(sel)), get_mode_name((*modes)[key->vnum]));
448 #endif /* DEBUG_libfirm */
454 set_entity_link(ent, NULL);
459 * A list entry for the fixing lists
461 typedef struct _list_entry_t {
462 ir_node *node; /**< the node that must be fixed */
463 unsigned vnum; /**< the value number of this node */
467 * environment for memory walker
469 typedef struct _env_t {
470 struct obstack obst; /**< a obstack for the value blocks */
471 int nvals; /**< number of values */
472 ir_mode **modes; /**< the modes of the values */
473 list_entry_t *fix_phis; /**< list of all Phi nodes that must be fixed */
474 list_entry_t *fix_loads; /**< list of all Load nodes that must be fixed */
475 pset *sels; /**< A set of all Sel nodes that have a value number */
479 * topological walker.
481 static void topologic_walker(ir_node *node, void *ctx)
484 ir_op *op = get_irn_op(node);
485 ir_node *adr, *block, *mem, *unk, **value_arr, **in, *val;
492 /* a load, check if we can resolve it */
493 adr = get_Load_ptr(node);
498 if (! pset_find_ptr(env->sels, adr))
501 /* ok, we have a Load that will be replaced */
502 vnum = GET_VNUM(adr);
504 assert(vnum < (unsigned)env->nvals);
506 block = get_nodes_block(node);
507 value_arr = get_irn_link(block);
509 /* check, if we can replace this Load */
510 if (value_arr[vnum]) {
511 mem = get_Load_mem(node);
513 /* Beware: A Load can contain a hidden conversion in Firm.
514 This happens for instance in the following code:
517 unsigned j = *(unsigned *)&i;
520 val = value_arr[vnum];
521 mode = get_Load_mode(node);
522 if (mode != get_irn_mode(val))
523 val = new_d_Conv(get_irn_dbg_info(node), val, mode);
525 turn_into_tuple(node, pn_Load_max);
526 set_Tuple_pred(node, pn_Load_M, mem);
527 set_Tuple_pred(node, pn_Load_res, val);
528 set_Tuple_pred(node, pn_Load_X_except, new_Bad());
530 l = obstack_alloc(&env->obst, sizeof(*l));
534 set_irn_link(node, env->fix_loads);
537 } else if (op == op_Store) {
538 /* a Store always can be replaced */
539 adr = get_Store_ptr(node);
544 if (! pset_find_ptr(env->sels, adr))
547 vnum = GET_VNUM(adr);
549 assert(vnum < (unsigned)env->nvals);
551 block = get_nodes_block(node);
552 value_arr = get_irn_link(block);
554 /* Beware: A Store can contain a hidden conversion in Firm. */
555 val = get_Store_value(node);
556 if (get_irn_mode(val) != env->modes[vnum])
557 val = new_d_Conv(get_irn_dbg_info(node), val, env->modes[vnum]);
558 value_arr[vnum] = val;
560 mem = get_Store_mem(node);
562 turn_into_tuple(node, pn_Store_max);
563 set_Tuple_pred(node, pn_Store_M, mem);
564 set_Tuple_pred(node, pn_Store_X_except, new_Bad());
565 } else if (op == op_Phi && get_irn_mode(node) == mode_M) {
567 * found a memory Phi: Here, we must create new Phi nodes
569 block = get_nodes_block(node);
570 value_arr = get_irn_link(block);
572 n = get_Block_n_cfgpreds(block);
574 in = alloca(sizeof(*in) * n);
576 for (i = env->nvals - 1; i >= 0; --i) {
577 unk = new_Unknown(env->modes[i]);
578 for (j = n - 1; j >= 0; --j)
581 value_arr[i] = new_r_Phi(current_ir_graph, block, n, in, env->modes[i]);
583 l = obstack_alloc(&env->obst, sizeof(*l));
584 l->node = value_arr[i];
587 set_irn_link(value_arr[i], env->fix_phis);
594 * Walker: allocate the value array for every block.
596 static void alloc_value_arr(ir_node *block, void *ctx)
599 ir_node **var_arr = obstack_alloc(&env->obst, sizeof(*var_arr) * env->nvals);
601 /* the value array is empty at start */
602 memset(var_arr, 0, sizeof(*var_arr) * env->nvals);
603 set_irn_link(block, var_arr);
607 * searches through blocks beginning from block for value
608 * vnum and return it.
610 static ir_node *find_vnum_value(ir_node *block, unsigned vnum)
616 if (Block_not_block_visited(block)) {
617 mark_Block_block_visited(block);
619 value_arr = get_irn_link(block);
622 return value_arr[vnum];
624 for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
625 ir_node *pred = get_Block_cfgpred(block, i);
627 res = find_vnum_value(get_nodes_block(pred), vnum);
638 static void fix_phis(env_t *env)
641 ir_node *phi, *block, *pred, *val;
644 for (l = env->fix_phis; l; l = get_irn_link(phi)) {
647 block = get_nodes_block(phi);
648 for (i = get_irn_arity(phi) - 1; i >= 0; --i) {
649 pred = get_Block_cfgpred(block, i);
650 pred = get_nodes_block(pred);
652 inc_irg_block_visited(current_ir_graph);
653 val = find_vnum_value(pred, l->vnum);
656 set_irn_n(phi, i, val);
664 static void fix_loads(env_t *env)
667 ir_node *load, *block, *pred, *val = NULL, *mem;
671 for (l = env->fix_loads; l; l = get_irn_link(load)) {
674 block = get_nodes_block(load);
675 for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
676 pred = get_Block_cfgpred(block, i);
677 pred = get_nodes_block(pred);
679 inc_irg_block_visited(current_ir_graph);
680 val = find_vnum_value(pred, l->vnum);
687 /* access of an uninitialized value */
688 val = new_Unknown(env->modes[l->vnum]);
691 mem = get_Load_mem(load);
692 /* Beware: A Load can contain a hidden conversion in Firm.
694 mode = get_Load_mode(load);
695 if (mode != get_irn_mode(val))
696 val = new_d_Conv(get_irn_dbg_info(load), val, mode);
698 turn_into_tuple(load, pn_Load_max);
699 set_Tuple_pred(load, pn_Load_M, mem);
700 set_Tuple_pred(load, pn_Load_res, val);
701 set_Tuple_pred(load, pn_Load_X_except, new_Bad());
706 * Make scalar replacement.
708 * @param sels A set containing all Sel nodes that have a value number
709 * @param nvals The number of scalars.
710 * @param modes A flexible array, containing all the modes of
713 static void do_scalar_replacements(pset *sels, int nvals, ir_mode **modes)
717 obstack_init(&env.obst);
721 env.fix_loads = NULL;
724 /* first step: allocate the value arrays for every block */
725 irg_block_walk_graph(current_ir_graph, NULL, alloc_value_arr, &env);
728 * second step: walk over the graph blockwise in topological order
729 * and fill the array as much as possible.
731 irg_walk_blkwise_graph(current_ir_graph, NULL, topologic_walker, &env);
733 /* third, fix the list of Phis, then the list of Loads */
737 obstack_free(&env.obst, NULL);
741 * Find possible scalar replacements
743 * @param irg The current ir graph.
745 void scalar_replacement_opt(ir_graph *irg)
749 scalars_t key, *value;
757 if (! get_opt_scalar_replacement())
760 rem = current_ir_graph;
762 /* Call algorithm that computes the out edges */
763 assure_irg_outs(irg);
765 /* Find possible scalar replacements */
766 if (find_possible_replacements(irg)) {
768 if (get_opt_scalar_replacement_verbose()) {
769 printf("Scalar Replacement: %s\n", get_entity_name(get_irg_entity(irg)));
772 /* Insert in set the scalar replacements. */
773 irg_frame = get_irg_frame(irg);
775 modes = NEW_ARR_F(ir_mode *, 16);
776 set_ent = new_set(ent_cmp, 8);
777 sels = pset_new_ptr(8);
779 for (i = 0 ; i < get_irn_n_outs(irg_frame); i++) {
780 ir_node *succ = get_irn_out(irg_frame, i);
783 ir_entity *ent = get_Sel_entity(succ);
785 if (get_entity_link(ent) == NULL || get_entity_link(ent) == ADDRESS_TAKEN)
788 ent_type = get_entity_type(ent);
791 key.ent_owner = get_entity_owner(ent);
792 set_insert(set_ent, &key, sizeof(key), HASH_PTR(key.ent));
794 if (get_opt_scalar_replacement_verbose()) {
795 if (is_Array_type(ent_type)) {
796 printf(" found array %s\n", get_entity_name(ent));
798 else if (is_Struct_type(ent_type)) {
799 printf(" found struct %s\n", get_entity_name(ent));
801 else if (is_atomic_type(ent_type))
802 printf(" found atomic value %s\n", get_entity_name(ent));
804 assert(0 && "Neither an array nor a struct or atomic value");
808 nvals = allocate_value_numbers(sels, ent, nvals, &modes);
812 if (get_opt_scalar_replacement_verbose()) {
813 printf(" %u values will be needed\n", nvals);
816 /* If scalars were found. */
818 do_scalar_replacements(sels, nvals, modes);
820 for (value = set_first(set_ent); value; value = set_next(set_ent)) {
821 remove_class_member(value->ent_owner, value->ent);
831 * We changed the graph, but did NOT introduce new blocks
832 * neither changed control flow, cf-backedges should be still
835 set_irg_outs_inconsistent(irg);
836 set_irg_loopinfo_inconsistent(irg);
840 current_ir_graph = rem;