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