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