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 Lowering of Calls with compound parameters and return types.
23 * @author Michael Beck
39 #include "iroptimize.h"
44 /** A type map for def_find_pointer_type. */
45 static pmap *type_map;
48 * Default implementation for finding a pointer type for a given element type.
49 * Simple create a new one.
51 static ir_type *def_find_pointer_type(ir_type *e_type, ir_mode *mode, int alignment)
56 /* Mode and alignment are always identical in all calls to def_find_pointer_type(), so
57 we simply can use a map from the element type to the pointer type. */
58 e = pmap_find(type_map, e_type);
62 res = new_type_pointer(mangle_u(get_type_ident(e_type), new_id_from_chars("Ptr", 3)), e_type, mode);
63 set_type_alignment_bytes(res, alignment);
64 pmap_insert(type_map, e_type, res);
70 * Creates a new lowered type for a method type with compound
71 * arguments. The new type is associated to the old one and returned.
73 * @param lp parameter struct
74 * @param mtp the method type to lower
76 * The current implementation expects that a lowered type already
77 * includes the necessary changes ...
79 static ir_type *create_modified_mtd_type(const lower_params_t *lp, ir_type *mtp)
81 ir_type *lowered, *ptr_tp;
82 ir_type **params, **results, *res_tp;
83 ir_mode *modes[MAX_REGISTER_RET_VAL];
84 int n_ress, n_params, nn_ress, nn_params, i, first_variadic;
86 add_hidden hidden_params;
90 if (is_lowered_type(mtp)) {
91 /* the type is already lowered. Not handled yet. */
92 assert(0 && "lowered types NYI");
95 lowered = get_associated_type(mtp);
99 n_ress = get_method_n_ress(mtp);
100 NEW_ARR_A(ir_type *, results, n_ress);
102 n_params = get_method_n_params(mtp);
103 NEW_ARR_A(ir_type *, params, n_params + n_ress);
105 first_variadic = get_method_first_variadic_param_index(mtp);
107 hidden_params = lp->hidden_params;
108 if (hidden_params == ADD_HIDDEN_SMART &&
109 get_method_variadicity(mtp) == variadicity_variadic)
110 hidden_params = ADD_HIDDEN_ALWAYS_IN_FRONT;
112 if (hidden_params == ADD_HIDDEN_ALWAYS_IN_FRONT) {
113 /* add hidden in front */
114 for (nn_ress = nn_params = i = 0; i < n_ress; ++i) {
115 res_tp = get_method_res_type(mtp, i);
117 if (is_compound_type(res_tp)) {
120 if (lp->flags & LF_SMALL_CMP_IN_REGS)
121 n_regs = lp->ret_compound_in_regs(res_tp, modes);
124 /* this compound will be returned solely in registers */
125 panic("Returning compounds in registers not yet implemented");
128 /* this compound will be allocated on callers stack and its
129 address will be transmitted as a hidden parameter. */
130 ptr_tp = lp->find_pointer_type(res_tp, get_modeP_data(), lp->def_ptr_alignment);
131 params[nn_params++] = ptr_tp;
133 if (lp->flags & LF_RETURN_HIDDEN)
134 results[nn_ress++] = ptr_tp;
138 results[nn_ress++] = res_tp;
141 /* move the index of the first variadic parameter */
142 first_variadic += nn_params;
144 for (i = 0; i < n_params; ++i)
145 params[nn_params++] = get_method_param_type(mtp, i);
148 /* add hidden parameters last */
149 assert(get_method_variadicity(mtp) == variadicity_non_variadic &&
150 "Cannot add hidden parameters at end of variadic function");
152 for (nn_params = 0; nn_params < n_params; ++nn_params)
153 params[nn_params] = get_method_param_type(mtp, nn_params);
155 for (nn_ress = i = 0; i < n_ress; ++i) {
156 res_tp = get_method_res_type(mtp, i);
158 if (is_compound_type(res_tp))
159 params[nn_params++] = lp->find_pointer_type(res_tp, get_modeP_data(), lp->def_ptr_alignment);
161 results[nn_ress++] = res_tp;
165 /* create the new type */
166 id = mangle_u(new_id_from_chars("L", 1), get_type_ident(mtp));
167 lowered = new_d_type_method(id, nn_params, nn_ress, get_type_dbg_info(mtp));
170 for (i = 0; i < nn_params; ++i)
171 set_method_param_type(lowered, i, params[i]);
172 for (i = 0; i < nn_ress; ++i)
173 set_method_res_type(lowered, i, results[i]);
175 var = get_method_variadicity(mtp);
176 set_method_variadicity(lowered, var);
177 if (var == variadicity_variadic)
178 set_method_first_variadic_param_index(lowered, first_variadic);
180 /* associate the lowered type with the original one for easier access */
182 set_method_calling_convention(lowered, get_method_calling_convention(mtp) | cc_compound_ret);
184 set_lowered_type(mtp, lowered);
192 typedef struct cl_entry cl_entry;
194 cl_entry *next; /**< Pointer to the next entry. */
195 ir_node *call; /**< Pointer to the Call node. */
196 ir_node *copyb; /**< List of all CopyB nodes. */
200 * Walker environment for fix_args_and_collect_calls().
202 typedef struct _wlk_env_t {
203 int arg_shift; /**< The Argument index shift for parameters. */
204 int first_hidden; /**< The index of the first hidden argument. */
205 struct obstack obst; /**< An obstack to allocate the data on. */
206 cl_entry *cl_list; /**< The call list. */
207 pmap *dummy_map; /**< A map for finding the dummy arguments. */
208 unsigned dnr; /**< The dummy index number. */
209 const lower_params_t *params; /**< Lowering parameters. */
210 unsigned only_local_mem:1; /**< Set if only local memory access was found. */
211 unsigned changed:1; /**< Set if the current graph was changed. */
215 * Return the call list entry of a call node.
216 * If no entry exists yet, allocate one and enter the node into
217 * the call list of the environment.
219 * @param call A Call node.
220 * @param env The environment.
222 static cl_entry *get_Call_entry(ir_node *call, wlk_env *env) {
223 cl_entry *res = get_irn_link(call);
225 cl_entry *res = obstack_alloc(&env->obst, sizeof(*res));
226 res->next = env->cl_list;
229 set_irn_link(call, res);
236 * Finds the base address of an address by skipping Sel's and address
239 * @param adr the address
240 * @param pEnt points to the base entity if any
242 static ir_node *find_base_adr(ir_node *ptr, ir_entity **pEnt) {
243 ir_entity *ent = NULL;
244 assert(mode_is_reference(get_irn_mode(ptr)));
248 ent = get_Sel_entity(ptr);
249 ptr = get_Sel_ptr(ptr);
251 else if (is_Add(ptr)) {
252 ir_node *left = get_Add_left(ptr);
253 if (mode_is_reference(get_irn_mode(left)))
256 ptr = get_Add_right(ptr);
258 } else if (is_Sub(ptr)) {
259 ptr = get_Sub_left(ptr);
269 * Check if a given pointer represents non-local memory.
271 static void check_ptr(ir_node *ptr, wlk_env *env) {
272 ir_storage_class_class_t sc;
275 /* still alias free */
276 ptr = find_base_adr(ptr, &ent);
277 sc = classify_pointer(current_ir_graph, ptr, ent);
278 if (sc != ir_sc_localvar && sc != ir_sc_malloced) {
279 /* non-local memory access */
280 env->only_local_mem = 0;
285 * Post walker: shift all parameter indexes
286 * and collect Calls with compound returns in the call list.
287 * If a non-alias free memory access is found, reset the alias free
290 static void fix_args_and_collect_calls(ir_node *n, void *ctx) {
296 switch (get_irn_opcode(n)) {
299 if (env->only_local_mem) {
300 ptr = get_irn_n(n, 1);
305 if (env->arg_shift > 0) {
306 ir_node *pred = get_Proj_pred(n);
308 /* Fix the argument numbers */
309 if (pred == get_irg_args(current_ir_graph)) {
310 long pnr = get_Proj_proj(n);
311 set_Proj_proj(n, pnr + env->arg_shift);
317 if (! is_self_recursive_Call(n)) {
318 /* any non self recursive call might access global memory */
319 env->only_local_mem = 0;
322 ctp = get_Call_type(n);
323 if (env->params->flags & LF_COMPOUND_RETURN) {
324 /* check for compound returns */
325 for (i = get_method_n_ress(ctp) -1; i >= 0; --i) {
326 if (is_compound_type(get_method_res_type(ctp, i))) {
328 * This is a call with a compound return. As the result
329 * might be ignored, we must put it in the list.
331 (void)get_Call_entry(n, env);
338 if (env->only_local_mem) {
339 check_ptr(get_CopyB_src(n), env);
340 if (env->only_local_mem)
341 check_ptr(get_CopyB_dst(n), env);
343 if (env->params->flags & LF_COMPOUND_RETURN) {
344 /* check for compound returns */
345 ir_node *src = get_CopyB_src(n);
346 /* older scheme using value_res_ent */
348 ir_node *proj = get_Sel_ptr(src);
349 if (is_Proj(proj) && get_Proj_proj(proj) == pn_Call_P_value_res_base) {
350 ir_node *call = get_Proj_pred(proj);
352 /* found a CopyB from compound Call result */
353 cl_entry *e = get_Call_entry(call, env);
354 set_irn_link(n, e->copyb);
359 /* new scheme: compound results are determined by the call type only */
361 ir_node *proj = get_Proj_pred(src);
362 if (is_Proj(proj) && get_Proj_proj(proj) == pn_Call_T_result) {
363 ir_node *call = get_Proj_pred(proj);
365 ctp = get_Call_type(call);
366 if (is_compound_type(get_method_res_type(ctp, get_Proj_proj(src)))) {
367 /* found a CopyB from compound Call result */
368 cl_entry *e = get_Call_entry(call, env);
369 set_irn_link(n, e->copyb);
385 * Returns non-zero if a node is a compound address
386 * of a frame-type entity.
388 * @param ft the frame type
389 * @param adr the node
391 static int is_compound_address(ir_type *ft, ir_node *adr)
397 if (get_Sel_n_indexs(adr) != 0)
399 ent = get_Sel_entity(adr);
400 return get_entity_owner(ent) == ft;
403 /** A pair for the copy-return-optimization. */
404 typedef struct cr_pair {
405 ir_entity *ent; /**< the entity than can be removed from the frame */
406 ir_node *arg; /**< the argument that replaces the entities address */
410 * Post walker: fixes all entities addresses for the copy-return
413 * Note: We expect the length of the cr_pair array (ie number of compound
414 * return values) to be 1 (C, C++) in almost all cases, so ignore the
415 * linear search complexity here.
417 static void do_copy_return_opt(ir_node *n, void *ctx) {
422 ir_entity *ent = get_Sel_entity(n);
424 for (i = ARR_LEN(arr) - 1; i >= 0; --i) {
425 if (ent == arr[i].ent) {
426 exchange(n, arr[i].arg);
434 * Return a Sel node that selects a dummy argument of type tp.
435 * Dummy arguments are only needed once and we use a map
437 * We could even assign all dummy arguments the same offset
438 * in the frame type ...
440 * @param irg the graph
441 * @param block the block where a newly create Sel should be placed
442 * @param tp the type of the dummy entity that should be create
443 * @param env the environment
445 static ir_node *get_dummy_sel(ir_graph *irg, ir_node *block, ir_type *tp, wlk_env *env)
450 /* use a map the check if we already create such an entity */
451 e = pmap_find(env->dummy_map, tp);
455 ir_type *ft = get_irg_frame_type(irg);
458 snprintf(buf, sizeof(buf), "dummy.%u", env->dnr++);
459 ent = new_entity(ft, new_id_from_str(buf), tp);
460 pmap_insert(env->dummy_map, tp, ent);
462 if (get_type_state(ft) == layout_fixed) {
463 /* Fix the layout again */
464 assert(0 && "Fixed layout not implemented");
467 return new_r_simpleSel(
476 * Add the hidden parameter from the CopyB node to the Call node.
478 * @param irg the graph
479 * @param n_com number of compound results (will be number of hidden parameters)
480 * @param ins in array to store the hidden parameters into
481 * @param entry the call list
482 * @param env the environment
484 static void add_hidden_param(ir_graph *irg, int n_com, ir_node **ins, cl_entry *entry, wlk_env *env)
486 ir_node *p, *n, *src, *mem, *blk;
492 for (p = entry->copyb; p; p = n) {
494 src = get_CopyB_src(p);
496 /* old scheme using value_res_ent */
498 ent = get_Sel_entity(src);
499 owner = get_entity_owner(ent);
501 /* find the hidden parameter index */
502 for (idx = 0; idx < get_struct_n_members(owner); ++idx)
503 if (get_struct_member(owner, idx) == ent)
505 assert(idx < get_struct_n_members(owner));
507 /* new scheme: compound returns are determined by the call type and are Proj's */
508 idx = get_Proj_proj(src);
511 ins[idx] = get_CopyB_dst(p);
512 mem = get_CopyB_mem(p);
513 blk = get_nodes_block(p);
515 /* get rid of the CopyB */
516 turn_into_tuple(p, pn_CopyB_max);
517 set_Tuple_pred(p, pn_CopyB_M_regular, mem);
518 set_Tuple_pred(p, pn_CopyB_M_except, get_irg_bad(irg));
519 set_Tuple_pred(p, pn_CopyB_X_regular, new_r_Jmp(irg, blk));
520 set_Tuple_pred(p, pn_CopyB_X_except, get_irg_bad(irg));
524 /* now create dummy entities for function with ignored return value */
525 if (n_args < n_com) {
526 ir_type *ctp = get_Call_type(entry->call);
529 if (is_lowered_type(ctp))
530 ctp = get_associated_type(ctp);
532 for (j = i = 0; i < get_method_n_ress(ctp); ++i) {
533 ir_type *rtp = get_method_res_type(ctp, i);
534 if (is_compound_type(rtp)) {
536 ins[j] = get_dummy_sel(irg, get_nodes_block(entry->call), rtp, env);
544 * Fix all calls on a call list by adding hidden parameters.
546 * @param irg the graph
547 * @param env the environment
549 static void fix_call_list(ir_graph *irg, wlk_env *env) {
550 const lower_params_t *lp = env->params;
552 ir_node *call, **new_in;
553 ir_type *ctp, *lowered_mtp;
554 add_hidden hidden_params;
555 int i, n_params, n_com, pos;
557 new_in = NEW_ARR_F(ir_node *, 0);
558 for (p = env->cl_list; p; p = p->next) {
560 ctp = get_Call_type(call);
561 lowered_mtp = create_modified_mtd_type(lp, ctp);
562 set_Call_type(call, lowered_mtp);
564 hidden_params = lp->hidden_params;
565 if (hidden_params == ADD_HIDDEN_SMART &&
566 get_method_variadicity(ctp) == variadicity_variadic)
567 hidden_params = ADD_HIDDEN_ALWAYS_IN_FRONT;
569 n_params = get_Call_n_params(call);
572 for (i = get_method_n_ress(ctp) - 1; i >= 0; --i) {
573 if (is_compound_type(get_method_res_type(ctp, i)))
577 ARR_RESIZE(ir_node *, new_in, n_params + n_com + pos);
578 memset(new_in, 0, sizeof(*new_in) * (n_params + n_com + pos));
579 if (hidden_params == ADD_HIDDEN_ALWAYS_IN_FRONT) {
580 add_hidden_param(irg, n_com, &new_in[pos], p, env);
583 /* copy all other parameters */
584 for (i = 0; i < n_params; ++i)
585 new_in[pos++] = get_Call_param(call, i);
586 if (hidden_params == ADD_HIDDEN_ALWAYS_LAST) {
587 add_hidden_param(irg, n_com, &new_in[pos], p, env);
590 new_in[0] = get_Call_mem(call);
591 new_in[1] = get_Call_ptr(call);
593 set_irn_in(call, n_params + n_com + 2, new_in);
598 * Transform a graph. If it has compound parameter returns,
599 * remove them and use the hidden parameter instead.
600 * If it calls methods with compound parameter returns, add hidden
603 * @param lp parameter struct
604 * @param irg the graph to transform
606 static void transform_irg(const lower_params_t *lp, ir_graph *irg)
608 ir_graph * rem = current_ir_graph;
609 ir_entity *ent = get_irg_entity(irg);
610 ir_type *mtp, *lowered_mtp, *tp, *ft;
611 int i, j, k, n_ress = 0, n_ret_com = 0, n_cr_opt;
612 ir_node **new_in, *ret, *endbl, *bl, *mem, *copy;
615 add_hidden hidden_params;
617 current_ir_graph = irg;
619 assert(ent && "Cannot transform graph without an entity");
620 assert(get_irg_phase_state(irg) == phase_high && "call lowering must be done in phase high");
622 mtp = get_entity_type(ent);
624 if (lp->flags & LF_COMPOUND_RETURN) {
625 /* calculate the number of compound returns */
626 n_ress = get_method_n_ress(mtp);
627 for (n_ret_com = i = 0; i < n_ress; ++i) {
628 tp = get_method_res_type(mtp, i);
630 if (is_compound_type(tp))
636 /* much easier if we have only one return */
637 normalize_one_return(irg);
639 /* This graph has a compound argument. Create a new type */
640 lowered_mtp = create_modified_mtd_type(lp, mtp);
641 set_entity_type(ent, lowered_mtp);
643 hidden_params = lp->hidden_params;
644 if (hidden_params == ADD_HIDDEN_SMART &&
645 get_method_variadicity(mtp) == variadicity_variadic)
646 hidden_params = ADD_HIDDEN_ALWAYS_IN_FRONT;
648 if (hidden_params == ADD_HIDDEN_ALWAYS_IN_FRONT) {
649 /* hidden arguments are added first */
650 env.arg_shift = n_ret_com;
651 env.first_hidden = 0;
653 /* hidden arguments are added last */
655 env.first_hidden = get_method_n_params(mtp);
658 /* we must only search for calls */
661 obstack_init(&env.obst);
663 env.dummy_map = pmap_create_ex(8);
666 env.only_local_mem = 1;
669 /* scan the code, fix argument numbers and collect calls. */
670 irg_walk_graph(irg, firm_clear_link, fix_args_and_collect_calls, &env);
674 fix_call_list(irg, &env);
680 * Now fix the Return node of the current graph.
684 /* STEP 1: find the return. This is simple, we have normalized the graph. */
685 endbl = get_irg_end_block(irg);
687 for (i = get_Block_n_cfgpreds(endbl) - 1; i >= 0; --i) {
688 ir_node *pred = get_Block_cfgpred(endbl, i);
690 if (is_Return(pred)) {
695 /* there should always be a return */
699 * STEP 2: fix it. For all compound return values add a CopyB,
700 * all others are copied.
702 NEW_ARR_A(ir_node *, new_in, n_ress + 1);
704 bl = get_nodes_block(ret);
705 mem = get_Return_mem(ret);
707 ft = get_irg_frame_type(irg);
708 NEW_ARR_A(cr_pair, cr_opt, n_ret_com);
710 for (j = 1, i = k = 0; i < n_ress; ++i) {
711 ir_node *pred = get_Return_res(ret, i);
712 tp = get_method_res_type(mtp, i);
714 if (is_compound_type(tp)) {
715 ir_node *arg = get_irg_args(irg);
716 arg = new_r_Proj(irg, get_nodes_block(arg), arg, mode_P_data, env.first_hidden + k);
719 if (is_Unknown(pred)) {
720 /* The Return(Unknown) is the Firm construct for a missing return.
724 * Sorrily detecting that copy-return is possible isn't that simple.
725 * We must check, that the hidden address is alias free during the whole
727 * A simple heuristic: all Loads/Stores inside
728 * the function access only local frame.
730 if (env.only_local_mem && is_compound_address(ft, pred)) {
731 /* we can do the copy-return optimization here */
732 cr_opt[n_cr_opt].ent = get_Sel_entity(pred);
733 cr_opt[n_cr_opt].arg = arg;
735 } else { /* copy-return optimization is impossible, do the copy. */
743 mem = new_r_Proj(irg, bl, copy, mode_M, pn_CopyB_M_regular);
746 if (lp->flags & LF_RETURN_HIDDEN) {
750 } else { /* scalar return value */
755 /* replace the in of the Return */
757 set_irn_in(ret, j, new_in);
760 irg_walk_graph(irg, NULL, do_copy_return_opt, cr_opt);
762 for (i = ARR_LEN(cr_opt) - 1; i >= 0; --i) {
763 remove_class_member(ft, cr_opt[i].ent);
766 } /* if (n_ret_com) */
768 pmap_destroy(env.dummy_map);
769 obstack_free(&env.obst, NULL);
772 /* invalidate the analysis info */
773 set_irg_outs_inconsistent(irg);
774 set_irg_loopinfo_state(irg, loopinfo_inconsistent);
776 current_ir_graph = rem;
780 * Returns non-zero if the given type is a method
781 * type that must be lowered.
783 * @param lp lowering parameters
784 * @param tp The type.
786 static int must_be_lowered(const lower_params_t *lp, ir_type *tp) {
790 if (is_Method_type(tp)) {
791 if (lp->flags & LF_COMPOUND_RETURN) {
792 /* check for compound returns */
793 n_ress = get_method_n_ress(tp);
794 for (i = 0; i < n_ress; ++i) {
795 res_tp = get_method_res_type(tp, i);
797 if (is_compound_type(res_tp))
806 * type-walker: lower all method types of entities
807 * and points-to types.
809 static void lower_method_types(type_or_ent tore, void *env)
811 const lower_params_t *lp = env;
814 /* fix method entities */
815 if (is_entity(tore.ent)) {
816 ir_entity *ent = tore.ent;
817 tp = get_entity_type(ent);
819 if (must_be_lowered(lp, tp)) {
820 tp = create_modified_mtd_type(lp, tp);
821 set_entity_type(ent, tp);
826 /* fix pointer to methods */
827 if (is_Pointer_type(tp)) {
828 ir_type *etp = get_pointer_points_to_type(tp);
829 if (must_be_lowered(lp, etp)) {
830 etp = create_modified_mtd_type(lp, etp);
831 set_pointer_points_to_type(tp, etp);
838 * Lower calls with compound parameters and return types.
839 * This function does the following transformations:
841 * - Adds a new (hidden) pointer parameter for
842 * any return compound type.
844 * - Use of the hidden parameters in the function code.
846 * - Change all calls to functions with compound return
847 * by providing space for the hidden parameter on the callers
850 * - Replace a possible block copy after the function call.
852 void lower_calls_with_compounds(const lower_params_t *params)
856 lower_params_t param = *params;
858 if (param.find_pointer_type == NULL) {
859 param.find_pointer_type = def_find_pointer_type;
860 type_map = pmap_create_ex(8);
864 /* first step: Transform all graphs */
865 for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
866 irg = get_irp_irg(i);
868 if (irg == get_const_code_irg())
871 transform_irg(¶m, irg);
874 /* second step: Lower all method types of visible entities */
875 type_walk(NULL, lower_method_types, ¶m);
878 pmap_destroy(type_map);