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