beifg: Let be_ifg_foreach_neighbour() declare the node variable.
[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         arch_register_req_t const *const req = arch_get_irn_register_req(irn);
245         if (arch_register_req_is(req, ignore))
246                 return 0;
247
248         if (is_Reg_Phi(irn) || is_Perm_Proj(irn))
249                 return 1;
250
251         if (arch_register_req_is(req, should_be_same))
252                 return 1;
253
254         return 0;
255 }
256
257 /**
258  * Computes the costs of a copy according to loop depth
259  * @param pos  the argument position of arg in the root arguments
260  * @return     Must be >= 0 in all cases.
261  */
262 static int co_get_costs_loop_depth(const ir_node *root, int pos)
263 {
264         ir_node *block = get_nodes_block(root);
265         ir_loop *loop;
266         int      cost;
267
268         if (is_Phi(root)) {
269                 block = get_Block_cfgpred_block(block, pos);
270         }
271         loop = get_irn_loop(block);
272         if (loop) {
273                 int d = get_loop_depth(loop);
274                 cost = d*d;
275         } else {
276                 cost = 0;
277         }
278         return 1+cost;
279 }
280
281 static ir_execfreq_int_factors factors;
282
283 /**
284  * Computes the costs of a copy according to execution frequency
285  * @param pos  the argument position of arg in the root arguments
286  * @return Must be >= 0 in all cases.
287  */
288 static int co_get_costs_exec_freq(const ir_node *root, int pos)
289 {
290         ir_node *root_bl = get_nodes_block(root);
291         ir_node *copy_bl
292                 = is_Phi(root) ? get_Block_cfgpred_block(root_bl, pos) : root_bl;
293         int      res     = get_block_execfreq_int(&factors, copy_bl);
294
295         /* don't allow values smaller than one. */
296         return res < 1 ? 1 : res;
297 }
298
299 /**
300  * All costs equal 1. Using this will reduce the _number_ of copies.
301  * @param co   The copy opt object.
302  * @return Must be >= 0 in all cases.
303  */
304 static int co_get_costs_all_one(const ir_node *root, int pos)
305 {
306         (void) root;
307         (void) pos;
308         return 1;
309 }
310
311 /******************************************************************************
312    ____        _   _    _       _ _          _____ _
313   / __ \      | | | |  | |     (_) |        / ____| |
314  | |  | |_ __ | |_| |  | |_ __  _| |_ ___  | (___ | |_ ___  _ __ __ _  __ _  ___
315  | |  | | '_ \| __| |  | | '_ \| | __/ __|  \___ \| __/ _ \| '__/ _` |/ _` |/ _ \
316  | |__| | |_) | |_| |__| | | | | | |_\__ \  ____) | || (_) | | | (_| | (_| |  __/
317   \____/| .__/ \__|\____/|_| |_|_|\__|___/ |_____/ \__\___/|_|  \__,_|\__, |\___|
318         | |                                                            __/ |
319         |_|                                                           |___/
320  ******************************************************************************/
321
322 /**
323  * Determines a maximum weighted independent set with respect to
324  * the interference and conflict edges of all nodes in a qnode.
325  */
326 static int ou_max_ind_set_costs(unit_t *ou)
327 {
328         be_chordal_env_t *chordal_env = ou->co->cenv;
329         ir_node **safe, **unsafe;
330         int i, o, safe_count, safe_costs, unsafe_count, *unsafe_costs;
331         bitset_t *curr;
332         int curr_weight, best_weight = 0;
333
334         /* assign the nodes into two groups.
335          * safe: node has no interference, hence it is in every max stable set.
336          * unsafe: node has an interference
337          */
338         safe         = ALLOCAN(ir_node*, ou->node_count - 1);
339         safe_costs   = 0;
340         safe_count   = 0;
341         unsafe       = ALLOCAN(ir_node*, ou->node_count - 1);
342         unsafe_costs = ALLOCAN(int,      ou->node_count - 1);
343         unsafe_count = 0;
344         for (i=1; i<ou->node_count; ++i) {
345                 int is_safe = 1;
346                 for (o=1; o<ou->node_count; ++o) {
347                         if (i==o)
348                                 continue;
349                         if (nodes_interfere(chordal_env, ou->nodes[i], ou->nodes[o])) {
350                                 unsafe_costs[unsafe_count] = ou->costs[i];
351                                 unsafe[unsafe_count] = ou->nodes[i];
352                                 ++unsafe_count;
353                                 is_safe = 0;
354                                 break;
355                         }
356                 }
357                 if (is_safe) {
358                         safe_costs += ou->costs[i];
359                         safe[safe_count++] = ou->nodes[i];
360                 }
361         }
362
363
364         /* now compute the best set out of the unsafe nodes*/
365         if (unsafe_count > MIS_HEUR_TRIGGER) {
366                 bitset_t *best = bitset_alloca(unsafe_count);
367                 /* Heuristic: Greedy trial and error form index 0 to unsafe_count-1 */
368                 for (i=0; i<unsafe_count; ++i) {
369                         bitset_set(best, i);
370                         /* check if it is a stable set */
371                         for (o=bitset_next_set(best, 0); o!=-1 && o<i; o=bitset_next_set(best, o+1))
372                                 if (nodes_interfere(chordal_env, unsafe[i], unsafe[o])) {
373                                         bitset_clear(best, i); /* clear the bit and try next one */
374                                         break;
375                                 }
376                 }
377                 /* compute the weight */
378                 bitset_foreach(best, pos)
379                         best_weight += unsafe_costs[pos];
380         } else {
381                 /* Exact Algorithm: Brute force */
382                 curr = bitset_alloca(unsafe_count);
383                 bitset_set_all(curr);
384                 while (bitset_popcount(curr) != 0) {
385                         /* check if curr is a stable set */
386                         for (i=bitset_next_set(curr, 0); i!=-1; i=bitset_next_set(curr, i+1))
387                                 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) */
388                                                 if (nodes_interfere(chordal_env, unsafe[i], unsafe[o]))
389                                                         goto no_stable_set;
390
391                         /* if we arrive here, we have a stable set */
392                         /* compute the weight of the stable set*/
393                         curr_weight = 0;
394                         bitset_foreach(curr, pos)
395                                 curr_weight += unsafe_costs[pos];
396
397                         /* any better ? */
398                         if (curr_weight > best_weight) {
399                                 best_weight = curr_weight;
400                         }
401
402         no_stable_set:
403                         bitset_minus1(curr);
404                 }
405         }
406
407         return safe_costs+best_weight;
408 }
409
410 static void co_collect_units(ir_node *irn, void *env)
411 {
412         const arch_register_req_t *req;
413         copy_opt_t                *co  = (copy_opt_t*)env;
414         unit_t *unit;
415
416         if (get_irn_mode(irn) == mode_T)
417                 return;
418         req = arch_get_irn_register_req(irn);
419         if (req->cls != co->cls)
420                 return;
421         if (!co_is_optimizable_root(irn))
422                 return;
423
424         /* Init a new unit */
425         unit = XMALLOCZ(unit_t);
426         unit->co = co;
427         unit->node_count = 1;
428         INIT_LIST_HEAD(&unit->queue);
429
430         /* Phi with some/all of its arguments */
431         if (is_Reg_Phi(irn)) {
432                 int i, arity;
433
434                 /* init */
435                 arity = get_irn_arity(irn);
436                 unit->nodes = XMALLOCN(ir_node*, arity + 1);
437                 unit->costs = XMALLOCN(int,      arity + 1);
438                 unit->nodes[0] = irn;
439
440                 /* fill */
441                 for (i=0; i<arity; ++i) {
442                         int o, arg_pos;
443                         ir_node *arg = get_irn_n(irn, i);
444
445                         assert(arch_get_irn_reg_class(arg) == co->cls && "Argument not in same register class.");
446                         if (arg == irn)
447                                 continue;
448                         if (nodes_interfere(co->cenv, irn, arg)) {
449                                 unit->inevitable_costs += co->get_costs(irn, i);
450                                 continue;
451                         }
452
453                         /* Else insert the argument of the phi to the members of this ou */
454                         DBG((dbg, LEVEL_1, "\t   Member: %+F\n", arg));
455
456                         if (arch_irn_is_ignore(arg))
457                                 continue;
458
459                         /* Check if arg has occurred at a prior position in the arg/list */
460                         arg_pos = 0;
461                         for (o=1; o<unit->node_count; ++o) {
462                                 if (unit->nodes[o] == arg) {
463                                         arg_pos = o;
464                                         break;
465                                 }
466                         }
467
468                         if (!arg_pos) { /* a new argument */
469                                 /* insert node, set costs */
470                                 unit->nodes[unit->node_count] = arg;
471                                 unit->costs[unit->node_count] = co->get_costs(irn, i);
472                                 unit->node_count++;
473                         } else { /* arg has occurred before in same phi */
474                                 /* increase costs for existing arg */
475                                 unit->costs[arg_pos] += co->get_costs(irn, i);
476                         }
477                 }
478                 unit->nodes = XREALLOC(unit->nodes, ir_node*, unit->node_count);
479                 unit->costs = XREALLOC(unit->costs, int,      unit->node_count);
480         } else if (is_Perm_Proj(irn)) {
481                 /* Proj of a perm with corresponding arg */
482                 assert(!nodes_interfere(co->cenv, irn, get_Perm_src(irn)));
483                 unit->nodes = XMALLOCN(ir_node*, 2);
484                 unit->costs = XMALLOCN(int,      2);
485                 unit->node_count = 2;
486                 unit->nodes[0] = irn;
487                 unit->nodes[1] = get_Perm_src(irn);
488                 unit->costs[1] = co->get_costs(irn, -1);
489         } else if (arch_register_req_is(req, should_be_same)) {
490                 /* Src == Tgt of a 2-addr-code instruction */
491                 const unsigned other = req->other_same;
492                 int            count = 0;
493                 int            i;
494
495                 for (i = 0; (1U << i) <= other; ++i) {
496                         if (other & (1U << i)) {
497                                 ir_node *o  = get_irn_n(skip_Proj(irn), i);
498                                 if (arch_irn_is_ignore(o))
499                                         continue;
500                                 if (nodes_interfere(co->cenv, irn, o))
501                                         continue;
502                                 ++count;
503                         }
504                 }
505
506                 if (count != 0) {
507                         int k = 0;
508                         ++count;
509                         unit->nodes = XMALLOCN(ir_node*, count);
510                         unit->costs = XMALLOCN(int,      count);
511                         unit->node_count = count;
512                         unit->nodes[k++] = irn;
513
514                         for (i = 0; 1U << i <= other; ++i) {
515                                 if (other & (1U << i)) {
516                                         ir_node *o  = get_irn_n(skip_Proj(irn), i);
517                                         if (!arch_irn_is_ignore(o) &&
518                                                         !nodes_interfere(co->cenv, irn, o)) {
519                                                 unit->nodes[k] = o;
520                                                 unit->costs[k] = co->get_costs(irn, -1);
521                                                 ++k;
522                                         }
523                                 }
524                         }
525                 }
526         } else {
527                 assert(0 && "This is not an optimizable node!");
528         }
529
530         /* Insert the new unit at a position according to its costs */
531         if (unit->node_count > 1) {
532                 int i;
533                 struct list_head *tmp;
534
535                 /* Determine the maximum costs this unit can cause: all_nodes_cost */
536                 for (i=1; i<unit->node_count; ++i) {
537                         unit->sort_key = MAX(unit->sort_key, unit->costs[i]);
538                         unit->all_nodes_costs += unit->costs[i];
539                 }
540
541                 /* Determine the minimal costs this unit will cause: min_nodes_costs */
542                 unit->min_nodes_costs += unit->all_nodes_costs - ou_max_ind_set_costs(unit);
543                 /* Insert the new ou according to its sort_key */
544                 tmp = &co->units;
545                 while (tmp->next != &co->units && list_entry_units(tmp->next)->sort_key > unit->sort_key)
546                         tmp = tmp->next;
547                 list_add(&unit->units, tmp);
548         } else {
549                 free(unit);
550         }
551 }
552
553 #ifdef QUICK_AND_DIRTY_HACK
554
555 static int compare_ous(const void *k1, const void *k2)
556 {
557         const unit_t *u1 = *((const unit_t **) k1);
558         const unit_t *u2 = *((const unit_t **) k2);
559         int i, o, u1_has_constr, u2_has_constr;
560         arch_register_req_t req;
561
562         /* Units with constraints come first */
563         u1_has_constr = 0;
564         for (i=0; i<u1->node_count; ++i) {
565                 arch_get_irn_register_req(&req, u1->nodes[i]);
566                 if (arch_register_req_is(&req, limited)) {
567                         u1_has_constr = 1;
568                         break;
569                 }
570         }
571
572         u2_has_constr = 0;
573         for (i=0; i<u2->node_count; ++i) {
574                 arch_get_irn_register_req(&req, u2->nodes[i]);
575                 if (arch_register_req_is(&req, limited)) {
576                         u2_has_constr = 1;
577                         break;
578                 }
579         }
580
581         if (u1_has_constr != u2_has_constr)
582                 return u2_has_constr - u1_has_constr;
583
584         /* After all, the sort key decides. Greater keys come first. */
585         return u2->sort_key - u1->sort_key;
586
587 }
588
589 /**
590  * Sort the ou's according to constraints and their sort_key
591  */
592 static void co_sort_units(copy_opt_t *co)
593 {
594         int i, count = 0, costs;
595         unit_t **ous;
596
597         /* get the number of ous, remove them form the list and fill the array */
598         list_for_each_entry(unit_t, ou, &co->units, units)
599                 count++;
600         ous = ALLOCAN(unit_t, count);
601
602         costs = co_get_max_copy_costs(co);
603
604         i = 0;
605         list_for_each_entry(unit_t, ou, &co->units, units)
606                 ous[i++] = ou;
607
608         INIT_LIST_HEAD(&co->units);
609
610         assert(count == i && list_empty(&co->units));
611
612         for (i=0; i<count; ++i)
613                 ir_printf("%+F\n", ous[i]->nodes[0]);
614
615         qsort(ous, count, sizeof(*ous), compare_ous);
616
617         ir_printf("\n\n");
618         for (i=0; i<count; ++i)
619                 ir_printf("%+F\n", ous[i]->nodes[0]);
620
621         /* reinsert into list in correct order */
622         for (i=0; i<count; ++i)
623                 list_add_tail(&ous[i]->units, &co->units);
624
625         assert(costs == co_get_max_copy_costs(co));
626 }
627 #endif
628
629 void co_build_ou_structure(copy_opt_t *co)
630 {
631         DBG((dbg, LEVEL_1, "\tCollecting optimization units\n"));
632         INIT_LIST_HEAD(&co->units);
633         irg_walk_graph(co->irg, co_collect_units, NULL, co);
634 #ifdef QUICK_AND_DIRTY_HACK
635         co_sort_units(co);
636 #endif
637 }
638
639 void co_free_ou_structure(copy_opt_t *co)
640 {
641         ASSERT_OU_AVAIL(co);
642         list_for_each_entry_safe(unit_t, curr, tmp, &co->units, units) {
643                 xfree(curr->nodes);
644                 xfree(curr->costs);
645                 xfree(curr);
646         }
647         co->units.next = NULL;
648 }
649
650 /* co_solve_heuristic() is implemented in becopyheur.c */
651
652 int co_get_max_copy_costs(const copy_opt_t *co)
653 {
654         int i, res = 0;
655
656         ASSERT_OU_AVAIL(co);
657
658         list_for_each_entry(unit_t, curr, &co->units, units) {
659                 res += curr->inevitable_costs;
660                 for (i=1; i<curr->node_count; ++i)
661                         res += curr->costs[i];
662         }
663         return res;
664 }
665
666 int co_get_inevit_copy_costs(const copy_opt_t *co)
667 {
668         int res = 0;
669
670         ASSERT_OU_AVAIL(co);
671
672         list_for_each_entry(unit_t, curr, &co->units, units)
673                 res += curr->inevitable_costs;
674         return res;
675 }
676
677 int co_get_copy_costs(const copy_opt_t *co)
678 {
679         int i, res = 0;
680
681         ASSERT_OU_AVAIL(co);
682
683         list_for_each_entry(unit_t, curr, &co->units, units) {
684                 int root_col = get_irn_col(curr->nodes[0]);
685                 DBG((dbg, LEVEL_1, "  %3d costs for root %+F color %d\n", curr->inevitable_costs, curr->nodes[0], root_col));
686                 res += curr->inevitable_costs;
687                 for (i=1; i<curr->node_count; ++i) {
688                         int arg_col = get_irn_col(curr->nodes[i]);
689                         if (root_col != arg_col) {
690                                 DBG((dbg, LEVEL_1, "  %3d for arg %+F color %d\n", curr->costs[i], curr->nodes[i], arg_col));
691                                 res += curr->costs[i];
692                         }
693                 }
694         }
695         return res;
696 }
697
698 int co_get_lower_bound(const copy_opt_t *co)
699 {
700         int res = 0;
701
702         ASSERT_OU_AVAIL(co);
703
704         list_for_each_entry(unit_t, curr, &co->units, units)
705                 res += curr->inevitable_costs + curr->min_nodes_costs;
706         return res;
707 }
708
709 void co_complete_stats(const copy_opt_t *co, co_complete_stats_t *stat)
710 {
711         bitset_t *seen = bitset_malloc(get_irg_last_idx(co->irg));
712
713         memset(stat, 0, sizeof(stat[0]));
714
715         /* count affinity edges. */
716         co_gs_foreach_aff_node(co, an) {
717                 stat->aff_nodes += 1;
718                 bitset_set(seen, get_irn_idx(an->irn));
719                 co_gs_foreach_neighb(an, neigh) {
720                         if (!bitset_is_set(seen, get_irn_idx(neigh->irn))) {
721                                 stat->aff_edges += 1;
722                                 stat->max_costs += neigh->costs;
723
724                                 if (get_irn_col(an->irn) != get_irn_col(neigh->irn)) {
725                                         stat->costs += neigh->costs;
726                                         stat->unsatisfied_edges += 1;
727                                 }
728
729                                 if (nodes_interfere(co->cenv, an->irn, neigh->irn)) {
730                                         stat->aff_int += 1;
731                                         stat->inevit_costs += neigh->costs;
732                                 }
733
734                         }
735                 }
736         }
737
738         bitset_free(seen);
739 }
740
741 /******************************************************************************
742    _____                 _        _____ _
743   / ____|               | |      / ____| |
744  | |  __ _ __ __ _ _ __ | |__   | (___ | |_ ___  _ __ __ _  __ _  ___
745  | | |_ | '__/ _` | '_ \| '_ \   \___ \| __/ _ \| '__/ _` |/ _` |/ _ \
746  | |__| | | | (_| | |_) | | | |  ____) | || (_) | | | (_| | (_| |  __/
747   \_____|_|  \__,_| .__/|_| |_| |_____/ \__\___/|_|  \__,_|\__, |\___|
748                   | |                                       __/ |
749                   |_|                                      |___/
750  ******************************************************************************/
751
752 static int compare_affinity_node_t(const void *k1, const void *k2, size_t size)
753 {
754         const affinity_node_t *n1 = (const affinity_node_t*)k1;
755         const affinity_node_t *n2 = (const affinity_node_t*)k2;
756         (void) size;
757
758         return (n1->irn != n2->irn);
759 }
760
761 static void add_edge(copy_opt_t *co, ir_node *n1, ir_node *n2, int costs)
762 {
763         affinity_node_t new_node, *node;
764         neighb_t        *nbr;
765         int             allocnew = 1;
766
767         new_node.irn        = n1;
768         new_node.degree     = 0;
769         new_node.neighbours = NULL;
770         node = set_insert(affinity_node_t, co->nodes, &new_node, sizeof(new_node), hash_irn(new_node.irn));
771
772         for (nbr = node->neighbours; nbr; nbr = nbr->next)
773                 if (nbr->irn == n2) {
774                         allocnew = 0;
775                         break;
776                 }
777
778         /* if we did not find n2 in n1's neighbourhood insert it */
779         if (allocnew) {
780                 nbr        = OALLOC(&co->obst, neighb_t);
781                 nbr->irn   = n2;
782                 nbr->costs = 0;
783                 nbr->next  = node->neighbours;
784
785                 node->neighbours = nbr;
786                 node->degree++;
787         }
788
789         /* now nbr points to n1's neighbour-entry of n2 */
790         nbr->costs += costs;
791 }
792
793 static inline void add_edges(copy_opt_t *co, ir_node *n1, ir_node *n2, int costs)
794 {
795         if (! be_ifg_connected(co->cenv->ifg, n1, n2)) {
796                 add_edge(co, n1, n2, costs);
797                 add_edge(co, n2, n1, costs);
798         }
799 }
800
801 static void build_graph_walker(ir_node *irn, void *env)
802 {
803         const arch_register_req_t *req;
804         copy_opt_t                *co  = (copy_opt_t*)env;
805         int pos, max;
806
807         if (get_irn_mode(irn) == mode_T)
808                 return;
809         req = arch_get_irn_register_req(irn);
810         if (req->cls != co->cls || arch_register_req_is(req, ignore))
811                 return;
812
813         if (is_Reg_Phi(irn)) { /* Phis */
814                 for (pos=0, max=get_irn_arity(irn); pos<max; ++pos) {
815                         ir_node *arg = get_irn_n(irn, pos);
816                         add_edges(co, irn, arg, co->get_costs(irn, pos));
817                 }
818         } else if (is_Perm_Proj(irn)) { /* Perms */
819                 ir_node *arg = get_Perm_src(irn);
820                 add_edges(co, irn, arg, co->get_costs(irn, -1));
821         } else if (arch_register_req_is(req, should_be_same)) {
822                 const unsigned other = req->other_same;
823                 int i;
824
825                 for (i = 0; 1U << i <= other; ++i) {
826                         if (other & (1U << i)) {
827                                 ir_node *other = get_irn_n(skip_Proj(irn), i);
828                                 if (!arch_irn_is_ignore(other))
829                                         add_edges(co, irn, other, co->get_costs(irn, -1));
830                         }
831                 }
832         }
833 }
834
835 void co_build_graph_structure(copy_opt_t *co)
836 {
837         obstack_init(&co->obst);
838         co->nodes = new_set(compare_affinity_node_t, 32);
839
840         irg_walk_graph(co->irg, build_graph_walker, NULL, co);
841 }
842
843 void co_free_graph_structure(copy_opt_t *co)
844 {
845         ASSERT_GS_AVAIL(co);
846
847         del_set(co->nodes);
848         obstack_free(&co->obst, NULL);
849         co->nodes = NULL;
850 }
851
852 int co_gs_is_optimizable(copy_opt_t *co, ir_node *irn)
853 {
854         affinity_node_t new_node, *n;
855
856         ASSERT_GS_AVAIL(co);
857
858         new_node.irn = irn;
859         n = set_find(affinity_node_t, co->nodes, &new_node, sizeof(new_node), hash_irn(new_node.irn));
860         if (n) {
861                 return (n->degree > 0);
862         } else
863                 return 0;
864 }
865
866 static int co_dump_appel_disjoint_constraints(const copy_opt_t *co, ir_node *a, ir_node *b)
867 {
868         ir_node *nodes[]  = { a, b };
869         bitset_t *constr[] = { NULL, NULL };
870         int j;
871
872         constr[0] = bitset_alloca(co->cls->n_regs);
873         constr[1] = bitset_alloca(co->cls->n_regs);
874
875         for (j = 0; j < 2; ++j) {
876                 const arch_register_req_t *req = arch_get_irn_register_req(nodes[j]);
877                 if (arch_register_req_is(req, limited))
878                         rbitset_copy_to_bitset(req->limited, constr[j]);
879                 else
880                         bitset_set_all(constr[j]);
881
882         }
883
884         return !bitset_intersect(constr[0], constr[1]);
885 }
886
887 /**
888  * Dump the interference graph according to the Appel/George coalescing contest file format.
889  * See: http://www.cs.princeton.edu/~appel/coalesce/format.html
890  * @note Requires graph structure.
891  * @param co The copy opt object.
892  * @param f  A file to dump to.
893  */
894 static void co_dump_appel_graph(const copy_opt_t *co, FILE *f)
895 {
896         be_ifg_t *ifg       = co->cenv->ifg;
897         int      *color_map = ALLOCAN(int, co->cls->n_regs);
898         int      *node_map  = XMALLOCN(int, get_irg_last_idx(co->irg) + 1);
899         ir_graph *irg       = co->irg;
900         be_irg_t *birg      = be_birg_from_irg(irg);
901
902         ir_node *irn;
903         nodes_iter_t it;
904         neighbours_iter_t nit;
905         int n, n_regs;
906         unsigned i;
907
908         n_regs = 0;
909         for (i = 0; i < co->cls->n_regs; ++i) {
910                 const arch_register_t *reg = &co->cls->regs[i];
911                 if (rbitset_is_set(birg->allocatable_regs, reg->global_index)) {
912                         color_map[i] = n_regs++;
913                 } else {
914                         color_map[i] = -1;
915                 }
916         }
917
918         /*
919          * n contains the first node number.
920          * the values below n are the pre-colored register nodes
921          */
922
923         n = n_regs;
924         be_ifg_foreach_node(ifg, &it, irn) {
925                 if (arch_irn_is_ignore(irn))
926                         continue;
927                 node_map[get_irn_idx(irn)] = n++;
928         }
929
930         fprintf(f, "%d %d\n", n, n_regs);
931
932         be_ifg_foreach_node(ifg, &it, irn) {
933                 arch_register_req_t const *const req = arch_get_irn_register_req(irn);
934                 if (arch_register_req_is(req, ignore))
935                         continue;
936
937                 int              idx = node_map[get_irn_idx(irn)];
938                 affinity_node_t *a   = get_affinity_info(co, irn);
939
940                 if (arch_register_req_is(req, limited)) {
941                         for (i = 0; i < co->cls->n_regs; ++i) {
942                                 if (!rbitset_is_set(req->limited, i) && color_map[i] >= 0)
943                                         fprintf(f, "%d %d -1\n", color_map[i], idx);
944                         }
945                 }
946
947                 be_ifg_foreach_neighbour(ifg, &nit, irn, adj) {
948                         if (!arch_irn_is_ignore(adj) &&
949                                         !co_dump_appel_disjoint_constraints(co, irn, adj)) {
950                                 int adj_idx = node_map[get_irn_idx(adj)];
951                                 if (idx < adj_idx)
952                                         fprintf(f, "%d %d -1\n", idx, adj_idx);
953                         }
954                 }
955
956                 if (a) {
957                         co_gs_foreach_neighb(a, n) {
958                                 if (!arch_irn_is_ignore(n->irn)) {
959                                         int n_idx = node_map[get_irn_idx(n->irn)];
960                                         if (idx < n_idx)
961                                                 fprintf(f, "%d %d %d\n", idx, n_idx, (int) n->costs);
962                                 }
963                         }
964                 }
965         }
966
967         xfree(node_map);
968 }
969
970 static FILE *my_open(const be_chordal_env_t *env, const char *prefix,
971                      const char *suffix)
972 {
973         FILE *result;
974         char buf[1024];
975         size_t i, n;
976         char *tu_name;
977         const char *cup_name = be_get_irg_main_env(env->irg)->cup_name;
978
979         n = strlen(cup_name);
980         tu_name = XMALLOCN(char, n + 1);
981         strcpy(tu_name, cup_name);
982         for (i = 0; i < n; ++i)
983                 if (tu_name[i] == '.')
984                         tu_name[i] = '_';
985
986
987         ir_snprintf(buf, sizeof(buf), "%s%s_%F_%s%s", prefix, tu_name, env->irg, env->cls->name, suffix);
988         xfree(tu_name);
989         result = fopen(buf, "wt");
990         if (result == NULL) {
991                 panic("Couldn't open '%s' for writing.", buf);
992         }
993
994         return result;
995 }
996
997 void co_driver(be_chordal_env_t *cenv)
998 {
999         ir_timer_t          *timer = ir_timer_new();
1000         co_complete_stats_t before, after;
1001         copy_opt_t          *co;
1002         int                 was_optimal = 0;
1003
1004         assert(selected_copyopt);
1005
1006         /* skip copymin if algo is 'none' */
1007         if (selected_copyopt->copyopt == void_algo)
1008                 return;
1009
1010         be_assure_live_chk(cenv->irg);
1011
1012         co = new_copy_opt(cenv, cost_func);
1013         co_build_ou_structure(co);
1014         co_build_graph_structure(co);
1015
1016         co_complete_stats(co, &before);
1017
1018         stat_ev_ull("co_aff_nodes",    before.aff_nodes);
1019         stat_ev_ull("co_aff_edges",    before.aff_edges);
1020         stat_ev_ull("co_max_costs",    before.max_costs);
1021         stat_ev_ull("co_inevit_costs", before.inevit_costs);
1022         stat_ev_ull("co_aff_int",      before.aff_int);
1023
1024         stat_ev_ull("co_init_costs",   before.costs);
1025         stat_ev_ull("co_init_unsat",   before.unsatisfied_edges);
1026
1027         if (dump_flags & DUMP_BEFORE) {
1028                 FILE *f = my_open(cenv, "", "-before.vcg");
1029                 be_dump_ifg_co(f, co, style_flags & CO_IFG_DUMP_LABELS, style_flags & CO_IFG_DUMP_COLORS);
1030                 fclose(f);
1031         }
1032
1033         /* if the algo can improve results, provide an initial solution with heur1 */
1034         if (improve && selected_copyopt->can_improve_existing) {
1035                 co_complete_stats_t stats;
1036
1037                 /* produce a heuristic solution */
1038                 co_solve_heuristic(co);
1039
1040                 /* do the stats and provide the current costs */
1041                 co_complete_stats(co, &stats);
1042                 stat_ev_ull("co_prepare_costs", stats.costs);
1043         }
1044
1045         /* perform actual copy minimization */
1046         ir_timer_reset_and_start(timer);
1047         was_optimal = selected_copyopt->copyopt(co);
1048         ir_timer_stop(timer);
1049
1050         stat_ev_dbl("co_time", ir_timer_elapsed_msec(timer));
1051         stat_ev_ull("co_optimal", was_optimal);
1052         ir_timer_free(timer);
1053
1054         if (dump_flags & DUMP_AFTER) {
1055                 FILE *f = my_open(cenv, "", "-after.vcg");
1056                 be_dump_ifg_co(f, co, style_flags & CO_IFG_DUMP_LABELS, style_flags & CO_IFG_DUMP_COLORS);
1057                 fclose(f);
1058         }
1059
1060         co_complete_stats(co, &after);
1061
1062         if (do_stats) {
1063                 unsigned long long optimizable_costs = after.max_costs - after.inevit_costs;
1064                 unsigned long long evitable          = after.costs     - after.inevit_costs;
1065
1066                 ir_printf("%30F ", cenv->irg);
1067                 printf("%10s %10llu%10llu%10llu", cenv->cls->name, after.max_costs, before.costs, after.inevit_costs);
1068
1069                 if (optimizable_costs > 0)
1070                         printf("%10llu %5.2f\n", after.costs, (evitable * 100.0) / optimizable_costs);
1071                 else
1072                         printf("%10llu %5s\n", after.costs, "-");
1073         }
1074
1075         /* Dump the interference graph in Appel's format. */
1076         if (dump_flags & DUMP_APPEL) {
1077                 FILE *f = my_open(cenv, "", ".apl");
1078                 fprintf(f, "# %llu %llu\n", after.costs, after.unsatisfied_edges);
1079                 co_dump_appel_graph(co, f);
1080                 fclose(f);
1081         }
1082
1083         stat_ev_ull("co_after_costs", after.costs);
1084         stat_ev_ull("co_after_unsat", after.unsatisfied_edges);
1085
1086         co_free_graph_structure(co);
1087         co_free_ou_structure(co);
1088         free_copy_opt(co);
1089 }