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
32 #include "iroptimize.h"
33 #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))
216 /* Check the Sel successor of Sel */
217 int res = is_address_taken(succ);
225 /* The address of an entity is given as a parameter.
226 * As long as we do not have analyses that can tell what
227 * is done with parameters, think is taken.
228 * One special case: If the Call type tells that it's a
229 * value parameter, the address is NOT taken.
234 /* Non-optimized Tuple, happens in inlining */
235 for (input_nr = get_Tuple_n_preds(succ) - 1; input_nr >= 0; --input_nr) {
236 ir_node *pred = get_Tuple_pred(succ, input_nr);
239 /* we found one input */
240 for (k = get_irn_n_outs(succ) - 1; k >= 0; --k) {
241 ir_node *proj = get_irn_out(succ, k);
243 if (is_Proj(proj) && get_Proj_proj(proj) == input_nr) {
244 int res = is_address_taken(proj);
254 /* another op, the address is taken */
262 * Link all leave Sels with the entity.
264 * @param ent the entity that will be scalar replaced
265 * @param sel a Sel node that selects some fields of this entity
267 * Uses the visited flag to mark already linked Sel nodes.
269 static void link_all_leave_sels(ir_entity *ent, ir_node *sel) {
272 for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
273 ir_node *succ = get_irn_out(sel, i);
276 link_all_leave_sels(ent, succ);
282 /* if Sel nodes with memory inputs are used, a entity can be
283 * visited more than once causing a ring here, so we use the
284 * node flag to mark linked nodes
286 if (irn_visited(sel))
289 /* we know we are at a leave, because this function is only
290 * called if the address is NOT taken, so succ must be a Load
293 set_irn_link(sel, get_entity_link(ent));
294 set_entity_link(ent, sel);
296 mark_irn_visited(sel);
300 /* we need a special address that serves as an address taken marker */
302 static void *ADDRESS_TAKEN = &_x;
305 * Find possible scalar replacements.
307 * @param irg an IR graph
309 * This function finds variables on the (members of the) frame type
310 * that can be scalar replaced, because their address is never taken.
311 * If such a variable is found, it's entity link will hold a list of all
312 * Sel nodes, that selects the atomic fields of this entity.
313 * Otherwise, the link will be ADDRESS_TAKEN or NULL.
315 * @return non-zero if at least one entity could be replaced
318 static int find_possible_replacements(ir_graph *irg) {
324 ir_reserve_resources(irg, IR_RESOURCE_IRN_VISITED);
325 inc_irg_visited(irg);
328 * First, clear the link field of all interesting entities.
330 frame_tp = get_irg_frame_type(irg);
331 for (i = get_class_n_members(frame_tp) - 1; i >= 0; --i) {
332 ir_entity *ent = get_class_member(frame_tp, i);
333 set_entity_link(ent, NULL);
337 * Check the ir_graph for Sel nodes. If the entity of Sel
338 * isn't a scalar replacement set the link of this entity
339 * equal ADDRESS_TAKEN.
341 irg_frame = get_irg_frame(irg);
342 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
343 ir_node *succ = get_irn_out(irg_frame, i);
346 ir_entity *ent = get_Sel_entity(succ);
349 if (get_entity_link(ent) == ADDRESS_TAKEN)
353 * Beware: in rare cases even entities on the frame might be
354 * volatile. This might happen if the entity serves as a store
355 * to a value that must survive a exception. Do not optimize
356 * such entities away.
358 if (get_entity_volatility(ent) == volatility_is_volatile) {
359 set_entity_link(ent, ADDRESS_TAKEN);
363 ent_type = get_entity_type(ent);
365 /* we can handle arrays, structs and atomic types yet */
366 if (is_Array_type(ent_type) || is_Struct_type(ent_type) || is_atomic_type(ent_type)) {
367 if (is_address_taken(succ)) {
368 if (get_entity_link(ent)) /* killing one */
370 set_entity_link(ent, ADDRESS_TAKEN);
372 /* possible found one */
373 if (get_entity_link(ent) == NULL)
375 link_all_leave_sels(ent, succ);
381 ir_free_resources(irg, IR_RESOURCE_IRN_VISITED);
386 * Return a path from the Sel node sel to it's root.
388 * @param sel the Sel node
389 * @param len the length of the path so far
391 static path_t *find_path(ir_node *sel, unsigned len) {
394 ir_node *pred = get_Sel_ptr(sel);
396 /* the current Sel node will add some path elements */
397 n = get_Sel_n_indexs(sel);
400 if (! is_Sel(pred)) {
401 /* we found the root */
403 res = xmalloc(sizeof(*res) + (len - 1) * sizeof(res->path));
406 res = find_path(pred, len);
408 pos = res->path_len - len;
410 res->path[pos++].ent = get_Sel_entity(sel);
411 for (i = 0; i < n; ++i) {
412 ir_node *index = get_Sel_index(sel, i);
414 res->path[pos++].tv = get_Const_tarval(index);
421 * Allocate value numbers for the leaves
422 * in our found entities.
424 * @param sels a set that will contain all Sels that have a value number
425 * @param ent the entity that will be scalar replaced
426 * @param vnum the first value number we can assign
427 * @param modes a flexible array, containing all the modes of
430 * @return the next free value number
432 static unsigned allocate_value_numbers(pset *sels, ir_entity *ent, unsigned vnum, ir_mode ***modes)
436 set *pathes = new_set(path_cmp, 8);
438 DB((dbg, SET_LEVEL_3, " Visiting Sel nodes of entity %+F\n", ent));
439 /* visit all Sel nodes in the chain of the entity */
440 for (sel = get_entity_link(ent); sel; sel = next) {
441 next = get_irn_link(sel);
443 /* we must mark this sel for later */
444 pset_insert_ptr(sels, sel);
446 key = find_path(sel, 0);
447 path = set_find(pathes, key, PATH_SIZE(key), path_hash(key));
450 SET_VNUM(sel, path->vnum);
451 DB((dbg, SET_LEVEL_3, " %+F represents value %u\n", sel, path->vnum));
455 set_insert(pathes, key, PATH_SIZE(key), path_hash(key));
457 SET_VNUM(sel, key->vnum);
458 DB((dbg, SET_LEVEL_3, " %+F represents value %u\n", sel, key->vnum));
460 ARR_EXTO(ir_mode *, *modes, (int)((key->vnum + 15) & ~15));
462 (*modes)[key->vnum] = get_type_mode(get_entity_type(get_Sel_entity(sel)));
464 assert((*modes)[key->vnum] && "Value is not atomic");
470 DB((dbg, SET_LEVEL_2, " %s", get_entity_name(key->path[0].ent)));
471 for (i = 1; i < key->path_len; ++i) {
472 if (is_entity(key->path[i].ent))
473 DB((dbg, SET_LEVEL_2, ".%s", get_entity_name(key->path[i].ent)));
475 DB((dbg, SET_LEVEL_2, "[%ld]", get_tarval_long(key->path[i].tv)));
477 DB((dbg, SET_LEVEL_2, " = %u (%s)\n", PTR_TO_INT(get_irn_link(sel)), get_mode_name((*modes)[key->vnum])));
479 #endif /* DEBUG_libfirm */
485 set_entity_link(ent, NULL);
490 * A list entry for the fixing lists
492 typedef struct _list_entry_t {
493 ir_node *node; /**< the node that must be fixed */
494 unsigned vnum; /**< the value number of this node */
498 * environment for memory walker
500 typedef struct _env_t {
501 int nvals; /**< number of values */
502 ir_mode **modes; /**< the modes of the values */
503 pset *sels; /**< A set of all Sel nodes that have a value number */
507 * topological post-walker.
509 static void topologic_walker(ir_node *node, void *ctx) {
511 ir_node *adr, *block, *mem, *val;
516 /* a load, check if we can resolve it */
517 adr = get_Load_ptr(node);
519 DB((dbg, SET_LEVEL_3, " checking %+F for replacement ", node));
521 DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", adr));
525 if (! pset_find_ptr(env->sels, adr)) {
526 DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", adr));
530 /* ok, we have a Load that will be replaced */
531 vnum = GET_VNUM(adr);
532 assert(vnum < (unsigned)env->nvals);
534 DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
536 block = get_nodes_block(node);
537 set_cur_block(block);
539 /* check, if we can replace this Load */
540 val = get_value(vnum, env->modes[vnum]);
542 /* Beware: A Load can contain a hidden conversion in Firm.
543 This happens for instance in the following code:
546 unsigned j = *(unsigned *)&i;
549 mode = get_Load_mode(node);
550 if (mode != get_irn_mode(val))
551 val = new_d_Conv(get_irn_dbg_info(node), val, mode);
553 mem = get_Load_mem(node);
554 turn_into_tuple(node, pn_Load_max);
555 set_Tuple_pred(node, pn_Load_M, mem);
556 set_Tuple_pred(node, pn_Load_res, val);
557 set_Tuple_pred(node, pn_Load_X_regular, new_Jmp());
558 set_Tuple_pred(node, pn_Load_X_except, new_Bad());
559 } else if (is_Store(node)) {
560 DB((dbg, SET_LEVEL_3, " checking %+F for replacement ", node));
562 /* a Store always can be replaced */
563 adr = get_Store_ptr(node);
566 DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", adr));
570 if (! pset_find_ptr(env->sels, adr)) {
571 DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", adr));
575 vnum = GET_VNUM(adr);
576 assert(vnum < (unsigned)env->nvals);
578 DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
580 /* Beware: A Store can contain a hidden conversion in Firm. */
581 val = get_Store_value(node);
582 if (get_irn_mode(val) != env->modes[vnum])
583 val = new_d_Conv(get_irn_dbg_info(node), val, env->modes[vnum]);
585 block = get_nodes_block(node);
586 set_cur_block(block);
587 set_value(vnum, val);
589 mem = get_Store_mem(node);
590 turn_into_tuple(node, pn_Store_max);
591 set_Tuple_pred(node, pn_Store_M, mem);
592 set_Tuple_pred(node, pn_Store_X_regular, new_Jmp());
593 set_Tuple_pred(node, pn_Store_X_except, new_Bad());
598 * Make scalar replacement.
600 * @param sels A set containing all Sel nodes that have a value number
601 * @param nvals The number of scalars.
602 * @param modes A flexible array, containing all the modes of
605 static void do_scalar_replacements(pset *sels, int nvals, ir_mode **modes) {
608 ssa_cons_start(current_ir_graph, nvals);
615 * second step: walk over the graph blockwise in topological order
616 * and fill the array as much as possible.
618 DB((dbg, SET_LEVEL_3, "Substituting Loads and Stores in %+F\n", current_ir_graph));
619 irg_walk_blkwise_graph(current_ir_graph, NULL, topologic_walker, &env);
621 ssa_cons_finish(current_ir_graph);
625 * Find possible scalar replacements
627 * @param irg The current ir graph.
629 int scalar_replacement_opt(ir_graph *irg) {
632 scalars_t key, *value;
641 if (! get_opt_scalar_replacement())
644 rem = current_ir_graph;
645 current_ir_graph = irg;
647 /* Call algorithm that computes the out edges */
648 assure_irg_outs(irg);
650 /* Find possible scalar replacements */
651 if (find_possible_replacements(irg)) {
652 DB((dbg, SET_LEVEL_1, "Scalar Replacement: %s\n", get_entity_name(get_irg_entity(irg))));
654 /* Insert in set the scalar replacements. */
655 irg_frame = get_irg_frame(irg);
657 modes = NEW_ARR_F(ir_mode *, 16);
658 set_ent = new_set(ent_cmp, 8);
659 sels = pset_new_ptr(8);
661 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
662 ir_node *succ = get_irn_out(irg_frame, i);
665 ir_entity *ent = get_Sel_entity(succ);
667 if (get_entity_link(ent) == NULL || get_entity_link(ent) == ADDRESS_TAKEN)
670 ent_type = get_entity_type(ent);
673 key.ent_owner = get_entity_owner(ent);
674 set_insert(set_ent, &key, sizeof(key), HASH_PTR(key.ent));
677 if (is_Array_type(ent_type)) {
678 DB((dbg, SET_LEVEL_1, " found array %s\n", get_entity_name(ent)));
679 } else if (is_Struct_type(ent_type)) {
680 DB((dbg, SET_LEVEL_1, " found struct %s\n", get_entity_name(ent)));
681 } else if (is_atomic_type(ent_type))
682 DB((dbg, SET_LEVEL_1, " found atomic value %s\n", get_entity_name(ent)));
684 panic("Neither an array nor a struct or atomic value found in scalar replace");
686 #endif /* DEBUG_libfirm */
688 nvals = allocate_value_numbers(sels, ent, nvals, &modes);
692 DB((dbg, SET_LEVEL_1, " %u values will be needed\n", nvals));
694 /* If scalars were found. */
696 do_scalar_replacements(sels, nvals, modes);
698 foreach_set(set_ent, value) {
699 remove_class_member(value->ent_owner, value->ent);
703 * We changed the graph, but did NOT introduce new blocks
704 * neither changed control flow, cf-backedges should be still
707 set_irg_outs_inconsistent(irg);
708 set_irg_loopinfo_inconsistent(irg);
717 current_ir_graph = rem;
721 void firm_init_scalar_replace(void) {
722 FIRM_DBG_REGISTER(dbg, "firm.opt.scalar_replace");