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