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