ad5ca80d0c43f429cfb6c041ab2f3cc0a055aca1
[libfirm] / ir / be / becopyheur4.c
1 /*
2  * Copyright (C) 1995-2011 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       Simple copy minimization heuristics.
23  * @author      Christian Wuerdig
24  * @date        27.04.2007
25  *
26  * This is the C implementation of the mst algorithm
27  * originally written in Java by Sebastian Hack.
28  * (also known as "heur3" :)
29  * Performs simple copy minimization.
30  */
31 #include "config.h"
32
33 #define DISABLE_STATEV
34
35 #include <float.h>
36
37 #include "array.h"
38 #include "irnode_t.h"
39 #include "bitset.h"
40 #include "raw_bitset.h"
41 #include "irnodemap.h"
42 #include "pqueue.h"
43 #include "xmalloc.h"
44 #include "pdeq.h"
45 #include "irprintf.h"
46 #include "util.h"
47 #include "irtools.h"
48 #include "error.h"
49 #include "list.h"
50 #include "statev.h"
51
52 #include "bearch.h"
53 #include "beifg.h"
54 #include "be_t.h"
55 #include "becopyopt_t.h"
56 #include "bemodule.h"
57
58
59 #define COL_COST_INFEASIBLE       DBL_MAX
60 #define AFF_NEIGHBOUR_FIX_BENEFIT 128.0
61 #define NEIGHBOUR_CONSTR_COSTS    64.0
62
63
64 #ifdef DEBUG_libfirm
65
66 #define DBG_AFF_CHUNK(env, level, chunk) do { if (firm_dbg_get_mask(dbg) & (level)) dbg_aff_chunk((env), (chunk)); } while (0)
67 #define DBG_COL_COST(env, level, cost)   do { if (firm_dbg_get_mask(dbg) & (level)) dbg_col_cost((env), (cost)); } while (0)
68
69 static firm_dbg_module_t *dbg = NULL;
70
71 #else
72
73 #define DBG_AFF_CHUNK(env, level, chunk)
74 #define DBG_COL_COST(env, level, cost)
75
76 #endif
77
78 typedef float real_t;
79 #define REAL(C)   (C ## f)
80
81 static unsigned last_chunk_id   = 0;
82 static int recolor_limit        = 7;
83 static double dislike_influence = REAL(0.1);
84
85 typedef struct col_cost_t {
86         int     col;
87         real_t  cost;
88 } col_cost_t;
89
90 /**
91  * An affinity chunk.
92  */
93 typedef struct aff_chunk_t {
94         const ir_node  **n;                     /**< An ARR_F containing all nodes of the chunk. */
95         const ir_node  **interfere;             /**< An ARR_F containing all inference. */
96         int              weight;                /**< Weight of this chunk */
97         unsigned         weight_consistent : 1; /**< Set if the weight is consistent. */
98         unsigned         deleted           : 1; /**< For debugging: Set if the was deleted. */
99         unsigned         id;                    /**< An id of this chunk. */
100         unsigned         visited;
101         list_head        list;
102         col_cost_t       color_affinity[1];
103 } aff_chunk_t;
104
105 /**
106  * An affinity edge.
107  */
108 typedef struct aff_edge_t {
109         const ir_node *src;                   /**< Source node. */
110         const ir_node *tgt;                   /**< Target node. */
111         int           weight;                 /**< The weight of this edge. */
112 } aff_edge_t;
113
114 /* main coalescing environment */
115 typedef struct co_mst_env_t {
116         int              n_regs;         /**< number of regs in class */
117         int              k;              /**< number of non-ignore registers in class */
118         bitset_t         *allocatable_regs; /**< set containing all global ignore registers */
119         ir_nodemap        map;           /**< phase object holding data for nodes */
120         struct obstack    obst;
121         pqueue_t         *chunks;        /**< priority queue for chunks */
122         list_head         chunklist;     /**< list holding all chunks */
123         be_ifg_t         *ifg;           /**< the interference graph */
124         copy_opt_t       *co;            /**< the copy opt object */
125         unsigned         chunk_visited;
126         col_cost_t      **single_cols;
127 } co_mst_env_t;
128
129 /* stores coalescing related information for a node */
130 typedef struct co_mst_irn_t {
131         const ir_node    *irn;              /**< the irn this information belongs to */
132         aff_chunk_t      *chunk;            /**< the chunk this irn belongs to */
133         bitset_t         *adm_colors;       /**< set of admissible colors for this irn */
134         ir_node          **int_neighs;      /**< array of all interfering neighbours (cached for speed reasons) */
135         int              n_neighs;          /**< length of the interfering neighbours array. */
136         int              int_aff_neigh;     /**< number of interfering affinity neighbours */
137         int              col;               /**< color currently assigned */
138         int              init_col;          /**< the initial color */
139         int              tmp_col;           /**< a temporary assigned color */
140         unsigned         fixed     : 1;     /**< the color is fixed */
141         struct list_head list;              /**< Queue for coloring undo. */
142         real_t           constr_factor;
143 } co_mst_irn_t;
144
145 /**
146  * In case there is no phase information for irn, initialize it.
147  */
148 static co_mst_irn_t *co_mst_irn_init(co_mst_env_t *env, const ir_node *irn)
149 {
150         co_mst_irn_t *res = OALLOC(&env->obst, co_mst_irn_t);
151
152         const arch_register_req_t *req;
153         neighbours_iter_t nodes_it;
154         ir_node  *neigh;
155         unsigned len;
156
157         res->irn           = irn;
158         res->chunk         = NULL;
159         res->fixed         = 0;
160         res->tmp_col       = -1;
161         res->int_neighs    = NULL;
162         res->int_aff_neigh = 0;
163         res->col           = arch_register_get_index(arch_get_irn_register(irn));
164         res->init_col      = res->col;
165         INIT_LIST_HEAD(&res->list);
166
167         DB((dbg, LEVEL_4, "Creating phase info for %+F\n", irn));
168
169         /* set admissible registers */
170         res->adm_colors = bitset_obstack_alloc(&env->obst, env->n_regs);
171
172         /* Exclude colors not assignable to the irn */
173         req = arch_get_irn_register_req(irn);
174         if (arch_register_req_is(req, limited)) {
175                 rbitset_copy_to_bitset(req->limited, res->adm_colors);
176         } else {
177                 bitset_set_all(res->adm_colors);
178         }
179
180         /* exclude global ignore registers as well */
181         bitset_and(res->adm_colors, env->allocatable_regs);
182
183         /* compute the constraint factor */
184         res->constr_factor = (real_t) (1 + env->n_regs - bitset_popcount(res->adm_colors)) / env->n_regs;
185
186         /* set the number of interfering affinity neighbours to -1, they are calculated later */
187         res->int_aff_neigh = -1;
188
189         /* build list of interfering neighbours */
190         len = 0;
191         be_ifg_foreach_neighbour(env->ifg, &nodes_it, irn, neigh) {
192                 if (!arch_irn_is_ignore(neigh)) {
193                         obstack_ptr_grow(&env->obst, neigh);
194                         ++len;
195                 }
196         }
197         res->int_neighs = (ir_node**)obstack_finish(&env->obst);
198         res->n_neighs   = len;
199         return res;
200 }
201
202 static co_mst_irn_t *get_co_mst_irn(co_mst_env_t *env, const ir_node *node)
203 {
204         co_mst_irn_t *res = (co_mst_irn_t*)ir_nodemap_get(&env->map, node);
205         if (res == NULL) {
206                 res = co_mst_irn_init(env, node);
207                 ir_nodemap_insert(&env->map, node, res);
208         }
209         return res;
210 }
211
212 typedef int decide_func_t(const co_mst_irn_t *node, int col);
213
214 #ifdef DEBUG_libfirm
215
216 /**
217  * Write a chunk to stderr for debugging.
218  */
219 static void dbg_aff_chunk(const co_mst_env_t *env, const aff_chunk_t *c)
220 {
221         int i, l;
222         (void) env;
223         if (c->weight_consistent)
224                 ir_fprintf(stderr, " $%d ", c->weight);
225         ir_fprintf(stderr, "{");
226         for (i = 0, l = ARR_LEN(c->n); i < l; ++i) {
227                 const ir_node *n = c->n[i];
228                 ir_fprintf(stderr, " %+F,", n);
229         }
230         ir_fprintf(stderr, "}");
231 }
232
233 /**
234  * Dump all admissible colors to stderr.
235  */
236 static void dbg_admissible_colors(const co_mst_env_t *env, const co_mst_irn_t *node)
237 {
238         size_t idx;
239         (void) env;
240
241         if (bitset_popcount(node->adm_colors) < 1)
242                 fprintf(stderr, "no admissible colors?!?");
243         else {
244                 bitset_foreach(node->adm_colors, idx) {
245                         ir_fprintf(stderr, " %zu", idx);
246                 }
247         }
248 }
249
250 /**
251  * Dump color-cost pairs to stderr.
252  */
253 static void dbg_col_cost(const co_mst_env_t *env, const col_cost_t *cost)
254 {
255         int i;
256         for (i = 0; i < env->n_regs; ++i)
257                 fprintf(stderr, " (%d, %.4f)", cost[i].col, cost[i].cost);
258 }
259
260 #endif /* DEBUG_libfirm */
261
262 static inline int get_mst_irn_col(const co_mst_irn_t *node)
263 {
264         return node->tmp_col >= 0 ? node->tmp_col : node->col;
265 }
266
267 /**
268  * @return 1 if node @p node has color @p col, 0 otherwise.
269  */
270 static int decider_has_color(const co_mst_irn_t *node, int col)
271 {
272         return get_mst_irn_col(node) == col;
273 }
274
275 /**
276  * @return 1 if node @p node has not color @p col, 0 otherwise.
277  */
278 static int decider_hasnot_color(const co_mst_irn_t *node, int col)
279 {
280         return get_mst_irn_col(node) != col;
281 }
282
283 /**
284  * Always returns true.
285  */
286 static int decider_always_yes(const co_mst_irn_t *node, int col)
287 {
288         (void) node;
289         (void) col;
290         return 1;
291 }
292
293 /** compares two affinity edges by its weight */
294 static int cmp_aff_edge(const void *a, const void *b)
295 {
296         const aff_edge_t *e1 = (const aff_edge_t*)a;
297         const aff_edge_t *e2 = (const aff_edge_t*)b;
298
299         if (e2->weight == e1->weight) {
300                 if (e2->src->node_idx == e1->src->node_idx)
301                         return QSORT_CMP(e2->tgt->node_idx, e1->tgt->node_idx);
302                 else
303                         return QSORT_CMP(e2->src->node_idx, e1->src->node_idx);
304         }
305         /* sort in descending order */
306         return QSORT_CMP(e2->weight, e1->weight);
307 }
308
309 /** compares to color-cost pairs */
310 static __attribute__((unused)) int cmp_col_cost_lt(const void *a, const void *b)
311 {
312         const col_cost_t *c1 = (const col_cost_t*)a;
313         const col_cost_t *c2 = (const col_cost_t*)b;
314         real_t diff = c1->cost - c2->cost;
315         return (diff > 0) - (diff < 0);
316 }
317
318 static int cmp_col_cost_gt(const void *a, const void *b)
319 {
320         const col_cost_t *c1 = (const col_cost_t*)a;
321         const col_cost_t *c2 = (const col_cost_t*)b;
322         real_t diff = c2->cost - c1->cost;
323
324         if (diff == 0.0)
325                 return QSORT_CMP(c1->col, c2->col);
326
327         return (diff > 0) - (diff < 0);
328 }
329
330 /**
331  * Creates a new affinity chunk
332  */
333 static inline aff_chunk_t *new_aff_chunk(co_mst_env_t *env)
334 {
335         aff_chunk_t *c = XMALLOCF(aff_chunk_t, color_affinity, env->n_regs);
336         c->n                 = NEW_ARR_F(const ir_node *, 0);
337         c->interfere         = NEW_ARR_F(const ir_node *, 0);
338         c->weight            = -1;
339         c->weight_consistent = 0;
340         c->deleted           = 0;
341         c->id                = ++last_chunk_id;
342         c->visited           = 0;
343         list_add(&c->list, &env->chunklist);
344         return c;
345 }
346
347 /**
348  * Frees all memory allocated by an affinity chunk.
349  */
350 static inline void delete_aff_chunk(aff_chunk_t *c)
351 {
352         list_del(&c->list);
353         DEL_ARR_F(c->interfere);
354         DEL_ARR_F(c->n);
355         c->deleted = 1;
356         free(c);
357 }
358
359 /**
360  * binary search of sorted nodes.
361  *
362  * @return the position where n is found in the array arr or ~pos
363  * if the nodes is not here.
364  */
365 static inline int nodes_bsearch(const ir_node **arr, const ir_node *n)
366 {
367         int hi = ARR_LEN(arr);
368         int lo = 0;
369
370         while (lo < hi) {
371                 int md = lo + ((hi - lo) >> 1);
372
373                 if (arr[md] == n)
374                         return md;
375                 if (arr[md] < n)
376                         lo = md + 1;
377                 else
378                         hi = md;
379         }
380
381         return ~lo;
382 }
383
384 /** Check if a node n can be found inside arr. */
385 static int node_contains(const ir_node **arr, const ir_node *n)
386 {
387         int i = nodes_bsearch(arr, n);
388         return i >= 0;
389 }
390
391 /**
392  * Insert a node into the sorted nodes list.
393  *
394  * @return 1 if the node was inserted, 0 else
395  */
396 static int nodes_insert(const ir_node ***arr, const ir_node *irn)
397 {
398         int idx = nodes_bsearch(*arr, irn);
399
400         if (idx < 0) {
401                 int i, n = ARR_LEN(*arr);
402                 const ir_node **l;
403
404                 ARR_APP1(const ir_node *, *arr, irn);
405
406                 /* move it */
407                 idx = ~idx;
408                 l = *arr;
409                 for (i = n - 1; i >= idx; --i)
410                         l[i + 1] = l[i];
411                 l[idx] = irn;
412                 return 1;
413         }
414         return 0;
415 }
416
417 /**
418  * Adds a node to an affinity chunk
419  */
420 static inline void aff_chunk_add_node(aff_chunk_t *c, co_mst_irn_t *node)
421 {
422         int i;
423
424         if (! nodes_insert(&c->n, node->irn))
425                 return;
426
427         c->weight_consistent = 0;
428         node->chunk          = c;
429
430         for (i = node->n_neighs - 1; i >= 0; --i) {
431                 ir_node *neigh = node->int_neighs[i];
432                 nodes_insert(&c->interfere, neigh);
433         }
434 }
435
436 /**
437  * Check if affinity chunk @p chunk interferes with node @p irn.
438  */
439 static inline int aff_chunk_interferes(const aff_chunk_t *chunk, const ir_node *irn)
440 {
441         return node_contains(chunk->interfere, irn);
442 }
443
444 /**
445  * Check if there are interference edges from c1 to c2.
446  * @param c1    A chunk
447  * @param c2    Another chunk
448  * @return 1 if there are interferences between nodes of c1 and c2, 0 otherwise.
449  */
450 static inline int aff_chunks_interfere(const aff_chunk_t *c1, const aff_chunk_t *c2)
451 {
452         int i;
453
454         if (c1 == c2)
455                 return 0;
456
457         /* check if there is a node in c2 having an interfering neighbor in c1 */
458         for (i = ARR_LEN(c2->n) - 1; i >= 0; --i) {
459                 const ir_node *irn = c2->n[i];
460
461                 if (node_contains(c1->interfere, irn))
462                         return 1;
463         }
464         return 0;
465 }
466
467 /**
468  * Returns the affinity chunk of @p irn or creates a new
469  * one with @p irn as element if there is none assigned.
470  */
471 static inline aff_chunk_t *get_aff_chunk(co_mst_env_t *env, const ir_node *irn)
472 {
473         co_mst_irn_t *node = get_co_mst_irn(env, irn);
474         return node->chunk;
475 }
476
477 /**
478  * Let chunk(src) absorb the nodes of chunk(tgt) (only possible when there
479  * are no interference edges from chunk(src) to chunk(tgt)).
480  * @return 1 if successful, 0 if not possible
481  */
482 static int aff_chunk_absorb(co_mst_env_t *env, const ir_node *src, const ir_node *tgt)
483 {
484         aff_chunk_t *c1 = get_aff_chunk(env, src);
485         aff_chunk_t *c2 = get_aff_chunk(env, tgt);
486
487 #ifdef DEBUG_libfirm
488                 DB((dbg, LEVEL_4, "Attempt to let c1 (id %u): ", c1 ? c1->id : 0));
489                 if (c1) {
490                         DBG_AFF_CHUNK(env, LEVEL_4, c1);
491                 } else {
492                         DB((dbg, LEVEL_4, "{%+F}", src));
493                 }
494                 DB((dbg, LEVEL_4, "\n\tabsorb c2 (id %u): ", c2 ? c2->id : 0));
495                 if (c2) {
496                         DBG_AFF_CHUNK(env, LEVEL_4, c2);
497                 } else {
498                         DB((dbg, LEVEL_4, "{%+F}", tgt));
499                 }
500                 DB((dbg, LEVEL_4, "\n"));
501 #endif
502
503         if (c1 == NULL) {
504                 if (c2 == NULL) {
505                         /* no chunk exists */
506                         co_mst_irn_t *mirn = get_co_mst_irn(env, src);
507                         int i;
508
509                         for (i = mirn->n_neighs - 1; i >= 0; --i) {
510                                 if (mirn->int_neighs[i] == tgt)
511                                         break;
512                         }
513                         if (i < 0) {
514                                 /* create one containing both nodes */
515                                 c1 = new_aff_chunk(env);
516                                 aff_chunk_add_node(c1, get_co_mst_irn(env, src));
517                                 aff_chunk_add_node(c1, get_co_mst_irn(env, tgt));
518                                 goto absorbed;
519                         }
520                 } else {
521                         /* c2 already exists */
522                         if (! aff_chunk_interferes(c2, src)) {
523                                 aff_chunk_add_node(c2, get_co_mst_irn(env, src));
524                                 goto absorbed;
525                         }
526                 }
527         } else if (c2 == NULL) {
528                 /* c1 already exists */
529                 if (! aff_chunk_interferes(c1, tgt)) {
530                         aff_chunk_add_node(c1, get_co_mst_irn(env, tgt));
531                         goto absorbed;
532                 }
533         } else if (c1 != c2 && ! aff_chunks_interfere(c1, c2)) {
534                 int idx, len;
535
536                 for (idx = 0, len = ARR_LEN(c2->n); idx < len; ++idx)
537                         aff_chunk_add_node(c1, get_co_mst_irn(env, c2->n[idx]));
538
539                 for (idx = 0, len = ARR_LEN(c2->interfere); idx < len; ++idx) {
540                         const ir_node *irn = c2->interfere[idx];
541                         nodes_insert(&c1->interfere, irn);
542                 }
543
544                 c1->weight_consistent = 0;
545
546                 delete_aff_chunk(c2);
547                 goto absorbed;
548         }
549         DB((dbg, LEVEL_4, " ... c1 interferes with c2, skipped\n"));
550         return 0;
551
552 absorbed:
553         DB((dbg, LEVEL_4, " ... absorbed\n"));
554         return 1;
555 }
556
557 /**
558  * Assures that the weight of the given chunk is consistent.
559  */
560 static void aff_chunk_assure_weight(co_mst_env_t *env, aff_chunk_t *c)
561 {
562         if (! c->weight_consistent) {
563                 int w = 0;
564                 int idx, len, i;
565
566                 for (i = 0; i < env->n_regs; ++i) {
567                         c->color_affinity[i].col = i;
568                         c->color_affinity[i].cost = REAL(0.0);
569                 }
570
571                 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
572                         const ir_node         *n       = c->n[idx];
573                         const affinity_node_t *an      = get_affinity_info(env->co, n);
574                         co_mst_irn_t          *node    = get_co_mst_irn(env, n);
575
576                         node->chunk = c;
577                         if (node->constr_factor > REAL(0.0)) {
578                                 size_t col;
579                                 bitset_foreach (node->adm_colors, col)
580                                         c->color_affinity[col].cost += node->constr_factor;
581                         }
582
583                         if (an != NULL) {
584                                 neighb_t *neigh;
585                                 co_gs_foreach_neighb(an, neigh) {
586                                         const ir_node *m = neigh->irn;
587
588                                         if (arch_irn_is_ignore(m))
589                                                 continue;
590
591                                         w += node_contains(c->n, m) ? neigh->costs : 0;
592                                 }
593                         }
594                 }
595
596                 for (i = 0; i < env->n_regs; ++i)
597                         c->color_affinity[i].cost *= (REAL(1.0) / ARR_LEN(c->n));
598
599                 c->weight            = w;
600                 // c->weight            = bitset_popcount(c->nodes);
601                 c->weight_consistent = 1;
602         }
603 }
604
605 /**
606  * Count the number of interfering affinity neighbours
607  */
608 static int count_interfering_aff_neighs(co_mst_env_t *env, const affinity_node_t *an)
609 {
610         const neighb_t     *neigh;
611         const ir_node      *irn  = an->irn;
612         const co_mst_irn_t *node = get_co_mst_irn(env, irn);
613         int                res   = 0;
614
615         co_gs_foreach_neighb(an, neigh) {
616                 const ir_node *n = neigh->irn;
617                 int           i;
618
619                 if (arch_irn_is_ignore(n))
620                         continue;
621
622                 /* check if the affinity neighbour interfere */
623                 for (i = 0; i < node->n_neighs; ++i) {
624                         if (node->int_neighs[i] == n) {
625                                 ++res;
626                                 break;
627                         }
628                 }
629         }
630         return res;
631 }
632
633
634 /**
635  * Build chunks of nodes connected by affinity edges.
636  * We start at the heaviest affinity edge.
637  * The chunks of the two edge-defining nodes will be
638  * merged if there are no interference edges from one
639  * chunk to the other.
640  */
641 static void build_affinity_chunks(co_mst_env_t *env)
642 {
643         nodes_iter_t nodes_it;
644         aff_edge_t  *edges    = NEW_ARR_F(aff_edge_t, 0);
645         ir_node     *n;
646         int         i, len;
647         aff_chunk_t *curr_chunk;
648         size_t      pn;
649
650         /* at first we create the affinity edge objects */
651         be_ifg_foreach_node(env->ifg, &nodes_it, n) {
652                 int             n_idx = get_irn_idx(n);
653                 co_mst_irn_t    *n1;
654                 affinity_node_t *an;
655
656                 if (arch_irn_is_ignore(n))
657                         continue;
658
659                 n1 = get_co_mst_irn(env, n);
660                 an = get_affinity_info(env->co, n);
661
662                 if (an != NULL) {
663                         neighb_t *neigh;
664
665                         if (n1->int_aff_neigh < 0)
666                                 n1->int_aff_neigh = count_interfering_aff_neighs(env, an);
667
668                         /* build the affinity edges */
669                         co_gs_foreach_neighb(an, neigh) {
670                                 const ir_node *m     = neigh->irn;
671                                 int            m_idx = get_irn_idx(m);
672
673                                 /* record the edge in only one direction */
674                                 if (n_idx < m_idx) {
675                                         co_mst_irn_t *n2;
676                                         aff_edge_t   edge;
677
678                                         /* skip ignore nodes */
679                                         if (arch_irn_is_ignore(m))
680                                                 continue;
681
682                                         edge.src = n;
683                                         edge.tgt = m;
684
685                                         n2 = get_co_mst_irn(env, m);
686                                         if (n2->int_aff_neigh < 0) {
687                                                 affinity_node_t *am = get_affinity_info(env->co, m);
688                                                 n2->int_aff_neigh = count_interfering_aff_neighs(env, am);
689                                         }
690                                         /*
691                                          * these weights are pure hackery ;-).
692                                          * It's not chriswue's fault but mine.
693                                          */
694                                         edge.weight = neigh->costs;
695                                         ARR_APP1(aff_edge_t, edges, edge);
696                                 }
697                         }
698                 }
699         }
700
701         /* now: sort edges and build the affinity chunks */
702         len = ARR_LEN(edges);
703         qsort(edges, len, sizeof(edges[0]), cmp_aff_edge);
704         for (i = 0; i < len; ++i) {
705                 DBG((dbg, LEVEL_1, "edge (%u,%u) %f\n", edges[i].src->node_idx, edges[i].tgt->node_idx, edges[i].weight));
706
707                 (void)aff_chunk_absorb(env, edges[i].src, edges[i].tgt);
708         }
709
710         /* now insert all chunks into a priority queue */
711         list_for_each_entry(aff_chunk_t, curr_chunk, &env->chunklist, list) {
712                 aff_chunk_assure_weight(env, curr_chunk);
713
714                 DBG((dbg, LEVEL_1, "entry #%u", curr_chunk->id));
715                 DBG_AFF_CHUNK(env, LEVEL_1, curr_chunk);
716                 DBG((dbg, LEVEL_1, "\n"));
717
718                 pqueue_put(env->chunks, curr_chunk, curr_chunk->weight);
719         }
720
721         for (pn = 0; pn < ARR_LEN(env->map.data); ++pn) {
722                 co_mst_irn_t *mirn = env->map.data[pn];
723                 if (mirn == NULL)
724                         continue;
725                 if (mirn->chunk != NULL)
726                         continue;
727
728                 /* no chunk is allocated so far, do it now */
729                 aff_chunk_t *curr_chunk = new_aff_chunk(env);
730                 aff_chunk_add_node(curr_chunk, mirn);
731
732                 aff_chunk_assure_weight(env, curr_chunk);
733
734                 DBG((dbg, LEVEL_1, "entry #%u", curr_chunk->id));
735                 DBG_AFF_CHUNK(env, LEVEL_1, curr_chunk);
736                 DBG((dbg, LEVEL_1, "\n"));
737
738                 pqueue_put(env->chunks, curr_chunk, curr_chunk->weight);
739         }
740
741         DEL_ARR_F(edges);
742 }
743
744 static __attribute__((unused)) void chunk_order_nodes(co_mst_env_t *env, aff_chunk_t *chunk)
745 {
746         pqueue_t      *grow       = new_pqueue();
747         ir_node const *max_node   = NULL;
748         int            max_weight = 0;
749         size_t         i;
750
751         for (i = ARR_LEN(chunk->n); i != 0;) {
752                 const ir_node   *irn = chunk->n[--i];
753                 affinity_node_t *an  = get_affinity_info(env->co, irn);
754                 int w = 0;
755                 neighb_t *neigh;
756
757                 if (arch_irn_is_ignore(irn))
758                         continue;
759
760                 if (an) {
761                         co_gs_foreach_neighb(an, neigh)
762                                 w += neigh->costs;
763
764                         if (w > max_weight) {
765                                 max_weight = w;
766                                 max_node   = irn;
767                         }
768                 }
769         }
770
771         if (max_node) {
772                 bitset_t *visited = bitset_malloc(get_irg_last_idx(env->co->irg));
773
774                 for (i = ARR_LEN(chunk->n); i != 0;)
775                         bitset_set(visited, get_irn_idx(chunk->n[--i]));
776
777                 pqueue_put(grow, (void *) max_node, max_weight);
778                 bitset_clear(visited, get_irn_idx(max_node));
779                 i = 0;
780                 while (!pqueue_empty(grow)) {
781                         ir_node *irn = (ir_node*)pqueue_pop_front(grow);
782                         affinity_node_t *an = get_affinity_info(env->co, irn);
783                         neighb_t        *neigh;
784
785                         if (arch_irn_is_ignore(irn))
786                                 continue;
787
788                         assert(i <= ARR_LEN(chunk->n));
789                         chunk->n[i++] = irn;
790
791                         assert(an);
792
793                         /* build the affinity edges */
794                         co_gs_foreach_neighb(an, neigh) {
795                                 co_mst_irn_t *node = get_co_mst_irn(env, neigh->irn);
796
797                                 if (bitset_is_set(visited, get_irn_idx(node->irn))) {
798                                         pqueue_put(grow, (void *) neigh->irn, neigh->costs);
799                                         bitset_clear(visited, get_irn_idx(node->irn));
800                                 }
801                         }
802                 }
803
804                 del_pqueue(grow);
805                 bitset_free(visited);
806         }
807 }
808
809 /**
810  * Greedy collect affinity neighbours into thew new chunk @p chunk starting at node @p node.
811  */
812 static void expand_chunk_from(co_mst_env_t *env, co_mst_irn_t *node, bitset_t *visited,
813         aff_chunk_t *chunk, aff_chunk_t *orig_chunk, decide_func_t *decider, int col)
814 {
815         waitq *nodes = new_waitq();
816
817         DBG((dbg, LEVEL_1, "\n\tExpanding new chunk (#%u) from %+F, color %d:", chunk->id, node->irn, col));
818
819         /* init queue and chunk */
820         waitq_put(nodes, node);
821         bitset_set(visited, get_irn_idx(node->irn));
822         aff_chunk_add_node(chunk, node);
823         DB((dbg, LEVEL_1, " %+F", node->irn));
824
825         /* as long as there are nodes in the queue */
826         while (! waitq_empty(nodes)) {
827                 co_mst_irn_t    *n  = (co_mst_irn_t*)waitq_get(nodes);
828                 affinity_node_t *an = get_affinity_info(env->co, n->irn);
829
830                 /* check all affinity neighbors */
831                 if (an != NULL) {
832                         neighb_t *neigh;
833                         co_gs_foreach_neighb(an, neigh) {
834                                 const ir_node *m    = neigh->irn;
835                                 int            m_idx = get_irn_idx(m);
836                                 co_mst_irn_t *n2;
837
838                                 if (arch_irn_is_ignore(m))
839                                         continue;
840
841                                 n2 = get_co_mst_irn(env, m);
842
843                                 if (! bitset_is_set(visited, m_idx)  &&
844                                         decider(n2, col)                 &&
845                                         ! n2->fixed                      &&
846                                         ! aff_chunk_interferes(chunk, m) &&
847                                         node_contains(orig_chunk->n, m))
848                                 {
849                                         /*
850                                                 following conditions are met:
851                                                 - neighbour is not visited
852                                                 - neighbour likes the color
853                                                 - neighbour has not yet a fixed color
854                                                 - the new chunk doesn't interfere with the neighbour
855                                                 - neighbour belongs or belonged once to the original chunk
856                                         */
857                                         bitset_set(visited, m_idx);
858                                         aff_chunk_add_node(chunk, n2);
859                                         DB((dbg, LEVEL_1, " %+F", n2->irn));
860                                         /* enqueue for further search */
861                                         waitq_put(nodes, n2);
862                                 }
863                         }
864                 }
865         }
866
867         DB((dbg, LEVEL_1, "\n"));
868
869         del_waitq(nodes);
870 }
871
872 /**
873  * Fragment the given chunk into chunks having given color and not having given color.
874  */
875 static aff_chunk_t *fragment_chunk(co_mst_env_t *env, int col, aff_chunk_t *c, waitq *tmp)
876 {
877         bitset_t    *visited = bitset_malloc(get_irg_last_idx(env->co->irg));
878         int         idx, len;
879         aff_chunk_t *best = NULL;
880
881         for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
882                 const ir_node *irn;
883                 co_mst_irn_t  *node;
884                 aff_chunk_t   *tmp_chunk;
885                 decide_func_t *decider;
886                 int           check_for_best;
887
888                 irn = c->n[idx];
889                 if (bitset_is_set(visited, get_irn_idx(irn)))
890                         continue;
891
892                 node = get_co_mst_irn(env, irn);
893
894                 if (get_mst_irn_col(node) == col) {
895                         decider        = decider_has_color;
896                         check_for_best = 1;
897                         DBG((dbg, LEVEL_4, "\tcolor %d wanted\n", col));
898                 }
899                 else {
900                         decider        = decider_hasnot_color;
901                         check_for_best = 0;
902                         DBG((dbg, LEVEL_4, "\tcolor %d forbidden\n", col));
903                 }
904
905                 /* create a new chunk starting at current node */
906                 tmp_chunk = new_aff_chunk(env);
907                 waitq_put(tmp, tmp_chunk);
908                 expand_chunk_from(env, node, visited, tmp_chunk, c, decider, col);
909                 assert(ARR_LEN(tmp_chunk->n) > 0 && "No nodes added to chunk");
910
911                 /* remember the local best */
912                 aff_chunk_assure_weight(env, tmp_chunk);
913                 if (check_for_best && (! best || best->weight < tmp_chunk->weight))
914                         best = tmp_chunk;
915         }
916
917         assert(best && "No chunk found?");
918         bitset_free(visited);
919         return best;
920 }
921
922 /**
923  * Resets the temporary fixed color of all nodes within wait queue @p nodes.
924  * ATTENTION: the queue is empty after calling this function!
925  */
926 static inline void reject_coloring(struct list_head *nodes)
927 {
928         co_mst_irn_t *n, *temp;
929         DB((dbg, LEVEL_4, "\treject coloring for"));
930         list_for_each_entry_safe(co_mst_irn_t, n, temp, nodes, list) {
931                 DB((dbg, LEVEL_4, " %+F", n->irn));
932                 assert(n->tmp_col >= 0);
933                 n->tmp_col = -1;
934                 list_del_init(&n->list);
935         }
936         DB((dbg, LEVEL_4, "\n"));
937 }
938
939 static inline void materialize_coloring(struct list_head *nodes)
940 {
941         co_mst_irn_t *n, *temp;
942         list_for_each_entry_safe(co_mst_irn_t, n, temp, nodes, list) {
943                 assert(n->tmp_col >= 0);
944                 n->col     = n->tmp_col;
945                 n->tmp_col = -1;
946                 list_del_init(&n->list);
947         }
948 }
949
950 static inline void set_temp_color(co_mst_irn_t *node, int col, struct list_head *changed)
951 {
952         assert(col >= 0);
953         assert(!node->fixed);
954         assert(node->tmp_col < 0);
955         assert(node->list.next == &node->list && node->list.prev == &node->list);
956         assert(bitset_is_set(node->adm_colors, col));
957
958         list_add_tail(&node->list, changed);
959         node->tmp_col = col;
960 }
961
962 static inline int is_loose(co_mst_irn_t *node)
963 {
964         return !node->fixed && node->tmp_col < 0;
965 }
966
967 /**
968  * Determines the costs for each color if it would be assigned to node @p node.
969  */
970 static void determine_color_costs(co_mst_env_t *env, co_mst_irn_t *node, col_cost_t *costs)
971 {
972         int   *neigh_cols = ALLOCAN(int, env->n_regs);
973         int    n_loose    = 0;
974         real_t coeff;
975         int    i;
976
977         for (i = 0; i < env->n_regs; ++i) {
978                 neigh_cols[i] = 0;
979                 costs[i].col = i;
980                 costs[i].cost = bitset_is_set(node->adm_colors, i) ? node->constr_factor : REAL(0.0);
981         }
982
983         for (i = 0; i < node->n_neighs; ++i) {
984                 co_mst_irn_t *n = get_co_mst_irn(env, node->int_neighs[i]);
985                 int col = get_mst_irn_col(n);
986                 if (is_loose(n)) {
987                         ++n_loose;
988                         ++neigh_cols[col];
989                 } else
990                         costs[col].cost = REAL(0.0);
991         }
992
993         if (n_loose > 0) {
994                 coeff = REAL(1.0) / n_loose;
995                 for (i = 0; i < env->n_regs; ++i)
996                         costs[i].cost *= REAL(1.0) - coeff * neigh_cols[i];
997         }
998 }
999
1000 /* need forward declaration due to recursive call */
1001 static int recolor_nodes(co_mst_env_t *env, co_mst_irn_t *node, col_cost_t *costs, struct list_head *changed_ones, int depth, int *max_depth, int *trip);
1002
1003 /**
1004  * Tries to change node to a color but @p explude_col.
1005  * @return 1 if succeeded, 0 otherwise.
1006  */
1007 static int change_node_color_excluded(co_mst_env_t *env, co_mst_irn_t *node, int exclude_col, struct list_head *changed, int depth, int *max_depth, int *trip)
1008 {
1009         int col = get_mst_irn_col(node);
1010         int res = 0;
1011
1012         /* neighbours has already a different color -> good, temporary fix it */
1013         if (col != exclude_col) {
1014                 if (is_loose(node))
1015                         set_temp_color(node, col, changed);
1016                 return 1;
1017         }
1018
1019         /* The node has the color it should not have _and_ has not been visited yet. */
1020         if (is_loose(node)) {
1021                 col_cost_t *costs = ALLOCAN(col_cost_t, env->n_regs);
1022
1023                 /* Get the costs for giving the node a specific color. */
1024                 determine_color_costs(env, node, costs);
1025
1026                 /* Since the node must not have the not_col, set the costs for that color to "infinity" */
1027                 costs[exclude_col].cost = REAL(0.0);
1028
1029                 /* sort the colors according costs, cheapest first. */
1030                 qsort(costs, env->n_regs, sizeof(costs[0]), cmp_col_cost_gt);
1031
1032                 /* Try recoloring the node using the color list. */
1033                 res = recolor_nodes(env, node, costs, changed, depth + 1, max_depth, trip);
1034         }
1035
1036         return res;
1037 }
1038
1039 /**
1040  * Tries to bring node @p node to cheapest color and color all interfering neighbours with other colors.
1041  * ATTENTION: Expect @p costs already sorted by increasing costs.
1042  * @return 1 if coloring could be applied, 0 otherwise.
1043  */
1044 static int recolor_nodes(co_mst_env_t *env, co_mst_irn_t *node, col_cost_t *costs, struct list_head *changed, int depth, int *max_depth, int *trip)
1045 {
1046         int   i;
1047         struct list_head local_changed;
1048
1049         ++*trip;
1050         if (depth > *max_depth)
1051                 *max_depth = depth;
1052
1053         DBG((dbg, LEVEL_4, "\tRecoloring %+F with color-costs", node->irn));
1054         DBG_COL_COST(env, LEVEL_4, costs);
1055         DB((dbg, LEVEL_4, "\n"));
1056
1057         if (depth >= recolor_limit) {
1058                 DBG((dbg, LEVEL_4, "\tHit recolor limit\n"));
1059                 return 0;
1060         }
1061
1062         for (i = 0; i < env->n_regs; ++i) {
1063                 int tgt_col  = costs[i].col;
1064                 int neigh_ok = 1;
1065                 int j;
1066
1067                 /* If the costs for that color (and all successive) are infinite, bail out we won't make it anyway. */
1068                 if (costs[i].cost == REAL(0.0)) {
1069                         DBG((dbg, LEVEL_4, "\tAll further colors forbidden\n"));
1070                         return 0;
1071                 }
1072
1073                 /* Set the new color of the node and mark the node as temporarily fixed. */
1074                 assert(node->tmp_col < 0 && "Node must not have been temporary fixed.");
1075                 INIT_LIST_HEAD(&local_changed);
1076                 set_temp_color(node, tgt_col, &local_changed);
1077                 DBG((dbg, LEVEL_4, "\tTemporary setting %+F to color %d\n", node->irn, tgt_col));
1078
1079                 /* try to color all interfering neighbours with current color forbidden */
1080                 for (j = 0; j < node->n_neighs; ++j) {
1081                         co_mst_irn_t *nn;
1082                         ir_node      *neigh;
1083
1084                         neigh = node->int_neighs[j];
1085
1086                         if (arch_irn_is_ignore(neigh))
1087                                 continue;
1088
1089                         nn = get_co_mst_irn(env, neigh);
1090                         DB((dbg, LEVEL_4, "\tHandling neighbour %+F, at position %d (fixed: %d, tmp_col: %d, col: %d)\n",
1091                                 neigh, j, nn->fixed, nn->tmp_col, nn->col));
1092
1093                         /*
1094                                 Try to change the color of the neighbor and record all nodes which
1095                                 get changed in the tmp list. Add this list to the "changed" list for
1096                                 that color. If we did not succeed to change the color of the neighbor,
1097                                 we bail out and try the next color.
1098                         */
1099                         if (get_mst_irn_col(nn) == tgt_col) {
1100                                 /* try to color neighbour with tgt_col forbidden */
1101                                 neigh_ok = change_node_color_excluded(env, nn, tgt_col, &local_changed, depth + 1, max_depth, trip);
1102
1103                                 if (!neigh_ok)
1104                                         break;
1105                         }
1106                 }
1107
1108                 /*
1109                         We managed to assign the target color to all neighbors, so from the perspective
1110                         of the current node, every thing was ok and we can return safely.
1111                 */
1112                 if (neigh_ok) {
1113                         /* append the local_changed ones to global ones */
1114                         list_splice(&local_changed, changed);
1115                         return 1;
1116                 }
1117                 else {
1118                         /* coloring of neighbours failed, so we try next color */
1119                         reject_coloring(&local_changed);
1120                 }
1121         }
1122
1123         DBG((dbg, LEVEL_4, "\tAll colors failed\n"));
1124         return 0;
1125 }
1126
1127 /**
1128  * Tries to bring node @p node and all its neighbours to color @p tgt_col.
1129  * @return 1 if color @p col could be applied, 0 otherwise
1130  */
1131 static int change_node_color(co_mst_env_t *env, co_mst_irn_t *node, int tgt_col, struct list_head *changed)
1132 {
1133         int col = get_mst_irn_col(node);
1134
1135         /* if node already has the target color -> good, temporary fix it */
1136         if (col == tgt_col) {
1137                 DBG((dbg, LEVEL_4, "\t\tCNC: %+F has already color %d, fix temporary\n", node->irn, tgt_col));
1138                 if (is_loose(node))
1139                         set_temp_color(node, tgt_col, changed);
1140                 return 1;
1141         }
1142
1143         /*
1144                 Node has not yet a fixed color and target color is admissible
1145                 -> try to recolor node and its affinity neighbours
1146         */
1147         if (is_loose(node) && bitset_is_set(node->adm_colors, tgt_col)) {
1148                 col_cost_t *costs = env->single_cols[tgt_col];
1149                 int res, max_depth, trip;
1150
1151                 max_depth = 0;
1152                 trip      = 0;
1153
1154                 DBG((dbg, LEVEL_4, "\t\tCNC: Attempt to recolor %+F ===>>\n", node->irn));
1155                 res = recolor_nodes(env, node, costs, changed, 0, &max_depth, &trip);
1156                 DBG((dbg, LEVEL_4, "\t\tCNC: <<=== Recoloring of %+F %s\n", node->irn, res ? "succeeded" : "failed"));
1157                 stat_ev_int("heur4_recolor_depth_max", max_depth);
1158                 stat_ev_int("heur4_recolor_trip", trip);
1159
1160
1161                 return res;
1162         }
1163
1164 #ifdef DEBUG_libfirm
1165                 if (firm_dbg_get_mask(dbg) & LEVEL_4) {
1166                         if (!is_loose(node))
1167                                 DB((dbg, LEVEL_4, "\t\tCNC: %+F has already fixed color %d\n", node->irn, col));
1168                         else {
1169                                 DB((dbg, LEVEL_4, "\t\tCNC: color %d not admissible for %+F (", tgt_col, node->irn));
1170                                 dbg_admissible_colors(env, node);
1171                                 DB((dbg, LEVEL_4, ")\n"));
1172                         }
1173                 }
1174 #endif
1175
1176         return 0;
1177 }
1178
1179 /**
1180  * Tries to color an affinity chunk (or at least a part of it).
1181  * Inserts uncolored parts of the chunk as a new chunk into the priority queue.
1182  */
1183 static void color_aff_chunk(co_mst_env_t *env, aff_chunk_t *c)
1184 {
1185         aff_chunk_t *best_chunk   = NULL;
1186         int         n_nodes       = ARR_LEN(c->n);
1187         int         best_color    = -1;
1188         int         n_int_chunks  = 0;
1189         waitq       *tmp_chunks   = new_waitq();
1190         waitq       *best_starts  = NULL;
1191         col_cost_t  *order        = ALLOCANZ(col_cost_t, env->n_regs);
1192         bitset_t    *visited;
1193         int         i;
1194         size_t      idx;
1195         size_t      len;
1196         size_t      nidx;
1197         size_t      pos;
1198         struct list_head changed;
1199
1200         DB((dbg, LEVEL_2, "fragmentizing chunk #%u", c->id));
1201         DBG_AFF_CHUNK(env, LEVEL_2, c);
1202         DB((dbg, LEVEL_2, "\n"));
1203
1204         stat_ev_ctx_push_fmt("heur4_color_chunk", "%u", c->id);
1205
1206         ++env->chunk_visited;
1207
1208         /* compute color preference */
1209         for (pos = 0, len = ARR_LEN(c->interfere); pos < len; ++pos) {
1210                 const ir_node *n = c->interfere[pos];
1211                 co_mst_irn_t *node = get_co_mst_irn(env, n);
1212                 aff_chunk_t *chunk = node->chunk;
1213
1214                 if (is_loose(node) && chunk && chunk->visited < env->chunk_visited) {
1215                         assert(!chunk->deleted);
1216                         chunk->visited = env->chunk_visited;
1217                         ++n_int_chunks;
1218
1219                         aff_chunk_assure_weight(env, chunk);
1220                         for (i = 0; i < env->n_regs; ++i)
1221                                 order[i].cost += chunk->color_affinity[i].cost;
1222                 }
1223         }
1224
1225         for (i = 0; i < env->n_regs; ++i) {
1226                 real_t dislike = n_int_chunks > 0 ? REAL(1.0) - order[i].cost / n_int_chunks : REAL(0.0);
1227                 order[i].col  = i;
1228                 order[i].cost = (REAL(1.0) - dislike_influence) * c->color_affinity[i].cost + dislike_influence * dislike;
1229         }
1230
1231         qsort(order, env->n_regs, sizeof(order[0]), cmp_col_cost_gt);
1232
1233         DBG_COL_COST(env, LEVEL_2, order);
1234         DB((dbg, LEVEL_2, "\n"));
1235
1236         /* check which color is the "best" for the given chunk.
1237          * if we found a color which was ok for all nodes, we take it
1238          * and do not look further. (see did_all flag usage below.)
1239          * If we have many colors which fit all nodes it is hard to decide
1240          * which one to take anyway.
1241          * TODO Sebastian: Perhaps we should at all nodes and figure out
1242          * a suitable color using costs as done above (determine_color_costs).
1243          */
1244         for (i = 0; i < env->k; ++i) {
1245                 int         col = order[i].col;
1246                 waitq       *good_starts;
1247                 aff_chunk_t *local_best;
1248                 int          n_succeeded;
1249
1250                 /* skip ignore colors */
1251                 if (!bitset_is_set(env->allocatable_regs, col))
1252                         continue;
1253
1254                 DB((dbg, LEVEL_2, "\ttrying color %d\n", col));
1255
1256                 n_succeeded = 0;
1257                 good_starts = new_waitq();
1258
1259                 /* try to bring all nodes of given chunk to the current color. */
1260                 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1261                         const ir_node   *irn  = c->n[idx];
1262                         co_mst_irn_t    *node = get_co_mst_irn(env, irn);
1263                         int              good;
1264
1265                         assert(! node->fixed && "Node must not have a fixed color.");
1266                         DB((dbg, LEVEL_4, "\t\tBringing %+F from color %d to color %d ...\n", irn, node->col, col));
1267
1268                         /*
1269                                 The order of the colored nodes is important, so we record the successfully
1270                                 colored ones in the order they appeared.
1271                         */
1272                         INIT_LIST_HEAD(&changed);
1273                         stat_ev_tim_push();
1274                         good = change_node_color(env, node, col, &changed);
1275                         stat_ev_tim_pop("heur4_recolor");
1276                         if (good) {
1277                                 waitq_put(good_starts, node);
1278                                 materialize_coloring(&changed);
1279                                 node->fixed = 1;
1280                         }
1281
1282                         else
1283                                 reject_coloring(&changed);
1284
1285                         n_succeeded += good;
1286                         DB((dbg, LEVEL_4, "\t\t... %+F attempt from %d to %d %s\n", irn, node->col, col, good ? "succeeded" : "failed"));
1287                 }
1288
1289                 /* unfix all nodes */
1290                 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1291                         co_mst_irn_t *node = get_co_mst_irn(env, c->n[idx]);
1292                         node->fixed = 0;
1293                 }
1294
1295                 /* try next color when failed */
1296                 if (n_succeeded == 0) {
1297                         del_waitq(good_starts);
1298                         continue;
1299                 }
1300
1301                 /* fragment the chunk according to the coloring */
1302                 local_best = fragment_chunk(env, col, c, tmp_chunks);
1303
1304                 /* search the best of the good list
1305                    and make it the new best if it is better than the current */
1306                 if (local_best) {
1307                         aff_chunk_assure_weight(env, local_best);
1308
1309                         DB((dbg, LEVEL_3, "\t\tlocal best chunk (id %u) for color %d: ", local_best->id, col));
1310                         DBG_AFF_CHUNK(env, LEVEL_3, local_best);
1311
1312                         if (! best_chunk || best_chunk->weight < local_best->weight) {
1313                                 best_chunk = local_best;
1314                                 best_color = col;
1315                                 if (best_starts)
1316                                         del_waitq(best_starts);
1317                                 best_starts = good_starts;
1318                                 DB((dbg, LEVEL_3, "\n\t\t... setting global best chunk (id %u), color %d\n", best_chunk->id, best_color));
1319                         } else {
1320                                 DB((dbg, LEVEL_3, "\n\t\t... omitting, global best is better\n"));
1321                                 del_waitq(good_starts);
1322                         }
1323                 }
1324                 else {
1325                         del_waitq(good_starts);
1326                 }
1327
1328                 /* if all nodes were recolored, bail out */
1329                 if (n_succeeded == n_nodes)
1330                         break;
1331         }
1332
1333         stat_ev_int("heur4_colors_tried", i);
1334
1335         /* free all intermediate created chunks except best one */
1336         while (! waitq_empty(tmp_chunks)) {
1337                 aff_chunk_t *tmp = (aff_chunk_t*)waitq_get(tmp_chunks);
1338                 if (tmp != best_chunk)
1339                         delete_aff_chunk(tmp);
1340         }
1341         del_waitq(tmp_chunks);
1342
1343         /* return if coloring failed */
1344         if (! best_chunk) {
1345                 if (best_starts)
1346                         del_waitq(best_starts);
1347                 return;
1348         }
1349
1350         DB((dbg, LEVEL_2, "\tbest chunk #%u ", best_chunk->id));
1351         DBG_AFF_CHUNK(env, LEVEL_2, best_chunk);
1352         DB((dbg, LEVEL_2, "using color %d\n", best_color));
1353
1354         for (idx = 0, len = ARR_LEN(best_chunk->n); idx < len; ++idx) {
1355                 const ir_node *irn  = best_chunk->n[idx];
1356                 co_mst_irn_t  *node = get_co_mst_irn(env, irn);
1357                 int res;
1358
1359                 /* bring the node to the color. */
1360                 DB((dbg, LEVEL_4, "\tManifesting color %d for %+F, chunk #%u\n", best_color, node->irn, best_chunk->id));
1361                 INIT_LIST_HEAD(&changed);
1362                 stat_ev_tim_push();
1363                 res = change_node_color(env, node, best_color, &changed);
1364                 stat_ev_tim_pop("heur4_recolor");
1365                 if (res) {
1366                         materialize_coloring(&changed);
1367                         node->fixed = 1;
1368                 }
1369                 assert(list_empty(&changed));
1370         }
1371
1372         /* remove the nodes in best chunk from original chunk */
1373         len = ARR_LEN(best_chunk->n);
1374         for (idx = 0; idx < len; ++idx) {
1375                 const ir_node *irn = best_chunk->n[idx];
1376                 int pos = nodes_bsearch(c->n, irn);
1377
1378                 if (pos > 0)
1379                         c->n[pos] = NULL;
1380         }
1381         len = ARR_LEN(c->n);
1382         for (idx = nidx = 0; idx < len; ++idx) {
1383                 const ir_node *irn = c->n[idx];
1384
1385                 if (irn != NULL) {
1386                         c->n[nidx++] = irn;
1387                 }
1388         }
1389         ARR_SHRINKLEN(c->n, nidx);
1390
1391
1392         /* we have to get the nodes back into the original chunk because they are scattered over temporary chunks */
1393         for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1394                 const ir_node *n  = c->n[idx];
1395                 co_mst_irn_t  *nn = get_co_mst_irn(env, n);
1396                 nn->chunk = c;
1397         }
1398
1399         /* fragment the remaining chunk */
1400         visited = bitset_malloc(get_irg_last_idx(env->co->irg));
1401         for (idx = 0, len = ARR_LEN(best_chunk->n); idx < len; ++idx)
1402                 bitset_set(visited, get_irn_idx(best_chunk->n[idx]));
1403
1404         for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1405                 const ir_node *irn = c->n[idx];
1406                 if (! bitset_is_set(visited, get_irn_idx(irn))) {
1407                         aff_chunk_t  *new_chunk = new_aff_chunk(env);
1408                         co_mst_irn_t *node      = get_co_mst_irn(env, irn);
1409
1410                         expand_chunk_from(env, node, visited, new_chunk, c, decider_always_yes, 0);
1411                         aff_chunk_assure_weight(env, new_chunk);
1412                         pqueue_put(env->chunks, new_chunk, new_chunk->weight);
1413                 }
1414         }
1415
1416         for (idx = 0, len = ARR_LEN(best_chunk->n); idx < len; ++idx) {
1417                 const ir_node *n  = best_chunk->n[idx];
1418                 co_mst_irn_t  *nn = get_co_mst_irn(env, n);
1419                 nn->chunk = NULL;
1420         }
1421
1422         /* clear obsolete chunks and free some memory */
1423         delete_aff_chunk(best_chunk);
1424         bitset_free(visited);
1425         if (best_starts)
1426                 del_waitq(best_starts);
1427
1428         stat_ev_ctx_pop("heur4_color_chunk");
1429 }
1430
1431 /**
1432  * Main driver for mst safe coalescing algorithm.
1433  */
1434 static int co_solve_heuristic_mst(copy_opt_t *co)
1435 {
1436         unsigned     n_regs            = co->cls->n_regs;
1437         bitset_t     *allocatable_regs = bitset_alloca(n_regs);
1438         unsigned     i, j;
1439         size_t       k;
1440         size_t       pn;
1441         ir_node      *irn;
1442         co_mst_env_t mst_env;
1443
1444         last_chunk_id = 0;
1445
1446         stat_ev_tim_push();
1447
1448         /* init phase */
1449         ir_nodemap_init(&mst_env.map, co->irg);
1450         obstack_init(&mst_env.obst);
1451
1452         be_put_allocatable_regs(co->cenv->irg, co->cls, allocatable_regs);
1453         k = bitset_popcount(allocatable_regs);
1454
1455         mst_env.n_regs           = n_regs;
1456         mst_env.k                = k;
1457         mst_env.chunks           = new_pqueue();
1458         mst_env.co               = co;
1459         mst_env.allocatable_regs = allocatable_regs;
1460         mst_env.ifg              = co->cenv->ifg;
1461         INIT_LIST_HEAD(&mst_env.chunklist);
1462         mst_env.chunk_visited    = 0;
1463         mst_env.single_cols      = OALLOCN(&mst_env.obst, col_cost_t*, n_regs);
1464
1465         for (i = 0; i < n_regs; ++i) {
1466                 col_cost_t *vec = OALLOCN(&mst_env.obst, col_cost_t, n_regs);
1467
1468                 mst_env.single_cols[i] = vec;
1469                 for (j = 0; j < n_regs; ++j) {
1470                         vec[j].col  = j;
1471                         vec[j].cost = REAL(0.0);
1472                 }
1473                 vec[i].col  = 0;
1474                 vec[0].col  = i;
1475                 vec[0].cost = REAL(1.0);
1476         }
1477
1478         DBG((dbg, LEVEL_1, "==== Coloring %+F, class %s ====\n", co->irg, co->cls->name));
1479
1480         /* build affinity chunks */
1481         stat_ev_tim_push();
1482         build_affinity_chunks(&mst_env);
1483         stat_ev_tim_pop("heur4_initial_chunk");
1484
1485         /* color chunks as long as there are some */
1486         while (! pqueue_empty(mst_env.chunks)) {
1487                 aff_chunk_t *chunk = (aff_chunk_t*)pqueue_pop_front(mst_env.chunks);
1488
1489                 color_aff_chunk(&mst_env, chunk);
1490                 DB((dbg, LEVEL_4, "<<<====== Coloring chunk (%u) done\n", chunk->id));
1491                 delete_aff_chunk(chunk);
1492         }
1493
1494         /* apply coloring */
1495         for (pn = 0; pn < ARR_LEN(mst_env.map.data); ++pn) {
1496                 co_mst_irn_t *mirn = mst_env.map.data[pn];
1497                 const arch_register_t *reg;
1498                 if (mirn == NULL)
1499                         continue;
1500                 irn = get_idx_irn(co->irg, pn);
1501                 if (arch_irn_is_ignore(irn))
1502                         continue;
1503
1504                 /* skip nodes where color hasn't changed */
1505                 if (mirn->init_col == mirn->col)
1506                         continue;
1507
1508                 reg = arch_register_for_index(co->cls, mirn->col);
1509                 arch_set_irn_register(irn, reg);
1510                 DB((dbg, LEVEL_1, "%+F set color from %d to %d\n", irn, mirn->init_col, mirn->col));
1511         }
1512
1513         /* free allocated memory */
1514         del_pqueue(mst_env.chunks);
1515         obstack_free(&mst_env.obst, NULL);
1516         ir_nodemap_destroy(&mst_env.map);
1517
1518         stat_ev_tim_pop("heur4_total");
1519
1520         return 0;
1521 }
1522
1523 static const lc_opt_table_entry_t options[] = {
1524         LC_OPT_ENT_INT      ("limit", "limit recoloring",  &recolor_limit),
1525         LC_OPT_ENT_DBL      ("di",    "dislike influence", &dislike_influence),
1526         LC_OPT_LAST
1527 };
1528
1529 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_copyheur4)
1530 void be_init_copyheur4(void)
1531 {
1532         lc_opt_entry_t *be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
1533         lc_opt_entry_t *ra_grp = lc_opt_get_grp(be_grp, "ra");
1534         lc_opt_entry_t *chordal_grp = lc_opt_get_grp(ra_grp, "chordal");
1535         lc_opt_entry_t *co_grp = lc_opt_get_grp(chordal_grp, "co");
1536         lc_opt_entry_t *heur4_grp = lc_opt_get_grp(co_grp, "heur4");
1537
1538         static co_algo_info copyheur = {
1539                 co_solve_heuristic_mst, 0
1540         };
1541
1542         lc_opt_add_table(heur4_grp, options);
1543         be_register_copyopt("heur4", &copyheur);
1544
1545         FIRM_DBG_REGISTER(dbg, "firm.be.co.heur4");
1546 }