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