remove license stuff from files
[libfirm] / ir / lower / lower_calls.c
1 /*
2  * This file is part of libFirm.
3  * Copyright (C) 2012 University of Karlsruhe.
4  */
5
6 /**
7  * @file
8  * @brief   Lowering of Calls with compound parameters and return types.
9  * @author  Michael Beck, Matthias Braun
10  */
11 #include "config.h"
12
13 #include <stdbool.h>
14
15 #include "lower_calls.h"
16 #include "lowering.h"
17 #include "irprog_t.h"
18 #include "irnode_t.h"
19 #include "type_t.h"
20 #include "irmode_t.h"
21 #include "ircons.h"
22 #include "irgmod.h"
23 #include "irgwalk.h"
24 #include "irmemory.h"
25 #include "irtools.h"
26 #include "iroptimize.h"
27 #include "array_t.h"
28 #include "pmap.h"
29 #include "error.h"
30 #include "util.h"
31
32 static pmap *pointer_types;
33 static pmap *lowered_mtps;
34
35 static bool needs_lowering(const ir_type *type)
36 {
37         return is_compound_type(type) || is_Array_type(type);
38 }
39
40 /**
41  * Default implementation for finding a pointer type for a given element type.
42  * Simply create a new one.
43  */
44 static ir_type *get_pointer_type(ir_type *dest_type)
45 {
46         ir_type *res = pmap_get(ir_type, pointer_types, dest_type);
47         if (res == NULL) {
48                 res = new_type_pointer(dest_type);
49                 pmap_insert(pointer_types, dest_type, res);
50         }
51         return res;
52 }
53
54 static void fix_parameter_entities(ir_graph *irg, size_t n_compound_ret)
55 {
56         ir_type *frame_type = get_irg_frame_type(irg);
57         size_t   n_members  = get_compound_n_members(frame_type);
58         size_t   i;
59
60         for (i = 0; i < n_members; ++i) {
61                 ir_entity *member = get_compound_member(frame_type, i);
62                 size_t     num;
63                 if (!is_parameter_entity(member))
64                         continue;
65
66                 /* increase parameter number since we added a new parameter in front */
67                 num = get_entity_parameter_number(member);
68                 if (num == IR_VA_START_PARAMETER_NUMBER)
69                         continue;
70                 set_entity_parameter_number(member, num + n_compound_ret);
71         }
72 }
73
74 static void remove_compound_param_entities(ir_graph *irg)
75 {
76         ir_type *frame_type = get_irg_frame_type(irg);
77         size_t   n_members  = get_compound_n_members(frame_type);
78         size_t   i;
79
80         for (i = n_members; i > 0; ) {
81                 ir_entity *member = get_compound_member(frame_type, --i);
82                 ir_type   *type;
83                 if (!is_parameter_entity(member))
84                         continue;
85
86                 type = get_entity_type(member);
87                 if (needs_lowering(type)) {
88                         free_entity(member);
89                 }
90         }
91 }
92
93 /**
94  * Creates a new lowered type for a method type with compound
95  * arguments. The new type is associated to the old one and returned.
96  */
97 static ir_type *lower_mtp(compound_call_lowering_flags flags, ir_type *mtp)
98 {
99         bool      must_be_lowered = false;
100         ir_type  *lowered;
101         ir_type **params;
102         ir_type **results;
103         size_t    n_ress;
104         size_t    n_params;
105         size_t    nn_ress;
106         size_t    nn_params;
107         size_t    i;
108         unsigned  cconv;
109         mtp_additional_properties mtp_properties;
110
111         if (!is_Method_type(mtp))
112                 return mtp;
113
114         lowered = pmap_get(ir_type, lowered_mtps, mtp);
115         if (lowered != NULL)
116                 return lowered;
117
118         /* check if the type has to be lowered at all */
119         n_params = get_method_n_params(mtp);
120         n_ress   = get_method_n_ress(mtp);
121         for (i = 0; i < n_ress; ++i) {
122                 ir_type *res_tp = get_method_res_type(mtp, i);
123                 if (needs_lowering(res_tp)) {
124                         must_be_lowered = true;
125                         break;
126                 }
127         }
128         if (!must_be_lowered && !(flags & LF_DONT_LOWER_ARGUMENTS)) {
129                 for (i = 0; i < n_params; ++i) {
130                         ir_type *param_type = get_method_param_type(mtp, i);
131                         if (needs_lowering(param_type)) {
132                                 must_be_lowered = true;
133                                 break;
134                         }
135                 }
136         }
137         if (!must_be_lowered)
138                 return mtp;
139
140         results   = ALLOCANZ(ir_type*, n_ress);
141         params    = ALLOCANZ(ir_type*, n_params + n_ress);
142         nn_ress   = 0;
143         nn_params = 0;
144
145         /* add a hidden parameter in front for every compound result */
146         for (i = 0; i < n_ress; ++i) {
147                 ir_type *res_tp = get_method_res_type(mtp, i);
148
149                 if (needs_lowering(res_tp)) {
150                         /* this compound will be allocated on callers stack and its
151                            address will be transmitted as a hidden parameter. */
152                         ir_type *ptr_tp = get_pointer_type(res_tp);
153                         params[nn_params++] = ptr_tp;
154                         if (flags & LF_RETURN_HIDDEN)
155                                 results[nn_ress++] = ptr_tp;
156                 } else {
157                         /* scalar result */
158                         results[nn_ress++] = res_tp;
159                 }
160         }
161         /* copy over parameter types */
162         for (i = 0; i < n_params; ++i) {
163                 ir_type *param_type = get_method_param_type(mtp, i);
164                 if (! (flags & LF_DONT_LOWER_ARGUMENTS) && needs_lowering(param_type)) {
165                     /* turn parameter into a pointer type */
166                     param_type = new_type_pointer(param_type);
167                 }
168                 params[nn_params++] = param_type;
169         }
170         assert(nn_ress <= n_ress);
171         assert(nn_params <= n_params + n_ress);
172
173         /* create the new type */
174         lowered = new_d_type_method(nn_params, nn_ress, get_type_dbg_info(mtp));
175
176         /* fill it */
177         for (i = 0; i < nn_params; ++i)
178                 set_method_param_type(lowered, i, params[i]);
179         for (i = 0; i < nn_ress; ++i)
180                 set_method_res_type(lowered, i, results[i]);
181
182         set_method_variadicity(lowered, get_method_variadicity(mtp));
183
184         cconv = get_method_calling_convention(mtp);
185         if (nn_params > n_params) {
186                 cconv |= cc_compound_ret;
187         }
188         set_method_calling_convention(lowered, cconv);
189
190         mtp_properties = get_method_additional_properties(mtp);
191         /* after lowering the call is not const anymore, since it writes to the
192          * memory for the return value passed to it */
193         mtp_properties &= ~mtp_property_const;
194         set_method_additional_properties(lowered, mtp_properties);
195
196         /* associate the lowered type with the original one for easier access */
197         set_higher_type(lowered, mtp);
198         pmap_insert(lowered_mtps, mtp, lowered);
199
200         return lowered;
201 }
202
203 /**
204  * A call list entry.
205  */
206 typedef struct cl_entry cl_entry;
207 struct cl_entry {
208         cl_entry *next;   /**< Pointer to the next entry. */
209         ir_node  *call;   /**< Pointer to the Call node. */
210         ir_node  *copyb;  /**< List of all CopyB nodes. */
211         bool      has_compound_ret   : 1;
212         bool      has_compound_param : 1;
213 };
214
215 /**
216  * Walker environment for fix_args_and_collect_calls().
217  */
218 typedef struct wlk_env_t {
219         size_t               arg_shift;        /**< The Argument index shift for parameters. */
220         struct obstack       obst;             /**< An obstack to allocate the data on. */
221         cl_entry             *cl_list;         /**< The call list. */
222         compound_call_lowering_flags flags;
223         ir_type              *lowered_mtp;     /**< The lowered method type of the current irg if any. */
224         bool                  only_local_mem:1;/**< Set if only local memory access was found. */
225         bool                  changed:1;       /**< Set if the current graph was changed. */
226 } wlk_env;
227
228 /**
229  * Return the call list entry of a call node.
230  * If no entry exists yet, allocate one and enter the node into
231  * the call list of the environment.
232  *
233  * @param call   A Call node.
234  * @param env    The environment.
235  */
236 static cl_entry *get_call_entry(ir_node *call, wlk_env *env)
237 {
238         cl_entry *res = (cl_entry*)get_irn_link(call);
239         if (res == NULL) {
240                 res = OALLOC(&env->obst, cl_entry);
241                 res->next  = env->cl_list;
242                 res->call  = call;
243                 res->copyb = NULL;
244                 set_irn_link(call, res);
245                 env->cl_list = res;
246         }
247         return res;
248 }
249
250 /**
251  * Finds the base address of an address by skipping Sel's and address
252  * calculation.
253  *
254  * @param adr   the address
255  * @param pEnt  points to the base entity if any
256  */
257 static ir_node *find_base_adr(ir_node *ptr, ir_entity **pEnt)
258 {
259         ir_entity *ent = NULL;
260         assert(mode_is_reference(get_irn_mode(ptr)));
261
262         for (;;) {
263                 if (is_Sel(ptr)) {
264                         ent = get_Sel_entity(ptr);
265                         ptr = get_Sel_ptr(ptr);
266                 }
267                 else if (is_Add(ptr)) {
268                         ir_node *left = get_Add_left(ptr);
269                         if (mode_is_reference(get_irn_mode(left)))
270                                 ptr = left;
271                         else
272                                 ptr = get_Add_right(ptr);
273                         ent = NULL;
274                 } else if (is_Sub(ptr)) {
275                         ptr = get_Sub_left(ptr);
276                         ent = NULL;
277                 } else {
278                         *pEnt = ent;
279                         return ptr;
280                 }
281         }
282 }
283
284 /**
285  * Check if a given pointer represents non-local memory.
286  */
287 static void check_ptr(ir_node *ptr, wlk_env *env)
288 {
289         ir_storage_class_class_t sc;
290         ir_entity                *ent;
291
292         /* still alias free */
293         ptr = find_base_adr(ptr, &ent);
294         sc  = get_base_sc(classify_pointer(ptr, ent));
295         if (sc != ir_sc_localvar && sc != ir_sc_malloced) {
296                 /* non-local memory access */
297                 env->only_local_mem = false;
298         }
299 }
300
301 /*
302  * Returns non-zero if a Call is surely a self-recursive Call.
303  * Beware: if this functions returns 0, the call might be self-recursive!
304  */
305 static bool is_self_recursive_Call(const ir_node *call)
306 {
307         const ir_node *callee = get_Call_ptr(call);
308
309         if (is_SymConst_addr_ent(callee)) {
310                 const ir_entity *ent = get_SymConst_entity(callee);
311                 const ir_graph  *irg = get_entity_irg(ent);
312                 if (irg == get_irn_irg(call))
313                         return true;
314         }
315         return false;
316 }
317
318 /**
319  * Post walker: shift all parameter indexes
320  * and collect Calls with compound returns in the call list.
321  * If a non-alias free memory access is found, reset the alias free
322  * flag.
323  */
324 static void fix_args_and_collect_calls(ir_node *n, void *ctx)
325 {
326         wlk_env *env = (wlk_env*)ctx;
327         ir_node *ptr;
328
329         switch (get_irn_opcode(n)) {
330         case iro_Load:
331         case iro_Store:
332                 if (env->only_local_mem) {
333                         ptr = get_irn_n(n, 1);
334                         check_ptr(ptr, env);
335                 }
336                 break;
337         case iro_Proj:
338                 if (env->arg_shift > 0) {
339                         ir_node *pred = get_Proj_pred(n);
340                         ir_graph *irg = get_irn_irg(n);
341
342                         /* Fix the argument numbers */
343                         if (pred == get_irg_args(irg)) {
344                                 long pnr = get_Proj_proj(n);
345                                 set_Proj_proj(n, pnr + env->arg_shift);
346                                 env->changed = true;
347                         }
348                 }
349                 break;
350         case iro_Call: {
351                 ir_type *ctp      = get_Call_type(n);
352                 size_t   n_ress   = get_method_n_ress(ctp);
353                 size_t   n_params = get_method_n_params(ctp);
354                 size_t   i;
355                 if (! is_self_recursive_Call(n)) {
356                         /* any non self recursive call might access global memory */
357                         env->only_local_mem = false;
358                 }
359
360                 /* check for compound returns */
361                 for (i = 0; i < n_ress; ++i) {
362                         ir_type *type = get_method_res_type(ctp, i);
363                         if (needs_lowering(type)) {
364                                 /*
365                                  * This is a call with a compound return. As the result
366                                  * might be ignored, we must put it in the list.
367                                  */
368                                 cl_entry *entry = get_call_entry(n, env);
369                                 entry->has_compound_ret = true;
370                                 break;
371                         }
372                 }
373                 for (i = 0; i < n_params; ++i) {
374                         ir_type *type = get_method_param_type(ctp, i);
375                         if (needs_lowering(type)) {
376                                 cl_entry *entry = get_call_entry(n, env);
377                                 entry->has_compound_param = true;
378                                 break;
379                         }
380                 }
381                 break;
382         }
383         case iro_CopyB: {
384                 ir_node *src = get_CopyB_src(n);
385                 if (env->only_local_mem) {
386                         check_ptr(get_CopyB_src(n), env);
387                         if (env->only_local_mem)
388                                 check_ptr(get_CopyB_dst(n), env);
389                 }
390                 /* check for compound returns */
391                 if (is_Proj(src)) {
392                         ir_node *proj = get_Proj_pred(src);
393                         if (is_Proj(proj) && get_Proj_proj(proj) == pn_Call_T_result) {
394                                 ir_node *call = get_Proj_pred(proj);
395                                 if (is_Call(call)) {
396                                         ir_type *ctp = get_Call_type(call);
397                                         if (needs_lowering(get_method_res_type(ctp, get_Proj_proj(src)))) {
398                                                 /* found a CopyB from compound Call result */
399                                                 cl_entry *e = get_call_entry(call, env);
400                                                 set_irn_link(n, e->copyb);
401                                                 e->copyb = n;
402                                         }
403                                 }
404                         }
405                 }
406                 break;
407         }
408         case iro_Sel: {
409                 ir_entity *entity = get_Sel_entity(n);
410                 ir_type   *type   = get_entity_type(entity);
411
412                 if (is_parameter_entity(entity) && needs_lowering(type)) {
413                         if (! (env->flags & LF_DONT_LOWER_ARGUMENTS)) {
414                                 /* note that num was already modified by fix_parameter_entities
415                                  * so no need to add env->arg_shift again */
416                                 size_t num = get_entity_parameter_number(entity);
417                                 ir_graph *irg  = get_irn_irg(n);
418                                 ir_node  *args = get_irg_args(irg);
419                                 ir_node  *ptr  = new_r_Proj(args, mode_P, num);
420                                 exchange(n, ptr);
421                                 /* hack to avoid us visiting the proj again */
422                                 mark_irn_visited(ptr);
423                         }
424
425                         /* we need to copy compound parameters */
426                         env->only_local_mem = false;
427                 }
428                 break;
429         }
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 bool is_compound_address(ir_type *ft, ir_node *adr)
444 {
445         ir_entity *ent;
446
447         if (! is_Sel(adr))
448                 return false;
449         if (get_Sel_n_indexs(adr) != 0)
450                 return false;
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 (i.e. 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 {
471         if (is_Sel(n)) {
472                 ir_entity *ent = get_Sel_entity(n);
473                 cr_pair   *arr = (cr_pair*)ctx;
474                 size_t    i, l;
475
476                 for (i = 0, l = ARR_LEN(arr); i < l; ++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  *
488  * @param irg    the graph
489  * @param block  the block where a newly create Sel should be placed
490  * @param tp     the type of the dummy entity that should be create
491  */
492 static ir_node *get_dummy_sel(ir_graph *irg, ir_node *block, ir_type *tp)
493 {
494         ir_type   *ft       = get_irg_frame_type(irg);
495         ident     *dummy_id = id_unique("dummy.%u");
496         ir_entity *ent      = new_entity(ft, dummy_id, tp);
497
498         if (get_type_state(ft) == layout_fixed) {
499                 /* Fix the layout again */
500                 panic("Fixed layout not implemented");
501         }
502
503         return new_r_simpleSel(block, get_irg_no_mem(irg), get_irg_frame(irg), ent);
504 }
505
506 /**
507  * Add the hidden parameter from the CopyB node to the Call node.
508  */
509 static void add_hidden_param(ir_graph *irg, size_t n_com, ir_node **ins,
510                              cl_entry *entry, ir_type *ctp)
511 {
512         ir_node *p, *n;
513         size_t n_args;
514
515         n_args = 0;
516         for (p = entry->copyb; p; p = n) {
517                 ir_node *src = get_CopyB_src(p);
518                 size_t   idx = get_Proj_proj(src);
519                 n = (ir_node*)get_irn_link(p);
520
521                 /* consider only the first CopyB */
522                 if (ins[idx] == NULL) {
523                         ir_node *block = get_nodes_block(p);
524
525                         /* use the memory output of the call and not the input of the CopyB
526                          * otherwise stuff breaks if the call was mtp_property_const, because
527                          * then the copyb skips the call. But after lowering the call is not
528                          * const anymore, and its memory has to be used */
529                         ir_node *mem = new_r_Proj(entry->call, mode_M, pn_Call_M);
530
531                         ins[idx] = get_CopyB_dst(p);
532
533                         /* get rid of the CopyB */
534                         if (ir_throws_exception(p)) {
535                                 ir_node *const in[] = {
536                                         [pn_CopyB_M]         = mem,
537                                         [pn_CopyB_X_regular] = new_r_Jmp(block),
538                                         [pn_CopyB_X_except]  = new_r_Bad(irg, mode_X),
539                                 };
540                                 turn_into_tuple(p, ARRAY_SIZE(in), in);
541                         } else {
542                                 ir_node *const in[] = { mem };
543                                 turn_into_tuple(p, ARRAY_SIZE(in), in);
544                         }
545                         ++n_args;
546                 }
547         }
548
549         /* now create dummy entities for function with ignored return value */
550         if (n_args < n_com) {
551                 size_t i;
552                 size_t j;
553
554                 for (j = i = 0; i < get_method_n_ress(ctp); ++i) {
555                         ir_type *rtp = get_method_res_type(ctp, i);
556                         if (needs_lowering(rtp)) {
557                                 if (ins[j] == NULL)
558                                         ins[j] = get_dummy_sel(irg, get_nodes_block(entry->call), rtp);
559                                 ++j;
560                         }
561                 }
562         }
563 }
564
565 static void fix_compound_ret(cl_entry *entry, ir_type *ctp)
566 {
567         ir_node  *call     = entry->call;
568         ir_graph *irg      = get_irn_irg(call);
569         size_t    n_params = get_Call_n_params(call);
570         size_t    n_com    = 0;
571         size_t    n_res    = get_method_n_ress(ctp);
572         size_t    pos      = 0;
573         ir_node **new_in;
574         size_t    i;
575
576         for (i = 0; i < n_res; ++i) {
577                 ir_type *type = get_method_res_type(ctp, i);
578                 if (needs_lowering(type))
579                         ++n_com;
580         }
581
582         new_in = ALLOCANZ(ir_node*, n_params + n_com + (n_Call_max+1));
583         new_in[pos++] = get_Call_mem(call);
584         new_in[pos++] = get_Call_ptr(call);
585         assert(pos == n_Call_max+1);
586         add_hidden_param(irg, n_com, &new_in[pos], entry, ctp);
587         pos += n_com;
588
589         /* copy all other parameters */
590         for (i = 0; i < n_params; ++i) {
591                 ir_node *param = get_Call_param(call, i);
592                 new_in[pos++] = param;
593         }
594         assert(pos == n_params+n_com+(n_Call_max+1));
595         set_irn_in(call, pos, new_in);
596 }
597
598 static ir_entity *create_compound_arg_entity(ir_graph *irg, ir_type *type)
599 {
600         ir_type   *frame  = get_irg_frame_type(irg);
601         ident     *id     = id_unique("$compound_param.%u");
602         ir_entity *entity = new_entity(frame, id, type);
603         /* TODO:
604          * we could do some optimisations here and create a big union type for all
605          * different call types in a function */
606         return entity;
607 }
608
609 static void fix_compound_params(cl_entry *entry, ir_type *ctp)
610 {
611         ir_node  *call     = entry->call;
612         dbg_info *dbgi     = get_irn_dbg_info(call);
613         ir_node  *mem      = get_Call_mem(call);
614         ir_graph *irg      = get_irn_irg(call);
615         ir_node  *nomem    = new_r_NoMem(irg);
616         ir_node  *frame    = get_irg_frame(irg);
617         size_t    n_params = get_method_n_params(ctp);
618         size_t    i;
619
620         for (i = 0; i < n_params; ++i) {
621                 ir_type   *type = get_method_param_type(ctp, i);
622                 ir_node   *block;
623                 ir_node   *arg;
624                 ir_node   *sel;
625                 ir_node   *copyb;
626                 ir_entity *arg_entity;
627                 if (!needs_lowering(type))
628                         continue;
629
630                 arg        = get_Call_param(call, i);
631                 arg_entity = create_compound_arg_entity(irg, type);
632                 block      = get_nodes_block(call);
633                 sel        = new_rd_simpleSel(dbgi, block, nomem, frame, arg_entity);
634                 copyb      = new_rd_CopyB(dbgi, block, mem, sel, arg, type);
635                 mem        = new_r_Proj(copyb, mode_M, pn_CopyB_M);
636                 set_Call_param(call, i, sel);
637         }
638         set_Call_mem(call, mem);
639 }
640
641 static void fix_calls(wlk_env *env)
642 {
643         cl_entry *entry;
644         for (entry = env->cl_list; entry; entry = entry->next) {
645                 ir_node *call        = entry->call;
646                 ir_type *ctp         = get_Call_type(call);
647                 ir_type *lowered_mtp = lower_mtp(env->flags, ctp);
648                 set_Call_type(call, lowered_mtp);
649
650                 if (entry->has_compound_param) {
651                         fix_compound_params(entry, ctp);
652                 }
653                 if (entry->has_compound_ret) {
654                         fix_compound_ret(entry, ctp);
655                 }
656         }
657 }
658
659 /**
660  * Transform a graph. If it has compound parameter returns,
661  * remove them and use the hidden parameter instead.
662  * If it calls methods with compound parameter returns, add hidden
663  * parameters.
664  *
665  * @param irg  the graph to transform
666  */
667 static void transform_irg(compound_call_lowering_flags flags, ir_graph *irg)
668 {
669         ir_entity *ent         = get_irg_entity(irg);
670         ir_type   *mtp         = get_entity_type(ent);
671         size_t     n_ress      = get_method_n_ress(mtp);
672         size_t     n_params    = get_method_n_params(mtp);
673         size_t     n_param_com = 0;
674
675         ir_type   *lowered_mtp, *tp, *ft;
676         size_t    i, j, k;
677         size_t    n_cr_opt;
678         ir_node   **new_in, *ret, *endbl, *bl, *mem, *copy;
679         cr_pair   *cr_opt;
680         wlk_env   env;
681
682         /* calculate the number of compound returns */
683         size_t n_ret_com = 0;
684         for (i = 0; i < n_ress; ++i) {
685                 ir_type *type = get_method_res_type(mtp, i);
686                 if (needs_lowering(type))
687                         ++n_ret_com;
688         }
689         for (i = 0; i < n_params; ++i) {
690                 ir_type *type = get_method_param_type(mtp, i);
691                 if (needs_lowering(type))
692                         ++n_param_com;
693         }
694
695         if (n_ret_com > 0)
696                 fix_parameter_entities(irg, n_ret_com);
697
698         if (n_ret_com) {
699                 /* much easier if we have only one return */
700                 normalize_one_return(irg);
701
702                 /* This graph has a compound argument. Create a new type */
703                 lowered_mtp = lower_mtp(flags, mtp);
704                 set_entity_type(ent, lowered_mtp);
705
706                 /* hidden arguments are added first */
707                 env.arg_shift = n_ret_com;
708         } else {
709                 /* we must only search for calls */
710                 env.arg_shift = 0;
711                 lowered_mtp   = NULL;
712         }
713         obstack_init(&env.obst);
714         env.cl_list        = NULL;
715         env.flags          = flags;
716         env.lowered_mtp    = lowered_mtp;
717         env.only_local_mem = true;
718         env.changed        = false;
719
720         /* scan the code, fix argument numbers and collect calls. */
721         irg_walk_graph(irg, firm_clear_link, NULL, &env);
722         irg_walk_graph(irg, fix_args_and_collect_calls, NULL, &env);
723
724         if (n_param_com > 0 && !(flags & LF_DONT_LOWER_ARGUMENTS))
725                 remove_compound_param_entities(irg);
726
727         /* fix all calls */
728         if (env.cl_list != NULL) {
729                 fix_calls(&env);
730                 env.changed = true;
731         }
732
733         if (n_ret_com) {
734                 int idx;
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
748                 /* in case of infinite loops, there might be no return */
749                 if (ret != NULL) {
750                         /*
751                          * Now fix the Return node of the current graph.
752                          */
753                         env.changed = true;
754
755                         /*
756                          * STEP 2: fix it. For all compound return values add a CopyB,
757                          * all others are copied.
758                          */
759                         NEW_ARR_A(ir_node *, new_in, n_ress + 1);
760
761                         bl  = get_nodes_block(ret);
762                         mem = get_Return_mem(ret);
763
764                         ft = get_irg_frame_type(irg);
765                         NEW_ARR_A(cr_pair, cr_opt, n_ret_com);
766                         n_cr_opt = 0;
767                         for (j = 1, i = k = 0; i < n_ress; ++i) {
768                                 ir_node *pred = get_Return_res(ret, i);
769                                 tp = get_method_res_type(mtp, i);
770
771                                 if (needs_lowering(tp)) {
772                                         ir_node *arg = get_irg_args(irg);
773                                         arg = new_r_Proj(arg, mode_P_data, k);
774                                         ++k;
775
776                                         if (is_Unknown(pred)) {
777                                                 /* The Return(Unknown) is the Firm construct for a
778                                                  * missing return. Do nothing. */
779                                         } else {
780                                                 /**
781                                                  * Sorrily detecting that copy-return is possible isn't
782                                                  * that simple. We must check, that the hidden address
783                                                  * is alias free during the whole function.
784                                                  * A simple heuristic: all Loads/Stores inside
785                                                  * the function access only local frame.
786                                                  */
787                                                 if (env.only_local_mem && is_compound_address(ft, pred)) {
788                                                         /* we can do the copy-return optimization here */
789                                                         cr_opt[n_cr_opt].ent = get_Sel_entity(pred);
790                                                         cr_opt[n_cr_opt].arg = arg;
791                                                         ++n_cr_opt;
792                                                 } else { /* copy-return optimization is impossible, do the copy. */
793                                                         copy = new_r_CopyB(
794                                                                         bl,
795                                                                         mem,
796                                                                         arg,
797                                                                         pred,
798                                                                         tp
799                                                                         );
800                                                         mem = new_r_Proj(copy, mode_M, pn_CopyB_M);
801                                                 }
802                                         }
803                                         if (flags & LF_RETURN_HIDDEN) {
804                                                 new_in[j] = arg;
805                                                 ++j;
806                                         }
807                                 } else { /* scalar return value */
808                                         new_in[j] = pred;
809                                         ++j;
810                                 }
811                         }
812                         /* replace the in of the Return */
813                         new_in[0] = mem;
814                         set_irn_in(ret, j, new_in);
815
816                         if (n_cr_opt > 0) {
817                                 size_t c;
818                                 size_t n;
819
820                                 irg_walk_graph(irg, NULL, do_copy_return_opt, cr_opt);
821
822                                 for (c = 0, n = ARR_LEN(cr_opt); c < n; ++c) {
823                                         free_entity(cr_opt[c].ent);
824                                 }
825                         }
826                 }
827         }
828
829         obstack_free(&env.obst, NULL);
830 }
831
832 static void lower_method_types(type_or_ent tore, void *env)
833 {
834         const compound_call_lowering_flags *flags
835                 = (const compound_call_lowering_flags*)env;
836
837         /* fix method entities */
838         if (is_entity(tore.ent)) {
839                 ir_entity *ent     = tore.ent;
840                 ir_type   *tp      = get_entity_type(ent);
841                 ir_type   *lowered = lower_mtp(*flags, tp);
842                 set_entity_type(ent, lowered);
843         } else {
844                 ir_type *tp = tore.typ;
845
846                 /* fix pointer to methods */
847                 if (is_Pointer_type(tp)) {
848                         ir_type *points_to         = get_pointer_points_to_type(tp);
849                         ir_type *lowered_points_to = lower_mtp(*flags, points_to);
850                         set_pointer_points_to_type(tp, lowered_points_to);
851                 }
852         }
853 }
854
855 void lower_calls_with_compounds(compound_call_lowering_flags flags)
856 {
857         size_t i, n;
858
859         pointer_types = pmap_create();
860         lowered_mtps = pmap_create();
861
862         /* first step: Transform all graphs */
863         for (i = 0, n = get_irp_n_irgs(); i < n; ++i) {
864                 ir_graph *irg = get_irp_irg(i);
865                 transform_irg(flags, irg);
866         }
867
868         /* second step: Lower all method types of visible entities */
869         type_walk(NULL, lower_method_types, &flags);
870
871         pmap_destroy(lowered_mtps);
872         pmap_destroy(pointer_types);
873 }