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