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