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_sort(ent_mode) != get_mode_sort(mode) ||
178 get_mode_arithmetic(ent_mode) != irma_twos_complement ||
179 get_mode_arithmetic(mode) != irma_twos_complement)
186 * Returns non-zero, if the address of an entity
187 * represented by a Sel node (or its successor Sels) is taken.
189 bool is_address_taken(ir_node *sel)
192 ir_mode *emode, *mode;
196 if (! is_const_sel(sel))
199 for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
200 ir_node *succ = get_irn_out(sel, i);
202 switch (get_irn_opcode(succ)) {
204 /* do not remove volatile variables */
205 if (get_Load_volatility(succ) == volatility_is_volatile)
207 /* check if this load is not a hidden conversion */
208 mode = get_Load_mode(succ);
209 ent = get_Sel_entity(sel);
210 emode = get_type_mode(get_entity_type(ent));
211 if (! check_load_store_mode(mode, emode))
216 /* check that Sel is not the Store's value */
217 value = get_Store_value(succ);
220 /* do not remove volatile variables */
221 if (get_Store_volatility(succ) == volatility_is_volatile)
223 /* check if this Store is not a hidden conversion */
224 mode = get_irn_mode(value);
225 ent = get_Sel_entity(sel);
226 emode = get_type_mode(get_entity_type(ent));
227 if (! check_load_store_mode(mode, emode))
233 ir_entity *entity = get_Sel_entity(succ);
234 /* we can't handle unions correctly yet -> address taken */
235 if (is_Union_type(get_entity_owner(entity)))
238 /* Check the Sel successor of Sel */
239 res = is_address_taken(succ);
246 /* The address of an entity is given as a parameter.
247 * As long as we do not have analyses that can tell what
248 * is done with parameters, think is taken.
249 * One special case: If the Call type tells that it's a
250 * value parameter, the address is NOT taken.
255 int res = is_address_taken(succ);
262 /* Non-optimized Tuple, happens in inlining */
263 for (input_nr = get_Tuple_n_preds(succ) - 1; input_nr >= 0; --input_nr) {
264 ir_node *pred = get_Tuple_pred(succ, input_nr);
267 /* we found one input */
268 for (k = get_irn_n_outs(succ) - 1; k >= 0; --k) {
269 ir_node *proj = get_irn_out(succ, k);
271 if (is_Proj(proj) && get_Proj_proj(proj) == input_nr) {
272 int res = is_address_taken(proj);
282 /* another op, the address is taken */
290 * Link all leave Sels with the entity.
292 * @param ent the entity that will be scalar replaced
293 * @param sel a Sel node that selects some fields of this entity
295 static bool link_all_leave_sels(ir_entity *ent, ir_node *sel)
298 bool is_leave = true;
300 for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
301 ir_node *succ = get_irn_out(sel, i);
304 /* the current leave has further Sel's, no leave */
306 link_all_leave_sels(ent, succ);
307 } else if (is_Id(succ)) {
308 is_leave &= link_all_leave_sels(ent, succ);
316 /* we know we are at a leave, because this function is only
317 * called if the address is NOT taken, so sel's successor(s)
318 * must be Loads or Stores
320 set_irn_link(sel, get_entity_link(ent));
321 set_entity_link(ent, sel);
326 /* we need a special address that serves as an address taken marker */
328 static void *ADDRESS_TAKEN = &_x;
331 * Find possible scalar replacements.
333 * @param irg an IR graph
335 * This function finds variables on the (members of the) frame type
336 * that can be scalar replaced, because their address is never taken.
337 * If such a variable is found, its entity link will hold a list of all
338 * Sel nodes, that selects the atomic fields of this entity.
339 * Otherwise, the link will be ADDRESS_TAKEN or NULL.
341 * @return non-zero if at least one entity could be replaced
344 static int find_possible_replacements(ir_graph *irg)
350 long static_link_arg;
354 * First, clear the link field of all interesting entities.
356 frame_tp = get_irg_frame_type(irg);
357 for (mem_idx = get_class_n_members(frame_tp); mem_idx > 0;) {
358 ir_entity *ent = get_class_member(frame_tp, --mem_idx);
359 set_entity_link(ent, NULL);
362 /* check for inner functions:
363 * FIXME: need a way to get the argument position for the static link */
365 for (mem_idx = get_class_n_members(frame_tp); mem_idx > 0;) {
366 ir_entity *ent = get_class_member(frame_tp, --mem_idx);
367 if (is_method_entity(ent)) {
368 ir_graph *inner_irg = get_entity_irg(ent);
372 assure_irg_outs(inner_irg);
373 args = get_irg_args(inner_irg);
374 for (j = get_irn_n_outs(args) - 1; j >= 0; --j) {
375 ir_node *arg = get_irn_out(args, j);
377 if (get_Proj_proj(arg) == static_link_arg) {
379 for (k = get_irn_n_outs(arg) - 1; k >= 0; --k) {
380 ir_node *succ = get_irn_out(arg, k);
383 ir_entity *ent = get_Sel_entity(succ);
385 if (get_entity_owner(ent) == frame_tp) {
386 /* found an access to the outer frame */
387 set_entity_link(ent, ADDRESS_TAKEN);
397 * Check the ir_graph for Sel nodes. If the entity of Sel
398 * isn't a scalar replacement set the link of this entity
399 * equal ADDRESS_TAKEN.
401 irg_frame = get_irg_frame(irg);
402 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
403 ir_node *succ = get_irn_out(irg_frame, i);
406 ir_entity *ent = get_Sel_entity(succ);
409 /* we are only interested in entities on the frame, NOT
411 if (get_entity_owner(ent) != frame_tp)
414 if (get_entity_link(ent) == ADDRESS_TAKEN)
417 ent_type = get_entity_type(ent);
419 /* we can handle arrays, structs and atomic types yet */
420 if (is_Array_type(ent_type) || is_Struct_type(ent_type) || is_atomic_type(ent_type)) {
421 if (is_address_taken(succ)) {
423 if (get_entity_link(ent))
425 set_entity_link(ent, ADDRESS_TAKEN);
427 /* possible found one */
428 if (get_entity_link(ent) == NULL)
430 link_all_leave_sels(ent, succ);
440 * Return a path from the Sel node "sel" to its root.
442 * @param sel the Sel node
443 * @param len the length of the path so far
445 static path_t *find_path(ir_node *sel, size_t len)
450 ir_node *pred = get_Sel_ptr(sel);
452 /* the current Sel node will add some path elements */
453 n = get_Sel_n_indexs(sel);
456 if (! is_Sel(pred)) {
457 /* we found the root */
458 res = XMALLOCF(path_t, path, len);
461 res = find_path(pred, len);
463 assert(len <= res->path_len);
464 pos = res->path_len - len;
466 res->path[pos++].ent = get_Sel_entity(sel);
467 for (i = 0; i < n; ++i) {
468 ir_node *index = get_Sel_index(sel, i);
470 res->path[pos++].tv = get_Const_tarval(index);
477 * Allocate value numbers for the leaves
478 * in our found entities.
480 * @param sels a set that will contain all Sels that have a value number
481 * @param ent the entity that will be scalar replaced
482 * @param vnum the first value number we can assign
483 * @param modes a flexible array, containing all the modes of
486 * @return the next free value number
488 static unsigned allocate_value_numbers(pset *sels, ir_entity *ent, unsigned vnum, ir_mode ***modes)
492 set *pathes = new_set(path_cmp, 8);
494 DB((dbg, SET_LEVEL_3, " Visiting Sel nodes of entity %+F\n", ent));
495 /* visit all Sel nodes in the chain of the entity */
496 for (sel = (ir_node*)get_entity_link(ent); sel != NULL; sel = next) {
497 next = (ir_node*)get_irn_link(sel);
499 /* we must mark this sel for later */
500 pset_insert_ptr(sels, sel);
502 key = find_path(sel, 0);
503 path = (path_t*)set_find(pathes, key, path_size(key), path_hash(key));
506 set_vnum(sel, path->vnum);
507 DB((dbg, SET_LEVEL_3, " %+F represents value %u\n", sel, path->vnum));
511 set_insert(pathes, key, path_size(key), path_hash(key));
513 set_vnum(sel, key->vnum);
514 DB((dbg, SET_LEVEL_3, " %+F represents value %u\n", sel, key->vnum));
516 ARR_EXTO(ir_mode *, *modes, (key->vnum + 15) & ~15);
518 (*modes)[key->vnum] = get_type_mode(get_entity_type(get_Sel_entity(sel)));
520 assert((*modes)[key->vnum] && "Value is not atomic");
526 DB((dbg, SET_LEVEL_2, " %s", get_entity_name(key->path[0].ent)));
527 for (i = 1; i < key->path_len; ++i) {
528 if (is_entity(key->path[i].ent))
529 DB((dbg, SET_LEVEL_2, ".%s", get_entity_name(key->path[i].ent)));
531 DB((dbg, SET_LEVEL_2, "[%ld]", get_tarval_long(key->path[i].tv)));
533 DB((dbg, SET_LEVEL_2, " = %u (%s)\n", PTR_TO_INT(get_irn_link(sel)), get_mode_name((*modes)[key->vnum])));
535 #endif /* DEBUG_libfirm */
541 set_entity_link(ent, NULL);
546 * environment for memory walker
548 typedef struct env_t {
549 unsigned nvals; /**< number of values */
550 ir_mode **modes; /**< the modes of the values */
551 pset *sels; /**< A set of all Sel nodes that have a value number */
555 * topological post-walker.
557 static void walker(ir_node *node, void *ctx)
559 env_t *env = (env_t*)ctx;
560 ir_graph *irg = get_irn_irg(node);
561 ir_node *addr, *block, *mem, *val;
566 /* a load, check if we can resolve it */
567 addr = get_Load_ptr(node);
569 DB((dbg, SET_LEVEL_3, " checking %+F for replacement ", node));
570 if (! is_Sel(addr)) {
571 DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", addr));
575 if (! pset_find_ptr(env->sels, addr)) {
576 DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", addr));
580 /* ok, we have a Load that will be replaced */
581 vnum = get_vnum(addr);
582 assert(vnum < env->nvals);
584 DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
586 block = get_nodes_block(node);
587 set_cur_block(block);
589 /* check, if we can replace this Load */
590 val = get_value(vnum, env->modes[vnum]);
592 /* Beware: A Load can contain a hidden conversion in Firm.
593 This happens for instance in the following code:
596 unsigned j = *(unsigned *)&i;
599 mode = get_Load_mode(node);
600 if (mode != get_irn_mode(val))
601 val = new_rd_Conv(get_irn_dbg_info(node), block, val, mode);
603 mem = get_Load_mem(node);
604 turn_into_tuple(node, pn_Load_max+1);
605 set_Tuple_pred(node, pn_Load_M, mem);
606 set_Tuple_pred(node, pn_Load_res, val);
607 set_Tuple_pred(node, pn_Load_X_regular, new_r_Jmp(block));
608 set_Tuple_pred(node, pn_Load_X_except, new_r_Bad(irg, mode_X));
609 } else if (is_Store(node)) {
610 DB((dbg, SET_LEVEL_3, " checking %+F for replacement ", node));
612 /* a Store always can be replaced */
613 addr = get_Store_ptr(node);
615 if (! is_Sel(addr)) {
616 DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", addr));
620 if (! pset_find_ptr(env->sels, addr)) {
621 DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", addr));
625 vnum = get_vnum(addr);
626 assert(vnum < env->nvals);
628 DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
630 block = get_nodes_block(node);
631 set_cur_block(block);
633 /* Beware: A Store can contain a hidden conversion in Firm. */
634 val = get_Store_value(node);
635 if (get_irn_mode(val) != env->modes[vnum])
636 val = new_rd_Conv(get_irn_dbg_info(node), block, val, env->modes[vnum]);
638 set_value(vnum, val);
640 mem = get_Store_mem(node);
641 turn_into_tuple(node, pn_Store_max+1);
642 set_Tuple_pred(node, pn_Store_M, mem);
643 set_Tuple_pred(node, pn_Store_X_regular, new_r_Jmp(block));
644 set_Tuple_pred(node, pn_Store_X_except, new_r_Bad(irg, mode_X));
649 * Make scalar replacement.
651 * @param sels A set containing all Sel nodes that have a value number
652 * @param nvals The number of scalars.
653 * @param modes A flexible array, containing all the modes of
656 static void do_scalar_replacements(ir_graph *irg, pset *sels, unsigned nvals,
661 ssa_cons_start(irg, (int)nvals);
668 * second step: walk over the graph blockwise in topological order
669 * and fill the array as much as possible.
671 DB((dbg, SET_LEVEL_3, "Substituting Loads and Stores in %+F\n", irg));
672 irg_walk_blkwise_graph(irg, NULL, walker, &env);
674 ssa_cons_finish(irg);
678 * Find possible scalar replacements
680 * @param irg The current ir graph.
682 static ir_graph_state_t do_scalar_replacement(ir_graph *irg)
686 scalars_t key, *value;
691 ir_type *ent_type, *frame_tp;
693 /* we use the link field to store the VNUM */
694 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
695 irp_reserve_resources(irp, IRP_RESOURCE_ENTITY_LINK);
697 /* Find possible scalar replacements */
698 if (find_possible_replacements(irg)) {
699 DB((dbg, SET_LEVEL_1, "Scalar Replacement: %+F\n", irg));
701 /* Insert in set the scalar replacements. */
702 irg_frame = get_irg_frame(irg);
704 modes = NEW_ARR_F(ir_mode *, 16);
705 set_ent = new_set(ent_cmp, 8);
706 sels = pset_new_ptr(8);
707 frame_tp = get_irg_frame_type(irg);
709 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
710 ir_node *succ = get_irn_out(irg_frame, i);
713 ir_entity *ent = get_Sel_entity(succ);
715 /* we are only interested in entities on the frame, NOT
717 if (get_entity_owner(ent) != frame_tp
718 || is_parameter_entity(ent))
721 if (get_entity_link(ent) == NULL || get_entity_link(ent) == ADDRESS_TAKEN)
724 ent_type = get_entity_type(ent);
727 set_insert(set_ent, &key, sizeof(key), HASH_PTR(key.ent));
730 if (is_Array_type(ent_type)) {
731 DB((dbg, SET_LEVEL_1, " found array %s\n", get_entity_name(ent)));
732 } else if (is_Struct_type(ent_type)) {
733 DB((dbg, SET_LEVEL_1, " found struct %s\n", get_entity_name(ent)));
734 } else if (is_atomic_type(ent_type))
735 DB((dbg, SET_LEVEL_1, " found atomic value %s\n", get_entity_name(ent)));
737 panic("Neither an array nor a struct or atomic value found in scalar replace");
739 #endif /* DEBUG_libfirm */
741 nvals = allocate_value_numbers(sels, ent, nvals, &modes);
745 DB((dbg, SET_LEVEL_1, " %u values will be needed\n", nvals));
747 /* If scalars were found. */
749 do_scalar_replacements(irg, sels, nvals, modes);
751 foreach_set(set_ent, scalars_t*, value) {
752 free_entity(value->ent);
756 * We changed the graph, but did NOT introduce new blocks
757 * neither changed control flow, cf-backedges should be still
766 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
767 irp_free_resources(irp, IRP_RESOURCE_ENTITY_LINK);
772 static optdesc_t opt_scalar_rep = {
774 IR_GRAPH_STATE_NO_UNREACHABLE_CODE | IR_GRAPH_STATE_CONSISTENT_OUTS,
775 do_scalar_replacement,
778 int scalar_replacement_opt(ir_graph *irg)
780 perform_irg_optimization(irg, &opt_scalar_rep);
784 ir_graph_pass_t *scalar_replacement_opt_pass(const char *name)
786 return def_graph_pass_ret(name ? name : "scalar_rep",
787 scalar_replacement_opt);
790 void firm_init_scalar_replace(void)
792 FIRM_DBG_REGISTER(dbg, "firm.opt.scalar_replace");