2 * Copyright (C) 1995-2011 University of Karlsruhe. All right reserved.
4 * This file is part of libFirm.
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.
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.
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
22 * @brief Simple copy minimization heuristics.
23 * @author Christian Wuerdig
26 * This is the C implementation of the mst algorithm
27 * originally written in Java by Sebastian Hack.
28 * (also known as "heur3" :)
29 * Performs simple copy minimization.
33 #define DISABLE_STATEV
40 #include "raw_bitset.h"
41 #include "irnodemap.h"
55 #include "becopyopt_t.h"
59 #define COL_COST_INFEASIBLE DBL_MAX
60 #define AFF_NEIGHBOUR_FIX_BENEFIT 128.0
61 #define NEIGHBOUR_CONSTR_COSTS 64.0
66 #define DBG_AFF_CHUNK(env, level, chunk) do { if (firm_dbg_get_mask(dbg) & (level)) dbg_aff_chunk((env), (chunk)); } while (0)
67 #define DBG_COL_COST(env, level, cost) do { if (firm_dbg_get_mask(dbg) & (level)) dbg_col_cost((env), (cost)); } while (0)
69 static firm_dbg_module_t *dbg = NULL;
73 #define DBG_AFF_CHUNK(env, level, chunk)
74 #define DBG_COL_COST(env, level, cost)
79 #define REAL(C) (C ## f)
81 static unsigned last_chunk_id = 0;
82 static int recolor_limit = 7;
83 static double dislike_influence = REAL(0.1);
85 typedef struct col_cost_t {
93 typedef struct aff_chunk_t {
94 const ir_node **n; /**< An ARR_F containing all nodes of the chunk. */
95 const ir_node **interfere; /**< An ARR_F containing all inference. */
96 int weight; /**< Weight of this chunk */
97 unsigned weight_consistent : 1; /**< Set if the weight is consistent. */
98 unsigned deleted : 1; /**< For debugging: Set if the was deleted. */
99 unsigned id; /**< An id of this chunk. */
102 col_cost_t color_affinity[1];
108 typedef struct aff_edge_t {
109 const ir_node *src; /**< Source node. */
110 const ir_node *tgt; /**< Target node. */
111 int weight; /**< The weight of this edge. */
114 /* main coalescing environment */
115 typedef struct co_mst_env_t {
116 int n_regs; /**< number of regs in class */
117 int k; /**< number of non-ignore registers in class */
118 bitset_t *allocatable_regs; /**< set containing all global ignore registers */
119 ir_nodemap map; /**< phase object holding data for nodes */
121 pqueue_t *chunks; /**< priority queue for chunks */
122 list_head chunklist; /**< list holding all chunks */
123 be_ifg_t *ifg; /**< the interference graph */
124 copy_opt_t *co; /**< the copy opt object */
125 unsigned chunk_visited;
126 col_cost_t **single_cols;
129 /* stores coalescing related information for a node */
130 typedef struct co_mst_irn_t {
131 const ir_node *irn; /**< the irn this information belongs to */
132 aff_chunk_t *chunk; /**< the chunk this irn belongs to */
133 bitset_t *adm_colors; /**< set of admissible colors for this irn */
134 ir_node **int_neighs; /**< array of all interfering neighbours (cached for speed reasons) */
135 int n_neighs; /**< length of the interfering neighbours array. */
136 int int_aff_neigh; /**< number of interfering affinity neighbours */
137 int col; /**< color currently assigned */
138 int init_col; /**< the initial color */
139 int tmp_col; /**< a temporary assigned color */
140 unsigned fixed : 1; /**< the color is fixed */
141 struct list_head list; /**< Queue for coloring undo. */
142 real_t constr_factor;
146 * In case there is no phase information for irn, initialize it.
148 static co_mst_irn_t *co_mst_irn_init(co_mst_env_t *env, const ir_node *irn)
150 co_mst_irn_t *res = OALLOC(&env->obst, co_mst_irn_t);
152 const arch_register_req_t *req;
153 neighbours_iter_t nodes_it;
161 res->int_neighs = NULL;
162 res->int_aff_neigh = 0;
163 res->col = arch_register_get_index(arch_get_irn_register(irn));
164 res->init_col = res->col;
165 INIT_LIST_HEAD(&res->list);
167 DB((dbg, LEVEL_4, "Creating phase info for %+F\n", irn));
169 /* set admissible registers */
170 res->adm_colors = bitset_obstack_alloc(&env->obst, env->n_regs);
172 /* Exclude colors not assignable to the irn */
173 req = arch_get_irn_register_req(irn);
174 if (arch_register_req_is(req, limited)) {
175 rbitset_copy_to_bitset(req->limited, res->adm_colors);
177 bitset_set_all(res->adm_colors);
180 /* exclude global ignore registers as well */
181 bitset_and(res->adm_colors, env->allocatable_regs);
183 /* compute the constraint factor */
184 res->constr_factor = (real_t) (1 + env->n_regs - bitset_popcount(res->adm_colors)) / env->n_regs;
186 /* set the number of interfering affinity neighbours to -1, they are calculated later */
187 res->int_aff_neigh = -1;
189 /* build list of interfering neighbours */
191 be_ifg_foreach_neighbour(env->ifg, &nodes_it, irn, neigh) {
192 if (!arch_irn_is_ignore(neigh)) {
193 obstack_ptr_grow(&env->obst, neigh);
197 res->int_neighs = (ir_node**)obstack_finish(&env->obst);
202 static co_mst_irn_t *get_co_mst_irn(co_mst_env_t *env, const ir_node *node)
204 co_mst_irn_t *res = ir_nodemap_get(co_mst_irn_t, &env->map, node);
206 res = co_mst_irn_init(env, node);
207 ir_nodemap_insert(&env->map, node, res);
212 typedef int decide_func_t(const co_mst_irn_t *node, int col);
217 * Write a chunk to stderr for debugging.
219 static void dbg_aff_chunk(const co_mst_env_t *env, const aff_chunk_t *c)
223 if (c->weight_consistent)
224 ir_fprintf(stderr, " $%d ", c->weight);
225 ir_fprintf(stderr, "{");
226 for (i = 0, l = ARR_LEN(c->n); i < l; ++i) {
227 const ir_node *n = c->n[i];
228 ir_fprintf(stderr, " %+F,", n);
230 ir_fprintf(stderr, "}");
234 * Dump all admissible colors to stderr.
236 static void dbg_admissible_colors(const co_mst_env_t *env, const co_mst_irn_t *node)
241 if (bitset_popcount(node->adm_colors) < 1)
242 fprintf(stderr, "no admissible colors?!?");
244 bitset_foreach(node->adm_colors, idx) {
245 ir_fprintf(stderr, " %zu", idx);
251 * Dump color-cost pairs to stderr.
253 static void dbg_col_cost(const co_mst_env_t *env, const col_cost_t *cost)
256 for (i = 0; i < env->n_regs; ++i)
257 fprintf(stderr, " (%d, %.4f)", cost[i].col, cost[i].cost);
260 #endif /* DEBUG_libfirm */
262 static inline int get_mst_irn_col(const co_mst_irn_t *node)
264 return node->tmp_col >= 0 ? node->tmp_col : node->col;
268 * @return 1 if node @p node has color @p col, 0 otherwise.
270 static int decider_has_color(const co_mst_irn_t *node, int col)
272 return get_mst_irn_col(node) == col;
276 * @return 1 if node @p node has not color @p col, 0 otherwise.
278 static int decider_hasnot_color(const co_mst_irn_t *node, int col)
280 return get_mst_irn_col(node) != col;
284 * Always returns true.
286 static int decider_always_yes(const co_mst_irn_t *node, int col)
293 /** compares two affinity edges by its weight */
294 static int cmp_aff_edge(const void *a, const void *b)
296 const aff_edge_t *e1 = (const aff_edge_t*)a;
297 const aff_edge_t *e2 = (const aff_edge_t*)b;
299 if (e2->weight == e1->weight) {
300 if (e2->src->node_idx == e1->src->node_idx)
301 return QSORT_CMP(e2->tgt->node_idx, e1->tgt->node_idx);
303 return QSORT_CMP(e2->src->node_idx, e1->src->node_idx);
305 /* sort in descending order */
306 return QSORT_CMP(e2->weight, e1->weight);
309 /** compares to color-cost pairs */
310 static __attribute__((unused)) int cmp_col_cost_lt(const void *a, const void *b)
312 const col_cost_t *c1 = (const col_cost_t*)a;
313 const col_cost_t *c2 = (const col_cost_t*)b;
314 real_t diff = c1->cost - c2->cost;
321 return QSORT_CMP(c1->col, c2->col);
324 static int cmp_col_cost_gt(const void *a, const void *b)
326 const col_cost_t *c1 = (const col_cost_t*)a;
327 const col_cost_t *c2 = (const col_cost_t*)b;
328 real_t diff = c2->cost - c1->cost;
335 return QSORT_CMP(c1->col, c2->col);
339 * Creates a new affinity chunk
341 static inline aff_chunk_t *new_aff_chunk(co_mst_env_t *env)
343 aff_chunk_t *c = XMALLOCF(aff_chunk_t, color_affinity, env->n_regs);
344 c->n = NEW_ARR_F(const ir_node *, 0);
345 c->interfere = NEW_ARR_F(const ir_node *, 0);
347 c->weight_consistent = 0;
349 c->id = ++last_chunk_id;
351 list_add(&c->list, &env->chunklist);
356 * Frees all memory allocated by an affinity chunk.
358 static inline void delete_aff_chunk(aff_chunk_t *c)
361 DEL_ARR_F(c->interfere);
368 * binary search of sorted nodes.
370 * @return the position where n is found in the array arr or ~pos
371 * if the nodes is not here.
373 static inline int nodes_bsearch(const ir_node **arr, const ir_node *n)
375 int hi = ARR_LEN(arr);
379 int md = lo + ((hi - lo) >> 1);
392 /** Check if a node n can be found inside arr. */
393 static int node_contains(const ir_node **arr, const ir_node *n)
395 int i = nodes_bsearch(arr, n);
400 * Insert a node into the sorted nodes list.
402 * @return 1 if the node was inserted, 0 else
404 static int nodes_insert(const ir_node ***arr, const ir_node *irn)
406 int idx = nodes_bsearch(*arr, irn);
409 int i, n = ARR_LEN(*arr);
412 ARR_APP1(const ir_node *, *arr, irn);
417 for (i = n - 1; i >= idx; --i)
426 * Adds a node to an affinity chunk
428 static inline void aff_chunk_add_node(aff_chunk_t *c, co_mst_irn_t *node)
432 if (! nodes_insert(&c->n, node->irn))
435 c->weight_consistent = 0;
438 for (i = node->n_neighs - 1; i >= 0; --i) {
439 ir_node *neigh = node->int_neighs[i];
440 nodes_insert(&c->interfere, neigh);
445 * Check if affinity chunk @p chunk interferes with node @p irn.
447 static inline int aff_chunk_interferes(const aff_chunk_t *chunk, const ir_node *irn)
449 return node_contains(chunk->interfere, irn);
453 * Check if there are interference edges from c1 to c2.
455 * @param c2 Another chunk
456 * @return 1 if there are interferences between nodes of c1 and c2, 0 otherwise.
458 static inline int aff_chunks_interfere(const aff_chunk_t *c1, const aff_chunk_t *c2)
465 /* check if there is a node in c2 having an interfering neighbor in c1 */
466 for (i = ARR_LEN(c2->n) - 1; i >= 0; --i) {
467 const ir_node *irn = c2->n[i];
469 if (node_contains(c1->interfere, irn))
476 * Returns the affinity chunk of @p irn or creates a new
477 * one with @p irn as element if there is none assigned.
479 static inline aff_chunk_t *get_aff_chunk(co_mst_env_t *env, const ir_node *irn)
481 co_mst_irn_t *node = get_co_mst_irn(env, irn);
486 * Let chunk(src) absorb the nodes of chunk(tgt) (only possible when there
487 * are no interference edges from chunk(src) to chunk(tgt)).
488 * @return 1 if successful, 0 if not possible
490 static int aff_chunk_absorb(co_mst_env_t *env, const ir_node *src, const ir_node *tgt)
492 aff_chunk_t *c1 = get_aff_chunk(env, src);
493 aff_chunk_t *c2 = get_aff_chunk(env, tgt);
496 DB((dbg, LEVEL_4, "Attempt to let c1 (id %u): ", c1 ? c1->id : 0));
498 DBG_AFF_CHUNK(env, LEVEL_4, c1);
500 DB((dbg, LEVEL_4, "{%+F}", src));
502 DB((dbg, LEVEL_4, "\n\tabsorb c2 (id %u): ", c2 ? c2->id : 0));
504 DBG_AFF_CHUNK(env, LEVEL_4, c2);
506 DB((dbg, LEVEL_4, "{%+F}", tgt));
508 DB((dbg, LEVEL_4, "\n"));
513 /* no chunk exists */
514 co_mst_irn_t *mirn = get_co_mst_irn(env, src);
517 for (i = mirn->n_neighs - 1; i >= 0; --i) {
518 if (mirn->int_neighs[i] == tgt)
522 /* create one containing both nodes */
523 c1 = new_aff_chunk(env);
524 aff_chunk_add_node(c1, get_co_mst_irn(env, src));
525 aff_chunk_add_node(c1, get_co_mst_irn(env, tgt));
529 /* c2 already exists */
530 if (! aff_chunk_interferes(c2, src)) {
531 aff_chunk_add_node(c2, get_co_mst_irn(env, src));
535 } else if (c2 == NULL) {
536 /* c1 already exists */
537 if (! aff_chunk_interferes(c1, tgt)) {
538 aff_chunk_add_node(c1, get_co_mst_irn(env, tgt));
541 } else if (c1 != c2 && ! aff_chunks_interfere(c1, c2)) {
544 for (idx = 0, len = ARR_LEN(c2->n); idx < len; ++idx)
545 aff_chunk_add_node(c1, get_co_mst_irn(env, c2->n[idx]));
547 for (idx = 0, len = ARR_LEN(c2->interfere); idx < len; ++idx) {
548 const ir_node *irn = c2->interfere[idx];
549 nodes_insert(&c1->interfere, irn);
552 c1->weight_consistent = 0;
554 delete_aff_chunk(c2);
557 DB((dbg, LEVEL_4, " ... c1 interferes with c2, skipped\n"));
561 DB((dbg, LEVEL_4, " ... absorbed\n"));
566 * Assures that the weight of the given chunk is consistent.
568 static void aff_chunk_assure_weight(co_mst_env_t *env, aff_chunk_t *c)
570 if (! c->weight_consistent) {
574 for (i = 0; i < env->n_regs; ++i) {
575 c->color_affinity[i].col = i;
576 c->color_affinity[i].cost = REAL(0.0);
579 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
580 const ir_node *n = c->n[idx];
581 const affinity_node_t *an = get_affinity_info(env->co, n);
582 co_mst_irn_t *node = get_co_mst_irn(env, n);
585 if (node->constr_factor > REAL(0.0)) {
587 bitset_foreach (node->adm_colors, col)
588 c->color_affinity[col].cost += node->constr_factor;
592 co_gs_foreach_neighb(an, neigh) {
593 const ir_node *m = neigh->irn;
595 if (arch_irn_is_ignore(m))
598 w += node_contains(c->n, m) ? neigh->costs : 0;
603 for (i = 0; i < env->n_regs; ++i)
604 c->color_affinity[i].cost *= (REAL(1.0) / ARR_LEN(c->n));
607 // c->weight = bitset_popcount(c->nodes);
608 c->weight_consistent = 1;
613 * Count the number of interfering affinity neighbours
615 static int count_interfering_aff_neighs(co_mst_env_t *env, const affinity_node_t *an)
617 const ir_node *irn = an->irn;
618 const co_mst_irn_t *node = get_co_mst_irn(env, irn);
621 co_gs_foreach_neighb(an, neigh) {
622 const ir_node *n = neigh->irn;
625 if (arch_irn_is_ignore(n))
628 /* check if the affinity neighbour interfere */
629 for (i = 0; i < node->n_neighs; ++i) {
630 if (node->int_neighs[i] == n) {
641 * Build chunks of nodes connected by affinity edges.
642 * We start at the heaviest affinity edge.
643 * The chunks of the two edge-defining nodes will be
644 * merged if there are no interference edges from one
645 * chunk to the other.
647 static void build_affinity_chunks(co_mst_env_t *env)
649 nodes_iter_t nodes_it;
650 aff_edge_t *edges = NEW_ARR_F(aff_edge_t, 0);
653 aff_chunk_t *curr_chunk;
656 /* at first we create the affinity edge objects */
657 be_ifg_foreach_node(env->ifg, &nodes_it, n) {
658 int n_idx = get_irn_idx(n);
662 if (arch_irn_is_ignore(n))
665 n1 = get_co_mst_irn(env, n);
666 an = get_affinity_info(env->co, n);
669 if (n1->int_aff_neigh < 0)
670 n1->int_aff_neigh = count_interfering_aff_neighs(env, an);
672 /* build the affinity edges */
673 co_gs_foreach_neighb(an, neigh) {
674 const ir_node *m = neigh->irn;
675 int m_idx = get_irn_idx(m);
677 /* record the edge in only one direction */
682 /* skip ignore nodes */
683 if (arch_irn_is_ignore(m))
689 n2 = get_co_mst_irn(env, m);
690 if (n2->int_aff_neigh < 0) {
691 affinity_node_t *am = get_affinity_info(env->co, m);
692 n2->int_aff_neigh = count_interfering_aff_neighs(env, am);
695 * these weights are pure hackery ;-).
696 * It's not chriswue's fault but mine.
698 edge.weight = neigh->costs;
699 ARR_APP1(aff_edge_t, edges, edge);
705 /* now: sort edges and build the affinity chunks */
706 len = ARR_LEN(edges);
707 qsort(edges, len, sizeof(edges[0]), cmp_aff_edge);
708 for (i = 0; i < len; ++i) {
709 DBG((dbg, LEVEL_1, "edge (%u,%u) %f\n", edges[i].src->node_idx, edges[i].tgt->node_idx, edges[i].weight));
711 (void)aff_chunk_absorb(env, edges[i].src, edges[i].tgt);
714 /* now insert all chunks into a priority queue */
715 list_for_each_entry(aff_chunk_t, curr_chunk, &env->chunklist, list) {
716 aff_chunk_assure_weight(env, curr_chunk);
718 DBG((dbg, LEVEL_1, "entry #%u", curr_chunk->id));
719 DBG_AFF_CHUNK(env, LEVEL_1, curr_chunk);
720 DBG((dbg, LEVEL_1, "\n"));
722 pqueue_put(env->chunks, curr_chunk, curr_chunk->weight);
725 for (pn = 0; pn < ARR_LEN(env->map.data); ++pn) {
726 co_mst_irn_t *mirn = (co_mst_irn_t*)env->map.data[pn];
729 if (mirn->chunk != NULL)
732 /* no chunk is allocated so far, do it now */
733 aff_chunk_t *curr_chunk = new_aff_chunk(env);
734 aff_chunk_add_node(curr_chunk, mirn);
736 aff_chunk_assure_weight(env, curr_chunk);
738 DBG((dbg, LEVEL_1, "entry #%u", curr_chunk->id));
739 DBG_AFF_CHUNK(env, LEVEL_1, curr_chunk);
740 DBG((dbg, LEVEL_1, "\n"));
742 pqueue_put(env->chunks, curr_chunk, curr_chunk->weight);
748 static __attribute__((unused)) void chunk_order_nodes(co_mst_env_t *env, aff_chunk_t *chunk)
750 pqueue_t *grow = new_pqueue();
751 ir_node const *max_node = NULL;
755 for (i = ARR_LEN(chunk->n); i != 0;) {
756 const ir_node *irn = chunk->n[--i];
757 affinity_node_t *an = get_affinity_info(env->co, irn);
760 if (arch_irn_is_ignore(irn))
764 co_gs_foreach_neighb(an, neigh)
767 if (w > max_weight) {
775 bitset_t *visited = bitset_malloc(get_irg_last_idx(env->co->irg));
777 for (i = ARR_LEN(chunk->n); i != 0;)
778 bitset_set(visited, get_irn_idx(chunk->n[--i]));
780 pqueue_put(grow, (void *) max_node, max_weight);
781 bitset_clear(visited, get_irn_idx(max_node));
783 while (!pqueue_empty(grow)) {
784 ir_node *irn = (ir_node*)pqueue_pop_front(grow);
785 affinity_node_t *an = get_affinity_info(env->co, irn);
787 if (arch_irn_is_ignore(irn))
790 assert(i <= ARR_LEN(chunk->n));
795 /* build the affinity edges */
796 co_gs_foreach_neighb(an, neigh) {
797 co_mst_irn_t *node = get_co_mst_irn(env, neigh->irn);
799 if (bitset_is_set(visited, get_irn_idx(node->irn))) {
800 pqueue_put(grow, (void *) neigh->irn, neigh->costs);
801 bitset_clear(visited, get_irn_idx(node->irn));
807 bitset_free(visited);
812 * Greedy collect affinity neighbours into thew new chunk @p chunk starting at node @p node.
814 static void expand_chunk_from(co_mst_env_t *env, co_mst_irn_t *node, bitset_t *visited,
815 aff_chunk_t *chunk, aff_chunk_t *orig_chunk, decide_func_t *decider, int col)
817 waitq *nodes = new_waitq();
819 DBG((dbg, LEVEL_1, "\n\tExpanding new chunk (#%u) from %+F, color %d:", chunk->id, node->irn, col));
821 /* init queue and chunk */
822 waitq_put(nodes, node);
823 bitset_set(visited, get_irn_idx(node->irn));
824 aff_chunk_add_node(chunk, node);
825 DB((dbg, LEVEL_1, " %+F", node->irn));
827 /* as long as there are nodes in the queue */
828 while (! waitq_empty(nodes)) {
829 co_mst_irn_t *n = (co_mst_irn_t*)waitq_get(nodes);
830 affinity_node_t *an = get_affinity_info(env->co, n->irn);
832 /* check all affinity neighbors */
834 co_gs_foreach_neighb(an, neigh) {
835 const ir_node *m = neigh->irn;
836 int m_idx = get_irn_idx(m);
839 if (arch_irn_is_ignore(m))
842 n2 = get_co_mst_irn(env, m);
844 if (! bitset_is_set(visited, m_idx) &&
847 ! aff_chunk_interferes(chunk, m) &&
848 node_contains(orig_chunk->n, m))
851 following conditions are met:
852 - neighbour is not visited
853 - neighbour likes the color
854 - neighbour has not yet a fixed color
855 - the new chunk doesn't interfere with the neighbour
856 - neighbour belongs or belonged once to the original chunk
858 bitset_set(visited, m_idx);
859 aff_chunk_add_node(chunk, n2);
860 DB((dbg, LEVEL_1, " %+F", n2->irn));
861 /* enqueue for further search */
862 waitq_put(nodes, n2);
868 DB((dbg, LEVEL_1, "\n"));
874 * Fragment the given chunk into chunks having given color and not having given color.
876 static aff_chunk_t *fragment_chunk(co_mst_env_t *env, int col, aff_chunk_t *c, waitq *tmp)
878 bitset_t *visited = bitset_malloc(get_irg_last_idx(env->co->irg));
880 aff_chunk_t *best = NULL;
882 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
885 aff_chunk_t *tmp_chunk;
886 decide_func_t *decider;
890 if (bitset_is_set(visited, get_irn_idx(irn)))
893 node = get_co_mst_irn(env, irn);
895 if (get_mst_irn_col(node) == col) {
896 decider = decider_has_color;
898 DBG((dbg, LEVEL_4, "\tcolor %d wanted\n", col));
901 decider = decider_hasnot_color;
903 DBG((dbg, LEVEL_4, "\tcolor %d forbidden\n", col));
906 /* create a new chunk starting at current node */
907 tmp_chunk = new_aff_chunk(env);
908 waitq_put(tmp, tmp_chunk);
909 expand_chunk_from(env, node, visited, tmp_chunk, c, decider, col);
910 assert(ARR_LEN(tmp_chunk->n) > 0 && "No nodes added to chunk");
912 /* remember the local best */
913 aff_chunk_assure_weight(env, tmp_chunk);
914 if (check_for_best && (! best || best->weight < tmp_chunk->weight))
918 assert(best && "No chunk found?");
919 bitset_free(visited);
924 * Resets the temporary fixed color of all nodes within wait queue @p nodes.
925 * ATTENTION: the queue is empty after calling this function!
927 static inline void reject_coloring(struct list_head *nodes)
929 co_mst_irn_t *n, *temp;
930 DB((dbg, LEVEL_4, "\treject coloring for"));
931 list_for_each_entry_safe(co_mst_irn_t, n, temp, nodes, list) {
932 DB((dbg, LEVEL_4, " %+F", n->irn));
933 assert(n->tmp_col >= 0);
935 list_del_init(&n->list);
937 DB((dbg, LEVEL_4, "\n"));
940 static inline void materialize_coloring(struct list_head *nodes)
942 co_mst_irn_t *n, *temp;
943 list_for_each_entry_safe(co_mst_irn_t, n, temp, nodes, list) {
944 assert(n->tmp_col >= 0);
947 list_del_init(&n->list);
951 static inline void set_temp_color(co_mst_irn_t *node, int col, struct list_head *changed)
954 assert(!node->fixed);
955 assert(node->tmp_col < 0);
956 assert(node->list.next == &node->list && node->list.prev == &node->list);
957 assert(bitset_is_set(node->adm_colors, col));
959 list_add_tail(&node->list, changed);
963 static inline int is_loose(co_mst_irn_t *node)
965 return !node->fixed && node->tmp_col < 0;
969 * Determines the costs for each color if it would be assigned to node @p node.
971 static void determine_color_costs(co_mst_env_t *env, co_mst_irn_t *node, col_cost_t *costs)
973 int *neigh_cols = ALLOCAN(int, env->n_regs);
978 for (i = 0; i < env->n_regs; ++i) {
981 costs[i].cost = bitset_is_set(node->adm_colors, i) ? node->constr_factor : REAL(0.0);
984 for (i = 0; i < node->n_neighs; ++i) {
985 co_mst_irn_t *n = get_co_mst_irn(env, node->int_neighs[i]);
986 int col = get_mst_irn_col(n);
991 costs[col].cost = REAL(0.0);
995 coeff = REAL(1.0) / n_loose;
996 for (i = 0; i < env->n_regs; ++i)
997 costs[i].cost *= REAL(1.0) - coeff * neigh_cols[i];
1001 /* need forward declaration due to recursive call */
1002 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);
1005 * Tries to change node to a color but @p explude_col.
1006 * @return 1 if succeeded, 0 otherwise.
1008 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)
1010 int col = get_mst_irn_col(node);
1013 /* neighbours has already a different color -> good, temporary fix it */
1014 if (col != exclude_col) {
1016 set_temp_color(node, col, changed);
1020 /* The node has the color it should not have _and_ has not been visited yet. */
1021 if (is_loose(node)) {
1022 col_cost_t *costs = ALLOCAN(col_cost_t, env->n_regs);
1024 /* Get the costs for giving the node a specific color. */
1025 determine_color_costs(env, node, costs);
1027 /* Since the node must not have the not_col, set the costs for that color to "infinity" */
1028 costs[exclude_col].cost = REAL(0.0);
1030 /* sort the colors according costs, cheapest first. */
1031 qsort(costs, env->n_regs, sizeof(costs[0]), cmp_col_cost_gt);
1033 /* Try recoloring the node using the color list. */
1034 res = recolor_nodes(env, node, costs, changed, depth + 1, max_depth, trip);
1041 * Tries to bring node @p node to cheapest color and color all interfering neighbours with other colors.
1042 * ATTENTION: Expect @p costs already sorted by increasing costs.
1043 * @return 1 if coloring could be applied, 0 otherwise.
1045 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)
1048 struct list_head local_changed;
1051 if (depth > *max_depth)
1054 DBG((dbg, LEVEL_4, "\tRecoloring %+F with color-costs", node->irn));
1055 DBG_COL_COST(env, LEVEL_4, costs);
1056 DB((dbg, LEVEL_4, "\n"));
1058 if (depth >= recolor_limit) {
1059 DBG((dbg, LEVEL_4, "\tHit recolor limit\n"));
1063 for (i = 0; i < env->n_regs; ++i) {
1064 int tgt_col = costs[i].col;
1068 /* If the costs for that color (and all successive) are infinite, bail out we won't make it anyway. */
1069 if (costs[i].cost == REAL(0.0)) {
1070 DBG((dbg, LEVEL_4, "\tAll further colors forbidden\n"));
1074 /* Set the new color of the node and mark the node as temporarily fixed. */
1075 assert(node->tmp_col < 0 && "Node must not have been temporary fixed.");
1076 INIT_LIST_HEAD(&local_changed);
1077 set_temp_color(node, tgt_col, &local_changed);
1078 DBG((dbg, LEVEL_4, "\tTemporary setting %+F to color %d\n", node->irn, tgt_col));
1080 /* try to color all interfering neighbours with current color forbidden */
1081 for (j = 0; j < node->n_neighs; ++j) {
1085 neigh = node->int_neighs[j];
1087 if (arch_irn_is_ignore(neigh))
1090 nn = get_co_mst_irn(env, neigh);
1091 DB((dbg, LEVEL_4, "\tHandling neighbour %+F, at position %d (fixed: %d, tmp_col: %d, col: %d)\n",
1092 neigh, j, nn->fixed, nn->tmp_col, nn->col));
1095 Try to change the color of the neighbor and record all nodes which
1096 get changed in the tmp list. Add this list to the "changed" list for
1097 that color. If we did not succeed to change the color of the neighbor,
1098 we bail out and try the next color.
1100 if (get_mst_irn_col(nn) == tgt_col) {
1101 /* try to color neighbour with tgt_col forbidden */
1102 neigh_ok = change_node_color_excluded(env, nn, tgt_col, &local_changed, depth + 1, max_depth, trip);
1110 We managed to assign the target color to all neighbors, so from the perspective
1111 of the current node, every thing was ok and we can return safely.
1114 /* append the local_changed ones to global ones */
1115 list_splice(&local_changed, changed);
1119 /* coloring of neighbours failed, so we try next color */
1120 reject_coloring(&local_changed);
1124 DBG((dbg, LEVEL_4, "\tAll colors failed\n"));
1129 * Tries to bring node @p node and all its neighbours to color @p tgt_col.
1130 * @return 1 if color @p col could be applied, 0 otherwise
1132 static int change_node_color(co_mst_env_t *env, co_mst_irn_t *node, int tgt_col, struct list_head *changed)
1134 int col = get_mst_irn_col(node);
1136 /* if node already has the target color -> good, temporary fix it */
1137 if (col == tgt_col) {
1138 DBG((dbg, LEVEL_4, "\t\tCNC: %+F has already color %d, fix temporary\n", node->irn, tgt_col));
1140 set_temp_color(node, tgt_col, changed);
1145 Node has not yet a fixed color and target color is admissible
1146 -> try to recolor node and its affinity neighbours
1148 if (is_loose(node) && bitset_is_set(node->adm_colors, tgt_col)) {
1149 col_cost_t *costs = env->single_cols[tgt_col];
1150 int res, max_depth, trip;
1155 DBG((dbg, LEVEL_4, "\t\tCNC: Attempt to recolor %+F ===>>\n", node->irn));
1156 res = recolor_nodes(env, node, costs, changed, 0, &max_depth, &trip);
1157 DBG((dbg, LEVEL_4, "\t\tCNC: <<=== Recoloring of %+F %s\n", node->irn, res ? "succeeded" : "failed"));
1158 stat_ev_int("heur4_recolor_depth_max", max_depth);
1159 stat_ev_int("heur4_recolor_trip", trip);
1165 #ifdef DEBUG_libfirm
1166 if (firm_dbg_get_mask(dbg) & LEVEL_4) {
1167 if (!is_loose(node))
1168 DB((dbg, LEVEL_4, "\t\tCNC: %+F has already fixed color %d\n", node->irn, col));
1170 DB((dbg, LEVEL_4, "\t\tCNC: color %d not admissible for %+F (", tgt_col, node->irn));
1171 dbg_admissible_colors(env, node);
1172 DB((dbg, LEVEL_4, ")\n"));
1181 * Tries to color an affinity chunk (or at least a part of it).
1182 * Inserts uncolored parts of the chunk as a new chunk into the priority queue.
1184 static void color_aff_chunk(co_mst_env_t *env, aff_chunk_t *c)
1186 aff_chunk_t *best_chunk = NULL;
1187 int n_nodes = ARR_LEN(c->n);
1188 int best_color = -1;
1189 int n_int_chunks = 0;
1190 waitq *tmp_chunks = new_waitq();
1191 waitq *best_starts = NULL;
1192 col_cost_t *order = ALLOCANZ(col_cost_t, env->n_regs);
1199 struct list_head changed;
1201 DB((dbg, LEVEL_2, "fragmentizing chunk #%u", c->id));
1202 DBG_AFF_CHUNK(env, LEVEL_2, c);
1203 DB((dbg, LEVEL_2, "\n"));
1205 stat_ev_ctx_push_fmt("heur4_color_chunk", "%u", c->id);
1207 ++env->chunk_visited;
1209 /* compute color preference */
1210 for (pos = 0, len = ARR_LEN(c->interfere); pos < len; ++pos) {
1211 const ir_node *n = c->interfere[pos];
1212 co_mst_irn_t *node = get_co_mst_irn(env, n);
1213 aff_chunk_t *chunk = node->chunk;
1215 if (is_loose(node) && chunk && chunk->visited < env->chunk_visited) {
1216 assert(!chunk->deleted);
1217 chunk->visited = env->chunk_visited;
1220 aff_chunk_assure_weight(env, chunk);
1221 for (i = 0; i < env->n_regs; ++i)
1222 order[i].cost += chunk->color_affinity[i].cost;
1226 for (i = 0; i < env->n_regs; ++i) {
1227 real_t dislike = n_int_chunks > 0 ? REAL(1.0) - order[i].cost / n_int_chunks : REAL(0.0);
1229 order[i].cost = (REAL(1.0) - dislike_influence) * c->color_affinity[i].cost + dislike_influence * dislike;
1232 qsort(order, env->n_regs, sizeof(order[0]), cmp_col_cost_gt);
1234 DBG_COL_COST(env, LEVEL_2, order);
1235 DB((dbg, LEVEL_2, "\n"));
1237 /* check which color is the "best" for the given chunk.
1238 * if we found a color which was ok for all nodes, we take it
1239 * and do not look further. (see did_all flag usage below.)
1240 * If we have many colors which fit all nodes it is hard to decide
1241 * which one to take anyway.
1242 * TODO Sebastian: Perhaps we should at all nodes and figure out
1243 * a suitable color using costs as done above (determine_color_costs).
1245 for (i = 0; i < env->k; ++i) {
1246 int col = order[i].col;
1248 aff_chunk_t *local_best;
1251 /* skip ignore colors */
1252 if (!bitset_is_set(env->allocatable_regs, col))
1255 DB((dbg, LEVEL_2, "\ttrying color %d\n", col));
1258 good_starts = new_waitq();
1260 /* try to bring all nodes of given chunk to the current color. */
1261 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1262 const ir_node *irn = c->n[idx];
1263 co_mst_irn_t *node = get_co_mst_irn(env, irn);
1266 assert(! node->fixed && "Node must not have a fixed color.");
1267 DB((dbg, LEVEL_4, "\t\tBringing %+F from color %d to color %d ...\n", irn, node->col, col));
1270 The order of the colored nodes is important, so we record the successfully
1271 colored ones in the order they appeared.
1273 INIT_LIST_HEAD(&changed);
1275 good = change_node_color(env, node, col, &changed);
1276 stat_ev_tim_pop("heur4_recolor");
1278 waitq_put(good_starts, node);
1279 materialize_coloring(&changed);
1284 reject_coloring(&changed);
1286 n_succeeded += good;
1287 DB((dbg, LEVEL_4, "\t\t... %+F attempt from %d to %d %s\n", irn, node->col, col, good ? "succeeded" : "failed"));
1290 /* unfix all nodes */
1291 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1292 co_mst_irn_t *node = get_co_mst_irn(env, c->n[idx]);
1296 /* try next color when failed */
1297 if (n_succeeded == 0) {
1298 del_waitq(good_starts);
1302 /* fragment the chunk according to the coloring */
1303 local_best = fragment_chunk(env, col, c, tmp_chunks);
1305 /* search the best of the good list
1306 and make it the new best if it is better than the current */
1308 aff_chunk_assure_weight(env, local_best);
1310 DB((dbg, LEVEL_3, "\t\tlocal best chunk (id %u) for color %d: ", local_best->id, col));
1311 DBG_AFF_CHUNK(env, LEVEL_3, local_best);
1313 if (! best_chunk || best_chunk->weight < local_best->weight) {
1314 best_chunk = local_best;
1317 del_waitq(best_starts);
1318 best_starts = good_starts;
1319 DB((dbg, LEVEL_3, "\n\t\t... setting global best chunk (id %u), color %d\n", best_chunk->id, best_color));
1321 DB((dbg, LEVEL_3, "\n\t\t... omitting, global best is better\n"));
1322 del_waitq(good_starts);
1326 del_waitq(good_starts);
1329 /* if all nodes were recolored, bail out */
1330 if (n_succeeded == n_nodes)
1334 stat_ev_int("heur4_colors_tried", i);
1336 /* free all intermediate created chunks except best one */
1337 while (! waitq_empty(tmp_chunks)) {
1338 aff_chunk_t *tmp = (aff_chunk_t*)waitq_get(tmp_chunks);
1339 if (tmp != best_chunk)
1340 delete_aff_chunk(tmp);
1342 del_waitq(tmp_chunks);
1344 /* return if coloring failed */
1347 del_waitq(best_starts);
1351 DB((dbg, LEVEL_2, "\tbest chunk #%u ", best_chunk->id));
1352 DBG_AFF_CHUNK(env, LEVEL_2, best_chunk);
1353 DB((dbg, LEVEL_2, "using color %d\n", best_color));
1355 for (idx = 0, len = ARR_LEN(best_chunk->n); idx < len; ++idx) {
1356 const ir_node *irn = best_chunk->n[idx];
1357 co_mst_irn_t *node = get_co_mst_irn(env, irn);
1360 /* bring the node to the color. */
1361 DB((dbg, LEVEL_4, "\tManifesting color %d for %+F, chunk #%u\n", best_color, node->irn, best_chunk->id));
1362 INIT_LIST_HEAD(&changed);
1364 res = change_node_color(env, node, best_color, &changed);
1365 stat_ev_tim_pop("heur4_recolor");
1367 materialize_coloring(&changed);
1370 assert(list_empty(&changed));
1373 /* remove the nodes in best chunk from original chunk */
1374 len = ARR_LEN(best_chunk->n);
1375 for (idx = 0; idx < len; ++idx) {
1376 const ir_node *irn = best_chunk->n[idx];
1377 int pos = nodes_bsearch(c->n, irn);
1382 len = ARR_LEN(c->n);
1383 for (idx = nidx = 0; idx < len; ++idx) {
1384 const ir_node *irn = c->n[idx];
1390 ARR_SHRINKLEN(c->n, nidx);
1393 /* we have to get the nodes back into the original chunk because they are scattered over temporary chunks */
1394 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1395 const ir_node *n = c->n[idx];
1396 co_mst_irn_t *nn = get_co_mst_irn(env, n);
1400 /* fragment the remaining chunk */
1401 visited = bitset_malloc(get_irg_last_idx(env->co->irg));
1402 for (idx = 0, len = ARR_LEN(best_chunk->n); idx < len; ++idx)
1403 bitset_set(visited, get_irn_idx(best_chunk->n[idx]));
1405 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1406 const ir_node *irn = c->n[idx];
1407 if (! bitset_is_set(visited, get_irn_idx(irn))) {
1408 aff_chunk_t *new_chunk = new_aff_chunk(env);
1409 co_mst_irn_t *node = get_co_mst_irn(env, irn);
1411 expand_chunk_from(env, node, visited, new_chunk, c, decider_always_yes, 0);
1412 aff_chunk_assure_weight(env, new_chunk);
1413 pqueue_put(env->chunks, new_chunk, new_chunk->weight);
1417 for (idx = 0, len = ARR_LEN(best_chunk->n); idx < len; ++idx) {
1418 const ir_node *n = best_chunk->n[idx];
1419 co_mst_irn_t *nn = get_co_mst_irn(env, n);
1423 /* clear obsolete chunks and free some memory */
1424 delete_aff_chunk(best_chunk);
1425 bitset_free(visited);
1427 del_waitq(best_starts);
1429 stat_ev_ctx_pop("heur4_color_chunk");
1433 * Main driver for mst safe coalescing algorithm.
1435 static int co_solve_heuristic_mst(copy_opt_t *co)
1437 unsigned n_regs = co->cls->n_regs;
1438 bitset_t *allocatable_regs = bitset_alloca(n_regs);
1443 co_mst_env_t mst_env;
1450 ir_nodemap_init(&mst_env.map, co->irg);
1451 obstack_init(&mst_env.obst);
1453 be_put_allocatable_regs(co->cenv->irg, co->cls, allocatable_regs);
1454 k = bitset_popcount(allocatable_regs);
1456 mst_env.n_regs = n_regs;
1458 mst_env.chunks = new_pqueue();
1460 mst_env.allocatable_regs = allocatable_regs;
1461 mst_env.ifg = co->cenv->ifg;
1462 INIT_LIST_HEAD(&mst_env.chunklist);
1463 mst_env.chunk_visited = 0;
1464 mst_env.single_cols = OALLOCN(&mst_env.obst, col_cost_t*, n_regs);
1466 for (i = 0; i < n_regs; ++i) {
1467 col_cost_t *vec = OALLOCN(&mst_env.obst, col_cost_t, n_regs);
1469 mst_env.single_cols[i] = vec;
1470 for (j = 0; j < n_regs; ++j) {
1472 vec[j].cost = REAL(0.0);
1476 vec[0].cost = REAL(1.0);
1479 DBG((dbg, LEVEL_1, "==== Coloring %+F, class %s ====\n", co->irg, co->cls->name));
1481 /* build affinity chunks */
1483 build_affinity_chunks(&mst_env);
1484 stat_ev_tim_pop("heur4_initial_chunk");
1486 /* color chunks as long as there are some */
1487 while (! pqueue_empty(mst_env.chunks)) {
1488 aff_chunk_t *chunk = (aff_chunk_t*)pqueue_pop_front(mst_env.chunks);
1490 color_aff_chunk(&mst_env, chunk);
1491 DB((dbg, LEVEL_4, "<<<====== Coloring chunk (%u) done\n", chunk->id));
1492 delete_aff_chunk(chunk);
1495 /* apply coloring */
1496 for (pn = 0; pn < ARR_LEN(mst_env.map.data); ++pn) {
1497 co_mst_irn_t *mirn = (co_mst_irn_t*)mst_env.map.data[pn];
1498 const arch_register_t *reg;
1501 irn = get_idx_irn(co->irg, pn);
1502 if (arch_irn_is_ignore(irn))
1505 /* skip nodes where color hasn't changed */
1506 if (mirn->init_col == mirn->col)
1509 reg = arch_register_for_index(co->cls, mirn->col);
1510 arch_set_irn_register(irn, reg);
1511 DB((dbg, LEVEL_1, "%+F set color from %d to %d\n", irn, mirn->init_col, mirn->col));
1514 /* free allocated memory */
1515 del_pqueue(mst_env.chunks);
1516 obstack_free(&mst_env.obst, NULL);
1517 ir_nodemap_destroy(&mst_env.map);
1519 stat_ev_tim_pop("heur4_total");
1524 static const lc_opt_table_entry_t options[] = {
1525 LC_OPT_ENT_INT ("limit", "limit recoloring", &recolor_limit),
1526 LC_OPT_ENT_DBL ("di", "dislike influence", &dislike_influence),
1530 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_copyheur4)
1531 void be_init_copyheur4(void)
1533 lc_opt_entry_t *be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
1534 lc_opt_entry_t *ra_grp = lc_opt_get_grp(be_grp, "ra");
1535 lc_opt_entry_t *chordal_grp = lc_opt_get_grp(ra_grp, "chordal");
1536 lc_opt_entry_t *co_grp = lc_opt_get_grp(chordal_grp, "co");
1537 lc_opt_entry_t *heur4_grp = lc_opt_get_grp(co_grp, "heur4");
1539 static co_algo_info copyheur = {
1540 co_solve_heuristic_mst, 0
1543 lc_opt_add_table(heur4_grp, options);
1544 be_register_copyopt("heur4", ©heur);
1546 FIRM_DBG_REGISTER(dbg, "firm.be.co.heur4");