2 * Copyright (C) 1995-2011 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 Scalar replacement of compounds.
23 * @author Beyhan Veliev, Michael Beck
30 #include "iroptimize.h"
31 #include "scalar_replace.h"
50 static unsigned get_vnum(const ir_node *node)
52 return (unsigned)PTR_TO_INT(get_irn_link(node));
55 static void set_vnum(ir_node *node, unsigned vnum)
57 set_irn_link(node, INT_TO_PTR(vnum));
61 * A path element entry: it is either an entity
62 * or a tarval, because we evaluate only constant array
63 * accesses like a.b.c[8].d
71 * An access path, used to assign value numbers
72 * to variables that will be scalar replaced.
74 typedef struct path_t {
75 unsigned vnum; /**< The value number. */
76 size_t path_len; /**< The length of the access path. */
77 path_elem_t path[1]; /**< The path. */
80 /** The size of a path in bytes. */
81 static size_t path_size(path_t *p)
83 return sizeof(*p) + sizeof(p->path[0]) * (p->path_len-1);
86 typedef struct scalars_t {
87 ir_entity *ent; /**< A entity for scalar replacement. */
90 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
95 * @return 0 if they are identically
97 static int path_cmp(const void *elt, const void *key, size_t size)
99 const path_t *p1 = (const path_t*)elt;
100 const path_t *p2 = (const path_t*)key;
103 /* we can use memcmp here, because identical tarvals should have identical addresses */
104 return memcmp(p1->path, p2->path, p1->path_len * sizeof(p1->path[0]));
108 * Compare two elements of the scalars_t set.
110 * @return 0 if they are identically
112 static int ent_cmp(const void *elt, const void *key, size_t size)
114 const scalars_t *c1 = (const scalars_t*)elt;
115 const scalars_t *c2 = (const scalars_t*)key;
118 return c1->ent != c2->ent;
122 * Calculate a hash value for a path.
124 static unsigned path_hash(const path_t *path)
129 for (i = 0; i < path->path_len; ++i)
130 hash ^= (unsigned)PTR_TO_INT(path->path[i].ent);
136 * Returns non-zero, if all indeces of a Sel node are constants.
138 * @param sel the Sel node that will be checked
140 static bool is_const_sel(ir_node *sel)
142 int i, n = get_Sel_n_indexs(sel);
144 for (i = 0; i < n; ++i) {
145 ir_node *idx = get_Sel_index(sel, i);
154 * Check the mode of a Load/Store with the mode of the entity
156 * If the mode of the entity and the Load/Store mode do not match, we
157 * have the bad reinterpret case:
160 * char b = *(char *)&i;
162 * We do NOT count this as one value and return address_taken
164 * However, we support an often used case. If the mode is two-complement
165 * we allow casts between signed/unsigned.
167 * @param mode the mode of the Load/Store
168 * @param ent_mode the mode of the accessed entity
170 static bool check_load_store_mode(ir_mode *mode, ir_mode *ent_mode)
172 if (ent_mode != mode) {
173 if (ent_mode == NULL ||
174 get_mode_size_bits(ent_mode) != get_mode_size_bits(mode) ||
175 get_mode_arithmetic(ent_mode) != irma_twos_complement ||
176 get_mode_arithmetic(mode) != irma_twos_complement)
183 * Returns non-zero, if the address of an entity
184 * represented by a Sel node (or its successor Sels) is taken.
186 bool is_address_taken(ir_node *sel)
189 ir_mode *emode, *mode;
193 if (! is_const_sel(sel))
196 for (unsigned i = get_irn_n_outs(sel); i-- > 0; ) {
197 ir_node *succ = get_irn_out(sel, i);
199 switch (get_irn_opcode(succ)) {
201 /* do not remove volatile variables */
202 if (get_Load_volatility(succ) == volatility_is_volatile)
204 /* check if this load is not a hidden conversion */
205 mode = get_Load_mode(succ);
206 ent = get_Sel_entity(sel);
207 emode = get_type_mode(get_entity_type(ent));
208 if (! check_load_store_mode(mode, emode))
213 /* check that Sel is not the Store's value */
214 value = get_Store_value(succ);
217 /* do not remove volatile variables */
218 if (get_Store_volatility(succ) == volatility_is_volatile)
220 /* check if this Store is not a hidden conversion */
221 mode = get_irn_mode(value);
222 ent = get_Sel_entity(sel);
223 emode = get_type_mode(get_entity_type(ent));
224 if (! check_load_store_mode(mode, emode))
230 ir_entity *entity = get_Sel_entity(succ);
231 /* we can't handle unions correctly yet -> address taken */
232 if (is_Union_type(get_entity_owner(entity)))
235 /* Check the Sel successor of Sel */
236 res = is_address_taken(succ);
243 /* The address of an entity is given as a parameter.
244 * As long as we do not have analyses that can tell what
245 * is done with parameters, think is taken.
246 * One special case: If the Call type tells that it's a
247 * value parameter, the address is NOT taken.
252 int res = is_address_taken(succ);
259 /* Non-optimized Tuple, happens in inlining */
260 for (input_nr = get_Tuple_n_preds(succ) - 1; input_nr >= 0; --input_nr) {
261 ir_node *pred = get_Tuple_pred(succ, input_nr);
264 /* we found one input */
265 for (unsigned k = get_irn_n_outs(succ); k-- > 0; ) {
266 ir_node *proj = get_irn_out(succ, k);
268 if (is_Proj(proj) && get_Proj_proj(proj) == input_nr) {
269 int res = is_address_taken(proj);
279 /* another op, the address is taken */
287 * Link all leave Sels with the entity.
289 * @param ent the entity that will be scalar replaced
290 * @param sel a Sel node that selects some fields of this entity
292 static bool link_all_leave_sels(ir_entity *ent, ir_node *sel)
294 bool is_leave = true;
296 for (unsigned i = get_irn_n_outs(sel); i-- > 0; ) {
297 ir_node *succ = get_irn_out(sel, i);
300 /* the current leave has further Sel's, no leave */
302 link_all_leave_sels(ent, succ);
303 } else if (is_Id(succ)) {
304 is_leave &= link_all_leave_sels(ent, succ);
312 /* we know we are at a leave, because this function is only
313 * called if the address is NOT taken, so sel's successor(s)
314 * must be Loads or Stores
316 set_irn_link(sel, get_entity_link(ent));
317 set_entity_link(ent, sel);
322 /* we need a special address that serves as an address taken marker */
324 static void *ADDRESS_TAKEN = &_x;
327 * Find possible scalar replacements.
329 * @param irg an IR graph
331 * This function finds variables on the (members of the) frame type
332 * that can be scalar replaced, because their address is never taken.
333 * If such a variable is found, its entity link will hold a list of all
334 * Sel nodes, that selects the atomic fields of this entity.
335 * Otherwise, the link will be ADDRESS_TAKEN or NULL.
337 * @return non-zero if at least one entity could be replaced
340 static int find_possible_replacements(ir_graph *irg)
345 long static_link_arg;
349 * First, clear the link field of all interesting entities.
351 frame_tp = get_irg_frame_type(irg);
352 for (mem_idx = get_class_n_members(frame_tp); mem_idx > 0;) {
353 ir_entity *ent = get_class_member(frame_tp, --mem_idx);
354 set_entity_link(ent, NULL);
357 /* check for inner functions:
358 * FIXME: need a way to get the argument position for the static link */
360 for (mem_idx = get_class_n_members(frame_tp); mem_idx > 0;) {
361 ir_entity *ent = get_class_member(frame_tp, --mem_idx);
362 if (is_method_entity(ent)) {
363 ir_graph *inner_irg = get_entity_irg(ent);
366 assure_irg_properties(inner_irg, IR_GRAPH_PROPERTY_CONSISTENT_OUTS);
367 args = get_irg_args(inner_irg);
368 for (unsigned j = get_irn_n_outs(args); j-- > 0; ) {
369 ir_node *arg = get_irn_out(args, j);
371 if (get_Proj_proj(arg) == static_link_arg) {
372 for (unsigned k = get_irn_n_outs(arg); k-- > 0; ) {
373 ir_node *succ = get_irn_out(arg, k);
376 ir_entity *ent = get_Sel_entity(succ);
378 if (get_entity_owner(ent) == frame_tp) {
379 /* found an access to the outer frame */
380 set_entity_link(ent, ADDRESS_TAKEN);
390 * Check the ir_graph for Sel nodes. If the entity of Sel
391 * isn't a scalar replacement set the link of this entity
392 * equal ADDRESS_TAKEN.
394 irg_frame = get_irg_frame(irg);
395 for (unsigned i = get_irn_n_outs(irg_frame); i-- > 0; ) {
396 ir_node *succ = get_irn_out(irg_frame, i);
399 ir_entity *ent = get_Sel_entity(succ);
402 /* we are only interested in entities on the frame, NOT
404 if (get_entity_owner(ent) != frame_tp)
407 if (get_entity_link(ent) == ADDRESS_TAKEN)
410 ent_type = get_entity_type(ent);
412 /* we can handle arrays, structs and atomic types yet */
413 if (is_Array_type(ent_type) || is_Struct_type(ent_type) || is_atomic_type(ent_type)) {
414 if (is_address_taken(succ)) {
416 if (get_entity_link(ent))
418 set_entity_link(ent, ADDRESS_TAKEN);
420 /* possible found one */
421 if (get_entity_link(ent) == NULL)
423 link_all_leave_sels(ent, succ);
433 * Return a path from the Sel node "sel" to its root.
435 * @param sel the Sel node
436 * @param len the length of the path so far
438 static path_t *find_path(ir_node *sel, size_t len)
443 ir_node *pred = get_Sel_ptr(sel);
445 /* the current Sel node will add some path elements */
446 n = get_Sel_n_indexs(sel);
449 if (! is_Sel(pred)) {
450 /* we found the root */
451 res = XMALLOCF(path_t, path, len);
454 res = find_path(pred, len);
456 assert(len <= res->path_len);
457 pos = res->path_len - len;
459 res->path[pos++].ent = get_Sel_entity(sel);
460 for (i = 0; i < n; ++i) {
461 ir_node *index = get_Sel_index(sel, i);
463 res->path[pos++].tv = get_Const_tarval(index);
470 * Allocate value numbers for the leaves
471 * in our found entities.
473 * @param sels a set that will contain all Sels that have a value number
474 * @param ent the entity that will be scalar replaced
475 * @param vnum the first value number we can assign
476 * @param modes a flexible array, containing all the modes of
479 * @return the next free value number
481 static unsigned allocate_value_numbers(pset *sels, ir_entity *ent, unsigned vnum, ir_mode ***modes)
485 set *pathes = new_set(path_cmp, 8);
487 DB((dbg, SET_LEVEL_3, " Visiting Sel nodes of entity %+F\n", ent));
488 /* visit all Sel nodes in the chain of the entity */
489 for (sel = (ir_node*)get_entity_link(ent); sel != NULL; sel = next) {
490 next = (ir_node*)get_irn_link(sel);
492 /* we must mark this sel for later */
493 pset_insert_ptr(sels, sel);
495 key = find_path(sel, 0);
496 path = set_find(path_t, pathes, key, path_size(key), path_hash(key));
499 set_vnum(sel, path->vnum);
500 DB((dbg, SET_LEVEL_3, " %+F represents value %u\n", sel, path->vnum));
504 (void)set_insert(path_t, pathes, key, path_size(key), path_hash(key));
506 set_vnum(sel, key->vnum);
507 DB((dbg, SET_LEVEL_3, " %+F represents value %u\n", sel, key->vnum));
509 ARR_EXTO(ir_mode *, *modes, (key->vnum + 15) & ~15);
511 (*modes)[key->vnum] = get_type_mode(get_entity_type(get_Sel_entity(sel)));
513 assert((*modes)[key->vnum] && "Value is not atomic");
519 DB((dbg, SET_LEVEL_2, " %s", get_entity_name(key->path[0].ent)));
520 for (i = 1; i < key->path_len; ++i) {
521 if (is_entity(key->path[i].ent))
522 DB((dbg, SET_LEVEL_2, ".%s", get_entity_name(key->path[i].ent)));
524 DB((dbg, SET_LEVEL_2, "[%ld]", get_tarval_long(key->path[i].tv)));
526 DB((dbg, SET_LEVEL_2, " = %u (%s)\n", PTR_TO_INT(get_irn_link(sel)), get_mode_name((*modes)[key->vnum])));
528 #endif /* DEBUG_libfirm */
534 set_entity_link(ent, NULL);
539 * environment for memory walker
541 typedef struct env_t {
542 unsigned nvals; /**< number of values */
543 ir_mode **modes; /**< the modes of the values */
544 pset *sels; /**< A set of all Sel nodes that have a value number */
548 * topological post-walker.
550 static void walker(ir_node *node, void *ctx)
552 env_t *env = (env_t*)ctx;
553 ir_graph *irg = get_irn_irg(node);
554 ir_node *addr, *block, *mem, *val;
559 /* a load, check if we can resolve it */
560 addr = get_Load_ptr(node);
562 DB((dbg, SET_LEVEL_3, " checking %+F for replacement ", node));
563 if (! is_Sel(addr)) {
564 DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", addr));
568 if (! pset_find_ptr(env->sels, addr)) {
569 DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", addr));
573 /* ok, we have a Load that will be replaced */
574 vnum = get_vnum(addr);
575 assert(vnum < env->nvals);
577 DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
579 block = get_nodes_block(node);
580 set_cur_block(block);
582 /* check, if we can replace this Load */
583 val = get_value(vnum, env->modes[vnum]);
585 /* Beware: A Load can contain a hidden conversion in Firm.
586 This happens for instance in the following code:
589 unsigned j = *(unsigned *)&i;
592 mode = get_Load_mode(node);
593 if (mode != get_irn_mode(val))
594 val = new_rd_Conv(get_irn_dbg_info(node), block, val, mode);
596 mem = get_Load_mem(node);
597 turn_into_tuple(node, pn_Load_max+1);
598 set_Tuple_pred(node, pn_Load_M, mem);
599 set_Tuple_pred(node, pn_Load_res, val);
600 set_Tuple_pred(node, pn_Load_X_regular, new_r_Jmp(block));
601 set_Tuple_pred(node, pn_Load_X_except, new_r_Bad(irg, mode_X));
602 } else if (is_Store(node)) {
603 DB((dbg, SET_LEVEL_3, " checking %+F for replacement ", node));
605 /* a Store always can be replaced */
606 addr = get_Store_ptr(node);
608 if (! is_Sel(addr)) {
609 DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", addr));
613 if (! pset_find_ptr(env->sels, addr)) {
614 DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", addr));
618 vnum = get_vnum(addr);
619 assert(vnum < env->nvals);
621 DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
623 block = get_nodes_block(node);
624 set_cur_block(block);
626 /* Beware: A Store can contain a hidden conversion in Firm. */
627 val = get_Store_value(node);
628 if (get_irn_mode(val) != env->modes[vnum])
629 val = new_rd_Conv(get_irn_dbg_info(node), block, val, env->modes[vnum]);
631 set_value(vnum, val);
633 mem = get_Store_mem(node);
634 turn_into_tuple(node, pn_Store_max+1);
635 set_Tuple_pred(node, pn_Store_M, mem);
636 set_Tuple_pred(node, pn_Store_X_regular, new_r_Jmp(block));
637 set_Tuple_pred(node, pn_Store_X_except, new_r_Bad(irg, mode_X));
642 * Make scalar replacement.
644 * @param sels A set containing all Sel nodes that have a value number
645 * @param nvals The number of scalars.
646 * @param modes A flexible array, containing all the modes of
649 static void do_scalar_replacements(ir_graph *irg, pset *sels, unsigned nvals,
654 ssa_cons_start(irg, (int)nvals);
661 * second step: walk over the graph blockwise in topological order
662 * and fill the array as much as possible.
664 DB((dbg, SET_LEVEL_3, "Substituting Loads and Stores in %+F\n", irg));
665 irg_walk_blkwise_graph(irg, NULL, walker, &env);
667 ssa_cons_finish(irg);
671 * Find possible scalar replacements
673 * @param irg The current ir graph.
675 void scalar_replacement_opt(ir_graph *irg)
683 ir_type *ent_type, *frame_tp;
685 assure_irg_properties(irg,
686 IR_GRAPH_PROPERTY_NO_UNREACHABLE_CODE
687 | IR_GRAPH_PROPERTY_CONSISTENT_OUTS);
689 /* we use the link field to store the VNUM */
690 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
691 irp_reserve_resources(irp, IRP_RESOURCE_ENTITY_LINK);
693 /* Find possible scalar replacements */
694 if (find_possible_replacements(irg)) {
695 DB((dbg, SET_LEVEL_1, "Scalar Replacement: %+F\n", irg));
697 /* Insert in set the scalar replacements. */
698 irg_frame = get_irg_frame(irg);
700 modes = NEW_ARR_F(ir_mode *, 16);
701 set_ent = new_set(ent_cmp, 8);
702 sels = pset_new_ptr(8);
703 frame_tp = get_irg_frame_type(irg);
705 for (unsigned i = get_irn_n_outs(irg_frame); i-- > 0; ) {
706 ir_node *succ = get_irn_out(irg_frame, i);
709 ir_entity *ent = get_Sel_entity(succ);
711 /* we are only interested in entities on the frame, NOT
713 if (get_entity_owner(ent) != frame_tp
714 || is_parameter_entity(ent))
717 if (get_entity_link(ent) == NULL || get_entity_link(ent) == ADDRESS_TAKEN)
720 ent_type = get_entity_type(ent);
723 (void)set_insert(scalars_t, set_ent, &key, sizeof(key), hash_ptr(key.ent));
726 if (is_Array_type(ent_type)) {
727 DB((dbg, SET_LEVEL_1, " found array %s\n", get_entity_name(ent)));
728 } else if (is_Struct_type(ent_type)) {
729 DB((dbg, SET_LEVEL_1, " found struct %s\n", get_entity_name(ent)));
730 } else if (is_atomic_type(ent_type))
731 DB((dbg, SET_LEVEL_1, " found atomic value %s\n", get_entity_name(ent)));
733 panic("Neither an array nor a struct or atomic value found in scalar replace");
735 #endif /* DEBUG_libfirm */
737 nvals = allocate_value_numbers(sels, ent, nvals, &modes);
741 DB((dbg, SET_LEVEL_1, " %u values will be needed\n", nvals));
743 /* If scalars were found. */
745 do_scalar_replacements(irg, sels, nvals, modes);
747 foreach_set(set_ent, scalars_t, value) {
748 free_entity(value->ent);
752 * We changed the graph, but did NOT introduce new blocks
753 * neither changed control flow, cf-backedges should be still
762 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
763 irp_free_resources(irp, IRP_RESOURCE_ENTITY_LINK);
765 confirm_irg_properties(irg, IR_GRAPH_PROPERTIES_NONE);
768 ir_graph_pass_t *scalar_replacement_opt_pass(const char *name)
770 return def_graph_pass(name ? name : "scalar_rep", scalar_replacement_opt);
773 void firm_init_scalar_replace(void)
775 FIRM_DBG_REGISTER(dbg, "firm.opt.scalar_replace");