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