2 * Copyright (C) 1995-2008 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 New approach to allocation and copy coalescing
23 * @author Matthias Braun
27 * ... WE NEED A NAME FOR THIS ...
29 * Only a proof of concept at this moment...
31 * The idea is to allocate registers in 2 passes:
32 * 1. A first pass to determine "preferred" registers for live-ranges. This
33 * calculates for each register and each live-range a value indicating
34 * the usefulness. (You can roughly think of the value as the negative
35 * costs needed for copies when the value is in the specific registers...)
37 * 2. Walk blocks and assigns registers in a greedy fashion. Preferring registers
38 * with high preferences. When register constraints are not met, add copies
39 * and split live-ranges.
42 * - output constraints are not ensured. The algorithm fails to copy values
43 * away, so the registers for constrained outputs are free.
44 * - must_be_different constraint is not respected
45 * - No parallel copies at basic block borders are created, no additional phis
46 * created after copies have been inserted.
47 * - Phi color assignment should give bonus points towards registers already
48 * assigned at predecessors.
49 * - think about a smarter sequence of visiting the blocks. Sorted by
50 * execfreq might be good, or looptree from inner to outermost loops going
51 * over blocks in a reverse postorder
59 #include "irgraph_t.h"
60 #include "iredges_t.h"
69 #include "bechordal_t.h"
70 #include "besched_t.h"
73 #include "bespilloptions.h"
76 #include "bipartite.h"
77 #include "hungarian.h"
79 #define USE_FACTOR 1.0f
80 #define DEF_FACTOR 1.0f
81 #define NEIGHBOR_FACTOR 0.2f
82 #define SHOULD_BE_SAME 1.0f
84 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
86 static struct obstack obst;
87 static be_irg_t *birg;
89 static const arch_register_class_t *cls;
91 static const ir_exec_freq *execfreqs;
92 static unsigned n_regs;
93 static bitset_t *ignore_regs;
95 typedef struct assignment_t assignment_t;
97 ir_node *value; /**< currently assigned value */
100 static assignment_t *assignments;
102 typedef struct allocation_info_t allocation_info_t;
103 struct allocation_info_t {
104 unsigned last_uses; /**< bitset indicating last uses (input pos) */
105 assignment_t *current_assignment;
106 float prefs[0]; /**< register preferences */
109 typedef struct reg_pref_t reg_pref_t;
116 * Get the allocation info for a node.
117 * The info is allocated on the first visit of a node.
119 static allocation_info_t *get_allocation_info(ir_node *node)
121 allocation_info_t *info;
122 if (!irn_visited(node)) {
123 size_t size = sizeof(info[0]) + n_regs * sizeof(float);
124 info = obstack_alloc(&obst, size);
125 memset(info, 0, size);
126 set_irn_link(node, info);
127 mark_irn_visited(node);
129 info = get_irn_link(node);
136 * Link the allocation info of a node to a copy.
137 * Afterwards, both nodes uses the same allocation info.
138 * Copy must not have an allocation info assigned yet.
140 * @param copy the node that gets the allocation info assigned
141 * @param value the original node
143 static void link_to(ir_node *copy, ir_node *value)
145 allocation_info_t *info = get_allocation_info(value);
146 assert(!irn_visited(copy));
147 set_irn_link(copy, info);
148 mark_irn_visited(copy);
152 * Calculate the penalties for every register on a node and its live neighbors.
154 * @param live_nodes the set of live nodes at the current position, may be NULL
155 * @param penalty the penalty to subtract from
156 * @param limited a raw bitset containing the limited set for the node
157 * @param node the node
159 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
160 float penalty, const unsigned* limited,
163 ir_nodeset_iterator_t iter;
165 allocation_info_t *info = get_allocation_info(node);
168 /* give penalty for all forbidden regs */
169 for (r = 0; r < n_regs; ++r) {
170 if (rbitset_is_set(limited, r))
173 info->prefs[r] -= penalty;
176 /* all other live values should get a penalty for allowed regs */
177 if (live_nodes == NULL)
180 /* TODO: reduce penalty if there are multiple allowed registers... */
181 penalty *= NEIGHBOR_FACTOR;
182 foreach_ir_nodeset(live_nodes, neighbor, iter) {
183 allocation_info_t *neighbor_info;
185 /* TODO: if op is used on multiple inputs we might not do a
187 if (neighbor == node)
190 neighbor_info = get_allocation_info(neighbor);
191 for (r = 0; r < n_regs; ++r) {
192 if (!rbitset_is_set(limited, r))
195 neighbor_info->prefs[r] -= penalty;
201 * Calculate the preferences of a definition for the current register class.
202 * If the definition uses a limited set of registers, reduce the preferences
203 * for the limited register on the node and its neighbors.
205 * @param live_nodes the set of live nodes at the current node
206 * @param weight the weight
207 * @param node the current node
209 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
212 const arch_register_req_t *req;
214 if (get_irn_mode(node) == mode_T) {
215 const ir_edge_t *edge;
216 foreach_out_edge(node, edge) {
217 ir_node *proj = get_edge_src_irn(edge);
218 check_defs(live_nodes, weight, proj);
223 if (!arch_irn_consider_in_reg_alloc(cls, node))
226 req = arch_get_register_req_out(node);
227 if (req->type & arch_register_req_type_limited) {
228 const unsigned *limited = req->limited;
229 float penalty = weight * DEF_FACTOR;
230 give_penalties_for_limits(live_nodes, penalty, limited, node);
233 if (req->type & arch_register_req_type_should_be_same) {
234 ir_node *insn = skip_Proj(node);
235 allocation_info_t *info = get_allocation_info(node);
236 int arity = get_irn_arity(insn);
239 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
240 for (i = 0; i < arity; ++i) {
243 allocation_info_t *op_info;
245 if (!rbitset_is_set(&req->other_same, i))
248 op = get_irn_n(insn, i);
249 op_info = get_allocation_info(op);
250 for (r = 0; r < n_regs; ++r) {
251 if (bitset_is_set(ignore_regs, r))
253 op_info->prefs[r] += info->prefs[r] * factor;
260 * Walker: Runs an a block calculates the preferences for any
261 * node and every register from the considered register class.
263 static void analyze_block(ir_node *block, void *data)
265 float weight = get_block_execfreq(execfreqs, block);
266 ir_nodeset_t live_nodes;
270 ir_nodeset_init(&live_nodes);
271 be_liveness_end_of_block(lv, cls, block, &live_nodes);
273 sched_foreach_reverse(block, node) {
274 allocation_info_t *info;
278 /* TODO: handle constrained phi-nodes */
282 /* TODO give/take penalties for should_be_same/different) */
283 check_defs(&live_nodes, weight, node);
286 arity = get_irn_arity(node);
287 /* I was lazy, and only allocated 1 unsigned
288 => maximum of 32 uses per node (rewrite if necessary) */
289 assert(arity <= (int) sizeof(unsigned) * 8);
291 info = get_allocation_info(node);
292 for (i = 0; i < arity; ++i) {
293 ir_node *op = get_irn_n(node, i);
294 if (!arch_irn_consider_in_reg_alloc(cls, op))
297 /* last usage of a value? */
298 if (!ir_nodeset_contains(&live_nodes, op)) {
299 rbitset_set(&info->last_uses, i);
303 be_liveness_transfer(cls, node, &live_nodes);
305 /* update weights based on usage constraints */
306 for (i = 0; i < arity; ++i) {
307 const arch_register_req_t *req;
308 const unsigned *limited;
309 ir_node *op = get_irn_n(node, i);
311 if (!arch_irn_consider_in_reg_alloc(cls, op))
314 req = arch_get_register_req(node, i);
315 if ((req->type & arch_register_req_type_limited) == 0)
318 /* TODO: give penalties to neighbors for precolored nodes! */
320 limited = req->limited;
321 give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
326 ir_nodeset_destroy(&live_nodes);
330 * Assign register reg to the given node.
332 * @param node the node
333 * @param reg the register
335 static void use_reg(ir_node *node, const arch_register_t *reg)
337 unsigned r = arch_register_get_index(reg);
338 assignment_t *assignment = &assignments[r];
339 allocation_info_t *info;
341 assert(assignment->value == NULL);
342 assignment->value = node;
344 info = get_allocation_info(node);
345 info->current_assignment = assignment;
347 arch_set_irn_register(node, reg);
351 * Compare two register preferences in decreasing order.
353 static int compare_reg_pref(const void *e1, const void *e2)
355 const reg_pref_t *rp1 = (const reg_pref_t*) e1;
356 const reg_pref_t *rp2 = (const reg_pref_t*) e2;
357 if (rp1->pref < rp2->pref)
359 if (rp1->pref > rp2->pref)
364 static void fill_sort_candidates(reg_pref_t *regprefs,
365 const allocation_info_t *info)
369 for (r = 0; r < n_regs; ++r) {
370 float pref = info->prefs[r];
371 if (bitset_is_set(ignore_regs, r)) {
375 regprefs[r].pref = pref;
377 /* TODO: use a stable sort here to avoid unnecessary register jumping */
378 qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
381 static void assign_reg(const ir_node *block, ir_node *node)
383 const arch_register_t *reg;
384 allocation_info_t *info;
385 const arch_register_req_t *req;
386 reg_pref_t *reg_prefs;
390 assert(arch_irn_consider_in_reg_alloc(cls, node));
392 /* preassigned register? */
393 reg = arch_get_irn_register(node);
395 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
400 /* give should_be_same boni */
401 info = get_allocation_info(node);
402 req = arch_get_register_req_out(node);
404 in_node = skip_Proj(node);
405 if (req->type & arch_register_req_type_should_be_same) {
406 float weight = get_block_execfreq(execfreqs, block);
407 int arity = get_irn_arity(in_node);
410 assert(arity <= (int) sizeof(req->other_same) * 8);
411 for (i = 0; i < arity; ++i) {
413 const arch_register_t *reg;
415 if (!rbitset_is_set(&req->other_same, i))
418 in = get_irn_n(in_node, i);
419 reg = arch_get_irn_register(in);
421 r = arch_register_get_index(reg);
422 if (bitset_is_set(ignore_regs, r))
424 info->prefs[r] += weight * SHOULD_BE_SAME;
428 /* TODO: handle must_be_different */
431 DB((dbg, LEVEL_2, "Candidates for %+F:", node));
432 reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
433 fill_sort_candidates(reg_prefs, info);
434 for (i = 0; i < n_regs; ++i) {
435 unsigned num = reg_prefs[i].num;
436 const arch_register_t *reg = arch_register_for_index(cls, num);
437 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
439 DB((dbg, LEVEL_2, "\n"));
441 for (i = 0; i < n_regs; ++i) {
442 unsigned r = reg_prefs[i].num;
443 /* ignores should be last and we should have a non-ignore left */
444 assert(!bitset_is_set(ignore_regs, r));
445 /* already used? TODO: It might be better to copy the value occupying the register around here, find out when... */
446 if (assignments[r].value != NULL)
448 reg = arch_register_for_index(cls, r);
449 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
455 static void free_reg_of_value(ir_node *node)
457 allocation_info_t *info;
458 assignment_t *assignment;
461 if (!arch_irn_consider_in_reg_alloc(cls, node))
464 info = get_allocation_info(node);
465 assignment = info->current_assignment;
467 assert(assignment != NULL);
469 r = assignment - assignments;
470 DB((dbg, LEVEL_2, "Value %+F ended, freeing %s\n",
471 node, arch_register_for_index(cls, r)->name));
472 assignment->value = NULL;
473 info->current_assignment = NULL;
477 * Return the index of the currently assigned register of a node.
479 static unsigned get_current_reg(ir_node *node)
481 allocation_info_t *info = get_allocation_info(node);
482 assignment_t *assignment = info->current_assignment;
483 return assignment - assignments;
487 * Return the currently assigned assignment of a node.
489 static assignment_t *get_current_assignment(ir_node *node)
491 allocation_info_t *info = get_allocation_info(node);
492 return info->current_assignment;
496 * Add an permutation in front of a node and change the assignments
497 * due to this permutation.
499 * @param live_nodes the set of live nodes, updated due to live range split
500 * @param before the node before we add the permutation
501 * @param permutation the permutation array (map indexes to indexes)
503 static void permutate_values(ir_nodeset_t *live_nodes, ir_node *before,
504 unsigned *permutation)
507 ir_node **srcs = ALLOCANZ(ir_node*, n_regs);
508 unsigned *n_used = ALLOCANZ(unsigned, n_regs);
511 /* create a list of values which really need to be "permed" */
512 for (r = 0; r < n_regs; ++r) {
513 unsigned new_reg = permutation[r];
514 assignment_t *assignment;
520 assignment = &assignments[r];
521 value = assignment->value;
523 /* nothing to do here, reg is not live */
528 assert(srcs[new_reg] == NULL);
529 srcs[new_reg] = value;
532 free_reg_of_value(value);
533 ir_nodeset_remove(live_nodes, value);
536 block = get_nodes_block(before);
538 /* step1: create copies where immediately possible */
539 for (r = 0; r < n_regs; /* empty */) {
541 ir_node *src = srcs[r];
543 const arch_register_t *reg;
545 if (src == NULL || n_used[r] > 0) {
551 copy = be_new_Copy(cls, block, src);
552 reg = arch_register_for_index(cls, r);
553 DB((dbg, LEVEL_2, "Copy %+F (from %+F) -> %s\n", copy, src, reg->name));
556 sched_add_before(before, copy);
558 /* old register has 1 user less */
559 reg = arch_get_irn_register(src);
560 old_r = arch_register_get_index(reg);
561 assert(n_used[old_r] > 0);
572 /* create perms with the rest */
573 for (r = 0; r < n_regs; ++r) {
574 if (srcs[r] != NULL) {
575 assert (false && "perm creation not implemented yet");
581 * Free regs for values last used.
583 * @param live_nodes set of live nodes, will be updated
584 * @param node the node to consider
586 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
588 allocation_info_t *info = get_allocation_info(node);
589 int arity = get_irn_arity(node);
591 for (i = 0; i < arity; ++i) {
594 /* check if one operand is the last use */
595 if (!rbitset_is_set(&info->last_uses, i))
598 op = get_irn_n(node, i);
599 free_reg_of_value(op);
600 ir_nodeset_remove(live_nodes, op);
605 * Enforce constraints at a node by live range splits.
607 * @param live_nodes the set of live nodes, might be changed
608 * @param node the current node
610 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node)
612 int arity = get_irn_arity(node);
614 hungarian_problem_t *bp;
616 unsigned *assignment;
618 /* see if any use constraints are not met */
620 for (i = 0; i < arity; ++i) {
621 ir_node *op = get_irn_n(node, i);
622 const arch_register_req_t *req;
623 const unsigned *limited;
626 if (!arch_irn_consider_in_reg_alloc(cls, op))
629 /* are there any limitations for the i'th operand? */
630 req = arch_get_register_req(node, i);
631 if ((req->type & arch_register_req_type_limited) == 0)
634 limited = req->limited;
635 r = get_current_reg(op);
636 if (!rbitset_is_set(limited, r)) {
637 /* found an assignement outside the limited set */
646 /* swap values around */
647 bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
649 /* add all combinations, then remove not allowed ones */
650 for (l = 0; l < n_regs; ++l) {
651 if (bitset_is_set(ignore_regs, l)) {
652 hungarian_add(bp, l, l, 90);
656 for (r = 0; r < n_regs; ++r) {
657 if (bitset_is_set(ignore_regs, r))
660 hungarian_add(bp, l, r, l == r ? 90 : 89);
664 for (i = 0; i < arity; ++i) {
665 ir_node *op = get_irn_n(node, i);
666 const arch_register_req_t *req;
667 const unsigned *limited;
668 unsigned current_reg;
670 if (!arch_irn_consider_in_reg_alloc(cls, op))
673 req = arch_get_register_req(node, i);
674 if ((req->type & arch_register_req_type_limited) == 0)
677 limited = req->limited;
678 current_reg = get_current_reg(op);
679 for (r = 0; r < n_regs; ++r) {
680 if (rbitset_is_set(limited, r))
682 hungarian_remv(bp, current_reg, r);
686 hungarian_print_costmatrix(bp, 1);
687 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
689 assignment = ALLOCAN(unsigned, n_regs);
690 res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
693 printf("Swap result:");
694 for (p = 0; p < n_regs; ++p) {
695 printf(" %d", assignment[p]);
701 permutate_values(live_nodes, node, assignment);
705 * Walker: assign registers to all nodes of a block that
706 * needs registers from the currently considered register class.
708 static void allocate_coalesce_block(ir_node *block, void *data)
711 ir_nodeset_t live_nodes;
712 ir_nodeset_iterator_t iter;
713 ir_node *node, *start;
715 DB((dbg, LEVEL_2, "Allocating in block %+F\n",
718 /* clear assignments */
719 memset(assignments, 0, n_regs * sizeof(assignments[0]));
720 ir_nodeset_init(&live_nodes);
724 /* collect live-in nodes and preassigned values */
725 be_lv_foreach(lv, block, be_lv_state_in, i) {
726 const arch_register_t *reg;
728 node = be_lv_get_irn(lv, block, i);
729 if (!arch_irn_consider_in_reg_alloc(cls, node))
732 /* remember that this node is live at the beginning of the block */
733 ir_nodeset_insert(&live_nodes, node);
735 /* if the node already has a register assigned use it */
736 /* TODO: the value could already be copied away at this point and be in
738 reg = arch_get_irn_register(node);
745 node = sched_first(block);
746 for ( ; is_Phi(node); node = sched_next(node)) {
747 const arch_register_t *reg;
749 if (!arch_irn_consider_in_reg_alloc(cls, node))
752 /* fill in regs already assigned */
753 reg = arch_get_irn_register(node);
757 /* TODO: give boni for registers already assigned at the
763 /* assign regs for live-in values */
764 foreach_ir_nodeset(&live_nodes, node, iter) {
765 const arch_register_t *reg;
766 reg = arch_get_irn_register(node);
770 assign_reg(block, node);
773 /* assign instructions in the block */
774 for (node = start; !sched_is_end(node); node = sched_next(node)) {
775 int arity = get_irn_arity(node);
778 /* enforce use constraints */
779 enforce_constraints(&live_nodes, node);
781 /* exchange values to copied values where needed */
782 for (i = 0; i < arity; ++i) {
783 ir_node *op = get_irn_n(node, i);
784 assignment_t *assignment;
786 if (!arch_irn_consider_in_reg_alloc(cls, op))
788 assignment = get_current_assignment(op);
789 assert(assignment != NULL);
790 if (op != assignment->value) {
791 set_irn_n(node, i, assignment->value);
795 free_last_uses(&live_nodes, node);
797 /* assign output registers */
798 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
799 if (get_irn_mode(node) == mode_T) {
800 const ir_edge_t *edge;
801 foreach_out_edge(node, edge) {
802 ir_node *proj = get_edge_src_irn(edge);
803 if (!arch_irn_consider_in_reg_alloc(cls, proj))
805 assign_reg(block, proj);
807 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
808 assign_reg(block, node);
812 foreach_ir_nodeset(&live_nodes, node, iter) {
813 free_reg_of_value(node);
816 ir_nodeset_destroy(&live_nodes);
820 * Run the register allocator for the current register class.
822 static void be_straight_alloc_cls(void)
824 n_regs = arch_register_class_n_regs(cls);
825 lv = be_assure_liveness(birg);
826 be_liveness_assure_sets(lv);
827 be_liveness_assure_chk(lv);
829 assignments = obstack_alloc(&obst, n_regs * sizeof(assignments[0]));
831 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
832 inc_irg_visited(irg);
834 DB((dbg, LEVEL_2, "=== Registers in %s ===\n", cls->name));
836 irg_block_walk_graph(irg, NULL, analyze_block, NULL);
837 irg_block_walk_graph(irg, NULL, allocate_coalesce_block, NULL);
839 ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
843 * Run the spiller on the current graph.
845 static void spill(void)
847 /* make sure all nodes show their real register pressure */
848 BE_TIMER_PUSH(t_ra_constr);
849 be_pre_spill_prepare_constr(birg, cls);
850 BE_TIMER_POP(t_ra_constr);
853 BE_TIMER_PUSH(t_ra_spill);
854 be_do_spill(birg, cls);
855 BE_TIMER_POP(t_ra_spill);
857 BE_TIMER_PUSH(t_ra_spill_apply);
858 check_for_memory_operands(irg);
859 BE_TIMER_POP(t_ra_spill_apply);
863 * The straight register allocator for a whole procedure.
865 static void be_straight_alloc(be_irg_t *new_birg)
867 const arch_env_t *arch_env = new_birg->main_env->arch_env;
868 int n_cls = arch_env_get_n_reg_class(arch_env);
874 irg = be_get_birg_irg(birg);
875 execfreqs = birg->exec_freq;
877 /* TODO: extract some of the stuff from bechordal allocator, like
878 * statistics, time measurements, etc. and use them here too */
880 for (c = 0; c < n_cls; ++c) {
881 cls = arch_env_get_reg_class(arch_env, c);
882 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
885 stat_ev_ctx_push_str("bestraight_cls", cls->name);
887 n_regs = cls->n_regs;
888 ignore_regs = bitset_malloc(n_regs);
889 be_put_ignore_regs(birg, cls, ignore_regs);
893 /* verify schedule and register pressure */
894 BE_TIMER_PUSH(t_verify);
895 if (birg->main_env->options->vrfy_option == BE_CH_VRFY_WARN) {
896 be_verify_schedule(birg);
897 be_verify_register_pressure(birg, cls, irg);
898 } else if (birg->main_env->options->vrfy_option == BE_CH_VRFY_ASSERT) {
899 assert(be_verify_schedule(birg) && "Schedule verification failed");
900 assert(be_verify_register_pressure(birg, cls, irg)
901 && "Register pressure verification failed");
903 BE_TIMER_POP(t_verify);
905 BE_TIMER_PUSH(t_ra_color);
906 be_straight_alloc_cls();
907 BE_TIMER_POP(t_ra_color);
909 bitset_free(ignore_regs);
911 /* TODO: dump intermediate results */
913 stat_ev_ctx_pop("bestraight_cls");
916 obstack_free(&obst, NULL);
919 static be_ra_t be_ra_straight = {
924 * Initializes this module.
926 void be_init_straight_alloc(void)
928 FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
930 be_register_allocator("straight", &be_ra_straight);
933 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);