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