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
31 #include "iroptimize.h"
32 #include "scalar_replace.h"
50 #include "opt_manage.h"
52 static unsigned get_vnum(const ir_node *node)
54 return (unsigned)PTR_TO_INT(get_irn_link(node));
57 static void set_vnum(ir_node *node, unsigned vnum)
59 set_irn_link(node, INT_TO_PTR(vnum));
63 * A path element entry: it is either an entity
64 * or a tarval, because we evaluate only constant array
65 * accesses like a.b.c[8].d
73 * An access path, used to assign value numbers
74 * to variables that will be scalar replaced.
76 typedef struct path_t {
77 unsigned vnum; /**< The value number. */
78 size_t path_len; /**< The length of the access path. */
79 path_elem_t path[1]; /**< The path. */
82 /** The size of a path in bytes. */
83 static size_t path_size(path_t *p)
85 return sizeof(*p) + sizeof(p->path[0]) * (p->path_len-1);
88 typedef struct scalars_t {
89 ir_entity *ent; /**< A entity for scalar replacement. */
92 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
97 * @return 0 if they are identically
99 static int path_cmp(const void *elt, const void *key, size_t size)
101 const path_t *p1 = (const path_t*)elt;
102 const path_t *p2 = (const path_t*)key;
105 /* we can use memcmp here, because identical tarvals should have identical addresses */
106 return memcmp(p1->path, p2->path, p1->path_len * sizeof(p1->path[0]));
110 * Compare two elements of the scalars_t set.
112 * @return 0 if they are identically
114 static int ent_cmp(const void *elt, const void *key, size_t size)
116 const scalars_t *c1 = (const scalars_t*)elt;
117 const scalars_t *c2 = (const scalars_t*)key;
120 return c1->ent != c2->ent;
124 * Calculate a hash value for a path.
126 static unsigned path_hash(const path_t *path)
131 for (i = 0; i < path->path_len; ++i)
132 hash ^= (unsigned)PTR_TO_INT(path->path[i].ent);
138 * Returns non-zero, if all indeces of a Sel node are constants.
140 * @param sel the Sel node that will be checked
142 static bool is_const_sel(ir_node *sel)
144 int i, n = get_Sel_n_indexs(sel);
146 for (i = 0; i < n; ++i) {
147 ir_node *idx = get_Sel_index(sel, i);
156 * Check the mode of a Load/Store with the mode of the entity
158 * If the mode of the entity and the Load/Store mode do not match, we
159 * have the bad reinterpret case:
162 * char b = *(char *)&i;
164 * We do NOT count this as one value and return address_taken
166 * However, we support an often used case. If the mode is two-complement
167 * we allow casts between signed/unsigned.
169 * @param mode the mode of the Load/Store
170 * @param ent_mode the mode of the accessed entity
172 static bool check_load_store_mode(ir_mode *mode, ir_mode *ent_mode)
174 if (ent_mode != mode) {
175 if (ent_mode == NULL ||
176 get_mode_size_bits(ent_mode) != get_mode_size_bits(mode) ||
177 get_mode_arithmetic(ent_mode) != irma_twos_complement ||
178 get_mode_arithmetic(mode) != irma_twos_complement)
185 * Returns non-zero, if the address of an entity
186 * represented by a Sel node (or its successor Sels) is taken.
188 bool is_address_taken(ir_node *sel)
191 ir_mode *emode, *mode;
195 if (! is_const_sel(sel))
198 for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
199 ir_node *succ = get_irn_out(sel, i);
201 switch (get_irn_opcode(succ)) {
203 /* do not remove volatile variables */
204 if (get_Load_volatility(succ) == volatility_is_volatile)
206 /* check if this load is not a hidden conversion */
207 mode = get_Load_mode(succ);
208 ent = get_Sel_entity(sel);
209 emode = get_type_mode(get_entity_type(ent));
210 if (! check_load_store_mode(mode, emode))
215 /* check that Sel is not the Store's value */
216 value = get_Store_value(succ);
219 /* do not remove volatile variables */
220 if (get_Store_volatility(succ) == volatility_is_volatile)
222 /* check if this Store is not a hidden conversion */
223 mode = get_irn_mode(value);
224 ent = get_Sel_entity(sel);
225 emode = get_type_mode(get_entity_type(ent));
226 if (! check_load_store_mode(mode, emode))
232 ir_entity *entity = get_Sel_entity(succ);
233 /* we can't handle unions correctly yet -> address taken */
234 if (is_Union_type(get_entity_owner(entity)))
237 /* Check the Sel successor of Sel */
238 res = is_address_taken(succ);
245 /* The address of an entity is given as a parameter.
246 * As long as we do not have analyses that can tell what
247 * is done with parameters, think is taken.
248 * One special case: If the Call type tells that it's a
249 * value parameter, the address is NOT taken.
254 int res = is_address_taken(succ);
261 /* Non-optimized Tuple, happens in inlining */
262 for (input_nr = get_Tuple_n_preds(succ) - 1; input_nr >= 0; --input_nr) {
263 ir_node *pred = get_Tuple_pred(succ, input_nr);
266 /* we found one input */
267 for (k = get_irn_n_outs(succ) - 1; k >= 0; --k) {
268 ir_node *proj = get_irn_out(succ, k);
270 if (is_Proj(proj) && get_Proj_proj(proj) == input_nr) {
271 int res = is_address_taken(proj);
281 /* another op, the address is taken */
289 * Link all leave Sels with the entity.
291 * @param ent the entity that will be scalar replaced
292 * @param sel a Sel node that selects some fields of this entity
294 static bool link_all_leave_sels(ir_entity *ent, ir_node *sel)
297 bool is_leave = true;
299 for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
300 ir_node *succ = get_irn_out(sel, i);
303 /* the current leave has further Sel's, no leave */
305 link_all_leave_sels(ent, succ);
306 } else if (is_Id(succ)) {
307 is_leave &= link_all_leave_sels(ent, succ);
315 /* we know we are at a leave, because this function is only
316 * called if the address is NOT taken, so sel's successor(s)
317 * must be Loads or Stores
319 set_irn_link(sel, get_entity_link(ent));
320 set_entity_link(ent, sel);
325 /* we need a special address that serves as an address taken marker */
327 static void *ADDRESS_TAKEN = &_x;
330 * Find possible scalar replacements.
332 * @param irg an IR graph
334 * This function finds variables on the (members of the) frame type
335 * that can be scalar replaced, because their address is never taken.
336 * If such a variable is found, its entity link will hold a list of all
337 * Sel nodes, that selects the atomic fields of this entity.
338 * Otherwise, the link will be ADDRESS_TAKEN or NULL.
340 * @return non-zero if at least one entity could be replaced
343 static int find_possible_replacements(ir_graph *irg)
349 long static_link_arg;
353 * First, clear the link field of all interesting entities.
355 frame_tp = get_irg_frame_type(irg);
356 for (mem_idx = get_class_n_members(frame_tp); mem_idx > 0;) {
357 ir_entity *ent = get_class_member(frame_tp, --mem_idx);
358 set_entity_link(ent, NULL);
361 /* check for inner functions:
362 * FIXME: need a way to get the argument position for the static link */
364 for (mem_idx = get_class_n_members(frame_tp); mem_idx > 0;) {
365 ir_entity *ent = get_class_member(frame_tp, --mem_idx);
366 if (is_method_entity(ent)) {
367 ir_graph *inner_irg = get_entity_irg(ent);
371 assure_irg_outs(inner_irg);
372 args = get_irg_args(inner_irg);
373 for (j = get_irn_n_outs(args) - 1; j >= 0; --j) {
374 ir_node *arg = get_irn_out(args, j);
376 if (get_Proj_proj(arg) == static_link_arg) {
378 for (k = get_irn_n_outs(arg) - 1; k >= 0; --k) {
379 ir_node *succ = get_irn_out(arg, k);
382 ir_entity *ent = get_Sel_entity(succ);
384 if (get_entity_owner(ent) == frame_tp) {
385 /* found an access to the outer frame */
386 set_entity_link(ent, ADDRESS_TAKEN);
396 * Check the ir_graph for Sel nodes. If the entity of Sel
397 * isn't a scalar replacement set the link of this entity
398 * equal ADDRESS_TAKEN.
400 irg_frame = get_irg_frame(irg);
401 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
402 ir_node *succ = get_irn_out(irg_frame, i);
405 ir_entity *ent = get_Sel_entity(succ);
408 /* we are only interested in entities on the frame, NOT
410 if (get_entity_owner(ent) != frame_tp)
413 if (get_entity_link(ent) == ADDRESS_TAKEN)
416 ent_type = get_entity_type(ent);
418 /* we can handle arrays, structs and atomic types yet */
419 if (is_Array_type(ent_type) || is_Struct_type(ent_type) || is_atomic_type(ent_type)) {
420 if (is_address_taken(succ)) {
422 if (get_entity_link(ent))
424 set_entity_link(ent, ADDRESS_TAKEN);
426 /* possible found one */
427 if (get_entity_link(ent) == NULL)
429 link_all_leave_sels(ent, succ);
439 * Return a path from the Sel node "sel" to its root.
441 * @param sel the Sel node
442 * @param len the length of the path so far
444 static path_t *find_path(ir_node *sel, size_t len)
449 ir_node *pred = get_Sel_ptr(sel);
451 /* the current Sel node will add some path elements */
452 n = get_Sel_n_indexs(sel);
455 if (! is_Sel(pred)) {
456 /* we found the root */
457 res = XMALLOCF(path_t, path, len);
460 res = find_path(pred, len);
462 assert(len <= res->path_len);
463 pos = res->path_len - len;
465 res->path[pos++].ent = get_Sel_entity(sel);
466 for (i = 0; i < n; ++i) {
467 ir_node *index = get_Sel_index(sel, i);
469 res->path[pos++].tv = get_Const_tarval(index);
476 * Allocate value numbers for the leaves
477 * in our found entities.
479 * @param sels a set that will contain all Sels that have a value number
480 * @param ent the entity that will be scalar replaced
481 * @param vnum the first value number we can assign
482 * @param modes a flexible array, containing all the modes of
485 * @return the next free value number
487 static unsigned allocate_value_numbers(pset *sels, ir_entity *ent, unsigned vnum, ir_mode ***modes)
491 set *pathes = new_set(path_cmp, 8);
493 DB((dbg, SET_LEVEL_3, " Visiting Sel nodes of entity %+F\n", ent));
494 /* visit all Sel nodes in the chain of the entity */
495 for (sel = (ir_node*)get_entity_link(ent); sel != NULL; sel = next) {
496 next = (ir_node*)get_irn_link(sel);
498 /* we must mark this sel for later */
499 pset_insert_ptr(sels, sel);
501 key = find_path(sel, 0);
502 path = (path_t*)set_find(pathes, key, path_size(key), path_hash(key));
505 set_vnum(sel, path->vnum);
506 DB((dbg, SET_LEVEL_3, " %+F represents value %u\n", sel, path->vnum));
510 set_insert(pathes, key, path_size(key), path_hash(key));
512 set_vnum(sel, key->vnum);
513 DB((dbg, SET_LEVEL_3, " %+F represents value %u\n", sel, key->vnum));
515 ARR_EXTO(ir_mode *, *modes, (key->vnum + 15) & ~15);
517 (*modes)[key->vnum] = get_type_mode(get_entity_type(get_Sel_entity(sel)));
519 assert((*modes)[key->vnum] && "Value is not atomic");
525 DB((dbg, SET_LEVEL_2, " %s", get_entity_name(key->path[0].ent)));
526 for (i = 1; i < key->path_len; ++i) {
527 if (is_entity(key->path[i].ent))
528 DB((dbg, SET_LEVEL_2, ".%s", get_entity_name(key->path[i].ent)));
530 DB((dbg, SET_LEVEL_2, "[%ld]", get_tarval_long(key->path[i].tv)));
532 DB((dbg, SET_LEVEL_2, " = %u (%s)\n", PTR_TO_INT(get_irn_link(sel)), get_mode_name((*modes)[key->vnum])));
534 #endif /* DEBUG_libfirm */
540 set_entity_link(ent, NULL);
545 * environment for memory walker
547 typedef struct env_t {
548 unsigned nvals; /**< number of values */
549 ir_mode **modes; /**< the modes of the values */
550 pset *sels; /**< A set of all Sel nodes that have a value number */
554 * topological post-walker.
556 static void walker(ir_node *node, void *ctx)
558 env_t *env = (env_t*)ctx;
559 ir_graph *irg = get_irn_irg(node);
560 ir_node *addr, *block, *mem, *val;
565 /* a load, check if we can resolve it */
566 addr = get_Load_ptr(node);
568 DB((dbg, SET_LEVEL_3, " checking %+F for replacement ", node));
569 if (! is_Sel(addr)) {
570 DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", addr));
574 if (! pset_find_ptr(env->sels, addr)) {
575 DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", addr));
579 /* ok, we have a Load that will be replaced */
580 vnum = get_vnum(addr);
581 assert(vnum < env->nvals);
583 DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
585 block = get_nodes_block(node);
586 set_cur_block(block);
588 /* check, if we can replace this Load */
589 val = get_value(vnum, env->modes[vnum]);
591 /* Beware: A Load can contain a hidden conversion in Firm.
592 This happens for instance in the following code:
595 unsigned j = *(unsigned *)&i;
598 mode = get_Load_mode(node);
599 if (mode != get_irn_mode(val))
600 val = new_rd_Conv(get_irn_dbg_info(node), block, val, mode);
602 mem = get_Load_mem(node);
603 turn_into_tuple(node, pn_Load_max+1);
604 set_Tuple_pred(node, pn_Load_M, mem);
605 set_Tuple_pred(node, pn_Load_res, val);
606 set_Tuple_pred(node, pn_Load_X_regular, new_r_Jmp(block));
607 set_Tuple_pred(node, pn_Load_X_except, new_r_Bad(irg, mode_X));
608 } else if (is_Store(node)) {
609 DB((dbg, SET_LEVEL_3, " checking %+F for replacement ", node));
611 /* a Store always can be replaced */
612 addr = get_Store_ptr(node);
614 if (! is_Sel(addr)) {
615 DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", addr));
619 if (! pset_find_ptr(env->sels, addr)) {
620 DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", addr));
624 vnum = get_vnum(addr);
625 assert(vnum < env->nvals);
627 DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
629 block = get_nodes_block(node);
630 set_cur_block(block);
632 /* Beware: A Store can contain a hidden conversion in Firm. */
633 val = get_Store_value(node);
634 if (get_irn_mode(val) != env->modes[vnum])
635 val = new_rd_Conv(get_irn_dbg_info(node), block, val, env->modes[vnum]);
637 set_value(vnum, val);
639 mem = get_Store_mem(node);
640 turn_into_tuple(node, pn_Store_max+1);
641 set_Tuple_pred(node, pn_Store_M, mem);
642 set_Tuple_pred(node, pn_Store_X_regular, new_r_Jmp(block));
643 set_Tuple_pred(node, pn_Store_X_except, new_r_Bad(irg, mode_X));
648 * Make scalar replacement.
650 * @param sels A set containing all Sel nodes that have a value number
651 * @param nvals The number of scalars.
652 * @param modes A flexible array, containing all the modes of
655 static void do_scalar_replacements(ir_graph *irg, pset *sels, unsigned nvals,
660 ssa_cons_start(irg, (int)nvals);
667 * second step: walk over the graph blockwise in topological order
668 * and fill the array as much as possible.
670 DB((dbg, SET_LEVEL_3, "Substituting Loads and Stores in %+F\n", irg));
671 irg_walk_blkwise_graph(irg, NULL, walker, &env);
673 ssa_cons_finish(irg);
677 * Find possible scalar replacements
679 * @param irg The current ir graph.
681 static ir_graph_state_t do_scalar_replacement(ir_graph *irg)
685 scalars_t key, *value;
690 ir_type *ent_type, *frame_tp;
692 /* we use the link field to store the VNUM */
693 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
694 irp_reserve_resources(irp, IRP_RESOURCE_ENTITY_LINK);
696 /* Find possible scalar replacements */
697 if (find_possible_replacements(irg)) {
698 DB((dbg, SET_LEVEL_1, "Scalar Replacement: %+F\n", irg));
700 /* Insert in set the scalar replacements. */
701 irg_frame = get_irg_frame(irg);
703 modes = NEW_ARR_F(ir_mode *, 16);
704 set_ent = new_set(ent_cmp, 8);
705 sels = pset_new_ptr(8);
706 frame_tp = get_irg_frame_type(irg);
708 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
709 ir_node *succ = get_irn_out(irg_frame, i);
712 ir_entity *ent = get_Sel_entity(succ);
714 /* we are only interested in entities on the frame, NOT
716 if (get_entity_owner(ent) != frame_tp
717 || is_parameter_entity(ent))
720 if (get_entity_link(ent) == NULL || get_entity_link(ent) == ADDRESS_TAKEN)
723 ent_type = get_entity_type(ent);
726 set_insert(set_ent, &key, sizeof(key), HASH_PTR(key.ent));
729 if (is_Array_type(ent_type)) {
730 DB((dbg, SET_LEVEL_1, " found array %s\n", get_entity_name(ent)));
731 } else if (is_Struct_type(ent_type)) {
732 DB((dbg, SET_LEVEL_1, " found struct %s\n", get_entity_name(ent)));
733 } else if (is_atomic_type(ent_type))
734 DB((dbg, SET_LEVEL_1, " found atomic value %s\n", get_entity_name(ent)));
736 panic("Neither an array nor a struct or atomic value found in scalar replace");
738 #endif /* DEBUG_libfirm */
740 nvals = allocate_value_numbers(sels, ent, nvals, &modes);
744 DB((dbg, SET_LEVEL_1, " %u values will be needed\n", nvals));
746 /* If scalars were found. */
748 do_scalar_replacements(irg, sels, nvals, modes);
750 foreach_set(set_ent, scalars_t*, value) {
751 free_entity(value->ent);
755 * We changed the graph, but did NOT introduce new blocks
756 * neither changed control flow, cf-backedges should be still
765 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
766 irp_free_resources(irp, IRP_RESOURCE_ENTITY_LINK);
771 static optdesc_t opt_scalar_rep = {
773 IR_GRAPH_STATE_NO_UNREACHABLE_CODE | IR_GRAPH_STATE_CONSISTENT_OUTS,
774 do_scalar_replacement,
777 int scalar_replacement_opt(ir_graph *irg)
779 perform_irg_optimization(irg, &opt_scalar_rep);
783 ir_graph_pass_t *scalar_replacement_opt_pass(const char *name)
785 return def_graph_pass_ret(name ? name : "scalar_rep",
786 scalar_replacement_opt);
789 void firm_init_scalar_replace(void)
791 FIRM_DBG_REGISTER(dbg, "firm.opt.scalar_replace");