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