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"
48 #define SET_VNUM(node, vnum) set_irn_link(node, INT_TO_PTR(vnum))
49 #define GET_VNUM(node) (unsigned)PTR_TO_INT(get_irn_link(node))
52 * A path element entry: it is either an entity
53 * or a tarval, because we evaluate only constant array
54 * accesses like a.b.c[8].d
62 * An access path, used to assign value numbers
63 * to variables that will be scalar replaced.
65 typedef struct _path_t {
66 unsigned vnum; /**< The value number. */
67 unsigned path_len; /**< The length of the access path. */
68 path_elem_t path[1]; /**< The path. */
71 /** The size of a path in bytes. */
72 #define PATH_SIZE(p) (sizeof(*(p)) + sizeof((p)->path[0]) * ((p)->path_len - 1))
74 typedef struct _scalars_t {
75 ir_entity *ent; /**< A entity for scalar replacement. */
76 ir_type *ent_owner; /**< The owner of this entity. */
79 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
84 * @return 0 if they are identically
86 static int path_cmp(const void *elt, const void *key, size_t size) {
87 const path_t *p1 = elt;
88 const path_t *p2 = key;
91 /* we can use memcmp here, because identical tarvals should have identical addresses */
92 return memcmp(p1->path, p2->path, p1->path_len * sizeof(p1->path[0]));
96 * Compare two elements of the scalars_t set.
98 * @return 0 if they are identically
100 static int ent_cmp(const void *elt, const void *key, size_t size) {
101 const scalars_t *c1 = elt;
102 const scalars_t *c2 = key;
105 return c1->ent != c2->ent;
109 * Calculate a hash value for a path.
111 static unsigned path_hash(const path_t *path) {
115 for (i = 0; i < path->path_len; ++i)
116 hash ^= (unsigned)PTR_TO_INT(path->path[i].ent);
122 * Returns non-zero, if all indeces of a Sel node are constants.
124 * @param sel the Sel node that will be checked
126 static int is_const_sel(ir_node *sel) {
127 int i, n = get_Sel_n_indexs(sel);
129 for (i = 0; i < n; ++i) {
130 ir_node *idx = get_Sel_index(sel, i);
139 * Check the mode of a Load/Store with the mode of the entity
141 * If the mode of the entity and the Load/Store mode do not match, we
142 * have the bad reinterpret case:
145 * char b = *(char *)&i;
147 * We do NOT count this as one value and return address_taken
149 * However, we support an often used case. If the mode is two-complement
150 * we allow casts between signed/unsigned.
152 * @param mode the mode of the Load/Store
153 * @param ent_mode the mode of the accessed entity
155 static int check_load_store_mode(ir_mode *mode, ir_mode *ent_mode) {
156 if (ent_mode != mode) {
157 if (ent_mode == NULL ||
158 get_mode_size_bits(ent_mode) != get_mode_size_bits(mode) ||
159 get_mode_sort(ent_mode) != get_mode_sort(mode) ||
160 get_mode_arithmetic(ent_mode) != irma_twos_complement ||
161 get_mode_arithmetic(mode) != irma_twos_complement)
168 * Returns non-zero, if the address of an entity
169 * represented by a Sel node (or it's successor Sels) is taken.
171 int is_address_taken(ir_node *sel)
174 ir_mode *emode, *mode;
178 if (! is_const_sel(sel))
181 for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
182 ir_node *succ = get_irn_out(sel, i);
184 switch (get_irn_opcode(succ)) {
186 /* do not remove volatile variables */
187 if (get_Load_volatility(succ) == volatility_is_volatile)
189 /* check if this load is not a hidden conversion */
190 mode = get_Load_mode(succ);
191 ent = get_Sel_entity(sel);
192 emode = get_type_mode(get_entity_type(ent));
193 if (! check_load_store_mode(mode, emode))
198 /* check that Sel is not the Store's value */
199 value = get_Store_value(succ);
202 /* do not remove volatile variables */
203 if (get_Store_volatility(succ) == volatility_is_volatile)
205 /* check if this Store is not a hidden conversion */
206 mode = get_irn_mode(value);
207 ent = get_Sel_entity(sel);
208 emode = get_type_mode(get_entity_type(ent));
209 if (! check_load_store_mode(mode, emode))
214 /* Check the Sel successor of Sel */
215 int res = is_address_taken(succ);
223 /* The address of an entity is given as a parameter.
224 * As long as we do not have analyses that can tell what
225 * is done with parameters, think is taken.
226 * One special case: If the Call type tells that it's a
227 * value parameter, the address is NOT taken.
232 int res = is_address_taken(succ);
239 /* Non-optimized Tuple, happens in inlining */
240 for (input_nr = get_Tuple_n_preds(succ) - 1; input_nr >= 0; --input_nr) {
241 ir_node *pred = get_Tuple_pred(succ, input_nr);
244 /* we found one input */
245 for (k = get_irn_n_outs(succ) - 1; k >= 0; --k) {
246 ir_node *proj = get_irn_out(succ, k);
248 if (is_Proj(proj) && get_Proj_proj(proj) == input_nr) {
249 int res = is_address_taken(proj);
259 /* another op, the address is taken */
267 * Link all leave Sels with the entity.
269 * @param ent the entity that will be scalar replaced
270 * @param sel a Sel node that selects some fields of this entity
272 static int link_all_leave_sels(ir_entity *ent, ir_node *sel) {
275 for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
276 ir_node *succ = get_irn_out(sel, i);
279 /* the current leave has further Sel's, no leave */
281 link_all_leave_sels(ent, succ);
282 } else if (is_Id(succ)) {
283 is_leave &= link_all_leave_sels(ent, succ);
291 /* we know we are at a leave, because this function is only
292 * called if the address is NOT taken, so sel's successor(s)
293 * must be Loads or Stores
295 set_irn_link(sel, get_entity_link(ent));
296 set_entity_link(ent, sel);
301 /* we need a special address that serves as an address taken marker */
303 static void *ADDRESS_TAKEN = &_x;
306 * Find possible scalar replacements.
308 * @param irg an IR graph
310 * This function finds variables on the (members of the) frame type
311 * that can be scalar replaced, because their address is never taken.
312 * If such a variable is found, it's entity link will hold a list of all
313 * Sel nodes, that selects the atomic fields of this entity.
314 * Otherwise, the link will be ADDRESS_TAKEN or NULL.
316 * @return non-zero if at least one entity could be replaced
319 static int find_possible_replacements(ir_graph *irg) {
322 int i, j, k, static_link_arg;
326 * First, clear the link field of all interesting entities.
328 frame_tp = get_irg_frame_type(irg);
329 for (i = get_class_n_members(frame_tp) - 1; i >= 0; --i) {
330 ir_entity *ent = get_class_member(frame_tp, i);
331 set_entity_link(ent, NULL);
334 /* check for inner functions:
335 * FIXME: need a way to get the argument position for the static link */
337 for (i = get_class_n_members(frame_tp) - 1; i >= 0; --i) {
338 ir_entity *ent = get_class_member(frame_tp, i);
339 if (is_method_entity(ent)) {
340 ir_graph *inner_irg = get_entity_irg(ent);
343 assure_irg_outs(inner_irg);
344 args = get_irg_args(inner_irg);
345 for (j = get_irn_n_outs(args) - 1; j >= 0; --j) {
346 ir_node *arg = get_irn_out(args, j);
348 if (get_Proj_proj(arg) == static_link_arg) {
349 for (k = get_irn_n_outs(arg) - 1; k >= 0; --k) {
350 ir_node *succ = get_irn_out(arg, k);
353 ir_entity *ent = get_Sel_entity(succ);
355 if (get_entity_owner(ent) == frame_tp) {
356 /* found an access to the outer frame */
357 set_entity_link(ent, ADDRESS_TAKEN);
367 * Check the ir_graph for Sel nodes. If the entity of Sel
368 * isn't a scalar replacement set the link of this entity
369 * equal ADDRESS_TAKEN.
371 irg_frame = get_irg_frame(irg);
372 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
373 ir_node *succ = get_irn_out(irg_frame, i);
376 ir_entity *ent = get_Sel_entity(succ);
379 /* we are only interested in entities on the frame, NOT
381 if (get_entity_owner(ent) != frame_tp)
384 if (get_entity_link(ent) == ADDRESS_TAKEN)
388 * Beware: in rare cases even entities on the frame might be
389 * volatile. This might happen if the entity serves as a store
390 * to a value that must survive a exception. Do not optimize
391 * such entities away.
393 if (get_entity_volatility(ent) == volatility_is_volatile) {
394 set_entity_link(ent, ADDRESS_TAKEN);
398 ent_type = get_entity_type(ent);
400 /* we can handle arrays, structs and atomic types yet */
401 if (is_Array_type(ent_type) || is_Struct_type(ent_type) || is_atomic_type(ent_type)) {
402 if (is_address_taken(succ)) {
404 if (get_entity_link(ent))
406 set_entity_link(ent, ADDRESS_TAKEN);
408 /* possible found one */
409 if (get_entity_link(ent) == NULL)
411 link_all_leave_sels(ent, succ);
421 * Return a path from the Sel node sel to it's root.
423 * @param sel the Sel node
424 * @param len the length of the path so far
426 static path_t *find_path(ir_node *sel, unsigned len) {
429 ir_node *pred = get_Sel_ptr(sel);
431 /* the current Sel node will add some path elements */
432 n = get_Sel_n_indexs(sel);
435 if (! is_Sel(pred)) {
436 /* we found the root */
437 res = XMALLOCF(path_t, path, len);
440 res = find_path(pred, len);
442 pos = res->path_len - len;
444 res->path[pos++].ent = get_Sel_entity(sel);
445 for (i = 0; i < n; ++i) {
446 ir_node *index = get_Sel_index(sel, i);
448 res->path[pos++].tv = get_Const_tarval(index);
455 * Allocate value numbers for the leaves
456 * in our found entities.
458 * @param sels a set that will contain all Sels that have a value number
459 * @param ent the entity that will be scalar replaced
460 * @param vnum the first value number we can assign
461 * @param modes a flexible array, containing all the modes of
464 * @return the next free value number
466 static unsigned allocate_value_numbers(pset *sels, ir_entity *ent, unsigned vnum, ir_mode ***modes)
470 set *pathes = new_set(path_cmp, 8);
472 DB((dbg, SET_LEVEL_3, " Visiting Sel nodes of entity %+F\n", ent));
473 /* visit all Sel nodes in the chain of the entity */
474 for (sel = get_entity_link(ent); sel; sel = next) {
475 next = get_irn_link(sel);
477 /* we must mark this sel for later */
478 pset_insert_ptr(sels, sel);
480 key = find_path(sel, 0);
481 path = set_find(pathes, key, PATH_SIZE(key), path_hash(key));
484 SET_VNUM(sel, path->vnum);
485 DB((dbg, SET_LEVEL_3, " %+F represents value %u\n", sel, path->vnum));
489 set_insert(pathes, key, PATH_SIZE(key), path_hash(key));
491 SET_VNUM(sel, key->vnum);
492 DB((dbg, SET_LEVEL_3, " %+F represents value %u\n", sel, key->vnum));
494 ARR_EXTO(ir_mode *, *modes, (int)((key->vnum + 15) & ~15));
496 (*modes)[key->vnum] = get_type_mode(get_entity_type(get_Sel_entity(sel)));
498 assert((*modes)[key->vnum] && "Value is not atomic");
504 DB((dbg, SET_LEVEL_2, " %s", get_entity_name(key->path[0].ent)));
505 for (i = 1; i < key->path_len; ++i) {
506 if (is_entity(key->path[i].ent))
507 DB((dbg, SET_LEVEL_2, ".%s", get_entity_name(key->path[i].ent)));
509 DB((dbg, SET_LEVEL_2, "[%ld]", get_tarval_long(key->path[i].tv)));
511 DB((dbg, SET_LEVEL_2, " = %u (%s)\n", PTR_TO_INT(get_irn_link(sel)), get_mode_name((*modes)[key->vnum])));
513 #endif /* DEBUG_libfirm */
519 set_entity_link(ent, NULL);
524 * A list entry for the fixing lists
526 typedef struct _list_entry_t {
527 ir_node *node; /**< the node that must be fixed */
528 unsigned vnum; /**< the value number of this node */
532 * environment for memory walker
534 typedef struct _env_t {
535 int nvals; /**< number of values */
536 ir_mode **modes; /**< the modes of the values */
537 pset *sels; /**< A set of all Sel nodes that have a value number */
541 * topological post-walker.
543 static void topologic_walker(ir_node *node, void *ctx) {
545 ir_node *adr, *block, *mem, *val;
550 /* a load, check if we can resolve it */
551 adr = get_Load_ptr(node);
553 DB((dbg, SET_LEVEL_3, " checking %+F for replacement ", node));
555 DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", adr));
559 if (! pset_find_ptr(env->sels, adr)) {
560 DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", adr));
564 /* ok, we have a Load that will be replaced */
565 vnum = GET_VNUM(adr);
566 assert(vnum < (unsigned)env->nvals);
568 DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
570 block = get_nodes_block(node);
571 set_cur_block(block);
573 /* check, if we can replace this Load */
574 val = get_value(vnum, env->modes[vnum]);
576 /* Beware: A Load can contain a hidden conversion in Firm.
577 This happens for instance in the following code:
580 unsigned j = *(unsigned *)&i;
583 mode = get_Load_mode(node);
584 if (mode != get_irn_mode(val))
585 val = new_d_Conv(get_irn_dbg_info(node), val, mode);
587 mem = get_Load_mem(node);
588 turn_into_tuple(node, pn_Load_max);
589 set_Tuple_pred(node, pn_Load_M, mem);
590 set_Tuple_pred(node, pn_Load_res, val);
591 set_Tuple_pred(node, pn_Load_X_regular, new_Jmp());
592 set_Tuple_pred(node, pn_Load_X_except, new_Bad());
593 } else if (is_Store(node)) {
594 DB((dbg, SET_LEVEL_3, " checking %+F for replacement ", node));
596 /* a Store always can be replaced */
597 adr = get_Store_ptr(node);
600 DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", adr));
604 if (! pset_find_ptr(env->sels, adr)) {
605 DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", adr));
609 vnum = GET_VNUM(adr);
610 assert(vnum < (unsigned)env->nvals);
612 DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
614 block = get_nodes_block(node);
615 set_cur_block(block);
617 /* Beware: A Store can contain a hidden conversion in Firm. */
618 val = get_Store_value(node);
619 if (get_irn_mode(val) != env->modes[vnum])
620 val = new_d_Conv(get_irn_dbg_info(node), val, env->modes[vnum]);
622 set_value(vnum, val);
624 mem = get_Store_mem(node);
625 turn_into_tuple(node, pn_Store_max);
626 set_Tuple_pred(node, pn_Store_M, mem);
627 set_Tuple_pred(node, pn_Store_X_regular, new_Jmp());
628 set_Tuple_pred(node, pn_Store_X_except, new_Bad());
633 * Make scalar replacement.
635 * @param sels A set containing all Sel nodes that have a value number
636 * @param nvals The number of scalars.
637 * @param modes A flexible array, containing all the modes of
640 static void do_scalar_replacements(pset *sels, int nvals, ir_mode **modes) {
643 ssa_cons_start(current_ir_graph, nvals);
650 * second step: walk over the graph blockwise in topological order
651 * and fill the array as much as possible.
653 DB((dbg, SET_LEVEL_3, "Substituting Loads and Stores in %+F\n", current_ir_graph));
654 irg_walk_blkwise_graph(current_ir_graph, NULL, topologic_walker, &env);
656 ssa_cons_finish(current_ir_graph);
660 * Find possible scalar replacements
662 * @param irg The current ir graph.
664 int scalar_replacement_opt(ir_graph *irg) {
667 scalars_t key, *value;
676 if (! get_opt_scalar_replacement())
679 rem = current_ir_graph;
680 current_ir_graph = irg;
682 /* Call algorithm that computes the out edges */
683 assure_irg_outs(irg);
685 /* we use the link firld to store the VNUM */
686 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
687 irp_reserve_resources(irp, IR_RESOURCE_ENTITY_LINK);
689 /* Find possible scalar replacements */
690 if (find_possible_replacements(irg)) {
691 DB((dbg, SET_LEVEL_1, "Scalar Replacement: %+F\n", irg));
693 /* Insert in set the scalar replacements. */
694 irg_frame = get_irg_frame(irg);
696 modes = NEW_ARR_F(ir_mode *, 16);
697 set_ent = new_set(ent_cmp, 8);
698 sels = pset_new_ptr(8);
700 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
701 ir_node *succ = get_irn_out(irg_frame, i);
704 ir_entity *ent = get_Sel_entity(succ);
706 if (get_entity_link(ent) == NULL || get_entity_link(ent) == ADDRESS_TAKEN)
709 ent_type = get_entity_type(ent);
712 key.ent_owner = get_entity_owner(ent);
713 set_insert(set_ent, &key, sizeof(key), HASH_PTR(key.ent));
716 if (is_Array_type(ent_type)) {
717 DB((dbg, SET_LEVEL_1, " found array %s\n", get_entity_name(ent)));
718 } else if (is_Struct_type(ent_type)) {
719 DB((dbg, SET_LEVEL_1, " found struct %s\n", get_entity_name(ent)));
720 } else if (is_atomic_type(ent_type))
721 DB((dbg, SET_LEVEL_1, " found atomic value %s\n", get_entity_name(ent)));
723 panic("Neither an array nor a struct or atomic value found in scalar replace");
725 #endif /* DEBUG_libfirm */
727 nvals = allocate_value_numbers(sels, ent, nvals, &modes);
731 DB((dbg, SET_LEVEL_1, " %u values will be needed\n", nvals));
733 /* If scalars were found. */
735 do_scalar_replacements(sels, nvals, modes);
737 foreach_set(set_ent, value) {
738 remove_class_member(value->ent_owner, value->ent);
742 * We changed the graph, but did NOT introduce new blocks
743 * neither changed control flow, cf-backedges should be still
746 set_irg_outs_inconsistent(irg);
747 set_irg_loopinfo_inconsistent(irg);
756 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
757 irp_free_resources(irp, IR_RESOURCE_ENTITY_LINK);
759 current_ir_graph = rem;
763 void firm_init_scalar_replace(void) {
764 FIRM_DBG_REGISTER(dbg, "firm.opt.scalar_replace");