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