moved opt_calling_conventions() to mark_private_methods() in ir_memory.c
[libfirm] / ir / opt / proc_cloning.c
1 /*
2  * Copyright (C) 1995-2007 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   Procedure cloning.
23  * @author  Beyhan Veliev, Michael Beck
24  * @version $Id$
25  * @summary
26  *
27  * The purpose is first to find and analyze functions, that are called
28  * with constant parameter(s).
29  * The second step is to optimize the function that are found from our
30  * analyze. Optimize mean to make a new function with parameters, that
31  * aren't be constant. The constant parameters of the function are placed
32  * in the function graph. They aren't be passed as parameters.
33  */
34 #ifdef HAVE_CONFIG_H
35 #include "config.h"
36 #endif
37
38 #include <string.h>
39
40 #include "iroptimize.h"
41 #include "tv.h"
42 #include "set.h"
43 #include "irprog_t.h"
44 #include "hashptr.h"
45 #include "irgwalk.h"
46 #include "analyze_irg_args.h"
47 #include "irprintf.h"
48 #include "ircons.h"
49 #include "irouts.h"
50 #include "irnode_t.h"
51 #include "irtools.h"
52 #include "irgmod.h"
53 #include "array.h"
54 #include "xmalloc.h"
55
56 /* A macro to iterate sets.*/
57 #define ITERATE_SET(set_entries, entry) for(entry = set_first(set_entries); entry; entry = set_next(set_entries))
58
59 /**
60  * This struct contains the information quadruple for a Call, which we need to
61  * decide if this function must be cloned.
62  */
63 typedef struct quadruple {
64         ir_entity       *ent;     /**< The entity of our Call. */
65         int             pos;      /**< Position of a constant argument of our Call. */
66         tarval          *tv;      /**< The tarval of this argument if Const node. */
67         ir_node         **calls;  /**< The list of all calls with the same characteristics */
68 } quadruple_t;
69
70 /**
71  * The quadruplets are hold in a sorted list
72  */
73 typedef struct entry {
74         quadruple_t  q;      /**< the quadruple */
75         float        weight; /**< its weight */
76         struct entry *next;  /**< link to the next one */
77 } entry_t;
78
79 typedef struct q_set {
80         struct obstack obst;        /**< an obstack containing all entries */
81         pset           *map;        /**< a hash map containing the quadruples */
82         entry_t        *heavy_uses; /**< the ordered list of heavy uses */
83 } q_set;
84
85 /**
86  * Compare two quadruplets.
87  *
88  * @return zero if they are identically, non-zero else
89  */
90 static int entry_cmp(const void *elt, const void *key) {
91         const entry_t *e1 = elt;
92         const entry_t *e2 = key;
93
94         return (e1->q.ent != e2->q.ent) || (e1->q.pos != e2->q.pos) || (e1->q.tv != e2->q.tv);
95 }
96
97 /**
98  * Hash an element of type entry_t.
99  *
100  * @param entry  The element to be hashed.
101  */
102 static int hash_entry(const entry_t *entry) {
103         return HASH_PTR(entry->q.ent) ^ HASH_PTR(entry->q.tv) ^ (entry->q.pos * 9);
104 }
105
106 /**
107  * Free memory associated with a quadruplet.
108  */
109 static void kill_entry(entry_t *entry) {
110         if (entry->q.calls) {
111                 DEL_ARR_F(entry->q.calls);
112                 entry->q.calls = NULL;
113         }
114 }
115
116 /**
117  * Process a call node.
118  *
119  * @param call    A ir_node to be checked.
120  * @param callee  The entity of the callee
121  * @param hmap    The quadruple-set containing the calls with constant parameters
122  */
123 static void process_call(ir_node *call, ir_entity *callee, q_set *hmap) {
124         ir_type *mtp;
125         entry_t *key, *entry;
126         ir_node *call_param;
127         int i, n_params;
128
129         n_params = get_Call_n_params(call);
130
131         /* Beware: we cannot clone variadic parameters as well as the
132          * last non-variadic one, which might be needed for the va_start()
133          * magic
134          */
135         mtp = get_Call_type(call);
136         if (get_method_variadicity(mtp) != variadicity_non_variadic) {
137                 n_params = get_method_first_variadic_param_index(mtp) - 1;
138         }
139
140         /* In this for loop we collect the calls, that have
141            an constant parameter. */
142         for (i = n_params - 1; i >= 0; --i) {
143                 call_param = get_Call_param(call, i);
144                 if (is_Const(call_param)) {
145                         /* we have found a Call to collect and we save the informations,
146                            which we need.*/
147                         if (! hmap->map)
148                                 hmap->map = new_pset(entry_cmp, 8);
149
150                         key = obstack_alloc(&hmap->obst, sizeof(*key));
151
152                         key->q.ent   = callee;
153                         key->q.pos   = i;
154                         key->q.tv    = get_Const_tarval(call_param);
155                         key->q.calls = NULL;
156                         key->weight  = 0.0F;
157                         key->next    = NULL;
158
159                         /* We insert our information in the set, where we collect the calls.*/
160                         entry = pset_insert(hmap->map, key, hash_entry(key));
161
162                         if (entry != key)
163                                 obstack_free(&hmap->obst, key);
164
165                         /* add the call to the list */
166                         if (! entry->q.calls) {
167                                 entry->q.calls = NEW_ARR_F(ir_node *, 1);
168                                 entry->q.calls[0] = call;
169                         } else
170                                 ARR_APP1(ir_node *, entry->q.calls, call);
171                 }
172         }
173 }
174
175 /**
176  * Collect all calls in a ir_graph to a set.
177  *
178  * @param call   A ir_node to be checked.
179  * @param env   The quadruple-set containing the calls with constant parameters
180  */
181 static void collect_irg_calls(ir_node *call, void *env) {
182         q_set *hmap = env;
183         ir_node *call_ptr;
184         ir_entity *callee;
185
186         /* We collect just "Call" nodes */
187         if (is_Call(call)) {
188                 call_ptr = get_Call_ptr(call);
189
190                 /* Call pointer must be a SymConst*/
191                 if (op_SymConst != get_irn_op(call_ptr))
192                         return;
193                 /* Call pointer must be the address of an entity.*/
194                 if (get_SymConst_kind(call_ptr) != symconst_addr_ent)
195                         return;
196
197                 callee = get_SymConst_entity(call_ptr);
198
199                 /* we can only clone calls to existing entities */
200                 if (get_entity_visibility(callee) == visibility_external_allocated)
201                         return;
202
203                 process_call(call, callee, hmap);
204         }
205 }
206
207 /**
208  * Make a name for a clone. The clone name is
209  * the name of the original method suffixed with "_cl_pos_nr".
210  * pos is the pos from our quadruplet and nr is a counter.
211  *
212  * @param id  The ident of the cloned function.
213  * @param pos The "pos" from our quadruplet.
214  * @param nr  A counter for the clones.
215  */
216 static ident *get_clone_ident(ident *id, int pos, unsigned nr) {
217         char clone_postfix[32];
218
219         snprintf(clone_postfix, sizeof(clone_postfix), "_cl_%d_%u", pos, nr);
220
221         return mangle(id, new_id_from_str(clone_postfix));
222 }
223
224 /**
225  * Pre-Walker: Copies blocks and nodes from the original method graph
226  * to the cloned graph. Fixes the argument projection numbers for
227  * all arguments behind the removed one.
228  *
229  * @param irn  A node from the original method graph.
230  * @param env  The clone graph.
231  */
232 static void copy_nodes(ir_node *irn, void *env) {
233         ir_node *arg, *irg_args, *irn_copy;
234         int proj_nr;
235         ir_graph *clone_irg = env;
236
237         arg      = get_irg_link(clone_irg);
238         irg_args = get_Proj_pred(arg);
239
240         /* Copy all nodes except the arg. */
241         if (irn != arg)
242                 copy_irn_to_irg(irn, clone_irg);
243
244         irn_copy = get_irn_link(irn);
245
246         /* Fix argument numbers */
247         if (is_Proj(irn) && get_Proj_pred(irn) == irg_args) {
248                 proj_nr = get_Proj_proj(irn);
249                 if (get_Proj_proj(arg) < proj_nr)
250                         set_Proj_proj(irn_copy, proj_nr - 1);
251         }
252 }
253
254 /**
255  * Post-walker: Set the predecessors of the copied nodes.
256  * The copied nodes are set as link of their original nodes. The links of
257  * "irn" predecessors are the predecessors of copied node.
258  */
259 static void set_preds(ir_node *irn, void *env) {
260         int i;
261         ir_node *irn_copy, *pred, *arg;
262         ir_graph *clone_irg = env;
263
264         arg = get_irg_link(clone_irg);
265         /* Arg is the method argument, that we have replaced by a constant.*/
266         if (arg == irn)
267                 return;
268
269         irn_copy  = get_irn_link(irn);
270
271         if (is_Block(irn)) {
272                 for (i = get_Block_n_cfgpreds(irn) - 1; i >= 0; i--) {
273                         pred = get_Block_cfgpred(irn, i);
274                         /* "End" block must be handled extra, because it is not matured.*/
275                         if (get_irg_end_block(current_ir_graph) == irn)
276                                 add_immBlock_pred(get_irg_end_block(clone_irg), get_irn_link(pred));
277                         else
278                                 set_Block_cfgpred(irn_copy, i, get_irn_link(pred));
279                 }
280         } else {
281                 /* First we set the block our copy if it is not a block.*/
282                 set_nodes_block(irn_copy, get_irn_link(get_nodes_block(irn)));
283                 if (get_irn_op(irn) == op_End) {
284                         /* Handle the keep-alives. This must be done separately, because
285                            the End node was NOT copied */
286                         for (i = 0; i < get_End_n_keepalives(irn); ++i)
287                                 add_End_keepalive(irn_copy, get_irn_link(get_End_keepalive(irn, i)));
288                 } else {
289                         for (i = get_irn_arity(irn) - 1; i >= 0; i--) {
290                                 pred = get_irn_n(irn, i);
291                                 set_irn_n(irn_copy, i, get_irn_link(pred));
292                         }
293                 }
294         }
295 }
296
297 /**
298  * Get the method argument at the position "pos".
299  *
300  * @param irg  irg that must be cloned.
301  * @param pos  The position of the argument.
302  */
303 static ir_node *get_irg_arg(ir_graph *irg, int pos) {
304         ir_node *irg_args = get_irg_args(irg), *arg = NULL;
305         int i;
306
307         /* Call algorithm that computes the out edges */
308         assure_irg_outs(irg);
309
310         /* Search the argument with the number pos.*/
311         for (i = get_irn_n_outs(irg_args) - 1; i >= 0; --i) {
312                 ir_node *proj = get_irn_out(irg_args, i);
313                 if (pos == get_Proj_proj(proj)) {
314                         if (arg) {
315                                 /*
316                                  * More than one arg node found:
317                                  * We rely on the fact the only one arg exists, so do
318                                  * a cheap CSE in this case.
319                                  */
320                                 set_irn_out(irg_args, i, arg);
321                                 exchange(proj, arg);
322                         } else
323                                 arg = proj;
324                 }
325         }
326         assert(arg && "Argument not found");
327         return arg;
328 }
329
330 /**
331  * Create a new graph for the clone of the method,
332  * that we want to clone.
333  *
334  * @param ent The entity of the method that must be cloned.
335  * @param q   Our quadruplet.
336  */
337 static void create_clone_proc_irg(ir_entity *ent, quadruple_t *q) {
338         ir_graph *method_irg, *clone_irg;
339         ir_node *arg, *const_arg;
340
341         method_irg = get_entity_irg(ent);
342
343         /* We create the skeleton of the clone irg.*/
344         clone_irg  = new_ir_graph(ent, 0);
345
346         arg        = get_irg_arg(get_entity_irg(q->ent), q->pos);
347         /* we will replace the argument in position "q->pos" by this constant. */
348         const_arg  = new_r_Const_type(
349                 clone_irg, get_nodes_block(arg), get_irn_mode(arg), q->tv,
350                 get_method_param_type(get_entity_type(q->ent), q->pos));
351
352         /* args copy in the cloned graph will be the const. */
353         set_irn_link(arg, const_arg);
354
355         /* Store the arg that will be replaced here, so we can easily detect it. */
356         set_irg_link(clone_irg, arg);
357
358         /* We copy the blocks and nodes, that must be in
359         the clone graph and set their predecessors. */
360         irg_walk_graph(method_irg, copy_nodes, set_preds, clone_irg);
361
362         /* The "cloned" graph must be matured. */
363         mature_immBlock(get_irg_end_block(clone_irg));
364         irg_finalize_cons(clone_irg);
365 }
366
367 /**
368  * The function create a new entity type
369  * for our clone and set it to clone entity.
370  *
371  * @param q   Contains information for the method to clone.
372  * @param ent The entity of the clone.
373  * @param nr  A pointer to the counter of clones.
374  **/
375 static void change_entity_type(quadruple_t *q, ir_entity *ent, unsigned *nr) {
376         ir_type *mtp, *new_mtp, *tp;
377         ident   *tp_name;
378         int     i, j, n_params, n_ress;
379
380         mtp      = get_entity_type(q->ent);
381         tp_name  = get_clone_ident(get_type_ident(mtp), q->pos, (*nr)++);
382         n_params = get_method_n_params(mtp);
383         n_ress   = get_method_n_ress(mtp);
384
385         /* Create the new type for our clone. It must have one parameter
386            less then the original.*/
387         new_mtp  = new_type_method(tp_name, n_params - 1, n_ress);
388
389         /* We must set the type of the methods parameters.*/
390         for (i = j = 0; i < n_params; ++i) {
391                 if (i == q->pos)
392                 /* This is the position of the argument, that we have
393                 replaced. */
394                 continue;
395
396                 tp = get_method_param_type(mtp, i);
397                 set_method_param_type(new_mtp, j++, tp);
398         }
399         /* Copy the methods result types. */
400         for (i = 0; i < n_ress; ++i) {
401                 tp = get_method_res_type(mtp, i);
402                 set_method_res_type(new_mtp, i, tp);
403         }
404         set_entity_type(ent, new_mtp);
405 }
406
407 /**
408  * Make a clone of a method.
409  *
410  * @param q   Contains information for the method to clone.
411  */
412 static ir_entity *clone_method(quadruple_t *q) {
413         ir_entity *new_entity;
414         ident *clone_ident;
415         ir_graph *rem;
416         symconst_symbol sym;
417         /* A counter for the clones.*/
418         static unsigned nr = 0;
419
420         /* We get a new ident for our clone method.*/
421         clone_ident = get_clone_ident(get_entity_ident(q->ent), q->pos, nr);
422         /* We get our entity for the clone method. */
423         new_entity  = copy_entity_name(q->ent, clone_ident);
424
425         /* a cloned entity is always local */
426         set_entity_visibility(new_entity, visibility_local);
427
428         /* set a ld name here: Should we mangle this ? */
429         set_entity_ld_ident(new_entity, get_entity_ident(new_entity));
430
431         /* set a new type here. */
432         change_entity_type(q, new_entity, &nr);
433
434         /* We need now a new ir_graph for our clone method. */
435         create_clone_proc_irg(new_entity, q);
436
437         /* We must set the atomic value of our "new_entity". */
438         sym.entity_p = new_entity;
439         rem = current_ir_graph;
440         current_ir_graph =  get_const_code_irg();
441         new_entity->value = new_SymConst(sym, symconst_addr_ent);
442         current_ir_graph = rem;
443
444         /* The "new_entity" don't have this information. */
445         new_entity->attr.mtd_attr.param_access = NULL;
446         new_entity->attr.mtd_attr.param_weight = NULL;
447
448         return new_entity;
449 }
450
451 /**
452  * Creates a new "cloned" Call node and return it.
453  *
454  * @param call        The call that must be cloned.
455  * @param new_entity  The entity of the cloned function.
456  * @param pos         The position of the replaced parameter of this call.
457  **/
458 static ir_node *new_cl_Call(ir_node *call, ir_entity *new_entity, int pos) {
459         ir_node **in;
460         ir_type *mtp;
461         int i, n_params, new_params = 0;
462         ir_node *callee;
463         symconst_symbol sym;
464         ir_graph *irg = get_irn_irg(call);
465         ir_node *bl = get_nodes_block(call);
466
467         sym.entity_p = new_entity;
468         callee = new_r_SymConst(irg, bl, sym, symconst_addr_ent);
469
470         mtp      = get_entity_type(new_entity);
471         n_params = get_Call_n_params(call);
472         NEW_ARR_A(ir_node *, in, n_params - 1);
473
474         /* we save the parameters of the new call in the array "in" without the
475          * parameter in position "pos", that is replaced with a constant.*/
476         for (i = 0; i < n_params; i++){
477                 if (pos != i)
478                         in[new_params++] = get_Call_param(call, i);
479         }
480         /* Create and return the new Call. */
481         return new_r_Call(irg, bl, get_Call_mem(call),
482                 callee, n_params - 1, in, get_entity_type(new_entity));
483 }
484
485 /**
486  * Exchange all Calls stored in the quadruplet to Calls of the cloned entity.
487  *
488  * @param q             The quadruple
489  * @param cloned_ent    The entity of the new function that must be called
490  *                      from the new Call.
491  */
492 static void exchange_calls(quadruple_t *q, ir_entity *cloned_ent) {
493         int pos = q->pos;
494         ir_node *new_call, *call;
495         int i;
496
497         /* We iterate the list of the "call".*/
498         for (i = 0; i < ARR_LEN(q->calls); ++i) {
499                 call = q->calls[i];
500
501                 /* A clone exist and the copy of "call" in this
502                  * clone graph must be exchanged with new one.*/
503                 new_call = new_cl_Call(call, cloned_ent, pos);
504                 exchange(call, new_call);
505         }
506 }
507
508 /**
509  * The weight formula:
510  * We save one instruction in every caller and param_weight instructions
511  * in the callee.
512  */
513 static float calculate_weight(const entry_t *entry) {
514         return ARR_LEN(entry->q.calls) *
515                 (get_method_param_weight(entry->q.ent, entry->q.pos) + 1);
516 }
517
518 /**
519  * After we exchanged all calls, some entries on the list for
520  * the next cloned entity may get invalid, so we have to check
521  * them and may even update the list of heavy uses.
522  */
523 static void reorder_weights(q_set *hmap, float threshold) {
524         entry_t **adr, *p, *entry;
525         int i, len;
526         ir_entity *callee;
527
528 restart:
529         entry = hmap->heavy_uses;
530         if (! entry)
531                 return;
532
533         len = ARR_LEN(entry->q.calls);
534         for (i = 0; i < len; ++i) {
535                 ir_node *ptr, *call = entry->q.calls[i];
536
537                 /* might be exchanged, so skip Id nodes here. */
538                 call = skip_Id(call);
539
540                 /* we know, that a SymConst is here */
541                 ptr = get_Call_ptr(call);
542                 assert(get_irn_op(ptr) == op_SymConst);
543
544                 callee = get_SymConst_entity(ptr);
545                 if (callee != entry->q.ent) {
546                         /*
547                          * This call is already changed because of a previous
548                          * optimization. Remove it from the list.
549                          */
550                         --len;
551                         entry->q.calls[i] = entry->q.calls[len];
552                         entry->q.calls[len] = NULL;
553
554                         /* the new call should be processed */
555                         process_call(call, callee, hmap);
556                         --i;
557                 }
558         }
559
560         /* the length might be changed */
561         ARR_SHRINKLEN(entry->q.calls, len);
562
563         /* recalculate the weight and resort the heavy uses map */
564         entry->weight = calculate_weight(entry);
565
566         if (len <= 0 || entry->weight < threshold) {
567                 hmap->heavy_uses = entry->next;
568                 kill_entry(entry);
569
570                 /* we have changed the list, check the next one */
571                 goto restart;
572         }
573
574         adr = NULL;
575         for (p = entry->next; p && entry->weight < p->weight; p = p->next) {
576                 adr = &p->next;
577         }
578
579         if (adr) {
580                 hmap->heavy_uses = entry->next;
581                 entry->next      = *adr;
582                 *adr             = entry;
583                 entry            = hmap->heavy_uses;
584
585                 /* we have changed the list, check the next one */
586                 goto restart;
587         }
588 }
589
590 /*
591  * Do the procedure cloning. Evaluate a heuristic weight for every
592  * call(..., Const, ...). If the weight is bigger than threshold,
593  * clone the entity and fix the calls.
594  */
595 void proc_cloning(float threshold) {
596         entry_t *entry = NULL, *p;
597         ir_graph *irg;
598         int i;
599         q_set hmap;
600
601         obstack_init(&hmap.obst);
602         hmap.map        = NULL;
603         hmap.heavy_uses = NULL;
604
605         /* initially fill our map by visiting all irgs */
606         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
607                 irg = get_irp_irg(i);
608                 irg_walk_graph(irg, collect_irg_calls, NULL, &hmap);
609         }
610
611         /* We have the "Call" nodes to optimize in set "set_entries". Our algorithm
612            replace one constant parameter and make a new "Call" node for all found "Calls". It exchange the
613            old one with the new one and the algorithm is called with the new "Call".
614          */
615         while (hmap.map || hmap.heavy_uses) {
616                 /* We iterate the set and arrange the element of the set in a list.
617                    The elements are arranged dependent of their value descending.*/
618                 if (hmap.map) {
619                         foreach_pset(hmap.map, entry) {
620                                 entry->weight = calculate_weight(entry);
621
622                                 /*
623                                  * Do not put entry with a weight < threshold in the list
624                                  */
625                                 if (entry->weight < threshold) {
626                                         kill_entry(entry);
627                                         continue;
628                                 }
629
630                                 /* put entry in the heavy uses list */
631                                 entry->next = NULL;
632                                 if (! hmap.heavy_uses)
633                                         hmap.heavy_uses = entry;
634                                 else {
635                                         if (entry->weight >= hmap.heavy_uses->weight) {
636                                                 entry->next     = hmap.heavy_uses;
637                                                 hmap.heavy_uses = entry;
638                                         } else {
639                                                 for (p = hmap.heavy_uses; p->next; p = p->next) {
640                                                         if (entry->weight >= p->next->weight) {
641                                                                 entry->next = p->next;
642                                                                 p->next     = entry;
643                                                                 break;
644                                                         }
645                                                 }
646                                                 if (! p->next)
647                                                         p->next = entry;
648                                         }
649                                 }
650                         }
651                         del_pset(hmap.map);
652                         hmap.map = NULL;
653                 }
654
655                 /* Print some information about the list. */
656                 printf("-----------------\n");
657                 for (entry = hmap.heavy_uses; entry; entry = entry->next) {
658                         printf("\nweight: is %f\n", entry->weight);
659                         ir_printf("Call for Method %E\n", entry->q.ent);
660                         printf("Position %i\n", entry->q.pos);
661                         ir_printf("Value %T\n", entry->q.tv);
662                 }
663
664                 entry = hmap.heavy_uses;
665                 if (entry) {
666                         ir_entity *ent = clone_method(&entry->q);
667
668                         hmap.heavy_uses = entry->next;
669
670                         /* We must exchange the copies of this call in all clones too.*/
671                         exchange_calls(&entry->q, ent);
672                         kill_entry(entry);
673
674                         /*
675                          * after we exchanged all calls, some entries on the list for
676                          * the next cloned entity may get invalid, so we have to check
677                          * them and may even update the list of heavy uses.
678                          */
679                         reorder_weights(&hmap, threshold);
680                 }
681         }
682         obstack_free(&hmap.obst, NULL);
683 }