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
38 * registers with high preferences. When register constraints are not met,
39 * add copies and split live-ranges.
42 * - make use of free registers in the permutate_values code
43 * - We have to pessimistically construct Phi_0s when not all predecessors
44 * of a block are known.
45 * - Phi color assignment should give bonus points towards registers already
46 * assigned at predecessors.
47 * - think about a smarter sequence of visiting the blocks. Sorted by
48 * execfreq might be good, or looptree from inner to outermost loops going
49 * over blocks in a reverse postorder
50 * - propagate preferences through Phis
61 #include "iredges_t.h"
62 #include "irgraph_t.h"
66 #include "raw_bitset.h"
69 #include "bechordal_t.h"
78 #include "bespillutil.h"
81 #include "hungarian.h"
83 #define USE_FACTOR 1.0f
84 #define DEF_FACTOR 1.0f
85 #define NEIGHBOR_FACTOR 0.2f
86 #define AFF_SHOULD_BE_SAME 1.0f
89 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
91 static struct obstack obst;
92 static be_irg_t *birg;
94 static const arch_register_class_t *cls;
95 static const arch_register_req_t *default_cls_req;
97 static const ir_exec_freq *execfreqs;
98 static unsigned n_regs;
99 static unsigned *normal_regs;
101 /** info about the current assignment for a register */
102 struct assignment_t {
103 ir_node *value; /**< currently assigned value */
105 typedef struct assignment_t assignment_t;
107 /** currently active assignments (while processing a basic block) */
108 static assignment_t *assignments;
111 * allocation information: last_uses, register preferences
112 * the information is per firm-node.
114 struct allocation_info_t {
115 unsigned last_uses; /**< bitset indicating last uses (input pos) */
116 ir_node *current_value; /**< copy of the value that should be used */
117 ir_node *original_value; /**< for copies point to original value */
118 float prefs[0]; /**< register preferences */
120 typedef struct allocation_info_t allocation_info_t;
122 /** helper datastructure used when sorting register preferences */
127 typedef struct reg_pref_t reg_pref_t;
129 /** per basic-block information */
130 struct block_info_t {
131 bool processed; /**< indicate wether block is processed */
132 assignment_t assignments[0]; /**< register assignments at end of block */
134 typedef struct block_info_t block_info_t;
137 * Get the allocation info for a node.
138 * The info is allocated on the first visit of a node.
140 static allocation_info_t *get_allocation_info(ir_node *node)
142 allocation_info_t *info;
143 if (!irn_visited_else_mark(node)) {
144 size_t size = sizeof(info[0]) + n_regs * sizeof(info->prefs[0]);
145 info = obstack_alloc(&obst, size);
146 memset(info, 0, size);
147 info->current_value = node;
148 info->original_value = node;
149 set_irn_link(node, info);
151 info = get_irn_link(node);
158 * Get allocation information for a basic block
160 static block_info_t *get_block_info(ir_node *block)
164 assert(is_Block(block));
165 if (!irn_visited_else_mark(block)) {
166 size_t size = sizeof(info[0]) + n_regs * sizeof(info->assignments[0]);
167 info = obstack_alloc(&obst, size);
168 memset(info, 0, size);
169 set_irn_link(block, info);
171 info = get_irn_link(block);
178 * Get default register requirement for the current register class
180 static const arch_register_req_t *get_default_req_current_cls(void)
182 if (default_cls_req == NULL) {
183 struct obstack *obst = get_irg_obstack(irg);
184 arch_register_req_t *req = obstack_alloc(obst, sizeof(*req));
185 memset(req, 0, sizeof(*req));
187 req->type = arch_register_req_type_normal;
190 default_cls_req = req;
192 return default_cls_req;
196 * Link the allocation info of a node to a copy.
197 * Afterwards, both nodes uses the same allocation info.
198 * Copy must not have an allocation info assigned yet.
200 * @param copy the node that gets the allocation info assigned
201 * @param value the original node
203 static void mark_as_copy_of(ir_node *copy, ir_node *value)
206 allocation_info_t *info = get_allocation_info(value);
207 allocation_info_t *copy_info = get_allocation_info(copy);
209 /* find original value */
210 original = info->original_value;
211 if (original != value) {
212 info = get_allocation_info(original);
215 assert(info->original_value == original);
216 info->current_value = copy;
218 /* the copy should not be linked to something else yet */
219 assert(copy_info->original_value == copy);
220 /* copy over allocation preferences */
221 memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
222 copy_info->original_value = original;
226 * Calculate the penalties for every register on a node and its live neighbors.
228 * @param live_nodes the set of live nodes at the current position, may be NULL
229 * @param penalty the penalty to subtract from
230 * @param limited a raw bitset containing the limited set for the node
231 * @param node the node
233 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
234 float penalty, const unsigned* limited,
237 ir_nodeset_iterator_t iter;
239 allocation_info_t *info = get_allocation_info(node);
242 /* give penalty for all forbidden regs */
243 for (r = 0; r < n_regs; ++r) {
244 if (rbitset_is_set(limited, r))
247 info->prefs[r] -= penalty;
250 /* all other live values should get a penalty for allowed regs */
251 if (live_nodes == NULL)
254 /* TODO: reduce penalty if there are multiple allowed registers... */
255 penalty *= NEIGHBOR_FACTOR;
256 foreach_ir_nodeset(live_nodes, neighbor, iter) {
257 allocation_info_t *neighbor_info;
259 /* TODO: if op is used on multiple inputs we might not do a
261 if (neighbor == node)
264 neighbor_info = get_allocation_info(neighbor);
265 for (r = 0; r < n_regs; ++r) {
266 if (!rbitset_is_set(limited, r))
269 neighbor_info->prefs[r] -= penalty;
275 * Calculate the preferences of a definition for the current register class.
276 * If the definition uses a limited set of registers, reduce the preferences
277 * for the limited register on the node and its neighbors.
279 * @param live_nodes the set of live nodes at the current node
280 * @param weight the weight
281 * @param node the current node
283 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
286 const arch_register_req_t *req;
288 if (get_irn_mode(node) == mode_T) {
289 const ir_edge_t *edge;
290 foreach_out_edge(node, edge) {
291 ir_node *proj = get_edge_src_irn(edge);
292 check_defs(live_nodes, weight, proj);
297 if (!arch_irn_consider_in_reg_alloc(cls, node))
300 req = arch_get_register_req_out(node);
301 if (req->type & arch_register_req_type_limited) {
302 const unsigned *limited = req->limited;
303 float penalty = weight * DEF_FACTOR;
304 give_penalties_for_limits(live_nodes, penalty, limited, node);
307 if (req->type & arch_register_req_type_should_be_same) {
308 ir_node *insn = skip_Proj(node);
309 allocation_info_t *info = get_allocation_info(node);
310 int arity = get_irn_arity(insn);
313 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
314 for (i = 0; i < arity; ++i) {
317 allocation_info_t *op_info;
319 if (!rbitset_is_set(&req->other_same, i))
322 op = get_irn_n(insn, i);
323 op_info = get_allocation_info(op);
324 for (r = 0; r < n_regs; ++r) {
325 op_info->prefs[r] += info->prefs[r] * factor;
332 * Walker: Runs an a block calculates the preferences for any
333 * node and every register from the considered register class.
335 static void analyze_block(ir_node *block, void *data)
337 float weight = get_block_execfreq(execfreqs, block);
338 ir_nodeset_t live_nodes;
342 ir_nodeset_init(&live_nodes);
343 be_liveness_end_of_block(lv, cls, block, &live_nodes);
345 sched_foreach_reverse(block, node) {
346 allocation_info_t *info;
353 /* TODO give/take penalties for should_be_same/different) */
354 check_defs(&live_nodes, weight, node);
357 arity = get_irn_arity(node);
359 /* the allocation info node currently only uses 1 unsigned value
360 to mark last used inputs. So we will fail for a node with more than
362 if (arity >= (int) sizeof(unsigned) * 8) {
363 panic("Node with more than %d inputs not supported yet",
364 (int) sizeof(unsigned) * 8);
367 info = get_allocation_info(node);
368 for (i = 0; i < arity; ++i) {
369 ir_node *op = get_irn_n(node, i);
370 if (!arch_irn_consider_in_reg_alloc(cls, op))
373 /* last usage of a value? */
374 if (!ir_nodeset_contains(&live_nodes, op)) {
375 rbitset_set(&info->last_uses, i);
379 be_liveness_transfer(cls, node, &live_nodes);
381 /* update weights based on usage constraints */
382 for (i = 0; i < arity; ++i) {
383 const arch_register_req_t *req;
384 const unsigned *limited;
385 ir_node *op = get_irn_n(node, i);
387 if (!arch_irn_consider_in_reg_alloc(cls, op))
390 req = arch_get_register_req(node, i);
391 if (!(req->type & arch_register_req_type_limited))
394 /* TODO: give penalties to neighbors for precolored nodes! */
396 limited = req->limited;
397 give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
402 ir_nodeset_destroy(&live_nodes);
406 * Assign register reg to the given node.
408 * @param node the node
409 * @param reg the register
411 static void use_reg(ir_node *node, const arch_register_t *reg)
413 unsigned r = arch_register_get_index(reg);
414 assignments[r].value = node;
415 arch_set_irn_register(node, reg);
419 * Compare two register preferences in decreasing order.
421 static int compare_reg_pref(const void *e1, const void *e2)
423 const reg_pref_t *rp1 = (const reg_pref_t*) e1;
424 const reg_pref_t *rp2 = (const reg_pref_t*) e2;
425 if (rp1->pref < rp2->pref)
427 if (rp1->pref > rp2->pref)
432 static void fill_sort_candidates(reg_pref_t *regprefs,
433 const allocation_info_t *info)
437 for (r = 0; r < n_regs; ++r) {
438 float pref = info->prefs[r];
440 regprefs[r].pref = pref;
442 /* TODO: use a stable sort here to avoid unnecessary register jumping */
443 qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
447 * Determine and assign a register for node @p node
449 static void assign_reg(const ir_node *block, ir_node *node)
451 const arch_register_t *reg;
452 allocation_info_t *info;
453 const arch_register_req_t *req;
454 reg_pref_t *reg_prefs;
457 const unsigned *allowed_regs;
459 assert(arch_irn_consider_in_reg_alloc(cls, node));
461 /* preassigned register? */
462 reg = arch_get_irn_register(node);
464 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
469 /* give should_be_same boni */
470 info = get_allocation_info(node);
471 req = arch_get_register_req_out(node);
473 in_node = skip_Proj(node);
474 if (req->type & arch_register_req_type_should_be_same) {
475 float weight = get_block_execfreq(execfreqs, block);
476 int arity = get_irn_arity(in_node);
479 assert(arity <= (int) sizeof(req->other_same) * 8);
480 for (i = 0; i < arity; ++i) {
482 const arch_register_t *reg;
484 if (!rbitset_is_set(&req->other_same, i))
487 in = get_irn_n(in_node, i);
488 reg = arch_get_irn_register(in);
490 r = arch_register_get_index(reg);
491 info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
495 DB((dbg, LEVEL_2, "Candidates for %+F:", node));
496 reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
497 fill_sort_candidates(reg_prefs, info);
498 for (i = 0; i < n_regs; ++i) {
499 unsigned num = reg_prefs[i].num;
500 const arch_register_t *reg = arch_register_for_index(cls, num);
501 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
503 DB((dbg, LEVEL_2, "\n"));
505 allowed_regs = normal_regs;
506 if (req->type & arch_register_req_type_limited) {
507 allowed_regs = req->limited;
510 for (i = 0; i < n_regs; ++i) {
511 unsigned r = reg_prefs[i].num;
513 TODO: It might be better to copy the value occupying the register
514 around here instead of trying the next one, find out when... */
515 if (assignments[r].value != NULL)
517 if (!rbitset_is_set(allowed_regs, r))
519 reg = arch_register_for_index(cls, r);
520 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
526 static void free_reg_of_value(ir_node *node)
528 assignment_t *assignment;
529 const arch_register_t *reg;
532 if (!arch_irn_consider_in_reg_alloc(cls, node))
535 reg = arch_get_irn_register(node);
536 r = arch_register_get_index(reg);
537 assignment = &assignments[r];
538 assert(assignment->value == node);
539 assignment->value = NULL;
543 * Add an permutation in front of a node and change the assignments
544 * due to this permutation.
546 * To understand this imagine a permutation like this:
556 * First we count how many destinations a single value has. At the same time
557 * we can be sure that each destination register has at most 1 source register
558 * (it can have 0 which means we don't care what value is in it).
559 * We ignore all fullfilled permuations (like 7->7)
560 * In a first pass we create as much copy instructions as possible as they
561 * are generally cheaper than exchanges. We do this by counting into how many
562 * destinations a register has to be copied (in the example it's 2 for register
563 * 3, or 1 for the registers 1,2,4 and 7).
564 * We can then create a copy into every destination register when the usecount
565 * of that register is 0 (= noone else needs the value in the register).
567 * After this step we should have cycles left. We implement a cyclic permutation
568 * of n registers with n-1 transpositions.
570 * @param live_nodes the set of live nodes, updated due to live range split
571 * @param before the node before we add the permutation
572 * @param permutation the permutation array indices are the destination
573 * registers, the values in the array are the source
576 static void permutate_values(ir_nodeset_t *live_nodes, ir_node *before,
577 unsigned *permutation)
579 unsigned *n_used = ALLOCANZ(unsigned, n_regs);
583 /* determine how often each source register needs to be read */
584 for (r = 0; r < n_regs; ++r) {
585 unsigned old_reg = permutation[r];
588 value = assignments[old_reg].value;
590 /* nothing to do here, reg is not live. Mark it as fixpoint
591 * so we ignore it in the next steps */
599 block = get_nodes_block(before);
601 /* step1: create copies where immediately possible */
602 for (r = 0; r < n_regs; /* empty */) {
605 const arch_register_t *reg;
606 unsigned old_r = permutation[r];
608 /* - no need to do anything for fixed points.
609 - we can't copy if the value in the dest reg is still needed */
610 if (old_r == r || n_used[r] > 0) {
616 src = assignments[old_r].value;
617 copy = be_new_Copy(cls, block, src);
618 sched_add_before(before, copy);
619 reg = arch_register_for_index(cls, r);
620 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
621 copy, src, before, reg->name));
622 mark_as_copy_of(copy, src);
625 if (live_nodes != NULL) {
626 ir_nodeset_insert(live_nodes, copy);
629 /* old register has 1 user less, permutation is resolved */
630 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
633 assert(n_used[old_r] > 0);
635 if (n_used[old_r] == 0) {
636 if (live_nodes != NULL) {
637 ir_nodeset_remove(live_nodes, src);
639 free_reg_of_value(src);
642 /* advance or jump back (if this copy enabled another copy) */
643 if (old_r < r && n_used[old_r] == 0) {
650 /* at this point we only have "cycles" left which we have to resolve with
652 * TODO: if we have free registers left, then we should really use copy
653 * instructions for any cycle longer than 2 registers...
654 * (this is probably architecture dependent, there might be archs where
655 * copies are preferable even for 2-cycles) */
657 /* create perms with the rest */
658 for (r = 0; r < n_regs; /* empty */) {
659 const arch_register_t *reg;
660 unsigned old_r = permutation[r];
672 /* we shouldn't have copies from 1 value to multiple destinations left*/
673 assert(n_used[old_r] == 1);
675 /* exchange old_r and r2; after that old_r is a fixed point */
676 r2 = permutation[old_r];
678 in[0] = assignments[r2].value;
679 in[1] = assignments[old_r].value;
680 perm = be_new_Perm(cls, block, 2, in);
681 sched_add_before(before, perm);
682 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
683 perm, in[0], in[1], before));
685 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
686 mark_as_copy_of(proj0, in[0]);
687 reg = arch_register_for_index(cls, old_r);
690 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
691 mark_as_copy_of(proj1, in[1]);
692 reg = arch_register_for_index(cls, r2);
695 /* 1 value is now in the correct register */
696 permutation[old_r] = old_r;
697 /* the source of r changed to r2 */
700 /* if we have reached a fixpoint update data structures */
701 if (live_nodes != NULL) {
702 ir_nodeset_remove(live_nodes, in[0]);
703 ir_nodeset_remove(live_nodes, in[1]);
704 ir_nodeset_remove(live_nodes, proj0);
705 ir_nodeset_insert(live_nodes, proj1);
710 /* now we should only have fixpoints left */
711 for (r = 0; r < n_regs; ++r) {
712 assert(permutation[r] == r);
718 * Free regs for values last used.
720 * @param live_nodes set of live nodes, will be updated
721 * @param node the node to consider
723 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
725 allocation_info_t *info = get_allocation_info(node);
726 const unsigned *last_uses = &info->last_uses;
727 int arity = get_irn_arity(node);
729 for (i = 0; i < arity; ++i) {
732 /* check if one operand is the last use */
733 if (!rbitset_is_set(last_uses, i))
736 op = get_irn_n(node, i);
737 free_reg_of_value(op);
738 ir_nodeset_remove(live_nodes, op);
743 * change inputs of a node to the current value (copies/perms)
745 static void rewire_inputs(ir_node *node)
748 int arity = get_irn_arity(node);
750 for (i = 0; i < arity; ++i) {
751 ir_node *op = get_irn_n(node, i);
752 allocation_info_t *info;
754 if (!arch_irn_consider_in_reg_alloc(cls, op))
757 info = get_allocation_info(op);
758 if (info->current_value != op) {
759 set_irn_n(node, i, info->current_value);
765 * Create a bitset of registers occupied with value living through an
768 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
770 const allocation_info_t *info = get_allocation_info(node);
775 /* mark all used registers as potentially live-through */
776 for (r = 0; r < n_regs; ++r) {
777 const assignment_t *assignment = &assignments[r];
778 if (assignment->value == NULL)
780 if (!rbitset_is_set(normal_regs, r))
783 rbitset_set(bitset, r);
786 /* remove registers of value dying at the instruction */
787 arity = get_irn_arity(node);
788 for (i = 0; i < arity; ++i) {
790 const arch_register_t *reg;
792 if (!rbitset_is_set(&info->last_uses, i))
795 op = get_irn_n(node, i);
796 op = get_allocation_info(op)->current_value;
797 reg = arch_get_irn_register(op);
798 rbitset_clear(bitset, arch_register_get_index(reg));
803 * Enforce constraints at a node by live range splits.
805 * @param live_nodes the set of live nodes, might be changed
806 * @param node the current node
808 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node)
810 int arity = get_irn_arity(node);
812 hungarian_problem_t *bp;
814 unsigned *assignment;
816 /* construct a list of register occupied by live-through values */
817 unsigned *live_through_regs = NULL;
818 unsigned *output_regs = NULL;
820 /* see if any use constraints are not met */
822 for (i = 0; i < arity; ++i) {
823 ir_node *op = get_irn_n(node, i);
824 const arch_register_t *reg;
825 const arch_register_req_t *req;
826 const unsigned *limited;
829 if (!arch_irn_consider_in_reg_alloc(cls, op))
832 /* are there any limitations for the i'th operand? */
833 req = arch_get_register_req(node, i);
834 if (!(req->type & arch_register_req_type_limited))
837 limited = req->limited;
838 reg = arch_get_irn_register(op);
839 r = arch_register_get_index(reg);
840 if (!rbitset_is_set(limited, r)) {
841 /* found an assignment outside the limited set */
847 /* is any of the live-throughs using a constrained output register? */
848 if (get_irn_mode(node) == mode_T) {
849 const ir_edge_t *edge;
851 foreach_out_edge(node, edge) {
852 ir_node *proj = get_edge_src_irn(edge);
853 const arch_register_req_t *req;
855 if (!arch_irn_consider_in_reg_alloc(cls, proj))
858 req = arch_get_register_req_out(proj);
859 if (!(req->type & arch_register_req_type_limited))
862 if (live_through_regs == NULL) {
863 rbitset_alloca(live_through_regs, n_regs);
864 determine_live_through_regs(live_through_regs, node);
866 rbitset_alloca(output_regs, n_regs);
869 rbitset_or(output_regs, req->limited, n_regs);
870 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
875 if (arch_irn_consider_in_reg_alloc(cls, node)) {
876 const arch_register_req_t *req = arch_get_register_req_out(node);
877 if (req->type & arch_register_req_type_limited) {
878 rbitset_alloca(live_through_regs, n_regs);
879 determine_live_through_regs(live_through_regs, node);
880 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
883 rbitset_alloca(output_regs, n_regs);
884 rbitset_or(output_regs, req->limited, n_regs);
893 /* create these arrays if we haven't yet */
894 if (output_regs == NULL) {
895 if (live_through_regs == NULL) {
896 rbitset_alloca(live_through_regs, n_regs);
898 rbitset_alloca(output_regs, n_regs);
901 /* at this point we have to construct a bipartite matching problem to see
902 * which values should go to which registers
903 * Note: We're building the matrix in "reverse" - source registers are
904 * right, destinations at l because this will produce the solution
905 * in the format required for permutate_values.
907 bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
909 /* add all combinations, then remove not allowed ones */
910 for (l = 0; l < n_regs; ++l) {
911 if (!rbitset_is_set(normal_regs, l)) {
912 hungarian_add(bp, l, l, 1);
916 for (r = 0; r < n_regs; ++r) {
917 if (!rbitset_is_set(normal_regs, r))
919 /* livethrough values may not use constrainted output registers */
920 if (rbitset_is_set(live_through_regs, l)
921 && rbitset_is_set(output_regs, r))
924 hungarian_add(bp, r, l, l == r ? 9 : 8);
928 for (i = 0; i < arity; ++i) {
929 ir_node *op = get_irn_n(node, i);
930 const arch_register_t *reg;
931 const arch_register_req_t *req;
932 const unsigned *limited;
933 unsigned current_reg;
935 if (!arch_irn_consider_in_reg_alloc(cls, op))
938 req = arch_get_register_req(node, i);
939 if (!(req->type & arch_register_req_type_limited))
942 limited = req->limited;
943 op = get_allocation_info(op)->current_value;
944 reg = arch_get_irn_register(op);
945 current_reg = arch_register_get_index(reg);
946 for (r = 0; r < n_regs; ++r) {
947 if (rbitset_is_set(limited, r))
949 hungarian_remv(bp, r, current_reg);
953 //hungarian_print_costmatrix(bp, 1);
954 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
956 assignment = ALLOCAN(unsigned, n_regs);
957 res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
961 fprintf(stderr, "Swap result:");
962 for (i = 0; i < (int) n_regs; ++i) {
963 fprintf(stderr, " %d", assignment[i]);
965 fprintf(stderr, "\n");
970 permutate_values(live_nodes, node, assignment);
973 /** test wether a node @p n is a copy of the value of node @p of */
974 static bool is_copy_of(ir_node *value, ir_node *test_value)
976 allocation_info_t *test_info;
977 allocation_info_t *info;
979 if (value == test_value)
982 info = get_allocation_info(value);
983 test_info = get_allocation_info(test_value);
984 return test_info->original_value == info->original_value;
988 * find a value in the end-assignment of a basic block
989 * @returns the index into the assignment array if found
992 static int find_value_in_block_info(block_info_t *info, ir_node *value)
995 assignment_t *assignments = info->assignments;
996 for (r = 0; r < n_regs; ++r) {
997 const assignment_t *assignment = &assignments[r];
998 ir_node *a_value = assignment->value;
1000 if (a_value == NULL)
1002 if (is_copy_of(a_value, value))
1010 * Create the necessary permutations at the end of a basic block to fullfill
1011 * the register assignment for phi-nodes in the next block
1013 static void add_phi_permutations(ir_node *block, int p)
1016 unsigned *permutation;
1017 assignment_t *old_assignments;
1018 bool need_permutation;
1020 ir_node *pred = get_Block_cfgpred_block(block, p);
1022 block_info_t *pred_info = get_block_info(pred);
1024 /* predecessor not processed yet? nothing to do */
1025 if (!pred_info->processed)
1028 permutation = ALLOCAN(unsigned, n_regs);
1029 for (r = 0; r < n_regs; ++r) {
1033 /* check phi nodes */
1034 need_permutation = false;
1035 node = sched_first(block);
1036 for ( ; is_Phi(node); node = sched_next(node)) {
1037 const arch_register_t *reg;
1042 if (!arch_irn_consider_in_reg_alloc(cls, node))
1045 op = get_Phi_pred(node, p);
1046 a = find_value_in_block_info(pred_info, op);
1049 reg = arch_get_irn_register(node);
1050 regn = arch_register_get_index(reg);
1052 permutation[regn] = a;
1053 need_permutation = true;
1057 if (need_permutation) {
1058 /* permutate values at end of predecessor */
1059 old_assignments = assignments;
1060 assignments = pred_info->assignments;
1061 permutate_values(NULL, be_get_end_of_block_insertion_point(pred),
1063 assignments = old_assignments;
1066 /* change phi nodes to use the copied values */
1067 node = sched_first(block);
1068 for ( ; is_Phi(node); node = sched_next(node)) {
1072 if (!arch_irn_consider_in_reg_alloc(cls, node))
1075 /* we have permutated all values into the correct registers so we can
1076 simply query which value occupies the phis register in the
1078 a = arch_register_get_index(arch_get_irn_register(node));
1079 op = pred_info->assignments[a].value;
1080 set_Phi_pred(node, p, op);
1084 static void handle_phi_prefs(ir_node *phi)
1087 int arity = get_irn_arity(phi);
1088 ir_node *block = get_nodes_block(phi);
1089 allocation_info_t *info = get_allocation_info(phi);
1091 for (i = 0; i < arity; ++i) {
1092 ir_node *op = get_irn_n(phi, i);
1093 const arch_register_t *reg = arch_get_irn_register(op);
1101 /* give bonus for already assigned register */
1102 pred = get_Block_cfgpred_block(block, i);
1103 weight = get_block_execfreq(execfreqs, pred);
1104 r = arch_register_get_index(reg);
1105 info->prefs[r] += weight * AFF_PHI;
1110 * Walker: assign registers to all nodes of a block that
1111 * need registers from the currently considered register class.
1113 static void allocate_coalesce_block(ir_node *block, void *data)
1116 ir_nodeset_t live_nodes;
1117 ir_nodeset_iterator_t iter;
1118 ir_node *node, *start;
1120 block_info_t *block_info;
1121 block_info_t **pred_block_infos;
1125 DB((dbg, LEVEL_2, "* Block %+F\n", block));
1127 /* clear assignments */
1128 block_info = get_block_info(block);
1129 assignments = block_info->assignments;
1131 ir_nodeset_init(&live_nodes);
1133 /* gather regalloc infos of predecessor blocks */
1134 n_preds = get_Block_n_cfgpreds(block);
1135 pred_block_infos = ALLOCAN(block_info_t*, n_preds);
1136 for (i = 0; i < n_preds; ++i) {
1137 ir_node *pred = get_Block_cfgpred_block(block, i);
1138 block_info_t *pred_info = get_block_info(pred);
1139 pred_block_infos[i] = pred_info;
1142 phi_ins = ALLOCAN(ir_node*, n_preds);
1144 /* collect live-in nodes and preassigned values */
1145 be_lv_foreach(lv, block, be_lv_state_in, i) {
1146 const arch_register_t *reg;
1148 bool need_phi = false;
1150 node = be_lv_get_irn(lv, block, i);
1151 if (!arch_irn_consider_in_reg_alloc(cls, node))
1154 /* check all predecessors for this value, if it is not everywhere the
1155 same or unknown then we have to construct a phi
1156 (we collect the potential phi inputs here) */
1157 for (p = 0; p < n_preds; ++p) {
1158 block_info_t *pred_info = pred_block_infos[p];
1160 if (!pred_info->processed) {
1161 /* use node for now, it will get fixed later */
1165 int a = find_value_in_block_info(pred_info, node);
1167 /* must live out of predecessor */
1169 phi_ins[p] = pred_info->assignments[a].value;
1170 /* different value from last time? then we need a phi */
1171 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1178 ir_mode *mode = get_irn_mode(node);
1179 const arch_register_req_t *req = get_default_req_current_cls();
1182 phi = new_r_Phi(block, n_preds, phi_ins, mode);
1183 be_set_phi_reg_req(phi, req);
1185 DB((dbg, LEVEL_3, "Create Phi %+F (for %+F)\n", phi, node));
1187 mark_as_copy_of(phi, node);
1188 sched_add_after(block, phi);
1192 allocation_info_t *info = get_allocation_info(node);
1193 info->current_value = phi_ins[0];
1195 /* Grab 1 of the inputs we constructed (might not be the same as
1196 * "node" as we could see the same copy of the value in all
1201 /* if the node already has a register assigned use it */
1202 reg = arch_get_irn_register(node);
1204 /* TODO: consult pred-block infos here. The value could be copied
1205 away in some/all predecessor blocks. We need to construct
1206 phi-nodes in this case.
1207 We even need to construct some Phi_0 like constructs in cases
1208 where the predecessor allocation is not determined yet. */
1212 /* remember that this node is live at the beginning of the block */
1213 ir_nodeset_insert(&live_nodes, node);
1216 /* handle phis... */
1217 node = sched_first(block);
1218 for ( ; is_Phi(node); node = sched_next(node)) {
1219 const arch_register_t *reg;
1221 if (!arch_irn_consider_in_reg_alloc(cls, node))
1224 /* fill in regs already assigned */
1225 reg = arch_get_irn_register(node);
1229 /* TODO: give boni for registers already assigned at the
1231 handle_phi_prefs(node);
1232 assign_reg(block, node);
1237 /* assign regs for live-in values */
1238 foreach_ir_nodeset(&live_nodes, node, iter) {
1239 const arch_register_t *reg = arch_get_irn_register(node);
1243 assign_reg(block, node);
1246 /* assign instructions in the block */
1247 for (node = start; !sched_is_end(node); node = sched_next(node)) {
1248 /* enforce use constraints */
1249 enforce_constraints(&live_nodes, node);
1251 rewire_inputs(node);
1253 /* free registers of values last used at this instruction */
1254 free_last_uses(&live_nodes, node);
1256 /* assign output registers */
1257 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1258 if (get_irn_mode(node) == mode_T) {
1259 const ir_edge_t *edge;
1260 foreach_out_edge(node, edge) {
1261 ir_node *proj = get_edge_src_irn(edge);
1262 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1264 assign_reg(block, proj);
1266 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1267 assign_reg(block, node);
1271 ir_nodeset_destroy(&live_nodes);
1274 block_info->processed = true;
1276 /* permutate values at end of predecessor blocks in case of phi-nodes */
1279 for (p = 0; p < n_preds; ++p) {
1280 add_phi_permutations(block, p);
1284 /* if we have exactly 1 successor then we might be able to produce phi
1286 if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1287 const ir_edge_t *edge
1288 = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1289 ir_node *succ = get_edge_src_irn(edge);
1290 int p = get_edge_src_pos(edge);
1291 block_info_t *succ_info = get_block_info(succ);
1293 if (succ_info->processed) {
1294 add_phi_permutations(succ, p);
1300 * Run the register allocator for the current register class.
1302 static void be_straight_alloc_cls(void)
1304 lv = be_assure_liveness(birg);
1305 be_liveness_assure_sets(lv);
1306 be_liveness_assure_chk(lv);
1308 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1309 inc_irg_visited(irg);
1311 DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1313 irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1314 /* we need some dominance pre-order walk to ensure we see all
1315 * definitions/create copies before we encounter their users */
1316 dom_tree_walk_irg(irg, allocate_coalesce_block, NULL, NULL);
1318 ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1321 static void dump(int mask, ir_graph *irg, const char *suffix,
1322 void (*dumper)(ir_graph *, const char *))
1324 if(birg->main_env->options->dump_flags & mask)
1325 be_dump(irg, suffix, dumper);
1329 * Run the spiller on the current graph.
1331 static void spill(void)
1333 /* make sure all nodes show their real register pressure */
1334 BE_TIMER_PUSH(t_ra_constr);
1335 be_pre_spill_prepare_constr(birg, cls);
1336 BE_TIMER_POP(t_ra_constr);
1338 dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1341 BE_TIMER_PUSH(t_ra_spill);
1342 be_do_spill(birg, cls);
1343 BE_TIMER_POP(t_ra_spill);
1345 BE_TIMER_PUSH(t_ra_spill_apply);
1346 check_for_memory_operands(irg);
1347 BE_TIMER_POP(t_ra_spill_apply);
1349 dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1353 * The straight register allocator for a whole procedure.
1355 static void be_straight_alloc(be_irg_t *new_birg)
1357 const arch_env_t *arch_env = new_birg->main_env->arch_env;
1358 int n_cls = arch_env_get_n_reg_class(arch_env);
1361 obstack_init(&obst);
1364 irg = be_get_birg_irg(birg);
1365 execfreqs = birg->exec_freq;
1367 /* TODO: extract some of the stuff from bechordal allocator, like
1368 * statistics, time measurements, etc. and use them here too */
1370 for (c = 0; c < n_cls; ++c) {
1371 cls = arch_env_get_reg_class(arch_env, c);
1372 default_cls_req = NULL;
1373 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1376 stat_ev_ctx_push_str("regcls", cls->name);
1378 n_regs = arch_register_class_n_regs(cls);
1379 normal_regs = rbitset_malloc(n_regs);
1380 be_abi_set_non_ignore_regs(birg->abi, cls, normal_regs);
1384 /* verify schedule and register pressure */
1385 BE_TIMER_PUSH(t_verify);
1386 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1387 be_verify_schedule(birg);
1388 be_verify_register_pressure(birg, cls, irg);
1389 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1390 assert(be_verify_schedule(birg) && "Schedule verification failed");
1391 assert(be_verify_register_pressure(birg, cls, irg)
1392 && "Register pressure verification failed");
1394 BE_TIMER_POP(t_verify);
1396 BE_TIMER_PUSH(t_ra_color);
1397 be_straight_alloc_cls();
1398 BE_TIMER_POP(t_ra_color);
1400 /* we most probably constructed new Phis so liveness info is invalid
1402 /* TODO: test liveness_introduce */
1403 be_liveness_invalidate(lv);
1406 stat_ev_ctx_pop("regcls");
1409 BE_TIMER_PUSH(t_ra_spill_apply);
1410 be_abi_fix_stack_nodes(birg->abi);
1411 BE_TIMER_POP(t_ra_spill_apply);
1413 BE_TIMER_PUSH(t_verify);
1414 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1415 be_verify_register_allocation(birg);
1416 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1417 assert(be_verify_register_allocation(birg)
1418 && "Register allocation invalid");
1420 BE_TIMER_POP(t_verify);
1422 obstack_free(&obst, NULL);
1426 * Initializes this module.
1428 void be_init_straight_alloc(void)
1430 static be_ra_t be_ra_straight = {
1434 FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
1436 be_register_allocator("straight", &be_ra_straight);
1439 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);