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