7f15ee5ffe786adc133941e3d5cc9f3b2f82f7b3
[libfirm] / ir / lower / lower_calls.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
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.
10  *
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.
14  *
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
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   Lowering of Calls with compound parameters and return types.
23  * @author  Michael Beck
24  * @version $Id$
25  */
26
27 #include "config.h"
28
29 #include "lowering.h"
30 #include "irprog_t.h"
31 #include "irnode_t.h"
32 #include "type_t.h"
33 #include "irmode_t.h"
34 #include "ircons.h"
35 #include "irgmod.h"
36 #include "irgwalk.h"
37 #include "irmemory.h"
38 #include "irtools.h"
39 #include "iroptimize.h"
40 #include "array_t.h"
41 #include "pmap.h"
42 #include "error.h"
43
44 /** A type map for def_find_pointer_type. */
45 static pmap *type_map;
46
47 /**
48  * Default implementation for finding a pointer type for a given element type.
49  * Simple create a new one.
50  */
51 static ir_type *def_find_pointer_type(ir_type *e_type, ir_mode *mode, int alignment)
52 {
53         ir_type *res;
54         pmap_entry *e;
55
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);
59         if (e && get_type_mode(e->value) == mode)
60                 res = e->value;
61         else {
62                 res = new_type_pointer(e_type);
63                 set_type_mode(res, mode);
64                 set_type_alignment_bytes(res, alignment);
65                 pmap_insert(type_map, e_type, res);
66         }
67         return res;
68 }
69
70 /**
71  * Creates a new lowered type for a method type with compound
72  * arguments. The new type is associated to the old one and returned.
73  *
74  * @param lp   parameter struct
75  * @param mtp  the method type to lower
76  *
77  * The current implementation expects that a lowered type already
78  * includes the necessary changes ...
79  */
80 static ir_type *create_modified_mtd_type(const lower_params_t *lp, ir_type *mtp)
81 {
82         ir_type *lowered, *ptr_tp, *value_type;
83         ir_type **params, **results, *res_tp;
84         int     *param_map;
85         ir_mode *modes[MAX_REGISTER_RET_VAL];
86         int n_ress, n_params, nn_ress, nn_params, i, first_variadic;
87         add_hidden hidden_params;
88         int        changed = 0;
89         ir_variadicity var;
90
91         if (is_lowered_type(mtp)) {
92                 /* the type is already lowered. Not handled yet. */
93                 assert(0 && "lowered types NYI");
94         }
95
96         lowered = get_associated_type(mtp);
97         if (lowered != NULL)
98                 return lowered;
99
100         n_ress   = get_method_n_ress(mtp);
101         NEW_ARR_A(ir_type *, results, n_ress);
102
103         n_params = get_method_n_params(mtp);
104         NEW_ARR_A(ir_type *, params, n_params + n_ress);
105
106         NEW_ARR_A(int, param_map, n_params + n_ress);
107
108         first_variadic = get_method_first_variadic_param_index(mtp);
109
110         hidden_params = lp->hidden_params;
111         if (hidden_params == ADD_HIDDEN_SMART &&
112                 get_method_variadicity(mtp) == variadicity_variadic)
113                 hidden_params = ADD_HIDDEN_ALWAYS_IN_FRONT;
114
115         if (hidden_params == ADD_HIDDEN_ALWAYS_IN_FRONT) {
116                 /* add hidden in front */
117                 for (nn_ress = nn_params = i = 0; i < n_ress; ++i) {
118                         res_tp = get_method_res_type(mtp, i);
119
120                         if (is_compound_type(res_tp)) {
121                                 int n_regs = 0;
122
123                                 if (lp->flags & LF_SMALL_CMP_IN_REGS)
124                                         n_regs = lp->ret_compound_in_regs(res_tp, modes);
125
126                                 if (n_regs > 0) {
127                                         /* this compound will be returned solely in registers */
128                                         panic("Returning compounds in registers not yet implemented");
129                                 }
130                                 else {
131                                         /* this compound will be allocated on callers stack and its
132                                            address will be transmitted as a hidden parameter. */
133                                         ptr_tp = lp->find_pointer_type(res_tp, get_modeP_data(), lp->def_ptr_alignment);
134                                         params[nn_params]    = ptr_tp;
135                                         param_map[nn_params] = -1 - i;
136                                         ++nn_params;
137                                         changed++;
138                                         if (lp->flags & LF_RETURN_HIDDEN)
139                                                 results[nn_ress++] = ptr_tp;
140                                 }
141                         } else {
142                                 /* scalar result */
143                                 results[nn_ress++] = res_tp;
144                         }
145                 }
146
147                 /* move the index of the first variadic parameter */
148                 first_variadic += nn_params;
149
150                 for (i = 0; i < n_params; ++i, ++nn_params) {
151                         params[nn_params]    = get_method_param_type(mtp, i);
152                         param_map[nn_params] = i;
153                 }
154         } else {
155                 /* add hidden parameters last */
156                 assert(get_method_variadicity(mtp) == variadicity_non_variadic &&
157                         "Cannot add hidden parameters at end of variadic function");
158
159                 for (nn_params = 0; nn_params < n_params; ++nn_params) {
160                         params[nn_params]    = get_method_param_type(mtp, nn_params);
161                         param_map[nn_params] = nn_params;
162                 }
163
164                 for (nn_ress = i = 0; i < n_ress; ++i) {
165                         res_tp = get_method_res_type(mtp, i);
166
167                         if (is_compound_type(res_tp)) {
168                                 params[nn_params] = lp->find_pointer_type(res_tp, get_modeP_data(), lp->def_ptr_alignment);
169                                 param_map[nn_params] = -1 - i;
170                                 ++nn_params;
171                         } else {
172                                 results[nn_ress++] = res_tp;
173                         }
174                 }
175         }
176
177         /* create the new type */
178         lowered = new_d_type_method(nn_params, nn_ress, get_type_dbg_info(mtp));
179
180         /* fill it */
181         for (i = 0; i < nn_params; ++i)
182                 set_method_param_type(lowered, i, params[i]);
183         for (i = 0; i < nn_ress; ++i)
184                 set_method_res_type(lowered, i, results[i]);
185
186         var = get_method_variadicity(mtp);
187         set_method_variadicity(lowered, var);
188         if (var == variadicity_variadic)
189                 set_method_first_variadic_param_index(lowered, first_variadic);
190
191         /* associate the lowered type with the original one for easier access */
192         if (changed) {
193                 set_method_calling_convention(lowered, get_method_calling_convention(mtp) | cc_compound_ret);
194         }
195
196         set_lowered_type(mtp, lowered);
197
198         value_type = get_method_value_param_type(mtp);
199         if (value_type != NULL) {
200                 /* set new param positions */
201                 for (i = 0; i < nn_params; ++i) {
202                         ir_entity *ent = get_method_value_param_ent(lowered, i);
203                         int       pos  = param_map[i];
204                         ident     *id;
205
206                         set_entity_link(ent, INT_TO_PTR(pos));
207                         if (pos < 0) {
208                                 /* formally return value, ignore for now */
209                                 continue;
210                         }
211
212                         id = get_method_param_ident(mtp, pos);
213                         if (id != NULL) {
214                                 set_method_param_ident(lowered, i, id);
215                                 set_entity_ident(ent, id);
216                         }
217                 }
218
219                 set_lowered_type(value_type, get_method_value_param_type(lowered));
220         }
221
222         return lowered;
223 }
224
225 /**
226  * A call list entry.
227  */
228 typedef struct cl_entry cl_entry;
229 struct cl_entry {
230         cl_entry *next;   /**< Pointer to the next entry. */
231         ir_node  *call;   /**< Pointer to the Call node. */
232         ir_node  *copyb;  /**< List of all CopyB nodes. */
233 };
234
235 /**
236  * Walker environment for fix_args_and_collect_calls().
237  */
238 typedef struct _wlk_env_t {
239         int                  arg_shift;        /**< The Argument index shift for parameters. */
240         int                  first_hidden;     /**< The index of the first hidden argument. */
241         struct obstack       obst;             /**< An obstack to allocate the data on. */
242         cl_entry             *cl_list;         /**< The call list. */
243         pmap                 *dummy_map;       /**< A map for finding the dummy arguments. */
244         unsigned             dnr;              /**< The dummy index number. */
245         const lower_params_t *params;          /**< Lowering parameters. */
246         ir_type              *lowered_mtp;     /**< The lowered method type of the current irg if any. */
247         ir_type              *value_params;    /**< The value params type if any. */
248         unsigned             only_local_mem:1; /**< Set if only local memory access was found. */
249         unsigned             changed:1;        /**< Set if the current graph was changed. */
250 } wlk_env;
251
252 /**
253  * Return the call list entry of a call node.
254  * If no entry exists yet, allocate one and enter the node into
255  * the call list of the environment.
256  *
257  * @param call   A Call node.
258  * @param env    The environment.
259  */
260 static cl_entry *get_Call_entry(ir_node *call, wlk_env *env) {
261         cl_entry *res = get_irn_link(call);
262         if (res == NULL) {
263                 cl_entry *res = OALLOC(&env->obst, cl_entry);
264                 res->next  = env->cl_list;
265                 res->call  = call;
266                 res->copyb = NULL;
267                 set_irn_link(call, res);
268                 env->cl_list = res;
269         }
270         return res;
271 }
272
273 /**
274  * Finds the base address of an address by skipping Sel's and address
275  * calculation.
276  *
277  * @param adr   the address
278  * @param pEnt  points to the base entity if any
279  */
280 static ir_node *find_base_adr(ir_node *ptr, ir_entity **pEnt) {
281         ir_entity *ent = NULL;
282         assert(mode_is_reference(get_irn_mode(ptr)));
283
284         for (;;) {
285                 if (is_Sel(ptr)) {
286                         ent = get_Sel_entity(ptr);
287                         ptr = get_Sel_ptr(ptr);
288                 }
289                 else if (is_Add(ptr)) {
290                         ir_node *left = get_Add_left(ptr);
291                         if (mode_is_reference(get_irn_mode(left)))
292                                 ptr = left;
293                         else
294                                 ptr = get_Add_right(ptr);
295                         ent = NULL;
296                 } else if (is_Sub(ptr)) {
297                         ptr = get_Sub_left(ptr);
298                         ent = NULL;
299                 } else {
300                         *pEnt = ent;
301                         return ptr;
302                 }
303         }
304 }
305
306 /**
307  * Check if a given pointer represents non-local memory.
308  */
309 static void check_ptr(ir_node *ptr, wlk_env *env) {
310         ir_storage_class_class_t sc;
311         ir_entity                *ent;
312
313         /* still alias free */
314         ptr = find_base_adr(ptr, &ent);
315         sc  = GET_BASE_SC(classify_pointer(current_ir_graph, ptr, ent));
316         if (sc != ir_sc_localvar && sc != ir_sc_malloced) {
317                 /* non-local memory access */
318                 env->only_local_mem = 0;
319         }
320 }
321
322 /**
323  * Post walker: shift all parameter indexes
324  * and collect Calls with compound returns in the call list.
325  * If a non-alias free memory access is found, reset the alias free
326  * flag.
327  */
328 static void fix_args_and_collect_calls(ir_node *n, void *ctx) {
329         wlk_env *env = ctx;
330         int      i;
331         ir_type *ctp;
332         ir_node *ptr;
333
334         switch (get_irn_opcode(n)) {
335         case iro_Sel:
336                 if (env->lowered_mtp != NULL && env->value_params != NULL) {
337                         ir_entity *ent = get_Sel_entity(n);
338
339                         if (get_entity_owner(ent) == env->value_params) {
340                                 int pos = get_struct_member_index(env->value_params, ent) + env->arg_shift;
341                                 ir_entity *new_ent;
342
343                                 new_ent = get_method_value_param_ent(env->lowered_mtp, pos);
344                                 set_entity_ident(new_ent, get_entity_ident(ent));
345                                 set_Sel_entity(n, new_ent);
346                         }
347                 }
348                 break;
349         case iro_Load:
350         case iro_Store:
351                 if (env->only_local_mem) {
352                         ptr = get_irn_n(n, 1);
353                         check_ptr(ptr, env);
354                 }
355                 break;
356         case iro_Proj:
357                 if (env->arg_shift > 0) {
358                         ir_node *pred = get_Proj_pred(n);
359
360                         /* Fix the argument numbers */
361                         if (pred == get_irg_args(current_ir_graph)) {
362                                 long pnr = get_Proj_proj(n);
363                                 set_Proj_proj(n, pnr + env->arg_shift);
364                                 env->changed = 1;
365                         }
366                 }
367                 break;
368         case iro_Call:
369                 if (! is_self_recursive_Call(n)) {
370                         /* any non self recursive call might access global memory */
371                         env->only_local_mem = 0;
372                 }
373
374                 ctp = get_Call_type(n);
375                 if (env->params->flags & LF_COMPOUND_RETURN) {
376                         /* check for compound returns */
377                         for (i = get_method_n_ress(ctp) -1; i >= 0; --i) {
378                                 if (is_compound_type(get_method_res_type(ctp, i))) {
379                                         /*
380                                          * This is a call with a compound return. As the result
381                                          * might be ignored, we must put it in the list.
382                                          */
383                                         (void)get_Call_entry(n, env);
384                                         break;
385                                 }
386                         }
387                 }
388                 break;
389         case iro_CopyB:
390                 if (env->only_local_mem) {
391                         check_ptr(get_CopyB_src(n), env);
392                         if (env->only_local_mem)
393                                 check_ptr(get_CopyB_dst(n), env);
394                 }
395                 if (env->params->flags & LF_COMPOUND_RETURN) {
396                         /* check for compound returns */
397                         ir_node *src = get_CopyB_src(n);
398                         /* older scheme using value_res_ent */
399                         if (is_Sel(src)) {
400                                 ir_node *proj = get_Sel_ptr(src);
401                                 if (is_Proj(proj) && get_Proj_proj(proj) == pn_Call_P_value_res_base) {
402                                         ir_node *call = get_Proj_pred(proj);
403                                         if (is_Call(call)) {
404                                                 /* found a CopyB from compound Call result */
405                                                 cl_entry *e = get_Call_entry(call, env);
406                                                 set_irn_link(n, e->copyb);
407                                                 e->copyb = n;
408                                         }
409                                 }
410                         } else {
411                                 /* new scheme: compound results are determined by the call type only */
412                                 if (is_Proj(src)) {
413                                         ir_node *proj = get_Proj_pred(src);
414                                         if (is_Proj(proj) && get_Proj_proj(proj) == pn_Call_T_result) {
415                                                 ir_node *call = get_Proj_pred(proj);
416                                                 if (is_Call(call)) {
417                                                         ctp = get_Call_type(call);
418                                                         if (is_compound_type(get_method_res_type(ctp, get_Proj_proj(src)))) {
419                                                                 /* found a CopyB from compound Call result */
420                                                                 cl_entry *e = get_Call_entry(call, env);
421                                                                 set_irn_link(n, e->copyb);
422                                                                 e->copyb = n;
423                                                         }
424                                                 }
425                                         }
426                                 }
427                         }
428                 }
429                 break;
430         default:
431                 /* do nothing */
432                 break;
433         }
434 }
435
436 /**
437  * Returns non-zero if a node is a compound address
438  * of a frame-type entity.
439  *
440  * @param ft   the frame type
441  * @param adr  the node
442  */
443 static int is_compound_address(ir_type *ft, ir_node *adr)
444 {
445         ir_entity *ent;
446
447         if (! is_Sel(adr))
448                 return 0;
449         if (get_Sel_n_indexs(adr) != 0)
450                 return 0;
451         ent = get_Sel_entity(adr);
452         return get_entity_owner(ent) == ft;
453 }
454
455 /** A pair for the copy-return-optimization. */
456 typedef struct cr_pair {
457         ir_entity *ent; /**< the entity than can be removed from the frame */
458         ir_node *arg;   /**< the argument that replaces the entities address */
459 } cr_pair;
460
461 /**
462  * Post walker: fixes all entities addresses for the copy-return
463  * optimization.
464  *
465  * Note: We expect the length of the cr_pair array (ie number of compound
466  * return values) to be 1 (C, C++) in almost all cases, so ignore the
467  * linear search complexity here.
468  */
469 static void do_copy_return_opt(ir_node *n, void *ctx) {
470         cr_pair *arr = ctx;
471         int i;
472
473         if (is_Sel(n)) {
474                 ir_entity *ent = get_Sel_entity(n);
475
476                 for (i = ARR_LEN(arr) - 1; i >= 0; --i) {
477                         if (ent == arr[i].ent) {
478                                 exchange(n, arr[i].arg);
479                                 break;
480                         }
481                 }
482         }
483 }
484
485 /**
486  * Return a Sel node that selects a dummy argument of type tp.
487  * Dummy arguments are only needed once and we use a map
488  * to store them.
489  * We could even assign all dummy arguments the same offset
490  * in the frame type ...
491  *
492  * @param irg    the graph
493  * @param block  the block where a newly create Sel should be placed
494  * @param tp     the type of the dummy entity that should be create
495  * @param env    the environment
496  */
497 static ir_node *get_dummy_sel(ir_graph *irg, ir_node *block, ir_type *tp, wlk_env *env)
498 {
499         ir_entity *ent;
500         pmap_entry *e;
501
502         /* use a map the check if we already create such an entity */
503         e = pmap_find(env->dummy_map, tp);
504         if (e)
505                 ent = e->value;
506         else {
507                 ir_type *ft = get_irg_frame_type(irg);
508                 char buf[16];
509
510                 snprintf(buf, sizeof(buf), "dummy.%u", env->dnr++);
511                 ent = new_entity(ft, new_id_from_str(buf), tp);
512                 pmap_insert(env->dummy_map, tp, ent);
513
514                 if (get_type_state(ft) == layout_fixed) {
515                         /* Fix the layout again */
516                         assert(0 && "Fixed layout not implemented");
517                 }
518         }
519         return new_r_simpleSel(
520                 block,
521                 get_irg_no_mem(irg),
522                 get_irg_frame(irg),
523                 ent);
524 }
525
526 /**
527  * Add the hidden parameter from the CopyB node to the Call node.
528  *
529  * @param irg    the graph
530  * @param n_com  number of compound results (will be number of hidden parameters)
531  * @param ins    in array to store the hidden parameters into
532  * @param entry  the call list
533  * @param env    the environment
534  */
535 static void add_hidden_param(ir_graph *irg, int n_com, ir_node **ins, cl_entry *entry, wlk_env *env)
536 {
537         ir_node *p, *n, *src, *mem, *blk;
538         ir_entity *ent;
539         ir_type *owner;
540         int idx, n_args;
541
542         n_args = 0;
543         for (p = entry->copyb; p; p = n) {
544                 n   = get_irn_link(p);
545                 src = get_CopyB_src(p);
546
547                 /* old scheme using value_res_ent */
548                 if (is_Sel(src)) {
549                         ent = get_Sel_entity(src);
550                         owner = get_entity_owner(ent);
551
552                         /* find the hidden parameter index */
553                         for (idx = 0; idx < get_struct_n_members(owner); ++idx)
554                                 if (get_struct_member(owner, idx) == ent)
555                                         break;
556                         assert(idx < get_struct_n_members(owner));
557                 } else {
558                         /* new scheme: compound returns are determined by the call type and are Proj's */
559                         idx = get_Proj_proj(src);
560                 }
561
562                 ins[idx] = get_CopyB_dst(p);
563                 mem      = get_CopyB_mem(p);
564                 blk      = get_nodes_block(p);
565
566                 /* get rid of the CopyB */
567                 turn_into_tuple(p, pn_CopyB_max);
568                 set_Tuple_pred(p, pn_CopyB_M,         mem);
569                 set_Tuple_pred(p, pn_CopyB_X_regular, new_r_Jmp(blk));
570                 set_Tuple_pred(p, pn_CopyB_X_except,  get_irg_bad(irg));
571                 ++n_args;
572         }
573
574         /* now create dummy entities for function with ignored return value */
575         if (n_args < n_com) {
576                 ir_type *ctp = get_Call_type(entry->call);
577                 int i, j;
578
579                 if (is_lowered_type(ctp))
580                         ctp = get_associated_type(ctp);
581
582                 for (j = i = 0; i < get_method_n_ress(ctp); ++i) {
583                         ir_type *rtp = get_method_res_type(ctp, i);
584                         if (is_compound_type(rtp)) {
585                                 if (ins[j] == NULL)
586                                         ins[j] = get_dummy_sel(irg, get_nodes_block(entry->call), rtp, env);
587                                 ++j;
588                         }
589                 }
590         }
591 }
592
593 /**
594  * Fix all calls on a call list by adding hidden parameters.
595  *
596  * @param irg  the graph
597  * @param env  the environment
598  */
599 static void fix_call_list(ir_graph *irg, wlk_env *env) {
600         const lower_params_t *lp = env->params;
601         cl_entry *p;
602         ir_node *call, **new_in;
603         ir_type *ctp, *lowered_mtp;
604         add_hidden hidden_params;
605         int i, n_params, n_com, pos;
606
607         new_in = NEW_ARR_F(ir_node *, 0);
608         for (p = env->cl_list; p; p = p->next) {
609                 call = p->call;
610                 ctp = get_Call_type(call);
611                 lowered_mtp = create_modified_mtd_type(lp, ctp);
612                 set_Call_type(call, lowered_mtp);
613
614                 hidden_params = lp->hidden_params;
615                 if (hidden_params == ADD_HIDDEN_SMART &&
616                         get_method_variadicity(ctp) == variadicity_variadic)
617                         hidden_params = ADD_HIDDEN_ALWAYS_IN_FRONT;
618
619                 n_params = get_Call_n_params(call);
620
621                 n_com = 0;
622                 for (i = get_method_n_ress(ctp) - 1; i >= 0; --i) {
623                         if (is_compound_type(get_method_res_type(ctp, i)))
624                                 ++n_com;
625                 }
626                 pos = 2;
627                 ARR_RESIZE(ir_node *, new_in, n_params + n_com + pos);
628                 memset(new_in, 0, sizeof(*new_in) * (n_params + n_com + pos));
629                 if (hidden_params == ADD_HIDDEN_ALWAYS_IN_FRONT) {
630                         add_hidden_param(irg, n_com, &new_in[pos], p, env);
631                         pos += n_com;
632                 }
633                 /* copy all other parameters */
634                 for (i = 0; i < n_params; ++i)
635                         new_in[pos++] = get_Call_param(call, i);
636                 if (hidden_params == ADD_HIDDEN_ALWAYS_LAST) {
637                         add_hidden_param(irg, n_com, &new_in[pos], p, env);
638                         pos += n_com;
639                 }
640                 new_in[0] = get_Call_mem(call);
641                 new_in[1] = get_Call_ptr(call);
642
643                 set_irn_in(call, n_params + n_com + 2, new_in);
644         }
645 }
646
647 /**
648  * Transform a graph. If it has compound parameter returns,
649  * remove them and use the hidden parameter instead.
650  * If it calls methods with compound parameter returns, add hidden
651  * parameters.
652  *
653  * @param lp   parameter struct
654  * @param irg  the graph to transform
655  */
656 static void transform_irg(const lower_params_t *lp, ir_graph *irg)
657 {
658         ir_graph   * rem = current_ir_graph;
659         ir_entity  *ent = get_irg_entity(irg);
660         ir_type    *mtp, *lowered_mtp, *tp, *ft;
661         int        i, j, k, n_ress = 0, n_ret_com = 0, n_cr_opt;
662         ir_node    **new_in, *ret, *endbl, *bl, *mem, *copy;
663         cr_pair    *cr_opt;
664         wlk_env    env;
665         add_hidden hidden_params;
666
667         current_ir_graph = irg;
668
669         assert(ent && "Cannot transform graph without an entity");
670         assert(get_irg_phase_state(irg) == phase_high && "call lowering must be done in phase high");
671
672         mtp = get_entity_type(ent);
673
674         if (lp->flags & LF_COMPOUND_RETURN) {
675                 /* calculate the number of compound returns */
676                 n_ress = get_method_n_ress(mtp);
677                 for (n_ret_com = i = 0; i < n_ress; ++i) {
678                         tp = get_method_res_type(mtp, i);
679
680                         if (is_compound_type(tp))
681                                 ++n_ret_com;
682                 }
683         }
684
685         if (n_ret_com) {
686                 /* much easier if we have only one return */
687                 normalize_one_return(irg);
688
689                 /* This graph has a compound argument. Create a new type */
690                 lowered_mtp = create_modified_mtd_type(lp, mtp);
691                 set_entity_type(ent, lowered_mtp);
692
693                 hidden_params = lp->hidden_params;
694                 if (hidden_params == ADD_HIDDEN_SMART &&
695                         get_method_variadicity(mtp) == variadicity_variadic)
696                         hidden_params = ADD_HIDDEN_ALWAYS_IN_FRONT;
697
698                 if (hidden_params == ADD_HIDDEN_ALWAYS_IN_FRONT) {
699                         /* hidden arguments are added first */
700                         env.arg_shift    = n_ret_com;
701                         env.first_hidden = 0;
702                 } else {
703                         /* hidden arguments are added last */
704                         env.arg_shift    = 0;
705                         env.first_hidden = get_method_n_params(mtp);
706                 }
707         } else {
708                 /* we must only search for calls */
709                 env.arg_shift = 0;
710                 lowered_mtp   = NULL;
711         }
712         obstack_init(&env.obst);
713         env.cl_list        = NULL;
714         env.dummy_map      = pmap_create_ex(8);
715         env.dnr            = 0;
716         env.params         = lp;
717         env.lowered_mtp    = lowered_mtp;
718         env.value_params   = get_method_value_param_type(mtp);
719         env.only_local_mem = 1;
720         env.changed        = 0;
721
722         /* scan the code, fix argument numbers and collect calls. */
723         irg_walk_graph(irg, firm_clear_link, fix_args_and_collect_calls, &env);
724
725         /* fix all calls */
726         if (env.cl_list) {
727                 fix_call_list(irg, &env);
728                 env.changed = 1;
729         }
730
731         if (n_ret_com) {
732                 /*
733                  * Now fix the Return node of the current graph.
734                  */
735                 env.changed = 1;
736
737                 /* STEP 1: find the return. This is simple, we have normalized the graph. */
738                 endbl = get_irg_end_block(irg);
739                 ret = NULL;
740                 for (i = get_Block_n_cfgpreds(endbl) - 1; i >= 0; --i) {
741                         ir_node *pred = get_Block_cfgpred(endbl, i);
742
743                         if (is_Return(pred)) {
744                                 ret = pred;
745                                 break;
746                         }
747                 }
748                 /* there should always be a return */
749                 assert(ret);
750
751                 /*
752                  * STEP 2: fix it. For all compound return values add a CopyB,
753                  * all others are copied.
754                  */
755                 NEW_ARR_A(ir_node *, new_in, n_ress + 1);
756
757                 bl  = get_nodes_block(ret);
758                 mem = get_Return_mem(ret);
759
760                 ft = get_irg_frame_type(irg);
761                 NEW_ARR_A(cr_pair, cr_opt, n_ret_com);
762                 n_cr_opt = 0;
763                 for (j = 1, i = k = 0; i < n_ress; ++i) {
764                         ir_node *pred = get_Return_res(ret, i);
765                         tp = get_method_res_type(mtp, i);
766
767                         if (is_compound_type(tp)) {
768                                 ir_node *arg = get_irg_args(irg);
769                                 arg = new_r_Proj(get_nodes_block(arg), arg, mode_P_data, env.first_hidden + k);
770                                 ++k;
771
772                                 if (is_Unknown(pred)) {
773                                         /* The Return(Unknown) is the Firm construct for a missing return.
774                                            Do nothing. */
775                                 } else {
776                                         /**
777                                          * Sorrily detecting that copy-return is possible isn't that simple.
778                                          * We must check, that the hidden address is alias free during the whole
779                                          * function.
780                                          * A simple heuristic: all Loads/Stores inside
781                                          * the function access only local frame.
782                                          */
783                                         if (env.only_local_mem && is_compound_address(ft, pred)) {
784                                                 /* we can do the copy-return optimization here */
785                                                 cr_opt[n_cr_opt].ent = get_Sel_entity(pred);
786                                                 cr_opt[n_cr_opt].arg = arg;
787                                                 ++n_cr_opt;
788                                         } else { /* copy-return optimization is impossible, do the copy. */
789                                                 copy = new_r_CopyB(
790                                                         bl,
791                                                         mem,
792                                                         arg,
793                                                         pred,
794                                                         tp
795                                                         );
796                                                 mem = new_r_Proj(bl, copy, mode_M, pn_CopyB_M);
797                                         }
798                                 }
799                                 if (lp->flags & LF_RETURN_HIDDEN) {
800                                         new_in[j] = arg;
801                                         ++j;
802                                 }
803                         } else { /* scalar return value */
804                                 new_in[j] = pred;
805                                 ++j;
806                         }
807                 }
808                 /* replace the in of the Return */
809                 new_in[0] = mem;
810                 set_irn_in(ret, j, new_in);
811
812                 if (n_cr_opt > 0) {
813                         irg_walk_graph(irg, NULL, do_copy_return_opt, cr_opt);
814
815                         for (i = ARR_LEN(cr_opt) - 1; i >= 0; --i) {
816                                 remove_class_member(ft, cr_opt[i].ent);
817                         }
818                 }
819         } /* if (n_ret_com) */
820
821         pmap_destroy(env.dummy_map);
822         obstack_free(&env.obst, NULL);
823
824         if (env.changed) {
825                 /* invalidate the analysis info */
826                 set_irg_outs_inconsistent(irg);
827                 set_irg_loopinfo_state(irg, loopinfo_inconsistent);
828         }
829         current_ir_graph = rem;
830 }
831
832 /**
833  * Returns non-zero if the given type is a method
834  * type that must be lowered.
835  *
836  * @param lp  lowering parameters
837  * @param tp  The type.
838  */
839 static int must_be_lowered(const lower_params_t *lp, ir_type *tp) {
840   int i, n_ress;
841   ir_type *res_tp;
842
843   if (is_Method_type(tp)) {
844     if (lp->flags & LF_COMPOUND_RETURN) {
845       /* check for compound returns */
846       n_ress = get_method_n_ress(tp);
847       for (i = 0; i < n_ress; ++i) {
848         res_tp = get_method_res_type(tp, i);
849
850         if (is_compound_type(res_tp))
851           return 1;
852       }
853     }
854   }
855   return 0;
856 }
857
858 /**
859  * type-walker: lower all method types of entities
860  * and points-to types.
861  */
862 static void lower_method_types(type_or_ent tore, void *env)
863 {
864         const lower_params_t *lp = env;
865         ir_type *tp;
866
867         /* fix method entities */
868         if (is_entity(tore.ent)) {
869                 ir_entity *ent = tore.ent;
870                 tp = get_entity_type(ent);
871
872                 if (must_be_lowered(lp, tp)) {
873                         tp = create_modified_mtd_type(lp, tp);
874                         set_entity_type(ent, tp);
875                 }
876         } else {
877                 tp = tore.typ;
878
879                 /* fix pointer to methods */
880                 if (is_Pointer_type(tp)) {
881                         ir_type *etp = get_pointer_points_to_type(tp);
882                         if (must_be_lowered(lp, etp)) {
883                                 etp = create_modified_mtd_type(lp, etp);
884                                 set_pointer_points_to_type(tp, etp);
885                         }
886                 }
887         }
888 }
889
890 /*
891  * Lower calls with compound parameters and return types.
892  * This function does the following transformations:
893  *
894  * - Adds a new (hidden) pointer parameter for
895  *   any return compound type.
896  *
897  * - Use of the hidden parameters in the function code.
898  *
899  * - Change all calls to functions with compound return
900  *   by providing space for the hidden parameter on the callers
901  *   stack.
902  *
903  * - Replace a possible block copy after the function call.
904  */
905 void lower_calls_with_compounds(const lower_params_t *params)
906 {
907         int i;
908         ir_graph *irg;
909         lower_params_t param = *params;
910
911         if (param.find_pointer_type == NULL) {
912                 param.find_pointer_type = def_find_pointer_type;
913                 type_map = pmap_create_ex(8);
914         } else
915                 type_map = NULL;
916
917         /* first step: Transform all graphs */
918         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
919                 irg = get_irp_irg(i);
920
921                 transform_irg(&param, irg);
922         }
923
924         /* second step: Lower all method types of visible entities */
925         type_walk(NULL, lower_method_types, &param);
926
927         if (type_map)
928                 pmap_destroy(type_map);
929 }