2 * Copyright (C) 1995-2008 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 #define SET_VNUM(node, vnum) set_irn_link(node, INT_TO_PTR(vnum))
51 #define GET_VNUM(node) (unsigned)PTR_TO_INT(get_irn_link(node))
54 * A path element entry: it is either an entity
55 * or a tarval, because we evaluate only constant array
56 * accesses like a.b.c[8].d
64 * An access path, used to assign value numbers
65 * to variables that will be scalar replaced.
67 typedef struct _path_t {
68 unsigned vnum; /**< The value number. */
69 unsigned path_len; /**< The length of the access path. */
70 path_elem_t path[1]; /**< The path. */
73 /** The size of a path in bytes. */
74 #define PATH_SIZE(p) (sizeof(*(p)) + sizeof((p)->path[0]) * ((p)->path_len - 1))
76 typedef struct _scalars_t {
77 ir_entity *ent; /**< A entity for scalar replacement. */
78 ir_type *ent_owner; /**< The owner of this entity. */
81 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
86 * @return 0 if they are identically
88 static int path_cmp(const void *elt, const void *key, size_t size) {
89 const path_t *p1 = elt;
90 const path_t *p2 = key;
93 /* we can use memcmp here, because identical tarvals should have identical addresses */
94 return memcmp(p1->path, p2->path, p1->path_len * sizeof(p1->path[0]));
98 * Compare two elements of the scalars_t set.
100 * @return 0 if they are identically
102 static int ent_cmp(const void *elt, const void *key, size_t size) {
103 const scalars_t *c1 = elt;
104 const scalars_t *c2 = key;
107 return c1->ent != c2->ent;
111 * Calculate a hash value for a path.
113 static unsigned path_hash(const path_t *path) {
117 for (i = 0; i < path->path_len; ++i)
118 hash ^= (unsigned)PTR_TO_INT(path->path[i].ent);
124 * Returns non-zero, if all indeces of a Sel node are constants.
126 * @param sel the Sel node that will be checked
128 static int is_const_sel(ir_node *sel) {
129 int i, n = get_Sel_n_indexs(sel);
131 for (i = 0; i < n; ++i) {
132 ir_node *idx = get_Sel_index(sel, i);
141 * Check the mode of a Load/Store with the mode of the entity
143 * If the mode of the entity and the Load/Store mode do not match, we
144 * have the bad reinterpret case:
147 * char b = *(char *)&i;
149 * We do NOT count this as one value and return address_taken
151 * However, we support an often used case. If the mode is two-complement
152 * we allow casts between signed/unsigned.
154 * @param mode the mode of the Load/Store
155 * @param ent_mode the mode of the accessed entity
157 static int check_load_store_mode(ir_mode *mode, ir_mode *ent_mode) {
158 if (ent_mode != mode) {
159 if (ent_mode == NULL ||
160 get_mode_size_bits(ent_mode) != get_mode_size_bits(mode) ||
161 get_mode_sort(ent_mode) != get_mode_sort(mode) ||
162 get_mode_arithmetic(ent_mode) != irma_twos_complement ||
163 get_mode_arithmetic(mode) != irma_twos_complement)
170 * Returns non-zero, if the address of an entity
171 * represented by a Sel node (or it's successor Sels) is taken.
173 int is_address_taken(ir_node *sel)
176 ir_mode *emode, *mode;
180 if (! is_const_sel(sel))
183 for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
184 ir_node *succ = get_irn_out(sel, i);
186 switch (get_irn_opcode(succ)) {
188 /* do not remove volatile variables */
189 if (get_Load_volatility(succ) == volatility_is_volatile)
191 /* check if this load is not a hidden conversion */
192 mode = get_Load_mode(succ);
193 ent = get_Sel_entity(sel);
194 emode = get_type_mode(get_entity_type(ent));
195 if (! check_load_store_mode(mode, emode))
200 /* check that Sel is not the Store's value */
201 value = get_Store_value(succ);
204 /* do not remove volatile variables */
205 if (get_Store_volatility(succ) == volatility_is_volatile)
207 /* check if this Store is not a hidden conversion */
208 mode = get_irn_mode(value);
209 ent = get_Sel_entity(sel);
210 emode = get_type_mode(get_entity_type(ent));
211 if (! check_load_store_mode(mode, emode))
217 ir_entity *entity = get_Sel_entity(succ);
218 /* we can't handle unions correctly yet -> address taken */
219 if (is_Union_type(get_entity_owner(entity)))
222 /* Check the Sel successor of Sel */
223 res = is_address_taken(succ);
230 /* The address of an entity is given as a parameter.
231 * As long as we do not have analyses that can tell what
232 * is done with parameters, think is taken.
233 * One special case: If the Call type tells that it's a
234 * value parameter, the address is NOT taken.
239 int res = is_address_taken(succ);
246 /* Non-optimized Tuple, happens in inlining */
247 for (input_nr = get_Tuple_n_preds(succ) - 1; input_nr >= 0; --input_nr) {
248 ir_node *pred = get_Tuple_pred(succ, input_nr);
251 /* we found one input */
252 for (k = get_irn_n_outs(succ) - 1; k >= 0; --k) {
253 ir_node *proj = get_irn_out(succ, k);
255 if (is_Proj(proj) && get_Proj_proj(proj) == input_nr) {
256 int res = is_address_taken(proj);
266 /* another op, the address is taken */
274 * Link all leave Sels with the entity.
276 * @param ent the entity that will be scalar replaced
277 * @param sel a Sel node that selects some fields of this entity
279 static int link_all_leave_sels(ir_entity *ent, ir_node *sel) {
282 for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
283 ir_node *succ = get_irn_out(sel, i);
286 /* the current leave has further Sel's, no leave */
288 link_all_leave_sels(ent, succ);
289 } else if (is_Id(succ)) {
290 is_leave &= link_all_leave_sels(ent, succ);
298 /* we know we are at a leave, because this function is only
299 * called if the address is NOT taken, so sel's successor(s)
300 * must be Loads or Stores
302 set_irn_link(sel, get_entity_link(ent));
303 set_entity_link(ent, sel);
308 /* we need a special address that serves as an address taken marker */
310 static void *ADDRESS_TAKEN = &_x;
313 * Find possible scalar replacements.
315 * @param irg an IR graph
317 * This function finds variables on the (members of the) frame type
318 * that can be scalar replaced, because their address is never taken.
319 * If such a variable is found, it's entity link will hold a list of all
320 * Sel nodes, that selects the atomic fields of this entity.
321 * Otherwise, the link will be ADDRESS_TAKEN or NULL.
323 * @return non-zero if at least one entity could be replaced
326 static int find_possible_replacements(ir_graph *irg) {
329 int i, j, k, static_link_arg;
333 * First, clear the link field of all interesting entities.
335 frame_tp = get_irg_frame_type(irg);
336 for (i = get_class_n_members(frame_tp) - 1; i >= 0; --i) {
337 ir_entity *ent = get_class_member(frame_tp, i);
338 set_entity_link(ent, NULL);
341 /* check for inner functions:
342 * FIXME: need a way to get the argument position for the static link */
344 for (i = get_class_n_members(frame_tp) - 1; i >= 0; --i) {
345 ir_entity *ent = get_class_member(frame_tp, i);
346 if (is_method_entity(ent)) {
347 ir_graph *inner_irg = get_entity_irg(ent);
350 assure_irg_outs(inner_irg);
351 args = get_irg_args(inner_irg);
352 for (j = get_irn_n_outs(args) - 1; j >= 0; --j) {
353 ir_node *arg = get_irn_out(args, j);
355 if (get_Proj_proj(arg) == static_link_arg) {
356 for (k = get_irn_n_outs(arg) - 1; k >= 0; --k) {
357 ir_node *succ = get_irn_out(arg, k);
360 ir_entity *ent = get_Sel_entity(succ);
362 if (get_entity_owner(ent) == frame_tp) {
363 /* found an access to the outer frame */
364 set_entity_link(ent, ADDRESS_TAKEN);
374 * Check the ir_graph for Sel nodes. If the entity of Sel
375 * isn't a scalar replacement set the link of this entity
376 * equal ADDRESS_TAKEN.
378 irg_frame = get_irg_frame(irg);
379 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
380 ir_node *succ = get_irn_out(irg_frame, i);
383 ir_entity *ent = get_Sel_entity(succ);
386 /* we are only interested in entities on the frame, NOT
388 if (get_entity_owner(ent) != frame_tp)
391 if (get_entity_link(ent) == ADDRESS_TAKEN)
395 * Beware: in rare cases even entities on the frame might be
396 * volatile. This might happen if the entity serves as a store
397 * to a value that must survive a exception. Do not optimize
398 * such entities away.
400 if (get_entity_volatility(ent) == volatility_is_volatile) {
401 set_entity_link(ent, ADDRESS_TAKEN);
405 ent_type = get_entity_type(ent);
407 /* we can handle arrays, structs and atomic types yet */
408 if (is_Array_type(ent_type) || is_Struct_type(ent_type) || is_atomic_type(ent_type)) {
409 if (is_address_taken(succ)) {
411 if (get_entity_link(ent))
413 set_entity_link(ent, ADDRESS_TAKEN);
415 /* possible found one */
416 if (get_entity_link(ent) == NULL)
418 link_all_leave_sels(ent, succ);
428 * Return a path from the Sel node sel to it's root.
430 * @param sel the Sel node
431 * @param len the length of the path so far
433 static path_t *find_path(ir_node *sel, unsigned len) {
436 ir_node *pred = get_Sel_ptr(sel);
438 /* the current Sel node will add some path elements */
439 n = get_Sel_n_indexs(sel);
442 if (! is_Sel(pred)) {
443 /* we found the root */
444 res = XMALLOCF(path_t, path, len);
447 res = find_path(pred, len);
449 pos = res->path_len - len;
451 res->path[pos++].ent = get_Sel_entity(sel);
452 for (i = 0; i < n; ++i) {
453 ir_node *index = get_Sel_index(sel, i);
455 res->path[pos++].tv = get_Const_tarval(index);
462 * Allocate value numbers for the leaves
463 * in our found entities.
465 * @param sels a set that will contain all Sels that have a value number
466 * @param ent the entity that will be scalar replaced
467 * @param vnum the first value number we can assign
468 * @param modes a flexible array, containing all the modes of
471 * @return the next free value number
473 static unsigned allocate_value_numbers(pset *sels, ir_entity *ent, unsigned vnum, ir_mode ***modes)
477 set *pathes = new_set(path_cmp, 8);
479 DB((dbg, SET_LEVEL_3, " Visiting Sel nodes of entity %+F\n", ent));
480 /* visit all Sel nodes in the chain of the entity */
481 for (sel = get_entity_link(ent); sel; sel = next) {
482 next = get_irn_link(sel);
484 /* we must mark this sel for later */
485 pset_insert_ptr(sels, sel);
487 key = find_path(sel, 0);
488 path = set_find(pathes, key, PATH_SIZE(key), path_hash(key));
491 SET_VNUM(sel, path->vnum);
492 DB((dbg, SET_LEVEL_3, " %+F represents value %u\n", sel, path->vnum));
496 set_insert(pathes, key, PATH_SIZE(key), path_hash(key));
498 SET_VNUM(sel, key->vnum);
499 DB((dbg, SET_LEVEL_3, " %+F represents value %u\n", sel, key->vnum));
501 ARR_EXTO(ir_mode *, *modes, (int)((key->vnum + 15) & ~15));
503 (*modes)[key->vnum] = get_type_mode(get_entity_type(get_Sel_entity(sel)));
505 assert((*modes)[key->vnum] && "Value is not atomic");
511 DB((dbg, SET_LEVEL_2, " %s", get_entity_name(key->path[0].ent)));
512 for (i = 1; i < key->path_len; ++i) {
513 if (is_entity(key->path[i].ent))
514 DB((dbg, SET_LEVEL_2, ".%s", get_entity_name(key->path[i].ent)));
516 DB((dbg, SET_LEVEL_2, "[%ld]", get_tarval_long(key->path[i].tv)));
518 DB((dbg, SET_LEVEL_2, " = %u (%s)\n", PTR_TO_INT(get_irn_link(sel)), get_mode_name((*modes)[key->vnum])));
520 #endif /* DEBUG_libfirm */
526 set_entity_link(ent, NULL);
531 * A list entry for the fixing lists
533 typedef struct _list_entry_t {
534 ir_node *node; /**< the node that must be fixed */
535 unsigned vnum; /**< the value number of this node */
539 * environment for memory walker
541 typedef struct _env_t {
542 int 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 topologic_walker(ir_node *node, void *ctx) {
552 ir_node *adr, *block, *mem, *val;
557 /* a load, check if we can resolve it */
558 adr = get_Load_ptr(node);
560 DB((dbg, SET_LEVEL_3, " checking %+F for replacement ", node));
562 DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", adr));
566 if (! pset_find_ptr(env->sels, adr)) {
567 DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", adr));
571 /* ok, we have a Load that will be replaced */
572 vnum = GET_VNUM(adr);
573 assert(vnum < (unsigned)env->nvals);
575 DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
577 block = get_nodes_block(node);
578 set_cur_block(block);
580 /* check, if we can replace this Load */
581 val = get_value(vnum, env->modes[vnum]);
583 /* Beware: A Load can contain a hidden conversion in Firm.
584 This happens for instance in the following code:
587 unsigned j = *(unsigned *)&i;
590 mode = get_Load_mode(node);
591 if (mode != get_irn_mode(val))
592 val = new_d_Conv(get_irn_dbg_info(node), val, mode);
594 mem = get_Load_mem(node);
595 turn_into_tuple(node, pn_Load_max);
596 set_Tuple_pred(node, pn_Load_M, mem);
597 set_Tuple_pred(node, pn_Load_res, val);
598 set_Tuple_pred(node, pn_Load_X_regular, new_Jmp());
599 set_Tuple_pred(node, pn_Load_X_except, new_Bad());
600 } else if (is_Store(node)) {
601 DB((dbg, SET_LEVEL_3, " checking %+F for replacement ", node));
603 /* a Store always can be replaced */
604 adr = get_Store_ptr(node);
607 DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", adr));
611 if (! pset_find_ptr(env->sels, adr)) {
612 DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", adr));
616 vnum = GET_VNUM(adr);
617 assert(vnum < (unsigned)env->nvals);
619 DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
621 block = get_nodes_block(node);
622 set_cur_block(block);
624 /* Beware: A Store can contain a hidden conversion in Firm. */
625 val = get_Store_value(node);
626 if (get_irn_mode(val) != env->modes[vnum])
627 val = new_d_Conv(get_irn_dbg_info(node), val, env->modes[vnum]);
629 set_value(vnum, val);
631 mem = get_Store_mem(node);
632 turn_into_tuple(node, pn_Store_max);
633 set_Tuple_pred(node, pn_Store_M, mem);
634 set_Tuple_pred(node, pn_Store_X_regular, new_Jmp());
635 set_Tuple_pred(node, pn_Store_X_except, new_Bad());
640 * Make scalar replacement.
642 * @param sels A set containing all Sel nodes that have a value number
643 * @param nvals The number of scalars.
644 * @param modes A flexible array, containing all the modes of
647 static void do_scalar_replacements(pset *sels, int nvals, ir_mode **modes) {
650 ssa_cons_start(current_ir_graph, nvals);
657 * second step: walk over the graph blockwise in topological order
658 * and fill the array as much as possible.
660 DB((dbg, SET_LEVEL_3, "Substituting Loads and Stores in %+F\n", current_ir_graph));
661 irg_walk_blkwise_graph(current_ir_graph, NULL, topologic_walker, &env);
663 ssa_cons_finish(current_ir_graph);
667 * Find possible scalar replacements
669 * @param irg The current ir graph.
671 int scalar_replacement_opt(ir_graph *irg) {
674 scalars_t key, *value;
679 ir_type *ent_type, *frame_tp;
683 rem = current_ir_graph;
684 current_ir_graph = irg;
686 /* Call algorithm that computes the out edges */
687 assure_irg_outs(irg);
689 /* we use the link field to store the VNUM */
690 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
691 irp_reserve_resources(irp, IR_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 (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
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)
716 if (get_entity_link(ent) == NULL || get_entity_link(ent) == ADDRESS_TAKEN)
719 ent_type = get_entity_type(ent);
722 key.ent_owner = get_entity_owner(ent);
723 set_insert(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(sels, nvals, modes);
747 foreach_set(set_ent, value) {
748 remove_class_member(value->ent_owner, value->ent);
752 * We changed the graph, but did NOT introduce new blocks
753 * neither changed control flow, cf-backedges should be still
756 set_irg_outs_inconsistent(irg);
757 set_irg_loopinfo_inconsistent(irg);
766 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
767 irp_free_resources(irp, IR_RESOURCE_ENTITY_LINK);
769 current_ir_graph = rem;
773 ir_graph_pass_t *scalar_replacement_opt_pass(const char *name) {
774 return def_graph_pass_ret(name ? name : "scalar_rep",
775 scalar_replacement_opt);
778 void firm_init_scalar_replace(void) {
779 FIRM_DBG_REGISTER(dbg, "firm.opt.scalar_replace");