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))
215 ir_entity *entity = get_Sel_entity(succ);
216 /* we can't handle unions correctly yet -> address taken */
217 if (is_Union_type(get_entity_owner(entity)))
220 /* Check the Sel successor of Sel */
221 res = is_address_taken(succ);
228 /* The address of an entity is given as a parameter.
229 * As long as we do not have analyses that can tell what
230 * is done with parameters, think is taken.
231 * One special case: If the Call type tells that it's a
232 * value parameter, the address is NOT taken.
237 int res = is_address_taken(succ);
244 /* Non-optimized Tuple, happens in inlining */
245 for (input_nr = get_Tuple_n_preds(succ) - 1; input_nr >= 0; --input_nr) {
246 ir_node *pred = get_Tuple_pred(succ, input_nr);
249 /* we found one input */
250 for (k = get_irn_n_outs(succ) - 1; k >= 0; --k) {
251 ir_node *proj = get_irn_out(succ, k);
253 if (is_Proj(proj) && get_Proj_proj(proj) == input_nr) {
254 int res = is_address_taken(proj);
264 /* another op, the address is taken */
272 * Link all leave Sels with the entity.
274 * @param ent the entity that will be scalar replaced
275 * @param sel a Sel node that selects some fields of this entity
277 static int link_all_leave_sels(ir_entity *ent, ir_node *sel) {
280 for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
281 ir_node *succ = get_irn_out(sel, i);
284 /* the current leave has further Sel's, no leave */
286 link_all_leave_sels(ent, succ);
287 } else if (is_Id(succ)) {
288 is_leave &= link_all_leave_sels(ent, succ);
296 /* we know we are at a leave, because this function is only
297 * called if the address is NOT taken, so sel's successor(s)
298 * must be Loads or Stores
300 set_irn_link(sel, get_entity_link(ent));
301 set_entity_link(ent, sel);
306 /* we need a special address that serves as an address taken marker */
308 static void *ADDRESS_TAKEN = &_x;
311 * Find possible scalar replacements.
313 * @param irg an IR graph
315 * This function finds variables on the (members of the) frame type
316 * that can be scalar replaced, because their address is never taken.
317 * If such a variable is found, it's entity link will hold a list of all
318 * Sel nodes, that selects the atomic fields of this entity.
319 * Otherwise, the link will be ADDRESS_TAKEN or NULL.
321 * @return non-zero if at least one entity could be replaced
324 static int find_possible_replacements(ir_graph *irg) {
327 int i, j, k, static_link_arg;
331 * First, clear the link field of all interesting entities.
333 frame_tp = get_irg_frame_type(irg);
334 for (i = get_class_n_members(frame_tp) - 1; i >= 0; --i) {
335 ir_entity *ent = get_class_member(frame_tp, i);
336 set_entity_link(ent, NULL);
339 /* check for inner functions:
340 * FIXME: need a way to get the argument position for the static link */
342 for (i = get_class_n_members(frame_tp) - 1; i >= 0; --i) {
343 ir_entity *ent = get_class_member(frame_tp, i);
344 if (is_method_entity(ent)) {
345 ir_graph *inner_irg = get_entity_irg(ent);
348 assure_irg_outs(inner_irg);
349 args = get_irg_args(inner_irg);
350 for (j = get_irn_n_outs(args) - 1; j >= 0; --j) {
351 ir_node *arg = get_irn_out(args, j);
353 if (get_Proj_proj(arg) == static_link_arg) {
354 for (k = get_irn_n_outs(arg) - 1; k >= 0; --k) {
355 ir_node *succ = get_irn_out(arg, k);
358 ir_entity *ent = get_Sel_entity(succ);
360 if (get_entity_owner(ent) == frame_tp) {
361 /* found an access to the outer frame */
362 set_entity_link(ent, ADDRESS_TAKEN);
372 * Check the ir_graph for Sel nodes. If the entity of Sel
373 * isn't a scalar replacement set the link of this entity
374 * equal ADDRESS_TAKEN.
376 irg_frame = get_irg_frame(irg);
377 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
378 ir_node *succ = get_irn_out(irg_frame, i);
381 ir_entity *ent = get_Sel_entity(succ);
384 /* we are only interested in entities on the frame, NOT
386 if (get_entity_owner(ent) != frame_tp)
389 if (get_entity_link(ent) == ADDRESS_TAKEN)
393 * Beware: in rare cases even entities on the frame might be
394 * volatile. This might happen if the entity serves as a store
395 * to a value that must survive a exception. Do not optimize
396 * such entities away.
398 if (get_entity_volatility(ent) == volatility_is_volatile) {
399 set_entity_link(ent, ADDRESS_TAKEN);
403 ent_type = get_entity_type(ent);
405 /* we can handle arrays, structs and atomic types yet */
406 if (is_Array_type(ent_type) || is_Struct_type(ent_type) || is_atomic_type(ent_type)) {
407 if (is_address_taken(succ)) {
409 if (get_entity_link(ent))
411 set_entity_link(ent, ADDRESS_TAKEN);
413 /* possible found one */
414 if (get_entity_link(ent) == NULL)
416 link_all_leave_sels(ent, succ);
426 * Return a path from the Sel node sel to it's root.
428 * @param sel the Sel node
429 * @param len the length of the path so far
431 static path_t *find_path(ir_node *sel, unsigned len) {
434 ir_node *pred = get_Sel_ptr(sel);
436 /* the current Sel node will add some path elements */
437 n = get_Sel_n_indexs(sel);
440 if (! is_Sel(pred)) {
441 /* we found the root */
442 res = XMALLOCF(path_t, path, len);
445 res = find_path(pred, len);
447 pos = res->path_len - len;
449 res->path[pos++].ent = get_Sel_entity(sel);
450 for (i = 0; i < n; ++i) {
451 ir_node *index = get_Sel_index(sel, i);
453 res->path[pos++].tv = get_Const_tarval(index);
460 * Allocate value numbers for the leaves
461 * in our found entities.
463 * @param sels a set that will contain all Sels that have a value number
464 * @param ent the entity that will be scalar replaced
465 * @param vnum the first value number we can assign
466 * @param modes a flexible array, containing all the modes of
469 * @return the next free value number
471 static unsigned allocate_value_numbers(pset *sels, ir_entity *ent, unsigned vnum, ir_mode ***modes)
475 set *pathes = new_set(path_cmp, 8);
477 DB((dbg, SET_LEVEL_3, " Visiting Sel nodes of entity %+F\n", ent));
478 /* visit all Sel nodes in the chain of the entity */
479 for (sel = get_entity_link(ent); sel; sel = next) {
480 next = get_irn_link(sel);
482 /* we must mark this sel for later */
483 pset_insert_ptr(sels, sel);
485 key = find_path(sel, 0);
486 path = set_find(pathes, key, PATH_SIZE(key), path_hash(key));
489 SET_VNUM(sel, path->vnum);
490 DB((dbg, SET_LEVEL_3, " %+F represents value %u\n", sel, path->vnum));
494 set_insert(pathes, key, PATH_SIZE(key), path_hash(key));
496 SET_VNUM(sel, key->vnum);
497 DB((dbg, SET_LEVEL_3, " %+F represents value %u\n", sel, key->vnum));
499 ARR_EXTO(ir_mode *, *modes, (int)((key->vnum + 15) & ~15));
501 (*modes)[key->vnum] = get_type_mode(get_entity_type(get_Sel_entity(sel)));
503 assert((*modes)[key->vnum] && "Value is not atomic");
509 DB((dbg, SET_LEVEL_2, " %s", get_entity_name(key->path[0].ent)));
510 for (i = 1; i < key->path_len; ++i) {
511 if (is_entity(key->path[i].ent))
512 DB((dbg, SET_LEVEL_2, ".%s", get_entity_name(key->path[i].ent)));
514 DB((dbg, SET_LEVEL_2, "[%ld]", get_tarval_long(key->path[i].tv)));
516 DB((dbg, SET_LEVEL_2, " = %u (%s)\n", PTR_TO_INT(get_irn_link(sel)), get_mode_name((*modes)[key->vnum])));
518 #endif /* DEBUG_libfirm */
524 set_entity_link(ent, NULL);
529 * A list entry for the fixing lists
531 typedef struct _list_entry_t {
532 ir_node *node; /**< the node that must be fixed */
533 unsigned vnum; /**< the value number of this node */
537 * environment for memory walker
539 typedef struct _env_t {
540 int nvals; /**< number of values */
541 ir_mode **modes; /**< the modes of the values */
542 pset *sels; /**< A set of all Sel nodes that have a value number */
546 * topological post-walker.
548 static void topologic_walker(ir_node *node, void *ctx) {
550 ir_node *adr, *block, *mem, *val;
555 /* a load, check if we can resolve it */
556 adr = get_Load_ptr(node);
558 DB((dbg, SET_LEVEL_3, " checking %+F for replacement ", node));
560 DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", adr));
564 if (! pset_find_ptr(env->sels, adr)) {
565 DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", adr));
569 /* ok, we have a Load that will be replaced */
570 vnum = GET_VNUM(adr);
571 assert(vnum < (unsigned)env->nvals);
573 DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
575 block = get_nodes_block(node);
576 set_cur_block(block);
578 /* check, if we can replace this Load */
579 val = get_value(vnum, env->modes[vnum]);
581 /* Beware: A Load can contain a hidden conversion in Firm.
582 This happens for instance in the following code:
585 unsigned j = *(unsigned *)&i;
588 mode = get_Load_mode(node);
589 if (mode != get_irn_mode(val))
590 val = new_d_Conv(get_irn_dbg_info(node), val, mode);
592 mem = get_Load_mem(node);
593 turn_into_tuple(node, pn_Load_max);
594 set_Tuple_pred(node, pn_Load_M, mem);
595 set_Tuple_pred(node, pn_Load_res, val);
596 set_Tuple_pred(node, pn_Load_X_regular, new_Jmp());
597 set_Tuple_pred(node, pn_Load_X_except, new_Bad());
598 } else if (is_Store(node)) {
599 DB((dbg, SET_LEVEL_3, " checking %+F for replacement ", node));
601 /* a Store always can be replaced */
602 adr = get_Store_ptr(node);
605 DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", adr));
609 if (! pset_find_ptr(env->sels, adr)) {
610 DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", adr));
614 vnum = GET_VNUM(adr);
615 assert(vnum < (unsigned)env->nvals);
617 DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
619 block = get_nodes_block(node);
620 set_cur_block(block);
622 /* Beware: A Store can contain a hidden conversion in Firm. */
623 val = get_Store_value(node);
624 if (get_irn_mode(val) != env->modes[vnum])
625 val = new_d_Conv(get_irn_dbg_info(node), val, env->modes[vnum]);
627 set_value(vnum, val);
629 mem = get_Store_mem(node);
630 turn_into_tuple(node, pn_Store_max);
631 set_Tuple_pred(node, pn_Store_M, mem);
632 set_Tuple_pred(node, pn_Store_X_regular, new_Jmp());
633 set_Tuple_pred(node, pn_Store_X_except, new_Bad());
638 * Make scalar replacement.
640 * @param sels A set containing all Sel nodes that have a value number
641 * @param nvals The number of scalars.
642 * @param modes A flexible array, containing all the modes of
645 static void do_scalar_replacements(pset *sels, int nvals, ir_mode **modes) {
648 ssa_cons_start(current_ir_graph, nvals);
655 * second step: walk over the graph blockwise in topological order
656 * and fill the array as much as possible.
658 DB((dbg, SET_LEVEL_3, "Substituting Loads and Stores in %+F\n", current_ir_graph));
659 irg_walk_blkwise_graph(current_ir_graph, NULL, topologic_walker, &env);
661 ssa_cons_finish(current_ir_graph);
665 * Find possible scalar replacements
667 * @param irg The current ir graph.
669 int scalar_replacement_opt(ir_graph *irg) {
672 scalars_t key, *value;
677 ir_type *ent_type, *frame_tp;
681 if (! get_opt_scalar_replacement())
684 rem = current_ir_graph;
685 current_ir_graph = irg;
687 /* Call algorithm that computes the out edges */
688 assure_irg_outs(irg);
690 /* we use the link field to store the VNUM */
691 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
692 irp_reserve_resources(irp, IR_RESOURCE_ENTITY_LINK);
694 /* Find possible scalar replacements */
695 if (find_possible_replacements(irg)) {
696 DB((dbg, SET_LEVEL_1, "Scalar Replacement: %+F\n", irg));
698 /* Insert in set the scalar replacements. */
699 irg_frame = get_irg_frame(irg);
701 modes = NEW_ARR_F(ir_mode *, 16);
702 set_ent = new_set(ent_cmp, 8);
703 sels = pset_new_ptr(8);
704 frame_tp = get_irg_frame_type(irg);
706 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
707 ir_node *succ = get_irn_out(irg_frame, i);
710 ir_entity *ent = get_Sel_entity(succ);
712 /* we are only interested in entities on the frame, NOT
714 if (get_entity_owner(ent) != frame_tp)
717 if (get_entity_link(ent) == NULL || get_entity_link(ent) == ADDRESS_TAKEN)
720 ent_type = get_entity_type(ent);
723 key.ent_owner = get_entity_owner(ent);
724 set_insert(set_ent, &key, sizeof(key), HASH_PTR(key.ent));
727 if (is_Array_type(ent_type)) {
728 DB((dbg, SET_LEVEL_1, " found array %s\n", get_entity_name(ent)));
729 } else if (is_Struct_type(ent_type)) {
730 DB((dbg, SET_LEVEL_1, " found struct %s\n", get_entity_name(ent)));
731 } else if (is_atomic_type(ent_type))
732 DB((dbg, SET_LEVEL_1, " found atomic value %s\n", get_entity_name(ent)));
734 panic("Neither an array nor a struct or atomic value found in scalar replace");
736 #endif /* DEBUG_libfirm */
738 nvals = allocate_value_numbers(sels, ent, nvals, &modes);
742 DB((dbg, SET_LEVEL_1, " %u values will be needed\n", nvals));
744 /* If scalars were found. */
746 do_scalar_replacements(sels, nvals, modes);
748 foreach_set(set_ent, value) {
749 remove_class_member(value->ent_owner, value->ent);
753 * We changed the graph, but did NOT introduce new blocks
754 * neither changed control flow, cf-backedges should be still
757 set_irg_outs_inconsistent(irg);
758 set_irg_loopinfo_inconsistent(irg);
767 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
768 irp_free_resources(irp, IR_RESOURCE_ENTITY_LINK);
770 current_ir_graph = rem;
774 void firm_init_scalar_replace(void) {
775 FIRM_DBG_REGISTER(dbg, "firm.opt.scalar_replace");