5cfc8a96532de94c7b986fd0214670063db1e4ea
[libfirm] / ir / be / becopyopt.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       Copy minimization driver.
23  * @author      Daniel Grund
24  * @date        12.04.2005
25  *
26  * Main file for the optimization reducing the copies needed for:
27  * - Phi coalescing
28  * - Register-constrained nodes
29  * - Two-address code instructions
30  */
31 #include "config.h"
32
33 #include "debug.h"
34 #include "error.h"
35 #include "execfreq_t.h"
36 #include "irdump_t.h"
37 #include "iredges_t.h"
38 #include "irgraph.h"
39 #include "irgwalk.h"
40 #include "irloop_t.h"
41 #include "irnode.h"
42 #include "irprintf.h"
43 #include "irprog.h"
44 #include "irtools.h"
45 #include "pmap.h"
46 #include "raw_bitset.h"
47 #include "util.h"
48 #include "xmalloc.h"
49
50 #include "bearch.h"
51 #include "becopyopt_t.h"
52 #include "becopystat.h"
53 #include "bedump.h"
54 #include "beifg.h"
55 #include "beinsn_t.h"
56 #include "beintlive_t.h"
57 #include "beirg.h"
58 #include "belive_t.h"
59 #include "bemodule.h"
60 #include "benode.h"
61 #include "besched.h"
62 #include "statev_t.h"
63 #include "beutil.h"
64
65 #include "lc_opts.h"
66 #include "lc_opts_enum.h"
67
68 #define DUMP_BEFORE 1
69 #define DUMP_AFTER  2
70 #define DUMP_APPEL  4
71 #define DUMP_ALL    2 * DUMP_APPEL - 1
72
73 #define COST_FUNC_FREQ     1
74 #define COST_FUNC_LOOP     2
75 #define COST_FUNC_ALL_ONE  3
76
77 /**
78  * Flags for dumping the IFG.
79  */
80 enum {
81         CO_IFG_DUMP_COLORS = 1 << 0, /**< Dump the graph colored. */
82         CO_IFG_DUMP_LABELS = 1 << 1, /**< Dump node/edge labels. */
83         CO_IFG_DUMP_SHAPE  = 1 << 2, /**< Give constrained nodes special shapes. */
84         CO_IFG_DUMP_CONSTR = 1 << 3, /**< Dump the node constraints in the label. */
85 };
86
87 static int co_get_costs_loop_depth(const ir_node *root, int pos);
88 static int co_get_costs_exec_freq(const ir_node *root, int pos);
89 static int co_get_costs_all_one(const ir_node *root, int pos);
90
91 static unsigned   dump_flags  = 0;
92 static unsigned   style_flags = CO_IFG_DUMP_COLORS;
93 static int        do_stats    = 0;
94 static cost_fct_t cost_func   = co_get_costs_exec_freq;
95 static int        improve     = 1;
96
97 static const lc_opt_enum_mask_items_t dump_items[] = {
98         { "before",  DUMP_BEFORE },
99         { "after",   DUMP_AFTER  },
100         { "appel",   DUMP_APPEL  },
101         { "all",     DUMP_ALL    },
102         { NULL,      0 }
103 };
104
105 static const lc_opt_enum_mask_items_t style_items[] = {
106         { "color",   CO_IFG_DUMP_COLORS },
107         { "labels",  CO_IFG_DUMP_LABELS },
108         { "constr",  CO_IFG_DUMP_CONSTR },
109         { "shape",   CO_IFG_DUMP_SHAPE  },
110         { "full",    2 * CO_IFG_DUMP_SHAPE - 1 },
111         { NULL,      0 }
112 };
113
114 typedef int (*opt_funcptr)(void);
115 static const lc_opt_enum_func_ptr_items_t cost_func_items[] = {
116         { "freq",   (opt_funcptr) co_get_costs_exec_freq },
117         { "loop",   (opt_funcptr) co_get_costs_loop_depth },
118         { "one",    (opt_funcptr) co_get_costs_all_one },
119         { NULL,     NULL }
120 };
121
122 static lc_opt_enum_mask_var_t dump_var = {
123         &dump_flags, dump_items
124 };
125
126 static lc_opt_enum_mask_var_t style_var = {
127         &style_flags, style_items
128 };
129
130 static lc_opt_enum_func_ptr_var_t cost_func_var = {
131         (opt_funcptr*) &cost_func, cost_func_items
132 };
133
134 static const lc_opt_table_entry_t options[] = {
135         LC_OPT_ENT_ENUM_FUNC_PTR ("cost",    "select a cost function",                                  &cost_func_var),
136         LC_OPT_ENT_ENUM_MASK     ("dump",    "dump ifg before or after copy optimization",              &dump_var),
137         LC_OPT_ENT_ENUM_MASK     ("style",   "dump style for ifg dumping",                              &style_var),
138         LC_OPT_ENT_BOOL          ("stats",   "dump statistics after each optimization",                 &do_stats),
139         LC_OPT_ENT_BOOL          ("improve", "run heur1 before if algo can exploit start solutions",    &improve),
140         LC_OPT_LAST
141 };
142
143 static be_module_list_entry_t *copyopts = NULL;
144 static const co_algo_info *selected_copyopt = NULL;
145
146 void be_register_copyopt(const char *name, co_algo_info *copyopt)
147 {
148         if (selected_copyopt == NULL)
149                 selected_copyopt = copyopt;
150         be_add_module_to_list(&copyopts, name, copyopt);
151 }
152
153 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_copyopt)
154 void be_init_copyopt(void)
155 {
156         lc_opt_entry_t *be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
157         lc_opt_entry_t *ra_grp = lc_opt_get_grp(be_grp, "ra");
158         lc_opt_entry_t *chordal_grp = lc_opt_get_grp(ra_grp, "chordal");
159         lc_opt_entry_t *co_grp = lc_opt_get_grp(chordal_grp, "co");
160
161         lc_opt_add_table(co_grp, options);
162         be_add_module_list_opt(co_grp, "algo", "select copy optimization algo",
163                                        &copyopts, (void**) &selected_copyopt);
164 }
165
166 static int void_algo(copy_opt_t *co)
167 {
168         (void) co;
169         return 0;
170 }
171
172 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_copynone)
173 void be_init_copynone(void)
174 {
175         static co_algo_info copyheur = {
176                 void_algo, 0
177         };
178
179         be_register_copyopt("none", &copyheur);
180 }
181
182 #undef QUICK_AND_DIRTY_HACK
183
184 static int nodes_interfere(const be_chordal_env_t *env, const ir_node *a, const ir_node *b)
185 {
186         if (env->ifg)
187                 return be_ifg_connected(env->ifg, a, b);
188         else {
189                 be_lv_t *lv = be_get_irg_liveness(env->irg);
190                 return be_values_interfere(lv, a, b);
191         }
192 }
193
194
195 /******************************************************************************
196     _____                           _
197    / ____|                         | |
198   | |  __  ___ _ __   ___ _ __ __ _| |
199   | | |_ |/ _ \ '_ \ / _ \ '__/ _` | |
200   | |__| |  __/ | | |  __/ | | (_| | |
201    \_____|\___|_| |_|\___|_|  \__,_|_|
202
203  ******************************************************************************/
204
205 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
206
207
208 copy_opt_t *new_copy_opt(be_chordal_env_t *chordal_env, cost_fct_t get_costs)
209 {
210         const char *s1, *s2, *s3;
211         size_t len;
212         copy_opt_t *co;
213
214         FIRM_DBG_REGISTER(dbg, "ir.be.copyopt");
215
216         co = XMALLOCZ(copy_opt_t);
217         co->cenv      = chordal_env;
218         co->irg       = chordal_env->irg;
219         co->cls       = chordal_env->cls;
220         co->get_costs = get_costs;
221
222         s1 = get_irp_name();
223         s2 = get_entity_name(get_irg_entity(co->irg));
224         s3 = chordal_env->cls->name;
225         len = strlen(s1) + strlen(s2) + strlen(s3) + 5;
226         co->name = XMALLOCN(char, len);
227         snprintf(co->name, len, "%s__%s__%s", s1, s2, s3);
228
229         return co;
230 }
231
232 void free_copy_opt(copy_opt_t *co)
233 {
234         xfree(co->name);
235         free(co);
236 }
237
238 /**
239  * Checks if a node is optimizable, viz. has something to do with coalescing
240  * @param irn  The irn to check
241  */
242 static int co_is_optimizable_root(ir_node *irn)
243 {
244         const arch_register_req_t *req;
245
246         if (arch_irn_is_ignore(irn))
247                 return 0;
248
249         if (is_Reg_Phi(irn) || is_Perm_Proj(irn))
250                 return 1;
251
252         req = arch_get_irn_register_req(irn);
253         if (arch_register_req_is(req, should_be_same))
254                 return 1;
255
256         return 0;
257 }
258
259 /**
260  * Computes the costs of a copy according to loop depth
261  * @param pos  the argument position of arg in the root arguments
262  * @return     Must be >= 0 in all cases.
263  */
264 static int co_get_costs_loop_depth(const ir_node *root, int pos)
265 {
266         ir_node *block = get_nodes_block(root);
267         ir_loop *loop;
268         int      cost;
269
270         if (is_Phi(root)) {
271                 block = get_Block_cfgpred_block(block, pos);
272         }
273         loop = get_irn_loop(block);
274         if (loop) {
275                 int d = get_loop_depth(loop);
276                 cost = d*d;
277         } else {
278                 cost = 0;
279         }
280         return 1+cost;
281 }
282
283 static ir_execfreq_int_factors factors;
284
285 /**
286  * Computes the costs of a copy according to execution frequency
287  * @param pos  the argument position of arg in the root arguments
288  * @return Must be >= 0 in all cases.
289  */
290 static int co_get_costs_exec_freq(const ir_node *root, int pos)
291 {
292         ir_node *root_bl = get_nodes_block(root);
293         ir_node *copy_bl
294                 = is_Phi(root) ? get_Block_cfgpred_block(root_bl, pos) : root_bl;
295         int      res     = get_block_execfreq_int(&factors, copy_bl);
296
297         /* don't allow values smaller than one. */
298         return res < 1 ? 1 : res;
299 }
300
301 /**
302  * All costs equal 1. Using this will reduce the _number_ of copies.
303  * @param co   The copy opt object.
304  * @return Must be >= 0 in all cases.
305  */
306 static int co_get_costs_all_one(const ir_node *root, int pos)
307 {
308         (void) root;
309         (void) pos;
310         return 1;
311 }
312
313 /******************************************************************************
314    ____        _   _    _       _ _          _____ _
315   / __ \      | | | |  | |     (_) |        / ____| |
316  | |  | |_ __ | |_| |  | |_ __  _| |_ ___  | (___ | |_ ___  _ __ __ _  __ _  ___
317  | |  | | '_ \| __| |  | | '_ \| | __/ __|  \___ \| __/ _ \| '__/ _` |/ _` |/ _ \
318  | |__| | |_) | |_| |__| | | | | | |_\__ \  ____) | || (_) | | | (_| | (_| |  __/
319   \____/| .__/ \__|\____/|_| |_|_|\__|___/ |_____/ \__\___/|_|  \__,_|\__, |\___|
320         | |                                                            __/ |
321         |_|                                                           |___/
322  ******************************************************************************/
323
324 /**
325  * Determines a maximum weighted independent set with respect to
326  * the interference and conflict edges of all nodes in a qnode.
327  */
328 static int ou_max_ind_set_costs(unit_t *ou)
329 {
330         be_chordal_env_t *chordal_env = ou->co->cenv;
331         ir_node **safe, **unsafe;
332         int i, o, safe_count, safe_costs, unsafe_count, *unsafe_costs;
333         bitset_t *curr;
334         int curr_weight, best_weight = 0;
335
336         /* assign the nodes into two groups.
337          * safe: node has no interference, hence it is in every max stable set.
338          * unsafe: node has an interference
339          */
340         safe         = ALLOCAN(ir_node*, ou->node_count - 1);
341         safe_costs   = 0;
342         safe_count   = 0;
343         unsafe       = ALLOCAN(ir_node*, ou->node_count - 1);
344         unsafe_costs = ALLOCAN(int,      ou->node_count - 1);
345         unsafe_count = 0;
346         for (i=1; i<ou->node_count; ++i) {
347                 int is_safe = 1;
348                 for (o=1; o<ou->node_count; ++o) {
349                         if (i==o)
350                                 continue;
351                         if (nodes_interfere(chordal_env, ou->nodes[i], ou->nodes[o])) {
352                                 unsafe_costs[unsafe_count] = ou->costs[i];
353                                 unsafe[unsafe_count] = ou->nodes[i];
354                                 ++unsafe_count;
355                                 is_safe = 0;
356                                 break;
357                         }
358                 }
359                 if (is_safe) {
360                         safe_costs += ou->costs[i];
361                         safe[safe_count++] = ou->nodes[i];
362                 }
363         }
364
365
366         /* now compute the best set out of the unsafe nodes*/
367         if (unsafe_count > MIS_HEUR_TRIGGER) {
368                 bitset_t *best = bitset_alloca(unsafe_count);
369                 /* Heuristic: Greedy trial and error form index 0 to unsafe_count-1 */
370                 for (i=0; i<unsafe_count; ++i) {
371                         bitset_set(best, i);
372                         /* check if it is a stable set */
373                         for (o=bitset_next_set(best, 0); o!=-1 && o<i; o=bitset_next_set(best, o+1))
374                                 if (nodes_interfere(chordal_env, unsafe[i], unsafe[o])) {
375                                         bitset_clear(best, i); /* clear the bit and try next one */
376                                         break;
377                                 }
378                 }
379                 /* compute the weight */
380                 bitset_foreach(best, pos)
381                         best_weight += unsafe_costs[pos];
382         } else {
383                 /* Exact Algorithm: Brute force */
384                 curr = bitset_alloca(unsafe_count);
385                 bitset_set_all(curr);
386                 while (bitset_popcount(curr) != 0) {
387                         /* check if curr is a stable set */
388                         for (i=bitset_next_set(curr, 0); i!=-1; i=bitset_next_set(curr, i+1))
389                                 for (o=bitset_next_set(curr, i+1); o!=-1; o=bitset_next_set(curr, o+1)) /* !!!!! difference to qnode_max_ind_set(): NOT (curr, i) */
390                                                 if (nodes_interfere(chordal_env, unsafe[i], unsafe[o]))
391                                                         goto no_stable_set;
392
393                         /* if we arrive here, we have a stable set */
394                         /* compute the weight of the stable set*/
395                         curr_weight = 0;
396                         bitset_foreach(curr, pos)
397                                 curr_weight += unsafe_costs[pos];
398
399                         /* any better ? */
400                         if (curr_weight > best_weight) {
401                                 best_weight = curr_weight;
402                         }
403
404         no_stable_set:
405                         bitset_minus1(curr);
406                 }
407         }
408
409         return safe_costs+best_weight;
410 }
411
412 static void co_collect_units(ir_node *irn, void *env)
413 {
414         const arch_register_req_t *req;
415         copy_opt_t                *co  = (copy_opt_t*)env;
416         unit_t *unit;
417
418         if (get_irn_mode(irn) == mode_T)
419                 return;
420         req = arch_get_irn_register_req(irn);
421         if (req->cls != co->cls)
422                 return;
423         if (!co_is_optimizable_root(irn))
424                 return;
425
426         /* Init a new unit */
427         unit = XMALLOCZ(unit_t);
428         unit->co = co;
429         unit->node_count = 1;
430         INIT_LIST_HEAD(&unit->queue);
431
432         /* Phi with some/all of its arguments */
433         if (is_Reg_Phi(irn)) {
434                 int i, arity;
435
436                 /* init */
437                 arity = get_irn_arity(irn);
438                 unit->nodes = XMALLOCN(ir_node*, arity + 1);
439                 unit->costs = XMALLOCN(int,      arity + 1);
440                 unit->nodes[0] = irn;
441
442                 /* fill */
443                 for (i=0; i<arity; ++i) {
444                         int o, arg_pos;
445                         ir_node *arg = get_irn_n(irn, i);
446
447                         assert(arch_get_irn_reg_class(arg) == co->cls && "Argument not in same register class.");
448                         if (arg == irn)
449                                 continue;
450                         if (nodes_interfere(co->cenv, irn, arg)) {
451                                 unit->inevitable_costs += co->get_costs(irn, i);
452                                 continue;
453                         }
454
455                         /* Else insert the argument of the phi to the members of this ou */
456                         DBG((dbg, LEVEL_1, "\t   Member: %+F\n", arg));
457
458                         if (arch_irn_is_ignore(arg))
459                                 continue;
460
461                         /* Check if arg has occurred at a prior position in the arg/list */
462                         arg_pos = 0;
463                         for (o=1; o<unit->node_count; ++o) {
464                                 if (unit->nodes[o] == arg) {
465                                         arg_pos = o;
466                                         break;
467                                 }
468                         }
469
470                         if (!arg_pos) { /* a new argument */
471                                 /* insert node, set costs */
472                                 unit->nodes[unit->node_count] = arg;
473                                 unit->costs[unit->node_count] = co->get_costs(irn, i);
474                                 unit->node_count++;
475                         } else { /* arg has occurred before in same phi */
476                                 /* increase costs for existing arg */
477                                 unit->costs[arg_pos] += co->get_costs(irn, i);
478                         }
479                 }
480                 unit->nodes = XREALLOC(unit->nodes, ir_node*, unit->node_count);
481                 unit->costs = XREALLOC(unit->costs, int,      unit->node_count);
482         } else if (is_Perm_Proj(irn)) {
483                 /* Proj of a perm with corresponding arg */
484                 assert(!nodes_interfere(co->cenv, irn, get_Perm_src(irn)));
485                 unit->nodes = XMALLOCN(ir_node*, 2);
486                 unit->costs = XMALLOCN(int,      2);
487                 unit->node_count = 2;
488                 unit->nodes[0] = irn;
489                 unit->nodes[1] = get_Perm_src(irn);
490                 unit->costs[1] = co->get_costs(irn, -1);
491         } else if (arch_register_req_is(req, should_be_same)) {
492                 /* Src == Tgt of a 2-addr-code instruction */
493                 const unsigned other = req->other_same;
494                 int            count = 0;
495                 int            i;
496
497                 for (i = 0; (1U << i) <= other; ++i) {
498                         if (other & (1U << i)) {
499                                 ir_node *o  = get_irn_n(skip_Proj(irn), i);
500                                 if (arch_irn_is_ignore(o))
501                                         continue;
502                                 if (nodes_interfere(co->cenv, irn, o))
503                                         continue;
504                                 ++count;
505                         }
506                 }
507
508                 if (count != 0) {
509                         int k = 0;
510                         ++count;
511                         unit->nodes = XMALLOCN(ir_node*, count);
512                         unit->costs = XMALLOCN(int,      count);
513                         unit->node_count = count;
514                         unit->nodes[k++] = irn;
515
516                         for (i = 0; 1U << i <= other; ++i) {
517                                 if (other & (1U << i)) {
518                                         ir_node *o  = get_irn_n(skip_Proj(irn), i);
519                                         if (!arch_irn_is_ignore(o) &&
520                                                         !nodes_interfere(co->cenv, irn, o)) {
521                                                 unit->nodes[k] = o;
522                                                 unit->costs[k] = co->get_costs(irn, -1);
523                                                 ++k;
524                                         }
525                                 }
526                         }
527                 }
528         } else {
529                 assert(0 && "This is not an optimizable node!");
530         }
531
532         /* Insert the new unit at a position according to its costs */
533         if (unit->node_count > 1) {
534                 int i;
535                 struct list_head *tmp;
536
537                 /* Determine the maximum costs this unit can cause: all_nodes_cost */
538                 for (i=1; i<unit->node_count; ++i) {
539                         unit->sort_key = MAX(unit->sort_key, unit->costs[i]);
540                         unit->all_nodes_costs += unit->costs[i];
541                 }
542
543                 /* Determine the minimal costs this unit will cause: min_nodes_costs */
544                 unit->min_nodes_costs += unit->all_nodes_costs - ou_max_ind_set_costs(unit);
545                 /* Insert the new ou according to its sort_key */
546                 tmp = &co->units;
547                 while (tmp->next != &co->units && list_entry_units(tmp->next)->sort_key > unit->sort_key)
548                         tmp = tmp->next;
549                 list_add(&unit->units, tmp);
550         } else {
551                 free(unit);
552         }
553 }
554
555 #ifdef QUICK_AND_DIRTY_HACK
556
557 static int compare_ous(const void *k1, const void *k2)
558 {
559         const unit_t *u1 = *((const unit_t **) k1);
560         const unit_t *u2 = *((const unit_t **) k2);
561         int i, o, u1_has_constr, u2_has_constr;
562         arch_register_req_t req;
563
564         /* Units with constraints come first */
565         u1_has_constr = 0;
566         for (i=0; i<u1->node_count; ++i) {
567                 arch_get_irn_register_req(&req, u1->nodes[i]);
568                 if (arch_register_req_is(&req, limited)) {
569                         u1_has_constr = 1;
570                         break;
571                 }
572         }
573
574         u2_has_constr = 0;
575         for (i=0; i<u2->node_count; ++i) {
576                 arch_get_irn_register_req(&req, u2->nodes[i]);
577                 if (arch_register_req_is(&req, limited)) {
578                         u2_has_constr = 1;
579                         break;
580                 }
581         }
582
583         if (u1_has_constr != u2_has_constr)
584                 return u2_has_constr - u1_has_constr;
585
586         /* Now check, whether the two units are connected */
587 #if 0
588         for (i=0; i<u1->node_count; ++i)
589                 for (o=0; o<u2->node_count; ++o)
590                         if (u1->nodes[i] == u2->nodes[o])
591                                 return 0;
592 #endif
593
594         /* After all, the sort key decides. Greater keys come first. */
595         return u2->sort_key - u1->sort_key;
596
597 }
598
599 /**
600  * Sort the ou's according to constraints and their sort_key
601  */
602 static void co_sort_units(copy_opt_t *co)
603 {
604         int i, count = 0, costs;
605         unit_t **ous;
606
607         /* get the number of ous, remove them form the list and fill the array */
608         list_for_each_entry(unit_t, ou, &co->units, units)
609                 count++;
610         ous = ALLOCAN(unit_t, count);
611
612         costs = co_get_max_copy_costs(co);
613
614         i = 0;
615         list_for_each_entry(unit_t, ou, &co->units, units)
616                 ous[i++] = ou;
617
618         INIT_LIST_HEAD(&co->units);
619
620         assert(count == i && list_empty(&co->units));
621
622         for (i=0; i<count; ++i)
623                 ir_printf("%+F\n", ous[i]->nodes[0]);
624
625         qsort(ous, count, sizeof(*ous), compare_ous);
626
627         ir_printf("\n\n");
628         for (i=0; i<count; ++i)
629                 ir_printf("%+F\n", ous[i]->nodes[0]);
630
631         /* reinsert into list in correct order */
632         for (i=0; i<count; ++i)
633                 list_add_tail(&ous[i]->units, &co->units);
634
635         assert(costs == co_get_max_copy_costs(co));
636 }
637 #endif
638
639 void co_build_ou_structure(copy_opt_t *co)
640 {
641         DBG((dbg, LEVEL_1, "\tCollecting optimization units\n"));
642         INIT_LIST_HEAD(&co->units);
643         irg_walk_graph(co->irg, co_collect_units, NULL, co);
644 #ifdef QUICK_AND_DIRTY_HACK
645         co_sort_units(co);
646 #endif
647 }
648
649 void co_free_ou_structure(copy_opt_t *co)
650 {
651         ASSERT_OU_AVAIL(co);
652         list_for_each_entry_safe(unit_t, curr, tmp, &co->units, units) {
653                 xfree(curr->nodes);
654                 xfree(curr->costs);
655                 xfree(curr);
656         }
657         co->units.next = NULL;
658 }
659
660 /* co_solve_heuristic() is implemented in becopyheur.c */
661
662 int co_get_max_copy_costs(const copy_opt_t *co)
663 {
664         int i, res = 0;
665
666         ASSERT_OU_AVAIL(co);
667
668         list_for_each_entry(unit_t, curr, &co->units, units) {
669                 res += curr->inevitable_costs;
670                 for (i=1; i<curr->node_count; ++i)
671                         res += curr->costs[i];
672         }
673         return res;
674 }
675
676 int co_get_inevit_copy_costs(const copy_opt_t *co)
677 {
678         int res = 0;
679
680         ASSERT_OU_AVAIL(co);
681
682         list_for_each_entry(unit_t, curr, &co->units, units)
683                 res += curr->inevitable_costs;
684         return res;
685 }
686
687 int co_get_copy_costs(const copy_opt_t *co)
688 {
689         int i, res = 0;
690
691         ASSERT_OU_AVAIL(co);
692
693         list_for_each_entry(unit_t, curr, &co->units, units) {
694                 int root_col = get_irn_col(curr->nodes[0]);
695                 DBG((dbg, LEVEL_1, "  %3d costs for root %+F color %d\n", curr->inevitable_costs, curr->nodes[0], root_col));
696                 res += curr->inevitable_costs;
697                 for (i=1; i<curr->node_count; ++i) {
698                         int arg_col = get_irn_col(curr->nodes[i]);
699                         if (root_col != arg_col) {
700                                 DBG((dbg, LEVEL_1, "  %3d for arg %+F color %d\n", curr->costs[i], curr->nodes[i], arg_col));
701                                 res += curr->costs[i];
702                         }
703                 }
704         }
705         return res;
706 }
707
708 int co_get_lower_bound(const copy_opt_t *co)
709 {
710         int res = 0;
711
712         ASSERT_OU_AVAIL(co);
713
714         list_for_each_entry(unit_t, curr, &co->units, units)
715                 res += curr->inevitable_costs + curr->min_nodes_costs;
716         return res;
717 }
718
719 void co_complete_stats(const copy_opt_t *co, co_complete_stats_t *stat)
720 {
721         bitset_t *seen = bitset_malloc(get_irg_last_idx(co->irg));
722
723         memset(stat, 0, sizeof(stat[0]));
724
725         /* count affinity edges. */
726         co_gs_foreach_aff_node(co, an) {
727                 stat->aff_nodes += 1;
728                 bitset_set(seen, get_irn_idx(an->irn));
729                 co_gs_foreach_neighb(an, neigh) {
730                         if (!bitset_is_set(seen, get_irn_idx(neigh->irn))) {
731                                 stat->aff_edges += 1;
732                                 stat->max_costs += neigh->costs;
733
734                                 if (get_irn_col(an->irn) != get_irn_col(neigh->irn)) {
735                                         stat->costs += neigh->costs;
736                                         stat->unsatisfied_edges += 1;
737                                 }
738
739                                 if (nodes_interfere(co->cenv, an->irn, neigh->irn)) {
740                                         stat->aff_int += 1;
741                                         stat->inevit_costs += neigh->costs;
742                                 }
743
744                         }
745                 }
746         }
747
748         bitset_free(seen);
749 }
750
751 /******************************************************************************
752    _____                 _        _____ _
753   / ____|               | |      / ____| |
754  | |  __ _ __ __ _ _ __ | |__   | (___ | |_ ___  _ __ __ _  __ _  ___
755  | | |_ | '__/ _` | '_ \| '_ \   \___ \| __/ _ \| '__/ _` |/ _` |/ _ \
756  | |__| | | | (_| | |_) | | | |  ____) | || (_) | | | (_| | (_| |  __/
757   \_____|_|  \__,_| .__/|_| |_| |_____/ \__\___/|_|  \__,_|\__, |\___|
758                   | |                                       __/ |
759                   |_|                                      |___/
760  ******************************************************************************/
761
762 static int compare_affinity_node_t(const void *k1, const void *k2, size_t size)
763 {
764         const affinity_node_t *n1 = (const affinity_node_t*)k1;
765         const affinity_node_t *n2 = (const affinity_node_t*)k2;
766         (void) size;
767
768         return (n1->irn != n2->irn);
769 }
770
771 static void add_edge(copy_opt_t *co, ir_node *n1, ir_node *n2, int costs)
772 {
773         affinity_node_t new_node, *node;
774         neighb_t        *nbr;
775         int             allocnew = 1;
776
777         new_node.irn        = n1;
778         new_node.degree     = 0;
779         new_node.neighbours = NULL;
780         node = set_insert(affinity_node_t, co->nodes, &new_node, sizeof(new_node), hash_irn(new_node.irn));
781
782         for (nbr = node->neighbours; nbr; nbr = nbr->next)
783                 if (nbr->irn == n2) {
784                         allocnew = 0;
785                         break;
786                 }
787
788         /* if we did not find n2 in n1's neighbourhood insert it */
789         if (allocnew) {
790                 nbr        = OALLOC(&co->obst, neighb_t);
791                 nbr->irn   = n2;
792                 nbr->costs = 0;
793                 nbr->next  = node->neighbours;
794
795                 node->neighbours = nbr;
796                 node->degree++;
797         }
798
799         /* now nbr points to n1's neighbour-entry of n2 */
800         nbr->costs += costs;
801 }
802
803 static inline void add_edges(copy_opt_t *co, ir_node *n1, ir_node *n2, int costs)
804 {
805         if (! be_ifg_connected(co->cenv->ifg, n1, n2)) {
806                 add_edge(co, n1, n2, costs);
807                 add_edge(co, n2, n1, costs);
808         }
809 }
810
811 static void build_graph_walker(ir_node *irn, void *env)
812 {
813         const arch_register_req_t *req;
814         copy_opt_t                *co  = (copy_opt_t*)env;
815         int pos, max;
816
817         if (get_irn_mode(irn) == mode_T)
818                 return;
819         req = arch_get_irn_register_req(irn);
820         if (req->cls != co->cls || arch_irn_is_ignore(irn))
821                 return;
822
823         if (is_Reg_Phi(irn)) { /* Phis */
824                 for (pos=0, max=get_irn_arity(irn); pos<max; ++pos) {
825                         ir_node *arg = get_irn_n(irn, pos);
826                         add_edges(co, irn, arg, co->get_costs(irn, pos));
827                 }
828         } else if (is_Perm_Proj(irn)) { /* Perms */
829                 ir_node *arg = get_Perm_src(irn);
830                 add_edges(co, irn, arg, co->get_costs(irn, -1));
831         } else if (arch_register_req_is(req, should_be_same)) {
832                 const unsigned other = req->other_same;
833                 int i;
834
835                 for (i = 0; 1U << i <= other; ++i) {
836                         if (other & (1U << i)) {
837                                 ir_node *other = get_irn_n(skip_Proj(irn), i);
838                                 if (!arch_irn_is_ignore(other))
839                                         add_edges(co, irn, other, co->get_costs(irn, -1));
840                         }
841                 }
842         }
843 }
844
845 void co_build_graph_structure(copy_opt_t *co)
846 {
847         obstack_init(&co->obst);
848         co->nodes = new_set(compare_affinity_node_t, 32);
849
850         irg_walk_graph(co->irg, build_graph_walker, NULL, co);
851 }
852
853 void co_free_graph_structure(copy_opt_t *co)
854 {
855         ASSERT_GS_AVAIL(co);
856
857         del_set(co->nodes);
858         obstack_free(&co->obst, NULL);
859         co->nodes = NULL;
860 }
861
862 int co_gs_is_optimizable(copy_opt_t *co, ir_node *irn)
863 {
864         affinity_node_t new_node, *n;
865
866         ASSERT_GS_AVAIL(co);
867
868         new_node.irn = irn;
869         n = set_find(affinity_node_t, co->nodes, &new_node, sizeof(new_node), hash_irn(new_node.irn));
870         if (n) {
871                 return (n->degree > 0);
872         } else
873                 return 0;
874 }
875
876 static int co_dump_appel_disjoint_constraints(const copy_opt_t *co, ir_node *a, ir_node *b)
877 {
878         ir_node *nodes[]  = { a, b };
879         bitset_t *constr[] = { NULL, NULL };
880         int j;
881
882         constr[0] = bitset_alloca(co->cls->n_regs);
883         constr[1] = bitset_alloca(co->cls->n_regs);
884
885         for (j = 0; j < 2; ++j) {
886                 const arch_register_req_t *req = arch_get_irn_register_req(nodes[j]);
887                 if (arch_register_req_is(req, limited))
888                         rbitset_copy_to_bitset(req->limited, constr[j]);
889                 else
890                         bitset_set_all(constr[j]);
891
892         }
893
894         return !bitset_intersect(constr[0], constr[1]);
895 }
896
897 /**
898  * Dump the interference graph according to the Appel/George coalescing contest file format.
899  * See: http://www.cs.princeton.edu/~appel/coalesce/format.html
900  * @note Requires graph structure.
901  * @param co The copy opt object.
902  * @param f  A file to dump to.
903  */
904 static void co_dump_appel_graph(const copy_opt_t *co, FILE *f)
905 {
906         be_ifg_t *ifg       = co->cenv->ifg;
907         int      *color_map = ALLOCAN(int, co->cls->n_regs);
908         int      *node_map  = XMALLOCN(int, get_irg_last_idx(co->irg) + 1);
909         ir_graph *irg       = co->irg;
910         be_irg_t *birg      = be_birg_from_irg(irg);
911
912         ir_node *irn;
913         nodes_iter_t it;
914         neighbours_iter_t nit;
915         int n, n_regs;
916         unsigned i;
917
918         n_regs = 0;
919         for (i = 0; i < co->cls->n_regs; ++i) {
920                 const arch_register_t *reg = &co->cls->regs[i];
921                 if (rbitset_is_set(birg->allocatable_regs, reg->global_index)) {
922                         color_map[i] = n_regs++;
923                 } else {
924                         color_map[i] = -1;
925                 }
926         }
927
928         /*
929          * n contains the first node number.
930          * the values below n are the pre-colored register nodes
931          */
932
933         n = n_regs;
934         be_ifg_foreach_node(ifg, &it, irn) {
935                 if (arch_irn_is_ignore(irn))
936                         continue;
937                 node_map[get_irn_idx(irn)] = n++;
938         }
939
940         fprintf(f, "%d %d\n", n, n_regs);
941
942         be_ifg_foreach_node(ifg, &it, irn) {
943                 if (!arch_irn_is_ignore(irn)) {
944                         int idx                        = node_map[get_irn_idx(irn)];
945                         affinity_node_t           *a   = get_affinity_info(co, irn);
946                         const arch_register_req_t *req = arch_get_irn_register_req(irn);
947                         ir_node                   *adj;
948
949                         if (arch_register_req_is(req, limited)) {
950                                 for (i = 0; i < co->cls->n_regs; ++i) {
951                                         if (!rbitset_is_set(req->limited, i) && color_map[i] >= 0)
952                                                 fprintf(f, "%d %d -1\n", color_map[i], idx);
953                                 }
954                         }
955
956                         be_ifg_foreach_neighbour(ifg, &nit, irn, adj) {
957                                 if (!arch_irn_is_ignore(adj) &&
958                                                 !co_dump_appel_disjoint_constraints(co, irn, adj)) {
959                                         int adj_idx = node_map[get_irn_idx(adj)];
960                                         if (idx < adj_idx)
961                                                 fprintf(f, "%d %d -1\n", idx, adj_idx);
962                                 }
963                         }
964
965                         if (a) {
966                                 co_gs_foreach_neighb(a, n) {
967                                         if (!arch_irn_is_ignore(n->irn)) {
968                                                 int n_idx = node_map[get_irn_idx(n->irn)];
969                                                 if (idx < n_idx)
970                                                         fprintf(f, "%d %d %d\n", idx, n_idx, (int) n->costs);
971                                         }
972                                 }
973                         }
974                 }
975         }
976
977         xfree(node_map);
978 }
979
980 static FILE *my_open(const be_chordal_env_t *env, const char *prefix,
981                      const char *suffix)
982 {
983         FILE *result;
984         char buf[1024];
985         size_t i, n;
986         char *tu_name;
987         const char *cup_name = be_get_irg_main_env(env->irg)->cup_name;
988
989         n = strlen(cup_name);
990         tu_name = XMALLOCN(char, n + 1);
991         strcpy(tu_name, cup_name);
992         for (i = 0; i < n; ++i)
993                 if (tu_name[i] == '.')
994                         tu_name[i] = '_';
995
996
997         ir_snprintf(buf, sizeof(buf), "%s%s_%F_%s%s", prefix, tu_name, env->irg, env->cls->name, suffix);
998         xfree(tu_name);
999         result = fopen(buf, "wt");
1000         if (result == NULL) {
1001                 panic("Couldn't open '%s' for writing.", buf);
1002         }
1003
1004         return result;
1005 }
1006
1007 void co_driver(be_chordal_env_t *cenv)
1008 {
1009         ir_timer_t          *timer = ir_timer_new();
1010         co_complete_stats_t before, after;
1011         copy_opt_t          *co;
1012         int                 was_optimal = 0;
1013
1014         assert(selected_copyopt);
1015
1016         /* skip copymin if algo is 'none' */
1017         if (selected_copyopt->copyopt == void_algo)
1018                 return;
1019
1020         be_assure_live_chk(cenv->irg);
1021
1022         co = new_copy_opt(cenv, cost_func);
1023         co_build_ou_structure(co);
1024         co_build_graph_structure(co);
1025
1026         co_complete_stats(co, &before);
1027
1028         stat_ev_ull("co_aff_nodes",    before.aff_nodes);
1029         stat_ev_ull("co_aff_edges",    before.aff_edges);
1030         stat_ev_ull("co_max_costs",    before.max_costs);
1031         stat_ev_ull("co_inevit_costs", before.inevit_costs);
1032         stat_ev_ull("co_aff_int",      before.aff_int);
1033
1034         stat_ev_ull("co_init_costs",   before.costs);
1035         stat_ev_ull("co_init_unsat",   before.unsatisfied_edges);
1036
1037         if (dump_flags & DUMP_BEFORE) {
1038                 FILE *f = my_open(cenv, "", "-before.vcg");
1039                 be_dump_ifg_co(f, co, style_flags & CO_IFG_DUMP_LABELS, style_flags & CO_IFG_DUMP_COLORS);
1040                 fclose(f);
1041         }
1042
1043         /* if the algo can improve results, provide an initial solution with heur1 */
1044         if (improve && selected_copyopt->can_improve_existing) {
1045                 co_complete_stats_t stats;
1046
1047                 /* produce a heuristic solution */
1048                 co_solve_heuristic(co);
1049
1050                 /* do the stats and provide the current costs */
1051                 co_complete_stats(co, &stats);
1052                 stat_ev_ull("co_prepare_costs", stats.costs);
1053         }
1054
1055         /* perform actual copy minimization */
1056         ir_timer_reset_and_start(timer);
1057         was_optimal = selected_copyopt->copyopt(co);
1058         ir_timer_stop(timer);
1059
1060         stat_ev_dbl("co_time", ir_timer_elapsed_msec(timer));
1061         stat_ev_ull("co_optimal", was_optimal);
1062         ir_timer_free(timer);
1063
1064         if (dump_flags & DUMP_AFTER) {
1065                 FILE *f = my_open(cenv, "", "-after.vcg");
1066                 be_dump_ifg_co(f, co, style_flags & CO_IFG_DUMP_LABELS, style_flags & CO_IFG_DUMP_COLORS);
1067                 fclose(f);
1068         }
1069
1070         co_complete_stats(co, &after);
1071
1072         if (do_stats) {
1073                 unsigned long long optimizable_costs = after.max_costs - after.inevit_costs;
1074                 unsigned long long evitable          = after.costs     - after.inevit_costs;
1075
1076                 ir_printf("%30F ", cenv->irg);
1077                 printf("%10s %10llu%10llu%10llu", cenv->cls->name, after.max_costs, before.costs, after.inevit_costs);
1078
1079                 if (optimizable_costs > 0)
1080                         printf("%10llu %5.2f\n", after.costs, (evitable * 100.0) / optimizable_costs);
1081                 else
1082                         printf("%10llu %5s\n", after.costs, "-");
1083         }
1084
1085         /* Dump the interference graph in Appel's format. */
1086         if (dump_flags & DUMP_APPEL) {
1087                 FILE *f = my_open(cenv, "", ".apl");
1088                 fprintf(f, "# %llu %llu\n", after.costs, after.unsatisfied_edges);
1089                 co_dump_appel_graph(co, f);
1090                 fclose(f);
1091         }
1092
1093         stat_ev_ull("co_after_costs", after.costs);
1094         stat_ev_ull("co_after_unsat", after.unsatisfied_edges);
1095
1096         co_free_graph_structure(co);
1097         co_free_ou_structure(co);
1098         free_copy_opt(co);
1099 }