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