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