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