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 typedef struct _scalars_t {
66 entity *ent; /**< A entity for scalar replacement. */
67 type *ent_owner; /**< The owner of this entity. */
74 * @return 0 if they are identically
76 static int path_cmp(const void *elt, const void *key, size_t size)
78 const path_t *p1 = elt;
79 const path_t *p2 = key;
81 /* we can use memcmp here, because identical tarvals should have identical addresses */
82 return memcmp(p1->path, p2->path, p1->path_len * sizeof(p1->path[0]));
86 * Compare two elements of the scalars_t set.
88 * @return 0 if they are identically
90 static int ent_cmp(const void *elt, const void *key, size_t size)
92 const scalars_t *c1 = elt;
93 const scalars_t *c2 = key;
95 return c1->ent != c2->ent;
99 * Calculate a hash value for a path.
101 static unsigned path_hash(const path_t *path)
106 for (i = 0; i < path->path_len; ++i)
107 hash ^= (unsigned)PTR_TO_INT(path->path[i].ent);
113 * Returns non-zero, if all indeces of a Sel node are constants.
115 * @param sel the Sel node that will be checked
117 static int is_const_sel(ir_node *sel) {
118 int i, n = get_Sel_n_indexs(sel);
120 for (i = 0; i < n; ++i) {
121 ir_node *idx = get_Sel_index(sel, i);
123 if (get_irn_op(idx) != op_Const)
130 * Returns non-zero, if the address of an entity
131 * represented by a Sel node (or it's successor Sels) is taken.
133 int is_address_taken(ir_node *sel)
137 if (! is_const_sel(sel))
140 for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
141 ir_node *succ = get_irn_out(sel, i);
143 switch (get_irn_opcode(succ)) {
145 /* ok, we just load from that entity */
149 /* check that Sel is not the Store's value */
150 if (get_Store_value(succ) == sel)
155 /* Check the Sel successor of Sel */
156 int res = is_address_taken(succ);
164 /* The address of an entity is given as a parameter.
165 * As long as we do not have analyses that can tell what
166 * is done with parameters, think is taken.
171 /* another op, the address is taken */
179 * Link all leave Sels with the entity.
181 * @param ent the entity that will be scalar replaced
182 * @param sel a Sel node that selects some fields of this entity
184 static void link_all_leave_sels(entity *ent, ir_node *sel)
188 n = get_irn_n_outs(sel);
189 for (i = 0; i < n; ++i) {
190 ir_node *succ = get_irn_out(sel, i);
192 if (get_irn_op(succ) == op_Sel) {
193 link_all_leave_sels(ent, succ);
199 /* if Sel nodes with memory inputs are used, a entity can be
200 * visited more than once causing a ring here, so we use the
201 * node flag to mark linked nodes
203 if (irn_visited(sel))
206 /* we know we are at a leave, because this function is only
207 * called if the address is NOT taken, so succ must be a Load
210 set_irn_link(sel, get_entity_link(ent));
211 set_entity_link(ent, sel);
213 mark_irn_visited(sel);
217 /* we need a special address that serves as an address taken marker */
219 static void *ADDRESS_TAKEN = &_x;
222 * Find possible scalar replacements.
224 * @param irg an IR graph
226 * This function finds variables on the (members of the) frame type
227 * that can be scalar replaced, because their address is never taken.
228 * If such a variable is found, it's entity link will hold a list of all
229 * Sel nodes, that selects the atomic fields of this entity.
230 * Otherwise, the link will be ADDRESS_TAKEN or NULL.
232 * @return non-zero if at least one entity could be replaced
235 static int find_possible_replacements(ir_graph *irg)
237 ir_node *irg_frame = get_irg_frame(irg);
241 inc_irg_visited(irg);
243 n = get_irn_n_outs(irg_frame);
246 * First, clear the link field of all interesting entities.
247 * Note that we did not rely on the fact that there is only
248 * one Sel node per entity, so we might access one entity
249 * more than once here.
250 * That's why we have need two loops.
252 for (i = 0; i < n; ++i) {
253 ir_node *succ = get_irn_out(irg_frame, i);
255 if (get_irn_op(succ) == op_Sel) {
256 entity *ent = get_Sel_entity(succ);
257 set_entity_link(ent, NULL);
262 * Check the ir_graph for Sel nodes. If the entity of Sel
263 * isn't a scalar replacement set the link of this entity
264 * equal ADDRESS_TAKEN.
266 for (i = 0; i < n; ++i) {
267 ir_node *succ = get_irn_out(irg_frame, i);
269 if (get_irn_op(succ) == op_Sel) {
270 entity *ent = get_Sel_entity(succ);
273 if (get_entity_link(ent) == ADDRESS_TAKEN)
276 ent_type = get_entity_type(ent);
278 /* we can handle arrays, structs and atomic types yet */
279 if (is_Array_type(ent_type) || is_Struct_type(ent_type) || is_atomic_type(ent_type)) {
280 if (is_address_taken(succ)) {
281 if (get_entity_link(ent)) /* killing one */
283 set_entity_link(ent, ADDRESS_TAKEN);
286 /* possible found one */
287 if (get_entity_link(ent) == NULL)
289 link_all_leave_sels(ent, succ);
299 * Return a path from the Sel node sel to it's root.
301 * @param sel the Sel node
302 * @param len the length of the path so far
304 static path_t *find_path(ir_node *sel, unsigned len)
308 ir_node *pred = get_Sel_ptr(sel);
310 /* the current Sel node will add some path elements */
311 n = get_Sel_n_indexs(sel);
314 if (get_irn_op(pred) != op_Sel) {
315 /* we found the root */
317 res = xmalloc(sizeof(*res) + (len - 1) * sizeof(res->path));
321 res = find_path(pred, len);
323 pos = res->path_len - len;
325 res->path[pos++].ent = get_Sel_entity(sel);
326 for (i = 0; i < n; ++i) {
327 ir_node *index = get_Sel_index(sel, i);
329 res->path[pos++].tv = get_Const_tarval(index);
336 * Allocate value numbers for the leaves
337 * in our found entities.
339 * @param sels a set that will contain all Sels that have a value number
340 * @param ent the entity that will be scalar replaced
341 * @param vnum the first value number we can assign
342 * @param modes a flexible array, containing all the modes of
345 * @return the next free value number
347 static unsigned allocate_value_numbers(pset *sels, entity *ent, unsigned vnum, ir_mode ***modes)
351 set *pathes = new_set(path_cmp, 8);
353 /* visit all Sel nodes in the chain of the entity */
354 for (sel = get_entity_link(ent); sel; sel = next) {
355 next = get_irn_link(sel);
357 /* we must mark this sel for later */
358 pset_insert_ptr(sels, sel);
360 key = find_path(sel, 0);
361 path = set_find(pathes, key, sizeof(*key) + sizeof(key->path[0]) * key->path_len, path_hash(key));
364 SET_VNUM(sel, path->vnum);
370 set_insert(pathes, key, sizeof(*key) + sizeof(key->path[0]) * key->path_len, path_hash(key));
372 SET_VNUM(sel, key->vnum);
373 ARR_EXTO(ir_mode *, *modes, (key->vnum + 15) & ~15);
375 (*modes)[key->vnum] = get_type_mode(get_entity_type(get_Sel_entity(sel)));
377 assert((*modes)[key->vnum] && "Value is not atomic");
381 if (get_opt_scalar_replacement_verbose() && get_firm_verbosity() > 1) {
382 printf(" %s", get_entity_name(ent));
383 for (i = 1; i < key->path_len; ++i) {
384 if (is_entity(key->path[i].ent))
385 printf(".%s", get_entity_name(key->path[i].ent));
387 printf("[%ld]", get_tarval_long(key->path[i].tv));
389 printf(" = %u (%s)\n", PTR_TO_INT(get_irn_link(sel)), get_mode_name((*modes)[key->vnum]));
391 #endif /* DEBUG_libfirm */
397 set_entity_link(ent, NULL);
402 * A list entry for the fixing lists
404 typedef struct _list_entry_t {
405 ir_node *node; /**< the node that must be fixed */
406 unsigned vnum; /**< the value number of this node */
410 * environment for memory walker
412 typedef struct _env_t {
413 struct obstack obst; /**< a obstack for the value blocks */
414 int nvals; /**< number of values */
415 ir_mode **modes; /**< the modes of the values */
416 list_entry_t *fix_phis; /**< list of all Phi nodes that must be fixed */
417 list_entry_t *fix_loads; /**< list of all Load nodes that must be fixed */
418 pset *sels; /**< A set of all Sel nodes that have a value number */
424 static void handle_first(ir_node *node, void *ctx)
427 ir_op *op = get_irn_op(node);
428 ir_node *adr, *block, *mem, *unk, **value_arr, **in;
434 /* a load, check if we can resolve it */
435 adr = get_Load_ptr(node);
437 if (get_irn_op(adr) != op_Sel)
440 if (! pset_find_ptr(env->sels, adr))
443 /* ok, we have a Load that will be replaced */
444 vnum = GET_VNUM(adr);
446 assert(vnum < (unsigned)env->nvals);
448 block = get_nodes_block(node);
449 value_arr = get_irn_link(block);
451 /* check, if we can replace this Load */
452 if (value_arr[vnum]) {
453 mem = get_Load_mem(node);
455 turn_into_tuple(node, pn_Load_max);
456 set_Tuple_pred(node, pn_Load_M, mem);
457 set_Tuple_pred(node, pn_Load_res, value_arr[vnum]);
458 set_Tuple_pred(node, pn_Load_X_except, new_Bad());
461 l = obstack_alloc(&env->obst, sizeof(*l));
465 set_irn_link(node, env->fix_loads);
469 else if (op == op_Store) {
470 /* a Store always can be replaced */
471 adr = get_Store_ptr(node);
473 if (get_irn_op(adr) != op_Sel)
476 if (! pset_find_ptr(env->sels, adr))
479 vnum = GET_VNUM(adr);
481 assert(vnum < (unsigned)env->nvals);
483 block = get_nodes_block(node);
484 value_arr = get_irn_link(block);
486 value_arr[vnum] = get_Store_value(node);
488 mem = get_Store_mem(node);
490 turn_into_tuple(node, pn_Store_max);
491 set_Tuple_pred(node, pn_Store_M, mem);
492 set_Tuple_pred(node, pn_Store_X_except, new_Bad());
494 else if (op == op_Phi && get_irn_mode(node) == mode_M) {
496 * found a memory Phi: Here, we must create new Phi nodes
498 block = get_nodes_block(node);
499 value_arr = get_irn_link(block);
501 n = get_Block_n_cfgpreds(block);
503 in = alloca(sizeof(*in) * n);
505 for (i = env->nvals - 1; i >= 0; --i) {
506 unk = new_Unknown(env->modes[i]);
507 for (j = n - 1; j >= 0; --j)
510 value_arr[i] = new_r_Phi(current_ir_graph, block, n, in, env->modes[i]);
512 l = obstack_alloc(&env->obst, sizeof(*l));
513 l->node = value_arr[i];
516 set_irn_link(value_arr[i], env->fix_phis);
523 * Walker: allocate the value array for every block.
525 static void alloc_value_arr(ir_node *block, void *ctx)
528 ir_node **var_arr = obstack_alloc(&env->obst, sizeof(*var_arr) * env->nvals);
530 /* the value array is empty at start */
531 memset(var_arr, 0, sizeof(*var_arr) * env->nvals);
532 set_irn_link(block, var_arr);
536 * searches through blocks beginning from block for value
537 * vnum and return it.
539 static ir_node *find_value(ir_node *block, unsigned vnum)
545 if (Block_not_block_visited(block)) {
546 mark_Block_block_visited(block);
548 value_arr = get_irn_link(block);
551 return value_arr[vnum];
553 for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
554 ir_node *pred = get_Block_cfgpred(block, i);
556 res = find_value(get_nodes_block(pred), vnum);
567 static void fix_phis(env_t *env)
570 ir_node *phi, *block, *pred, *val;
573 for (l = env->fix_phis; l; l = get_irn_link(phi)) {
576 block = get_nodes_block(phi);
577 for (i = get_irn_arity(phi) - 1; i >= 0; --i) {
578 pred = get_Block_cfgpred(block, i);
579 pred = get_nodes_block(pred);
581 inc_irg_block_visited(current_ir_graph);
582 val = find_value(pred, l->vnum);
585 set_irn_n(phi, i, val);
593 static void fix_loads(env_t *env)
596 ir_node *load, *block, *pred, *val, *mem;
599 for (l = env->fix_loads; l; l = get_irn_link(load)) {
602 block = get_nodes_block(load);
603 for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
604 pred = get_Block_cfgpred(block, i);
605 pred = get_nodes_block(pred);
607 inc_irg_block_visited(current_ir_graph);
608 val = find_value(pred, l->vnum);
615 /* access of an uninitialized value */
616 val = new_Unknown(env->modes[l->vnum]);
619 mem = get_Load_mem(load);
621 turn_into_tuple(load, pn_Load_max);
622 set_Tuple_pred(load, pn_Load_M, mem);
623 set_Tuple_pred(load, pn_Load_res, val);
624 set_Tuple_pred(load, pn_Load_X_except, new_Bad());
629 * Make scalar replacement.
631 * @param sels A set containing all Sel nodes that have a value number
632 * @param nvals The number of scalars.
633 * @param modes A flexible array, containing all the modes of
636 static void do_scalar_replacements(pset *sels, int nvals, ir_mode **modes)
640 obstack_init(&env.obst);
644 env.fix_loads = NULL;
647 /* first step: allocate the value arrays for every block */
648 irg_block_walk_graph(current_ir_graph, NULL, alloc_value_arr, &env);
651 * second step: walk over the graph blockwise in topological order
652 * and fill the array as much as possible.
654 irg_walk_blkwise_graph(current_ir_graph, NULL, handle_first, &env);
656 /* third, fix the list of Phis, then the list of Loads */
660 obstack_free(&env.obst, NULL);
664 * Find possible scalar replacements
666 * @param irg The current ir graph.
668 void scalar_replacement_opt(ir_graph *irg)
672 scalars_t key, *value;
680 if (! get_opt_scalar_replacement())
683 rem = current_ir_graph;
685 /* Call algorithm that computes the out edges */
686 if (get_irg_outs_state(irg) != outs_consistent)
687 compute_irg_outs(irg);
689 /* Find possible scalar replacements */
690 if (find_possible_replacements(irg)) {
692 if (get_opt_scalar_replacement_verbose()) {
693 printf("Scalar Replacement: %s\n", get_entity_name(get_irg_entity(irg)));
696 /* Insert in set the scalar replacements. */
697 irg_frame = get_irg_frame(irg);
699 modes = NEW_ARR_F(ir_mode *, 16);
700 set_ent = new_set(ent_cmp, 8);
701 sels = pset_new_ptr(8);
703 for (i = 0 ; i < get_irn_n_outs(irg_frame); i++) {
704 ir_node *succ = get_irn_out(irg_frame, i);
706 if (get_irn_op(succ) == op_Sel) {
707 entity *ent = get_Sel_entity(succ);
709 if (get_entity_link(ent) == NULL || get_entity_link(ent) == ADDRESS_TAKEN)
712 ent_type = get_entity_type(ent);
715 key.ent_owner = get_entity_owner(ent);
716 set_insert(set_ent, &key, sizeof(key), HASH_PTR(key.ent));
718 if (get_opt_scalar_replacement_verbose()) {
719 if (is_Array_type(ent_type)) {
720 printf(" found array %s\n", get_entity_name(ent));
722 else if (is_Struct_type(ent_type)) {
723 printf(" found struct %s\n", get_entity_name(ent));
725 else if (is_atomic_type(ent_type))
726 printf(" found atomic value %s\n", get_entity_name(ent));
728 assert(0 && "Neither an array nor a struct or atomic value");
732 nvals = allocate_value_numbers(sels, ent, nvals, &modes);
736 if (get_opt_scalar_replacement_verbose()) {
737 printf(" %u values will be needed\n", nvals);
740 /* If scalars were found. */
742 do_scalar_replacements(sels, nvals, modes);
744 for (value = set_first(set_ent); value; value = set_next(set_ent)) {
745 remove_class_member(value->ent_owner, value->ent);
755 * We changed the graph, but did NOT introduce new blocks
756 * neither changed control flow, cf-backedges should be still
759 set_irg_outs_inconsistent(irg);
760 set_irg_loopinfo_inconsistent(irg);
764 current_ir_graph = rem;