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 permute_values code
43 * - think about a smarter sequence of visiting the blocks. Sorted by
44 * execfreq might be good, or looptree from inner to outermost loops going
45 * over blocks in a reverse postorder
46 * - propagate preferences through Phis
57 #include "iredges_t.h"
58 #include "irgraph_t.h"
62 #include "raw_bitset.h"
65 #include "bechordal_t.h"
74 #include "bespillutil.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 AFF_SHOULD_BE_SAME 0.5f
84 #define SPLIT_DELTA 1.0f
86 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
88 static struct obstack obst;
89 static be_irg_t *birg;
91 static const arch_register_class_t *cls;
92 static const arch_register_req_t *default_cls_req;
94 static const ir_exec_freq *execfreqs;
95 static unsigned n_regs;
96 static unsigned *normal_regs;
98 /** info about the current assignment for a register */
100 ir_node *value; /**< currently assigned value */
102 typedef struct assignment_t assignment_t;
104 /** currently active assignments (while processing a basic block) */
105 static assignment_t *assignments;
108 * allocation information: last_uses, register preferences
109 * the information is per firm-node.
111 struct allocation_info_t {
112 unsigned last_uses; /**< bitset indicating last uses (input pos) */
113 ir_node *current_value; /**< copy of the value that should be used */
114 ir_node *original_value; /**< for copies point to original value */
115 float prefs[0]; /**< register preferences */
117 typedef struct allocation_info_t allocation_info_t;
119 /** helper datastructure used when sorting register preferences */
124 typedef struct reg_pref_t reg_pref_t;
126 /** per basic-block information */
127 struct block_info_t {
128 bool processed; /**< indicate wether block is processed */
129 assignment_t assignments[0]; /**< register assignments at end of block */
131 typedef struct block_info_t block_info_t;
134 * Get the allocation info for a node.
135 * The info is allocated on the first visit of a node.
137 static allocation_info_t *get_allocation_info(ir_node *node)
139 allocation_info_t *info;
140 if (!irn_visited_else_mark(node)) {
141 size_t size = sizeof(info[0]) + n_regs * sizeof(info->prefs[0]);
142 info = obstack_alloc(&obst, size);
143 memset(info, 0, size);
144 info->current_value = node;
145 info->original_value = node;
146 set_irn_link(node, info);
148 info = get_irn_link(node);
155 * Get allocation information for a basic block
157 static block_info_t *get_block_info(ir_node *block)
161 assert(is_Block(block));
162 if (!irn_visited_else_mark(block)) {
163 size_t size = sizeof(info[0]) + n_regs * sizeof(info->assignments[0]);
164 info = obstack_alloc(&obst, size);
165 memset(info, 0, size);
166 set_irn_link(block, info);
168 info = get_irn_link(block);
175 * Get default register requirement for the current register class
177 static const arch_register_req_t *get_default_req_current_cls(void)
179 if (default_cls_req == NULL) {
180 struct obstack *obst = get_irg_obstack(irg);
181 arch_register_req_t *req = obstack_alloc(obst, sizeof(*req));
182 memset(req, 0, sizeof(*req));
184 req->type = arch_register_req_type_normal;
187 default_cls_req = req;
189 return default_cls_req;
193 * Link the allocation info of a node to a copy.
194 * Afterwards, both nodes uses the same allocation info.
195 * Copy must not have an allocation info assigned yet.
197 * @param copy the node that gets the allocation info assigned
198 * @param value the original node
200 static void mark_as_copy_of(ir_node *copy, ir_node *value)
203 allocation_info_t *info = get_allocation_info(value);
204 allocation_info_t *copy_info = get_allocation_info(copy);
206 /* find original value */
207 original = info->original_value;
208 if (original != value) {
209 info = get_allocation_info(original);
212 assert(info->original_value == original);
213 info->current_value = copy;
215 /* the copy should not be linked to something else yet */
216 assert(copy_info->original_value == copy);
217 /* copy over allocation preferences */
218 memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
219 copy_info->original_value = original;
223 * Calculate the penalties for every register on a node and its live neighbors.
225 * @param live_nodes the set of live nodes at the current position, may be NULL
226 * @param penalty the penalty to subtract from
227 * @param limited a raw bitset containing the limited set for the node
228 * @param node the node
230 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
231 float penalty, const unsigned* limited,
234 ir_nodeset_iterator_t iter;
236 allocation_info_t *info = get_allocation_info(node);
239 /* give penalty for all forbidden regs */
240 for (r = 0; r < n_regs; ++r) {
241 if (rbitset_is_set(limited, r))
244 info->prefs[r] -= penalty;
247 /* all other live values should get a penalty for allowed regs */
248 if (live_nodes == NULL)
251 /* TODO: reduce penalty if there are multiple allowed registers... */
252 penalty *= NEIGHBOR_FACTOR;
253 foreach_ir_nodeset(live_nodes, neighbor, iter) {
254 allocation_info_t *neighbor_info;
256 /* TODO: if op is used on multiple inputs we might not do a
258 if (neighbor == node)
261 neighbor_info = get_allocation_info(neighbor);
262 for (r = 0; r < n_regs; ++r) {
263 if (!rbitset_is_set(limited, r))
266 neighbor_info->prefs[r] -= penalty;
272 * Calculate the preferences of a definition for the current register class.
273 * If the definition uses a limited set of registers, reduce the preferences
274 * for the limited register on the node and its neighbors.
276 * @param live_nodes the set of live nodes at the current node
277 * @param weight the weight
278 * @param node the current node
280 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
283 const arch_register_req_t *req;
285 if (get_irn_mode(node) == mode_T) {
286 const ir_edge_t *edge;
287 foreach_out_edge(node, edge) {
288 ir_node *proj = get_edge_src_irn(edge);
289 check_defs(live_nodes, weight, proj);
294 if (!arch_irn_consider_in_reg_alloc(cls, node))
297 req = arch_get_register_req_out(node);
298 if (req->type & arch_register_req_type_limited) {
299 const unsigned *limited = req->limited;
300 float penalty = weight * DEF_FACTOR;
301 give_penalties_for_limits(live_nodes, penalty, limited, node);
304 if (req->type & arch_register_req_type_should_be_same) {
305 ir_node *insn = skip_Proj(node);
306 allocation_info_t *info = get_allocation_info(node);
307 int arity = get_irn_arity(insn);
310 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
311 for (i = 0; i < arity; ++i) {
314 allocation_info_t *op_info;
316 if (!rbitset_is_set(&req->other_same, i))
319 op = get_irn_n(insn, i);
321 /* if we the value at the should_be_same input doesn't die at the
322 * node, then it is no use to propagate the constraints (since a
323 * copy will emerge anyway) */
324 if (ir_nodeset_contains(live_nodes, op)) {
328 op_info = get_allocation_info(op);
329 for (r = 0; r < n_regs; ++r) {
330 op_info->prefs[r] += info->prefs[r] * factor;
337 * Walker: Runs an a block calculates the preferences for any
338 * node and every register from the considered register class.
340 static void analyze_block(ir_node *block, void *data)
342 float weight = get_block_execfreq(execfreqs, block);
343 ir_nodeset_t live_nodes;
347 ir_nodeset_init(&live_nodes);
348 be_liveness_end_of_block(lv, cls, block, &live_nodes);
350 sched_foreach_reverse(block, node) {
351 allocation_info_t *info;
358 check_defs(&live_nodes, weight, node);
361 arity = get_irn_arity(node);
363 /* the allocation info node currently only uses 1 unsigned value
364 to mark last used inputs. So we will fail for a node with more than
366 if (arity >= (int) sizeof(unsigned) * 8) {
367 panic("Node with more than %d inputs not supported yet",
368 (int) sizeof(unsigned) * 8);
371 info = get_allocation_info(node);
372 for (i = 0; i < arity; ++i) {
373 ir_node *op = get_irn_n(node, i);
374 if (!arch_irn_consider_in_reg_alloc(cls, op))
377 /* last usage of a value? */
378 if (!ir_nodeset_contains(&live_nodes, op)) {
379 rbitset_set(&info->last_uses, i);
383 be_liveness_transfer(cls, node, &live_nodes);
385 /* update weights based on usage constraints */
386 for (i = 0; i < arity; ++i) {
387 const arch_register_req_t *req;
388 const unsigned *limited;
389 ir_node *op = get_irn_n(node, i);
391 if (!arch_irn_consider_in_reg_alloc(cls, op))
394 req = arch_get_register_req(node, i);
395 if (!(req->type & arch_register_req_type_limited))
398 limited = req->limited;
399 give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
404 ir_nodeset_destroy(&live_nodes);
408 * Assign register reg to the given node.
410 * @param node the node
411 * @param reg the register
413 static void use_reg(ir_node *node, const arch_register_t *reg)
415 unsigned r = arch_register_get_index(reg);
416 assignments[r].value = node;
417 arch_set_irn_register(node, reg);
420 static void free_reg_of_value(ir_node *node)
422 assignment_t *assignment;
423 const arch_register_t *reg;
426 if (!arch_irn_consider_in_reg_alloc(cls, node))
429 reg = arch_get_irn_register(node);
430 r = arch_register_get_index(reg);
431 assignment = &assignments[r];
432 /* assignment->value may be NULL if a value is used at 2 inputs
433 so it gets freed twice. */
434 assert(assignment->value == node || assignment->value == NULL);
435 assignment->value = NULL;
439 * Compare two register preferences in decreasing order.
441 static int compare_reg_pref(const void *e1, const void *e2)
443 const reg_pref_t *rp1 = (const reg_pref_t*) e1;
444 const reg_pref_t *rp2 = (const reg_pref_t*) e2;
445 if (rp1->pref < rp2->pref)
447 if (rp1->pref > rp2->pref)
452 static void fill_sort_candidates(reg_pref_t *regprefs,
453 const allocation_info_t *info)
457 for (r = 0; r < n_regs; ++r) {
458 float pref = info->prefs[r];
460 regprefs[r].pref = pref;
462 /* TODO: use a stable sort here to avoid unnecessary register jumping */
463 qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
466 static bool try_optimistic_split(ir_node *to_split, ir_node *before,
467 float pref, float pref_delta,
468 unsigned *output_regs)
470 const arch_register_t *reg;
475 allocation_info_t *info = get_allocation_info(to_split);
479 /* find the best free position where we could move to */
480 reg_pref_t *prefs = ALLOCAN(reg_pref_t, n_regs);
481 fill_sort_candidates(prefs, info);
482 for (i = 0; i < n_regs; ++i) {
484 if (!rbitset_is_set(normal_regs, r))
486 if (rbitset_is_set(output_regs, r))
488 if (assignments[r].value == NULL)
494 /* TODO: use execfreq somehow... */
495 float delta = pref_delta + prefs[i].pref;
496 if (delta < SPLIT_DELTA) {
497 DB((dbg, LEVEL_3, "Not doing optimistical split, win %f too low\n",
502 reg = arch_register_for_index(cls, r);
503 block = get_nodes_block(before);
504 copy = be_new_Copy(cls, block, to_split);
505 mark_as_copy_of(copy, to_split);
506 free_reg_of_value(to_split);
508 sched_add_before(before, copy);
511 "Optimistic live-range split %+F move %+F -> %s before %+F (win %f)\n",
512 copy, to_split, reg->name, before, delta));
517 * Determine and assign a register for node @p node
519 static void assign_reg(const ir_node *block, ir_node *node,
520 unsigned *output_regs)
522 const arch_register_t *reg;
523 allocation_info_t *info;
524 const arch_register_req_t *req;
525 reg_pref_t *reg_prefs;
528 const unsigned *allowed_regs;
530 assert(arch_irn_consider_in_reg_alloc(cls, node));
532 /* preassigned register? */
533 reg = arch_get_irn_register(node);
535 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
540 /* give should_be_same boni */
541 info = get_allocation_info(node);
542 req = arch_get_register_req_out(node);
544 in_node = skip_Proj(node);
545 if (req->type & arch_register_req_type_should_be_same) {
546 float weight = get_block_execfreq(execfreqs, block);
547 int arity = get_irn_arity(in_node);
550 assert(arity <= (int) sizeof(req->other_same) * 8);
551 for (i = 0; i < arity; ++i) {
553 const arch_register_t *reg;
555 if (!rbitset_is_set(&req->other_same, i))
558 in = get_irn_n(in_node, i);
559 reg = arch_get_irn_register(in);
561 r = arch_register_get_index(reg);
562 info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
566 /* create list of register candidates and sort by their preference */
567 DB((dbg, LEVEL_2, "Candidates for %+F:", node));
568 reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
569 fill_sort_candidates(reg_prefs, info);
570 for (i = 0; i < n_regs; ++i) {
571 unsigned num = reg_prefs[i].num;
572 if (!rbitset_is_set(normal_regs, num))
575 const arch_register_t *reg = arch_register_for_index(cls, num);
576 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
578 DB((dbg, LEVEL_2, "\n"));
580 allowed_regs = normal_regs;
581 if (req->type & arch_register_req_type_limited) {
582 allowed_regs = req->limited;
586 for (i = 0; i < n_regs; ++i) {
587 r = reg_prefs[i].num;
588 if (!rbitset_is_set(allowed_regs, r))
590 if (assignments[r].value == NULL)
593 float pref = reg_prefs[i].pref;
594 float delta = i+1 < n_regs ? pref - reg_prefs[i+1].pref : 0;
595 ir_node *before = skip_Proj(node);
596 bool res = try_optimistic_split(assignments[r].value, before,
604 panic("No register left for %+F\n", node);
607 reg = arch_register_for_index(cls, r);
608 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
613 * Add an permutation in front of a node and change the assignments
614 * due to this permutation.
616 * To understand this imagine a permutation like this:
626 * First we count how many destinations a single value has. At the same time
627 * we can be sure that each destination register has at most 1 source register
628 * (it can have 0 which means we don't care what value is in it).
629 * We ignore all fullfilled permuations (like 7->7)
630 * In a first pass we create as much copy instructions as possible as they
631 * are generally cheaper than exchanges. We do this by counting into how many
632 * destinations a register has to be copied (in the example it's 2 for register
633 * 3, or 1 for the registers 1,2,4 and 7).
634 * We can then create a copy into every destination register when the usecount
635 * of that register is 0 (= noone else needs the value in the register).
637 * After this step we should have cycles left. We implement a cyclic permutation
638 * of n registers with n-1 transpositions.
640 * @param live_nodes the set of live nodes, updated due to live range split
641 * @param before the node before we add the permutation
642 * @param permutation the permutation array indices are the destination
643 * registers, the values in the array are the source
646 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
647 unsigned *permutation)
649 unsigned *n_used = ALLOCANZ(unsigned, n_regs);
653 /* determine how often each source register needs to be read */
654 for (r = 0; r < n_regs; ++r) {
655 unsigned old_reg = permutation[r];
658 value = assignments[old_reg].value;
660 /* nothing to do here, reg is not live. Mark it as fixpoint
661 * so we ignore it in the next steps */
669 block = get_nodes_block(before);
671 /* step1: create copies where immediately possible */
672 for (r = 0; r < n_regs; /* empty */) {
675 const arch_register_t *reg;
676 unsigned old_r = permutation[r];
678 /* - no need to do anything for fixed points.
679 - we can't copy if the value in the dest reg is still needed */
680 if (old_r == r || n_used[r] > 0) {
686 src = assignments[old_r].value;
687 copy = be_new_Copy(cls, block, src);
688 sched_add_before(before, copy);
689 reg = arch_register_for_index(cls, r);
690 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
691 copy, src, before, reg->name));
692 mark_as_copy_of(copy, src);
695 if (live_nodes != NULL) {
696 ir_nodeset_insert(live_nodes, copy);
699 /* old register has 1 user less, permutation is resolved */
700 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
703 assert(n_used[old_r] > 0);
705 if (n_used[old_r] == 0) {
706 if (live_nodes != NULL) {
707 ir_nodeset_remove(live_nodes, src);
709 free_reg_of_value(src);
712 /* advance or jump back (if this copy enabled another copy) */
713 if (old_r < r && n_used[old_r] == 0) {
720 /* at this point we only have "cycles" left which we have to resolve with
722 * TODO: if we have free registers left, then we should really use copy
723 * instructions for any cycle longer than 2 registers...
724 * (this is probably architecture dependent, there might be archs where
725 * copies are preferable even for 2-cycles) */
727 /* create perms with the rest */
728 for (r = 0; r < n_regs; /* empty */) {
729 const arch_register_t *reg;
730 unsigned old_r = permutation[r];
742 /* we shouldn't have copies from 1 value to multiple destinations left*/
743 assert(n_used[old_r] == 1);
745 /* exchange old_r and r2; after that old_r is a fixed point */
746 r2 = permutation[old_r];
748 in[0] = assignments[r2].value;
749 in[1] = assignments[old_r].value;
750 perm = be_new_Perm(cls, block, 2, in);
751 sched_add_before(before, perm);
752 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
753 perm, in[0], in[1], before));
755 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
756 mark_as_copy_of(proj0, in[0]);
757 reg = arch_register_for_index(cls, old_r);
760 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
761 mark_as_copy_of(proj1, in[1]);
762 reg = arch_register_for_index(cls, r2);
765 /* 1 value is now in the correct register */
766 permutation[old_r] = old_r;
767 /* the source of r changed to r2 */
770 /* if we have reached a fixpoint update data structures */
771 if (live_nodes != NULL) {
772 ir_nodeset_remove(live_nodes, in[0]);
773 ir_nodeset_remove(live_nodes, in[1]);
774 ir_nodeset_remove(live_nodes, proj0);
775 ir_nodeset_insert(live_nodes, proj1);
780 /* now we should only have fixpoints left */
781 for (r = 0; r < n_regs; ++r) {
782 assert(permutation[r] == r);
788 * Free regs for values last used.
790 * @param live_nodes set of live nodes, will be updated
791 * @param node the node to consider
793 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
795 allocation_info_t *info = get_allocation_info(node);
796 const unsigned *last_uses = &info->last_uses;
797 int arity = get_irn_arity(node);
800 for (i = 0; i < arity; ++i) {
803 /* check if one operand is the last use */
804 if (!rbitset_is_set(last_uses, i))
807 op = get_irn_n(node, i);
808 free_reg_of_value(op);
809 ir_nodeset_remove(live_nodes, op);
814 * change inputs of a node to the current value (copies/perms)
816 static void rewire_inputs(ir_node *node)
819 int arity = get_irn_arity(node);
821 for (i = 0; i < arity; ++i) {
822 ir_node *op = get_irn_n(node, i);
823 allocation_info_t *info;
825 if (!arch_irn_consider_in_reg_alloc(cls, op))
828 info = get_allocation_info(op);
829 info = get_allocation_info(info->original_value);
830 if (info->current_value != op) {
831 set_irn_n(node, i, info->current_value);
837 * Create a bitset of registers occupied with value living through an
840 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
842 const allocation_info_t *info = get_allocation_info(node);
847 /* mark all used registers as potentially live-through */
848 for (r = 0; r < n_regs; ++r) {
849 const assignment_t *assignment = &assignments[r];
850 if (assignment->value == NULL)
852 if (!rbitset_is_set(normal_regs, r))
855 rbitset_set(bitset, r);
858 /* remove registers of value dying at the instruction */
859 arity = get_irn_arity(node);
860 for (i = 0; i < arity; ++i) {
862 const arch_register_t *reg;
864 if (!rbitset_is_set(&info->last_uses, i))
867 op = get_irn_n(node, i);
868 reg = arch_get_irn_register(op);
869 rbitset_clear(bitset, arch_register_get_index(reg));
874 * Enforce constraints at a node by live range splits.
876 * @param live_nodes the set of live nodes, might be changed
877 * @param node the current node
879 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node,
880 unsigned *output_regs)
882 int arity = get_irn_arity(node);
884 hungarian_problem_t *bp;
886 unsigned *assignment;
888 /* construct a list of register occupied by live-through values */
889 unsigned *live_through_regs = NULL;
891 /* see if any use constraints are not met */
893 for (i = 0; i < arity; ++i) {
894 ir_node *op = get_irn_n(node, i);
895 const arch_register_t *reg;
896 const arch_register_req_t *req;
897 const unsigned *limited;
900 if (!arch_irn_consider_in_reg_alloc(cls, op))
903 /* are there any limitations for the i'th operand? */
904 req = arch_get_register_req(node, i);
905 if (!(req->type & arch_register_req_type_limited))
908 limited = req->limited;
909 reg = arch_get_irn_register(op);
910 r = arch_register_get_index(reg);
911 if (!rbitset_is_set(limited, r)) {
912 /* found an assignment outside the limited set */
918 /* is any of the live-throughs using a constrained output register? */
919 if (get_irn_mode(node) == mode_T) {
920 const ir_edge_t *edge;
922 foreach_out_edge(node, edge) {
923 ir_node *proj = get_edge_src_irn(edge);
924 const arch_register_req_t *req;
926 if (!arch_irn_consider_in_reg_alloc(cls, proj))
929 req = arch_get_register_req_out(proj);
930 if (!(req->type & arch_register_req_type_limited))
933 if (live_through_regs == NULL) {
934 rbitset_alloca(live_through_regs, n_regs);
935 determine_live_through_regs(live_through_regs, node);
938 rbitset_or(output_regs, req->limited, n_regs);
939 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
944 if (arch_irn_consider_in_reg_alloc(cls, node)) {
945 const arch_register_req_t *req = arch_get_register_req_out(node);
946 if (req->type & arch_register_req_type_limited) {
947 rbitset_alloca(live_through_regs, n_regs);
948 determine_live_through_regs(live_through_regs, node);
949 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
951 rbitset_or(output_regs, req->limited, n_regs);
960 /* create these arrays if we haven't yet */
961 if (live_through_regs == NULL) {
962 rbitset_alloca(live_through_regs, n_regs);
965 /* at this point we have to construct a bipartite matching problem to see
966 * which values should go to which registers
967 * Note: We're building the matrix in "reverse" - source registers are
968 * right, destinations left because this will produce the solution
969 * in the format required for permute_values.
971 bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
973 /* add all combinations, then remove not allowed ones */
974 for (l = 0; l < n_regs; ++l) {
975 if (!rbitset_is_set(normal_regs, l)) {
976 hungarian_add(bp, l, l, 1);
980 for (r = 0; r < n_regs; ++r) {
981 if (!rbitset_is_set(normal_regs, r))
983 /* livethrough values may not use constrainted output registers */
984 if (rbitset_is_set(live_through_regs, l)
985 && rbitset_is_set(output_regs, r))
988 hungarian_add(bp, r, l, l == r ? 9 : 8);
992 for (i = 0; i < arity; ++i) {
993 ir_node *op = get_irn_n(node, i);
994 const arch_register_t *reg;
995 const arch_register_req_t *req;
996 const unsigned *limited;
997 unsigned current_reg;
999 if (!arch_irn_consider_in_reg_alloc(cls, op))
1002 req = arch_get_register_req(node, i);
1003 if (!(req->type & arch_register_req_type_limited))
1006 limited = req->limited;
1007 reg = arch_get_irn_register(op);
1008 current_reg = arch_register_get_index(reg);
1009 for (r = 0; r < n_regs; ++r) {
1010 if (rbitset_is_set(limited, r))
1012 hungarian_remv(bp, r, current_reg);
1016 //hungarian_print_costmatrix(bp, 1);
1017 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1019 assignment = ALLOCAN(unsigned, n_regs);
1020 res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
1024 fprintf(stderr, "Swap result:");
1025 for (i = 0; i < (int) n_regs; ++i) {
1026 fprintf(stderr, " %d", assignment[i]);
1028 fprintf(stderr, "\n");
1033 permute_values(live_nodes, node, assignment);
1036 /** test wether a node @p n is a copy of the value of node @p of */
1037 static bool is_copy_of(ir_node *value, ir_node *test_value)
1039 allocation_info_t *test_info;
1040 allocation_info_t *info;
1042 if (value == test_value)
1045 info = get_allocation_info(value);
1046 test_info = get_allocation_info(test_value);
1047 return test_info->original_value == info->original_value;
1051 * find a value in the end-assignment of a basic block
1052 * @returns the index into the assignment array if found
1055 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1058 assignment_t *assignments = info->assignments;
1059 for (r = 0; r < n_regs; ++r) {
1060 const assignment_t *assignment = &assignments[r];
1061 ir_node *a_value = assignment->value;
1063 if (a_value == NULL)
1065 if (is_copy_of(a_value, value))
1073 * Create the necessary permutations at the end of a basic block to fullfill
1074 * the register assignment for phi-nodes in the next block
1076 static void add_phi_permutations(ir_node *block, int p)
1079 unsigned *permutation;
1080 assignment_t *old_assignments;
1081 bool need_permutation;
1083 ir_node *pred = get_Block_cfgpred_block(block, p);
1085 block_info_t *pred_info = get_block_info(pred);
1087 /* predecessor not processed yet? nothing to do */
1088 if (!pred_info->processed)
1091 permutation = ALLOCAN(unsigned, n_regs);
1092 for (r = 0; r < n_regs; ++r) {
1096 /* check phi nodes */
1097 need_permutation = false;
1098 node = sched_first(block);
1099 for ( ; is_Phi(node); node = sched_next(node)) {
1100 const arch_register_t *reg;
1105 if (!arch_irn_consider_in_reg_alloc(cls, node))
1108 op = get_Phi_pred(node, p);
1109 if (!arch_irn_consider_in_reg_alloc(cls, op))
1112 a = find_value_in_block_info(pred_info, op);
1115 reg = arch_get_irn_register(node);
1116 regn = arch_register_get_index(reg);
1118 permutation[regn] = a;
1119 need_permutation = true;
1123 if (need_permutation) {
1124 /* permute values at end of predecessor */
1125 old_assignments = assignments;
1126 assignments = pred_info->assignments;
1127 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1129 assignments = old_assignments;
1132 /* change phi nodes to use the copied values */
1133 node = sched_first(block);
1134 for ( ; is_Phi(node); node = sched_next(node)) {
1138 if (!arch_irn_consider_in_reg_alloc(cls, node))
1141 op = get_Phi_pred(node, p);
1142 /* no need to do anything for Unknown inputs */
1143 if (!arch_irn_consider_in_reg_alloc(cls, op))
1146 /* we have permuted all values into the correct registers so we can
1147 simply query which value occupies the phis register in the
1149 a = arch_register_get_index(arch_get_irn_register(node));
1150 op = pred_info->assignments[a].value;
1151 set_Phi_pred(node, p, op);
1156 * Set preferences for a phis register based on the registers used on the
1159 static void adapt_phi_prefs(ir_node *phi)
1162 int arity = get_irn_arity(phi);
1163 ir_node *block = get_nodes_block(phi);
1164 allocation_info_t *info = get_allocation_info(phi);
1166 for (i = 0; i < arity; ++i) {
1167 ir_node *op = get_irn_n(phi, i);
1168 const arch_register_t *reg = arch_get_irn_register(op);
1170 ir_node *pred_block;
1171 block_info_t *pred_block_info;
1177 /* we only give the bonus if the predecessor already has register
1178 * assigned, otherwise we only see a dummy value
1179 * and any conclusions about its register are useless */
1180 pred_block = get_Block_cfgpred_block(block, i);
1181 pred_block_info = get_block_info(pred_block);
1182 if (!pred_block_info->processed)
1185 /* give bonus for already assigned register */
1186 pred = get_Block_cfgpred_block(block, i);
1187 weight = get_block_execfreq(execfreqs, pred);
1188 r = arch_register_get_index(reg);
1189 info->prefs[r] += weight * AFF_PHI;
1194 * After a phi has been assigned a register propagate preference inputs
1195 * to the phi inputs.
1197 static void propagate_phi_register(ir_node *phi)
1200 ir_node *block = get_nodes_block(phi);
1201 int arity = get_irn_arity(phi);
1202 const arch_register_t *reg = arch_get_irn_register(phi);
1203 unsigned r = arch_register_get_index(reg);
1205 for (i = 0; i < arity; ++i) {
1206 ir_node *op = get_Phi_pred(phi, i);
1207 allocation_info_t *info = get_allocation_info(op);
1211 /* already a register assigned? then we can't influence it anyway */
1212 /* TODO: what about splits which we might still do... */
1213 if (arch_get_irn_register(op) != NULL)
1216 pred = get_Block_cfgpred_block(block, i);
1217 weight = get_block_execfreq(execfreqs, pred);
1219 /* promote the prefered register */
1220 info->prefs[r] += AFF_PHI * weight;
1225 * Walker: assign registers to all nodes of a block that
1226 * need registers from the currently considered register class.
1228 static void allocate_coalesce_block(ir_node *block, void *data)
1231 ir_nodeset_t live_nodes;
1232 ir_nodeset_iterator_t iter;
1233 ir_node *node, *start;
1235 block_info_t *block_info;
1236 block_info_t **pred_block_infos;
1238 unsigned *output_regs; /**< collects registers which must not
1239 be used for optimistic splits */
1242 DB((dbg, LEVEL_2, "* Block %+F\n", block));
1244 /* clear assignments */
1245 block_info = get_block_info(block);
1246 assignments = block_info->assignments;
1248 ir_nodeset_init(&live_nodes);
1250 /* gather regalloc infos of predecessor blocks */
1251 n_preds = get_Block_n_cfgpreds(block);
1252 pred_block_infos = ALLOCAN(block_info_t*, n_preds);
1253 for (i = 0; i < n_preds; ++i) {
1254 ir_node *pred = get_Block_cfgpred_block(block, i);
1255 block_info_t *pred_info = get_block_info(pred);
1256 pred_block_infos[i] = pred_info;
1259 phi_ins = ALLOCAN(ir_node*, n_preds);
1261 /* collect live-in nodes and preassigned values */
1262 be_lv_foreach(lv, block, be_lv_state_in, i) {
1263 const arch_register_t *reg;
1265 bool need_phi = false;
1267 node = be_lv_get_irn(lv, block, i);
1268 if (!arch_irn_consider_in_reg_alloc(cls, node))
1271 /* check all predecessors for this value, if it is not everywhere the
1272 same or unknown then we have to construct a phi
1273 (we collect the potential phi inputs here) */
1274 for (p = 0; p < n_preds; ++p) {
1275 block_info_t *pred_info = pred_block_infos[p];
1277 if (!pred_info->processed) {
1278 /* use node for now, it will get fixed later */
1282 int a = find_value_in_block_info(pred_info, node);
1284 /* must live out of predecessor */
1286 phi_ins[p] = pred_info->assignments[a].value;
1287 /* different value from last time? then we need a phi */
1288 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1295 ir_mode *mode = get_irn_mode(node);
1296 const arch_register_req_t *req = get_default_req_current_cls();
1300 phi = new_r_Phi(block, n_preds, phi_ins, mode);
1301 be_set_phi_reg_req(phi, req);
1303 DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1304 #ifdef DEBUG_libfirm
1305 for (i = 0; i < n_preds; ++i) {
1306 DB((dbg, LEVEL_3, " %+F", phi_ins[i]));
1308 DB((dbg, LEVEL_3, "\n"));
1310 mark_as_copy_of(phi, node);
1311 sched_add_after(block, phi);
1315 allocation_info_t *info = get_allocation_info(node);
1316 info->current_value = phi_ins[0];
1318 /* Grab 1 of the inputs we constructed (might not be the same as
1319 * "node" as we could see the same copy of the value in all
1324 /* if the node already has a register assigned use it */
1325 reg = arch_get_irn_register(node);
1327 /* TODO: consult pred-block infos here. The value could be copied
1328 away in some/all predecessor blocks. We need to construct
1329 phi-nodes in this case.
1330 We even need to construct some Phi_0 like constructs in cases
1331 where the predecessor allocation is not determined yet. */
1335 /* remember that this node is live at the beginning of the block */
1336 ir_nodeset_insert(&live_nodes, node);
1339 rbitset_alloca(output_regs, n_regs);
1341 /* handle phis... */
1342 node = sched_first(block);
1343 for ( ; is_Phi(node); node = sched_next(node)) {
1344 const arch_register_t *reg;
1346 if (!arch_irn_consider_in_reg_alloc(cls, node))
1349 /* fill in regs already assigned */
1350 reg = arch_get_irn_register(node);
1354 adapt_phi_prefs(node);
1355 assign_reg(block, node, output_regs);
1356 propagate_phi_register(node);
1361 /* assign regs for live-in values */
1362 foreach_ir_nodeset(&live_nodes, node, iter) {
1363 const arch_register_t *reg = arch_get_irn_register(node);
1367 assign_reg(block, node, output_regs);
1368 /* shouldn't happen if we color in dominance order */
1369 assert (!is_Phi(node));
1372 /* assign instructions in the block */
1373 for (node = start; !sched_is_end(node); node = sched_next(node)) {
1376 rewire_inputs(node);
1378 /* enforce use constraints */
1379 rbitset_clear_all(output_regs, n_regs);
1380 enforce_constraints(&live_nodes, node, output_regs);
1381 /* we may not use registers occupied here for optimistic splits */
1382 for (r = 0; r < n_regs; ++r) {
1383 if (assignments[r].value != NULL)
1384 rbitset_set(output_regs, r);
1387 rewire_inputs(node);
1389 /* free registers of values last used at this instruction */
1390 free_last_uses(&live_nodes, node);
1392 /* assign output registers */
1393 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1394 if (get_irn_mode(node) == mode_T) {
1395 const ir_edge_t *edge;
1396 foreach_out_edge(node, edge) {
1397 ir_node *proj = get_edge_src_irn(edge);
1398 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1400 assign_reg(block, proj, output_regs);
1402 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1403 assign_reg(block, node, output_regs);
1407 ir_nodeset_destroy(&live_nodes);
1410 block_info->processed = true;
1412 /* permute values at end of predecessor blocks in case of phi-nodes */
1415 for (p = 0; p < n_preds; ++p) {
1416 add_phi_permutations(block, p);
1420 /* if we have exactly 1 successor then we might be able to produce phi
1422 if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1423 const ir_edge_t *edge
1424 = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1425 ir_node *succ = get_edge_src_irn(edge);
1426 int p = get_edge_src_pos(edge);
1427 block_info_t *succ_info = get_block_info(succ);
1429 if (succ_info->processed) {
1430 add_phi_permutations(succ, p);
1436 * Run the register allocator for the current register class.
1438 static void be_straight_alloc_cls(void)
1440 lv = be_assure_liveness(birg);
1441 be_liveness_assure_sets(lv);
1442 be_liveness_assure_chk(lv);
1444 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1445 inc_irg_visited(irg);
1447 DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1449 irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1450 /* we need some dominance pre-order walk to ensure we see all
1451 * definitions/create copies before we encounter their users */
1452 dom_tree_walk_irg(irg, allocate_coalesce_block, NULL, NULL);
1454 ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1457 static void dump(int mask, ir_graph *irg, const char *suffix,
1458 void (*dumper)(ir_graph *, const char *))
1460 if(birg->main_env->options->dump_flags & mask)
1461 be_dump(irg, suffix, dumper);
1465 * Run the spiller on the current graph.
1467 static void spill(void)
1469 /* make sure all nodes show their real register pressure */
1470 BE_TIMER_PUSH(t_ra_constr);
1471 be_pre_spill_prepare_constr(birg, cls);
1472 BE_TIMER_POP(t_ra_constr);
1474 dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1477 BE_TIMER_PUSH(t_ra_spill);
1478 be_do_spill(birg, cls);
1479 BE_TIMER_POP(t_ra_spill);
1481 BE_TIMER_PUSH(t_ra_spill_apply);
1482 check_for_memory_operands(irg);
1483 BE_TIMER_POP(t_ra_spill_apply);
1485 dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1489 * The straight register allocator for a whole procedure.
1491 static void be_straight_alloc(be_irg_t *new_birg)
1493 const arch_env_t *arch_env = new_birg->main_env->arch_env;
1494 int n_cls = arch_env_get_n_reg_class(arch_env);
1497 obstack_init(&obst);
1500 irg = be_get_birg_irg(birg);
1501 execfreqs = birg->exec_freq;
1503 /* TODO: extract some of the stuff from bechordal allocator, like
1504 * statistics, time measurements, etc. and use them here too */
1506 for (c = 0; c < n_cls; ++c) {
1507 cls = arch_env_get_reg_class(arch_env, c);
1508 default_cls_req = NULL;
1509 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1512 stat_ev_ctx_push_str("regcls", cls->name);
1514 n_regs = arch_register_class_n_regs(cls);
1515 normal_regs = rbitset_malloc(n_regs);
1516 be_abi_set_non_ignore_regs(birg->abi, cls, normal_regs);
1520 /* verify schedule and register pressure */
1521 BE_TIMER_PUSH(t_verify);
1522 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1523 be_verify_schedule(birg);
1524 be_verify_register_pressure(birg, cls, irg);
1525 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1526 assert(be_verify_schedule(birg) && "Schedule verification failed");
1527 assert(be_verify_register_pressure(birg, cls, irg)
1528 && "Register pressure verification failed");
1530 BE_TIMER_POP(t_verify);
1532 BE_TIMER_PUSH(t_ra_color);
1533 be_straight_alloc_cls();
1534 BE_TIMER_POP(t_ra_color);
1536 /* we most probably constructed new Phis so liveness info is invalid
1538 /* TODO: test liveness_introduce */
1539 be_liveness_invalidate(lv);
1542 stat_ev_ctx_pop("regcls");
1545 BE_TIMER_PUSH(t_ra_spill_apply);
1546 be_abi_fix_stack_nodes(birg->abi);
1547 BE_TIMER_POP(t_ra_spill_apply);
1549 BE_TIMER_PUSH(t_verify);
1550 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1551 be_verify_register_allocation(birg);
1552 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1553 assert(be_verify_register_allocation(birg)
1554 && "Register allocation invalid");
1556 BE_TIMER_POP(t_verify);
1558 obstack_free(&obst, NULL);
1562 * Initializes this module.
1564 void be_init_straight_alloc(void)
1566 static be_ra_t be_ra_straight = {
1570 FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
1572 be_register_allocator("straight", &be_ra_straight);
1575 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);