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 * - 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 0.5f
88 #define SPLIT_DELTA 1.0f
90 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
92 static struct obstack obst;
93 static be_irg_t *birg;
95 static const arch_register_class_t *cls;
96 static const arch_register_req_t *default_cls_req;
98 static const ir_exec_freq *execfreqs;
99 static unsigned n_regs;
100 static unsigned *normal_regs;
102 /** info about the current assignment for a register */
103 struct assignment_t {
104 ir_node *value; /**< currently assigned value */
106 typedef struct assignment_t assignment_t;
108 /** currently active assignments (while processing a basic block) */
109 static assignment_t *assignments;
112 * allocation information: last_uses, register preferences
113 * the information is per firm-node.
115 struct allocation_info_t {
116 unsigned last_uses; /**< bitset indicating last uses (input pos) */
117 ir_node *current_value; /**< copy of the value that should be used */
118 ir_node *original_value; /**< for copies point to original value */
119 float prefs[0]; /**< register preferences */
121 typedef struct allocation_info_t allocation_info_t;
123 /** helper datastructure used when sorting register preferences */
128 typedef struct reg_pref_t reg_pref_t;
130 /** per basic-block information */
131 struct block_info_t {
132 bool processed; /**< indicate wether block is processed */
133 assignment_t assignments[0]; /**< register assignments at end of block */
135 typedef struct block_info_t block_info_t;
138 * Get the allocation info for a node.
139 * The info is allocated on the first visit of a node.
141 static allocation_info_t *get_allocation_info(ir_node *node)
143 allocation_info_t *info;
144 if (!irn_visited_else_mark(node)) {
145 size_t size = sizeof(info[0]) + n_regs * sizeof(info->prefs[0]);
146 info = obstack_alloc(&obst, size);
147 memset(info, 0, size);
148 info->current_value = node;
149 info->original_value = node;
150 set_irn_link(node, info);
152 info = get_irn_link(node);
159 * Get allocation information for a basic block
161 static block_info_t *get_block_info(ir_node *block)
165 assert(is_Block(block));
166 if (!irn_visited_else_mark(block)) {
167 size_t size = sizeof(info[0]) + n_regs * sizeof(info->assignments[0]);
168 info = obstack_alloc(&obst, size);
169 memset(info, 0, size);
170 set_irn_link(block, info);
172 info = get_irn_link(block);
179 * Get default register requirement for the current register class
181 static const arch_register_req_t *get_default_req_current_cls(void)
183 if (default_cls_req == NULL) {
184 struct obstack *obst = get_irg_obstack(irg);
185 arch_register_req_t *req = obstack_alloc(obst, sizeof(*req));
186 memset(req, 0, sizeof(*req));
188 req->type = arch_register_req_type_normal;
191 default_cls_req = req;
193 return default_cls_req;
197 * Link the allocation info of a node to a copy.
198 * Afterwards, both nodes uses the same allocation info.
199 * Copy must not have an allocation info assigned yet.
201 * @param copy the node that gets the allocation info assigned
202 * @param value the original node
204 static void mark_as_copy_of(ir_node *copy, ir_node *value)
207 allocation_info_t *info = get_allocation_info(value);
208 allocation_info_t *copy_info = get_allocation_info(copy);
210 /* find original value */
211 original = info->original_value;
212 if (original != value) {
213 info = get_allocation_info(original);
216 assert(info->original_value == original);
217 info->current_value = copy;
219 /* the copy should not be linked to something else yet */
220 assert(copy_info->original_value == copy);
221 /* copy over allocation preferences */
222 memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
223 copy_info->original_value = original;
227 * Calculate the penalties for every register on a node and its live neighbors.
229 * @param live_nodes the set of live nodes at the current position, may be NULL
230 * @param penalty the penalty to subtract from
231 * @param limited a raw bitset containing the limited set for the node
232 * @param node the node
234 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
235 float penalty, const unsigned* limited,
238 ir_nodeset_iterator_t iter;
240 allocation_info_t *info = get_allocation_info(node);
243 /* give penalty for all forbidden regs */
244 for (r = 0; r < n_regs; ++r) {
245 if (rbitset_is_set(limited, r))
248 info->prefs[r] -= penalty;
251 /* all other live values should get a penalty for allowed regs */
252 if (live_nodes == NULL)
255 /* TODO: reduce penalty if there are multiple allowed registers... */
256 penalty *= NEIGHBOR_FACTOR;
257 foreach_ir_nodeset(live_nodes, neighbor, iter) {
258 allocation_info_t *neighbor_info;
260 /* TODO: if op is used on multiple inputs we might not do a
262 if (neighbor == node)
265 neighbor_info = get_allocation_info(neighbor);
266 for (r = 0; r < n_regs; ++r) {
267 if (!rbitset_is_set(limited, r))
270 neighbor_info->prefs[r] -= penalty;
276 * Calculate the preferences of a definition for the current register class.
277 * If the definition uses a limited set of registers, reduce the preferences
278 * for the limited register on the node and its neighbors.
280 * @param live_nodes the set of live nodes at the current node
281 * @param weight the weight
282 * @param node the current node
284 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
287 const arch_register_req_t *req;
289 if (get_irn_mode(node) == mode_T) {
290 const ir_edge_t *edge;
291 foreach_out_edge(node, edge) {
292 ir_node *proj = get_edge_src_irn(edge);
293 check_defs(live_nodes, weight, proj);
298 if (!arch_irn_consider_in_reg_alloc(cls, node))
301 req = arch_get_register_req_out(node);
302 if (req->type & arch_register_req_type_limited) {
303 const unsigned *limited = req->limited;
304 float penalty = weight * DEF_FACTOR;
305 give_penalties_for_limits(live_nodes, penalty, limited, node);
308 if (req->type & arch_register_req_type_should_be_same) {
309 ir_node *insn = skip_Proj(node);
310 allocation_info_t *info = get_allocation_info(node);
311 int arity = get_irn_arity(insn);
314 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
315 for (i = 0; i < arity; ++i) {
318 allocation_info_t *op_info;
320 if (!rbitset_is_set(&req->other_same, i))
323 op = get_irn_n(insn, i);
325 /* if we the value at the should_be_same input doesn't die at the
326 * node, then it is no use to propagate the constraints (since a
327 * copy will emerge anyway) */
328 if (ir_nodeset_contains(live_nodes, op)) {
332 op_info = get_allocation_info(op);
333 for (r = 0; r < n_regs; ++r) {
334 op_info->prefs[r] += info->prefs[r] * factor;
341 * Walker: Runs an a block calculates the preferences for any
342 * node and every register from the considered register class.
344 static void analyze_block(ir_node *block, void *data)
346 float weight = get_block_execfreq(execfreqs, block);
347 ir_nodeset_t live_nodes;
351 ir_nodeset_init(&live_nodes);
352 be_liveness_end_of_block(lv, cls, block, &live_nodes);
354 sched_foreach_reverse(block, node) {
355 allocation_info_t *info;
362 /* TODO give/take penalties for should_be_same/different) */
363 check_defs(&live_nodes, weight, node);
366 arity = get_irn_arity(node);
368 /* the allocation info node currently only uses 1 unsigned value
369 to mark last used inputs. So we will fail for a node with more than
371 if (arity >= (int) sizeof(unsigned) * 8) {
372 panic("Node with more than %d inputs not supported yet",
373 (int) sizeof(unsigned) * 8);
376 info = get_allocation_info(node);
377 for (i = 0; i < arity; ++i) {
378 ir_node *op = get_irn_n(node, i);
379 if (!arch_irn_consider_in_reg_alloc(cls, op))
382 /* last usage of a value? */
383 if (!ir_nodeset_contains(&live_nodes, op)) {
384 rbitset_set(&info->last_uses, i);
388 be_liveness_transfer(cls, node, &live_nodes);
390 /* update weights based on usage constraints */
391 for (i = 0; i < arity; ++i) {
392 const arch_register_req_t *req;
393 const unsigned *limited;
394 ir_node *op = get_irn_n(node, i);
396 if (!arch_irn_consider_in_reg_alloc(cls, op))
399 req = arch_get_register_req(node, i);
400 if (!(req->type & arch_register_req_type_limited))
403 /* TODO: give penalties to neighbors for precolored nodes! */
405 limited = req->limited;
406 give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
411 ir_nodeset_destroy(&live_nodes);
415 * Assign register reg to the given node.
417 * @param node the node
418 * @param reg the register
420 static void use_reg(ir_node *node, const arch_register_t *reg)
422 unsigned r = arch_register_get_index(reg);
423 assignments[r].value = node;
424 arch_set_irn_register(node, reg);
427 static void free_reg_of_value(ir_node *node)
429 assignment_t *assignment;
430 const arch_register_t *reg;
433 if (!arch_irn_consider_in_reg_alloc(cls, node))
436 reg = arch_get_irn_register(node);
437 r = arch_register_get_index(reg);
438 assignment = &assignments[r];
439 /* assignment->value may be NULL if a value is used at 2 inputs
440 so it gets freed twice. */
441 assert(assignment->value == node || assignment->value == NULL);
442 assignment->value = NULL;
446 * Compare two register preferences in decreasing order.
448 static int compare_reg_pref(const void *e1, const void *e2)
450 const reg_pref_t *rp1 = (const reg_pref_t*) e1;
451 const reg_pref_t *rp2 = (const reg_pref_t*) e2;
452 if (rp1->pref < rp2->pref)
454 if (rp1->pref > rp2->pref)
459 static void fill_sort_candidates(reg_pref_t *regprefs,
460 const allocation_info_t *info)
464 for (r = 0; r < n_regs; ++r) {
465 float pref = info->prefs[r];
467 regprefs[r].pref = pref;
469 /* TODO: use a stable sort here to avoid unnecessary register jumping */
470 qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
473 static bool try_optimistic_split(ir_node *to_split, ir_node *before,
474 float pref, float pref_delta)
477 const arch_register_t *reg;
482 allocation_info_t *info = get_allocation_info(to_split);
486 /* find the best free position where we could move to */
487 reg_pref_t *prefs = ALLOCAN(reg_pref_t, n_regs);
488 fill_sort_candidates(prefs, info);
489 for (i = 0; i < n_regs; ++i) {
491 if (!rbitset_is_set(normal_regs, r))
493 if (assignments[r].value == NULL)
499 /* TODO: use execfreq somehow... */
500 float delta = pref_delta + prefs[i].pref;
501 if (delta < SPLIT_DELTA) {
502 DB((dbg, LEVEL_3, "Not doing optimistical split, win %f too low\n",
507 reg = arch_register_for_index(cls, r);
508 block = get_nodes_block(before);
509 copy = be_new_Copy(cls, block, to_split);
510 mark_as_copy_of(copy, to_split);
511 free_reg_of_value(to_split);
513 sched_add_before(before, copy);
516 "Optimistic live-range split %+F move %+F -> %s before %+F (win %f)\n",
517 copy, to_split, reg->name, before, delta));
525 * Determine and assign a register for node @p node
527 static void assign_reg(const ir_node *block, ir_node *node)
529 const arch_register_t *reg;
530 allocation_info_t *info;
531 const arch_register_req_t *req;
532 reg_pref_t *reg_prefs;
535 const unsigned *allowed_regs;
537 assert(arch_irn_consider_in_reg_alloc(cls, node));
539 /* preassigned register? */
540 reg = arch_get_irn_register(node);
542 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
547 /* give should_be_same boni */
548 info = get_allocation_info(node);
549 req = arch_get_register_req_out(node);
551 in_node = skip_Proj(node);
552 if (req->type & arch_register_req_type_should_be_same) {
553 float weight = get_block_execfreq(execfreqs, block);
554 int arity = get_irn_arity(in_node);
557 assert(arity <= (int) sizeof(req->other_same) * 8);
558 for (i = 0; i < arity; ++i) {
560 const arch_register_t *reg;
562 if (!rbitset_is_set(&req->other_same, i))
565 in = get_irn_n(in_node, i);
566 reg = arch_get_irn_register(in);
568 r = arch_register_get_index(reg);
569 info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
573 DB((dbg, LEVEL_2, "Candidates for %+F:", node));
574 reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
575 fill_sort_candidates(reg_prefs, info);
576 for (i = 0; i < n_regs; ++i) {
577 unsigned num = reg_prefs[i].num;
578 if (!rbitset_is_set(normal_regs, num))
581 const arch_register_t *reg = arch_register_for_index(cls, num);
582 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
584 DB((dbg, LEVEL_2, "\n"));
586 allowed_regs = normal_regs;
587 if (req->type & arch_register_req_type_limited) {
588 allowed_regs = req->limited;
592 for (i = 0; i < n_regs; ++i) {
593 r = reg_prefs[i].num;
594 if (!rbitset_is_set(allowed_regs, r))
596 if (assignments[r].value == NULL)
599 TODO: It might be better to copy the value occupying the register
600 around here instead of trying the next one, find out when... */
602 float pref = reg_prefs[i].pref;
603 float delta = i+1 < n_regs ? pref - reg_prefs[i+1].pref : 0;
604 ir_node *before = skip_Proj(node);
605 bool res = try_optimistic_split(assignments[r].value, before,
612 panic("No allowed register free for %+F\n", node);
615 reg = arch_register_for_index(cls, r);
616 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
621 * Add an permutation in front of a node and change the assignments
622 * due to this permutation.
624 * To understand this imagine a permutation like this:
634 * First we count how many destinations a single value has. At the same time
635 * we can be sure that each destination register has at most 1 source register
636 * (it can have 0 which means we don't care what value is in it).
637 * We ignore all fullfilled permuations (like 7->7)
638 * In a first pass we create as much copy instructions as possible as they
639 * are generally cheaper than exchanges. We do this by counting into how many
640 * destinations a register has to be copied (in the example it's 2 for register
641 * 3, or 1 for the registers 1,2,4 and 7).
642 * We can then create a copy into every destination register when the usecount
643 * of that register is 0 (= noone else needs the value in the register).
645 * After this step we should have cycles left. We implement a cyclic permutation
646 * of n registers with n-1 transpositions.
648 * @param live_nodes the set of live nodes, updated due to live range split
649 * @param before the node before we add the permutation
650 * @param permutation the permutation array indices are the destination
651 * registers, the values in the array are the source
654 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
655 unsigned *permutation)
657 unsigned *n_used = ALLOCANZ(unsigned, n_regs);
661 /* determine how often each source register needs to be read */
662 for (r = 0; r < n_regs; ++r) {
663 unsigned old_reg = permutation[r];
666 value = assignments[old_reg].value;
668 /* nothing to do here, reg is not live. Mark it as fixpoint
669 * so we ignore it in the next steps */
677 block = get_nodes_block(before);
679 /* step1: create copies where immediately possible */
680 for (r = 0; r < n_regs; /* empty */) {
683 const arch_register_t *reg;
684 unsigned old_r = permutation[r];
686 /* - no need to do anything for fixed points.
687 - we can't copy if the value in the dest reg is still needed */
688 if (old_r == r || n_used[r] > 0) {
694 src = assignments[old_r].value;
695 copy = be_new_Copy(cls, block, src);
696 sched_add_before(before, copy);
697 reg = arch_register_for_index(cls, r);
698 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
699 copy, src, before, reg->name));
700 mark_as_copy_of(copy, src);
703 if (live_nodes != NULL) {
704 ir_nodeset_insert(live_nodes, copy);
707 /* old register has 1 user less, permutation is resolved */
708 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
711 assert(n_used[old_r] > 0);
713 if (n_used[old_r] == 0) {
714 if (live_nodes != NULL) {
715 ir_nodeset_remove(live_nodes, src);
717 free_reg_of_value(src);
720 /* advance or jump back (if this copy enabled another copy) */
721 if (old_r < r && n_used[old_r] == 0) {
728 /* at this point we only have "cycles" left which we have to resolve with
730 * TODO: if we have free registers left, then we should really use copy
731 * instructions for any cycle longer than 2 registers...
732 * (this is probably architecture dependent, there might be archs where
733 * copies are preferable even for 2-cycles) */
735 /* create perms with the rest */
736 for (r = 0; r < n_regs; /* empty */) {
737 const arch_register_t *reg;
738 unsigned old_r = permutation[r];
750 /* we shouldn't have copies from 1 value to multiple destinations left*/
751 assert(n_used[old_r] == 1);
753 /* exchange old_r and r2; after that old_r is a fixed point */
754 r2 = permutation[old_r];
756 in[0] = assignments[r2].value;
757 in[1] = assignments[old_r].value;
758 perm = be_new_Perm(cls, block, 2, in);
759 sched_add_before(before, perm);
760 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
761 perm, in[0], in[1], before));
763 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
764 mark_as_copy_of(proj0, in[0]);
765 reg = arch_register_for_index(cls, old_r);
768 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
769 mark_as_copy_of(proj1, in[1]);
770 reg = arch_register_for_index(cls, r2);
773 /* 1 value is now in the correct register */
774 permutation[old_r] = old_r;
775 /* the source of r changed to r2 */
778 /* if we have reached a fixpoint update data structures */
779 if (live_nodes != NULL) {
780 ir_nodeset_remove(live_nodes, in[0]);
781 ir_nodeset_remove(live_nodes, in[1]);
782 ir_nodeset_remove(live_nodes, proj0);
783 ir_nodeset_insert(live_nodes, proj1);
788 /* now we should only have fixpoints left */
789 for (r = 0; r < n_regs; ++r) {
790 assert(permutation[r] == r);
796 * Free regs for values last used.
798 * @param live_nodes set of live nodes, will be updated
799 * @param node the node to consider
801 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
803 allocation_info_t *info = get_allocation_info(node);
804 const unsigned *last_uses = &info->last_uses;
805 int arity = get_irn_arity(node);
807 for (i = 0; i < arity; ++i) {
810 /* check if one operand is the last use */
811 if (!rbitset_is_set(last_uses, i))
814 op = get_irn_n(node, i);
815 free_reg_of_value(op);
816 ir_nodeset_remove(live_nodes, op);
821 * change inputs of a node to the current value (copies/perms)
823 static void rewire_inputs(ir_node *node)
826 int arity = get_irn_arity(node);
828 for (i = 0; i < arity; ++i) {
829 ir_node *op = get_irn_n(node, i);
830 allocation_info_t *info;
832 if (!arch_irn_consider_in_reg_alloc(cls, op))
835 info = get_allocation_info(op);
836 info = get_allocation_info(info->original_value);
837 if (info->current_value != op) {
838 set_irn_n(node, i, info->current_value);
844 * Create a bitset of registers occupied with value living through an
847 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
849 const allocation_info_t *info = get_allocation_info(node);
854 /* mark all used registers as potentially live-through */
855 for (r = 0; r < n_regs; ++r) {
856 const assignment_t *assignment = &assignments[r];
857 if (assignment->value == NULL)
859 if (!rbitset_is_set(normal_regs, r))
862 rbitset_set(bitset, r);
865 /* remove registers of value dying at the instruction */
866 arity = get_irn_arity(node);
867 for (i = 0; i < arity; ++i) {
869 const arch_register_t *reg;
871 if (!rbitset_is_set(&info->last_uses, i))
874 op = get_irn_n(node, i);
875 reg = arch_get_irn_register(op);
876 rbitset_clear(bitset, arch_register_get_index(reg));
881 * Enforce constraints at a node by live range splits.
883 * @param live_nodes the set of live nodes, might be changed
884 * @param node the current node
886 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node)
888 int arity = get_irn_arity(node);
890 hungarian_problem_t *bp;
892 unsigned *assignment;
894 /* construct a list of register occupied by live-through values */
895 unsigned *live_through_regs = NULL;
896 unsigned *output_regs = NULL;
898 /* see if any use constraints are not met */
900 for (i = 0; i < arity; ++i) {
901 ir_node *op = get_irn_n(node, i);
902 const arch_register_t *reg;
903 const arch_register_req_t *req;
904 const unsigned *limited;
907 if (!arch_irn_consider_in_reg_alloc(cls, op))
910 /* are there any limitations for the i'th operand? */
911 req = arch_get_register_req(node, i);
912 if (!(req->type & arch_register_req_type_limited))
915 limited = req->limited;
916 reg = arch_get_irn_register(op);
917 r = arch_register_get_index(reg);
918 if (!rbitset_is_set(limited, r)) {
919 /* found an assignment outside the limited set */
925 /* is any of the live-throughs using a constrained output register? */
926 if (get_irn_mode(node) == mode_T) {
927 const ir_edge_t *edge;
929 foreach_out_edge(node, edge) {
930 ir_node *proj = get_edge_src_irn(edge);
931 const arch_register_req_t *req;
933 if (!arch_irn_consider_in_reg_alloc(cls, proj))
936 req = arch_get_register_req_out(proj);
937 if (!(req->type & arch_register_req_type_limited))
940 if (live_through_regs == NULL) {
941 rbitset_alloca(live_through_regs, n_regs);
942 determine_live_through_regs(live_through_regs, node);
944 rbitset_alloca(output_regs, n_regs);
947 rbitset_or(output_regs, req->limited, n_regs);
948 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
953 if (arch_irn_consider_in_reg_alloc(cls, node)) {
954 const arch_register_req_t *req = arch_get_register_req_out(node);
955 if (req->type & arch_register_req_type_limited) {
956 rbitset_alloca(live_through_regs, n_regs);
957 determine_live_through_regs(live_through_regs, node);
958 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
961 rbitset_alloca(output_regs, n_regs);
962 rbitset_or(output_regs, req->limited, n_regs);
971 /* create these arrays if we haven't yet */
972 if (output_regs == NULL) {
973 if (live_through_regs == NULL) {
974 rbitset_alloca(live_through_regs, n_regs);
976 rbitset_alloca(output_regs, n_regs);
979 /* at this point we have to construct a bipartite matching problem to see
980 * which values should go to which registers
981 * Note: We're building the matrix in "reverse" - source registers are
982 * right, destinations at l because this will produce the solution
983 * in the format required for permute_values.
985 bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
987 /* add all combinations, then remove not allowed ones */
988 for (l = 0; l < n_regs; ++l) {
989 if (!rbitset_is_set(normal_regs, l)) {
990 hungarian_add(bp, l, l, 1);
994 for (r = 0; r < n_regs; ++r) {
995 if (!rbitset_is_set(normal_regs, r))
997 /* livethrough values may not use constrainted output registers */
998 if (rbitset_is_set(live_through_regs, l)
999 && rbitset_is_set(output_regs, r))
1002 hungarian_add(bp, r, l, l == r ? 9 : 8);
1006 for (i = 0; i < arity; ++i) {
1007 ir_node *op = get_irn_n(node, i);
1008 const arch_register_t *reg;
1009 const arch_register_req_t *req;
1010 const unsigned *limited;
1011 unsigned current_reg;
1013 if (!arch_irn_consider_in_reg_alloc(cls, op))
1016 req = arch_get_register_req(node, i);
1017 if (!(req->type & arch_register_req_type_limited))
1020 limited = req->limited;
1021 reg = arch_get_irn_register(op);
1022 current_reg = arch_register_get_index(reg);
1023 for (r = 0; r < n_regs; ++r) {
1024 if (rbitset_is_set(limited, r))
1026 hungarian_remv(bp, r, current_reg);
1030 //hungarian_print_costmatrix(bp, 1);
1031 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1033 assignment = ALLOCAN(unsigned, n_regs);
1034 res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
1038 fprintf(stderr, "Swap result:");
1039 for (i = 0; i < (int) n_regs; ++i) {
1040 fprintf(stderr, " %d", assignment[i]);
1042 fprintf(stderr, "\n");
1047 permute_values(live_nodes, node, assignment);
1050 /** test wether a node @p n is a copy of the value of node @p of */
1051 static bool is_copy_of(ir_node *value, ir_node *test_value)
1053 allocation_info_t *test_info;
1054 allocation_info_t *info;
1056 if (value == test_value)
1059 info = get_allocation_info(value);
1060 test_info = get_allocation_info(test_value);
1061 return test_info->original_value == info->original_value;
1065 * find a value in the end-assignment of a basic block
1066 * @returns the index into the assignment array if found
1069 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1072 assignment_t *assignments = info->assignments;
1073 for (r = 0; r < n_regs; ++r) {
1074 const assignment_t *assignment = &assignments[r];
1075 ir_node *a_value = assignment->value;
1077 if (a_value == NULL)
1079 if (is_copy_of(a_value, value))
1087 * Create the necessary permutations at the end of a basic block to fullfill
1088 * the register assignment for phi-nodes in the next block
1090 static void add_phi_permutations(ir_node *block, int p)
1093 unsigned *permutation;
1094 assignment_t *old_assignments;
1095 bool need_permutation;
1097 ir_node *pred = get_Block_cfgpred_block(block, p);
1099 block_info_t *pred_info = get_block_info(pred);
1101 /* predecessor not processed yet? nothing to do */
1102 if (!pred_info->processed)
1105 permutation = ALLOCAN(unsigned, n_regs);
1106 for (r = 0; r < n_regs; ++r) {
1110 /* check phi nodes */
1111 need_permutation = false;
1112 node = sched_first(block);
1113 for ( ; is_Phi(node); node = sched_next(node)) {
1114 const arch_register_t *reg;
1119 if (!arch_irn_consider_in_reg_alloc(cls, node))
1122 op = get_Phi_pred(node, p);
1123 if (!arch_irn_consider_in_reg_alloc(cls, op))
1126 a = find_value_in_block_info(pred_info, op);
1129 reg = arch_get_irn_register(node);
1130 regn = arch_register_get_index(reg);
1132 permutation[regn] = a;
1133 need_permutation = true;
1137 if (need_permutation) {
1138 /* permute values at end of predecessor */
1139 old_assignments = assignments;
1140 assignments = pred_info->assignments;
1141 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1143 assignments = old_assignments;
1146 /* change phi nodes to use the copied values */
1147 node = sched_first(block);
1148 for ( ; is_Phi(node); node = sched_next(node)) {
1152 if (!arch_irn_consider_in_reg_alloc(cls, node))
1155 op = get_Phi_pred(node, p);
1156 /* no need to do anything for Unknown inputs */
1157 if (!arch_irn_consider_in_reg_alloc(cls, op))
1160 /* we have permuted all values into the correct registers so we can
1161 simply query which value occupies the phis register in the
1163 a = arch_register_get_index(arch_get_irn_register(node));
1164 op = pred_info->assignments[a].value;
1165 set_Phi_pred(node, p, op);
1170 * Set preferences for a phis register based on the registers used on the
1173 static void adapt_phi_prefs(ir_node *phi)
1176 int arity = get_irn_arity(phi);
1177 ir_node *block = get_nodes_block(phi);
1178 allocation_info_t *info = get_allocation_info(phi);
1180 for (i = 0; i < arity; ++i) {
1181 ir_node *op = get_irn_n(phi, i);
1182 const arch_register_t *reg = arch_get_irn_register(op);
1184 ir_node *pred_block;
1185 block_info_t *pred_block_info;
1191 /* we only give the bonus if the predecessor already has register
1192 * assigned, otherwise we only see a dummy value
1193 * and any conclusions about its register are useless */
1194 pred_block = get_Block_cfgpred_block(block, i);
1195 pred_block_info = get_block_info(pred_block);
1196 if (!pred_block_info->processed)
1199 /* give bonus for already assigned register */
1200 pred = get_Block_cfgpred_block(block, i);
1201 weight = get_block_execfreq(execfreqs, pred);
1202 r = arch_register_get_index(reg);
1203 info->prefs[r] += weight * AFF_PHI;
1208 * After a phi has been assigned a register propagate preference inputs
1209 * to the phi inputs.
1211 static void propagate_phi_register(ir_node *phi)
1214 ir_node *block = get_nodes_block(phi);
1215 int arity = get_irn_arity(phi);
1216 const arch_register_t *reg = arch_get_irn_register(phi);
1217 unsigned r = arch_register_get_index(reg);
1219 for (i = 0; i < arity; ++i) {
1220 ir_node *op = get_Phi_pred(phi, i);
1221 allocation_info_t *info = get_allocation_info(op);
1225 /* already a register assigned? then we can't influence it anyway */
1226 /* TODO: what about splits which we might still do... */
1227 if (arch_get_irn_register(op) != NULL)
1230 pred = get_Block_cfgpred_block(block, i);
1231 weight = get_block_execfreq(execfreqs, pred);
1233 /* promote the prefered register */
1234 info->prefs[r] += AFF_PHI * weight;
1239 * Walker: assign registers to all nodes of a block that
1240 * need registers from the currently considered register class.
1242 static void allocate_coalesce_block(ir_node *block, void *data)
1245 ir_nodeset_t live_nodes;
1246 ir_nodeset_iterator_t iter;
1247 ir_node *node, *start;
1249 block_info_t *block_info;
1250 block_info_t **pred_block_infos;
1254 DB((dbg, LEVEL_2, "* Block %+F\n", block));
1256 /* clear assignments */
1257 block_info = get_block_info(block);
1258 assignments = block_info->assignments;
1260 ir_nodeset_init(&live_nodes);
1262 /* gather regalloc infos of predecessor blocks */
1263 n_preds = get_Block_n_cfgpreds(block);
1264 pred_block_infos = ALLOCAN(block_info_t*, n_preds);
1265 for (i = 0; i < n_preds; ++i) {
1266 ir_node *pred = get_Block_cfgpred_block(block, i);
1267 block_info_t *pred_info = get_block_info(pred);
1268 pred_block_infos[i] = pred_info;
1271 phi_ins = ALLOCAN(ir_node*, n_preds);
1273 /* collect live-in nodes and preassigned values */
1274 be_lv_foreach(lv, block, be_lv_state_in, i) {
1275 const arch_register_t *reg;
1277 bool need_phi = false;
1279 node = be_lv_get_irn(lv, block, i);
1280 if (!arch_irn_consider_in_reg_alloc(cls, node))
1283 /* check all predecessors for this value, if it is not everywhere the
1284 same or unknown then we have to construct a phi
1285 (we collect the potential phi inputs here) */
1286 for (p = 0; p < n_preds; ++p) {
1287 block_info_t *pred_info = pred_block_infos[p];
1289 if (!pred_info->processed) {
1290 /* use node for now, it will get fixed later */
1294 int a = find_value_in_block_info(pred_info, node);
1296 /* must live out of predecessor */
1298 phi_ins[p] = pred_info->assignments[a].value;
1299 /* different value from last time? then we need a phi */
1300 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1307 ir_mode *mode = get_irn_mode(node);
1308 const arch_register_req_t *req = get_default_req_current_cls();
1312 phi = new_r_Phi(block, n_preds, phi_ins, mode);
1313 be_set_phi_reg_req(phi, req);
1315 DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1316 #ifdef DEBUG_libfirm
1317 for (i = 0; i < n_preds; ++i) {
1318 DB((dbg, LEVEL_3, " %+F", phi_ins[i]));
1320 DB((dbg, LEVEL_3, "\n"));
1322 mark_as_copy_of(phi, node);
1323 sched_add_after(block, phi);
1327 allocation_info_t *info = get_allocation_info(node);
1328 info->current_value = phi_ins[0];
1330 /* Grab 1 of the inputs we constructed (might not be the same as
1331 * "node" as we could see the same copy of the value in all
1336 /* if the node already has a register assigned use it */
1337 reg = arch_get_irn_register(node);
1339 /* TODO: consult pred-block infos here. The value could be copied
1340 away in some/all predecessor blocks. We need to construct
1341 phi-nodes in this case.
1342 We even need to construct some Phi_0 like constructs in cases
1343 where the predecessor allocation is not determined yet. */
1347 /* remember that this node is live at the beginning of the block */
1348 ir_nodeset_insert(&live_nodes, node);
1351 /* handle phis... */
1352 node = sched_first(block);
1353 for ( ; is_Phi(node); node = sched_next(node)) {
1354 const arch_register_t *reg;
1356 if (!arch_irn_consider_in_reg_alloc(cls, node))
1359 /* fill in regs already assigned */
1360 reg = arch_get_irn_register(node);
1364 adapt_phi_prefs(node);
1365 assign_reg(block, node);
1366 propagate_phi_register(node);
1371 /* assign regs for live-in values */
1372 foreach_ir_nodeset(&live_nodes, node, iter) {
1373 const arch_register_t *reg = arch_get_irn_register(node);
1377 assign_reg(block, node);
1378 /* shouldn't happen if we color in dominance order */
1379 assert (!is_Phi(node));
1382 propagate_phi_register(node);
1386 /* assign instructions in the block */
1387 for (node = start; !sched_is_end(node); node = sched_next(node)) {
1389 rewire_inputs(node);
1391 /* enforce use constraints */
1392 enforce_constraints(&live_nodes, node);
1394 rewire_inputs(node);
1396 /* free registers of values last used at this instruction */
1397 free_last_uses(&live_nodes, node);
1399 /* assign output registers */
1400 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1401 if (get_irn_mode(node) == mode_T) {
1402 const ir_edge_t *edge;
1403 foreach_out_edge(node, edge) {
1404 ir_node *proj = get_edge_src_irn(edge);
1405 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1407 assign_reg(block, proj);
1409 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1410 assign_reg(block, node);
1414 ir_nodeset_destroy(&live_nodes);
1417 block_info->processed = true;
1419 /* permute values at end of predecessor blocks in case of phi-nodes */
1422 for (p = 0; p < n_preds; ++p) {
1423 add_phi_permutations(block, p);
1427 /* if we have exactly 1 successor then we might be able to produce phi
1429 if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1430 const ir_edge_t *edge
1431 = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1432 ir_node *succ = get_edge_src_irn(edge);
1433 int p = get_edge_src_pos(edge);
1434 block_info_t *succ_info = get_block_info(succ);
1436 if (succ_info->processed) {
1437 add_phi_permutations(succ, p);
1443 * Run the register allocator for the current register class.
1445 static void be_straight_alloc_cls(void)
1447 lv = be_assure_liveness(birg);
1448 be_liveness_assure_sets(lv);
1449 be_liveness_assure_chk(lv);
1451 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1452 inc_irg_visited(irg);
1454 DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1456 irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1457 /* we need some dominance pre-order walk to ensure we see all
1458 * definitions/create copies before we encounter their users */
1459 dom_tree_walk_irg(irg, allocate_coalesce_block, NULL, NULL);
1461 ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1464 static void dump(int mask, ir_graph *irg, const char *suffix,
1465 void (*dumper)(ir_graph *, const char *))
1467 if(birg->main_env->options->dump_flags & mask)
1468 be_dump(irg, suffix, dumper);
1472 * Run the spiller on the current graph.
1474 static void spill(void)
1476 /* make sure all nodes show their real register pressure */
1477 BE_TIMER_PUSH(t_ra_constr);
1478 be_pre_spill_prepare_constr(birg, cls);
1479 BE_TIMER_POP(t_ra_constr);
1481 dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1484 BE_TIMER_PUSH(t_ra_spill);
1485 be_do_spill(birg, cls);
1486 BE_TIMER_POP(t_ra_spill);
1488 BE_TIMER_PUSH(t_ra_spill_apply);
1489 check_for_memory_operands(irg);
1490 BE_TIMER_POP(t_ra_spill_apply);
1492 dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1496 * The straight register allocator for a whole procedure.
1498 static void be_straight_alloc(be_irg_t *new_birg)
1500 const arch_env_t *arch_env = new_birg->main_env->arch_env;
1501 int n_cls = arch_env_get_n_reg_class(arch_env);
1504 obstack_init(&obst);
1507 irg = be_get_birg_irg(birg);
1508 execfreqs = birg->exec_freq;
1510 /* TODO: extract some of the stuff from bechordal allocator, like
1511 * statistics, time measurements, etc. and use them here too */
1513 for (c = 0; c < n_cls; ++c) {
1514 cls = arch_env_get_reg_class(arch_env, c);
1515 default_cls_req = NULL;
1516 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1519 stat_ev_ctx_push_str("regcls", cls->name);
1521 n_regs = arch_register_class_n_regs(cls);
1522 normal_regs = rbitset_malloc(n_regs);
1523 be_abi_set_non_ignore_regs(birg->abi, cls, normal_regs);
1527 /* verify schedule and register pressure */
1528 BE_TIMER_PUSH(t_verify);
1529 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1530 be_verify_schedule(birg);
1531 be_verify_register_pressure(birg, cls, irg);
1532 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1533 assert(be_verify_schedule(birg) && "Schedule verification failed");
1534 assert(be_verify_register_pressure(birg, cls, irg)
1535 && "Register pressure verification failed");
1537 BE_TIMER_POP(t_verify);
1539 BE_TIMER_PUSH(t_ra_color);
1540 be_straight_alloc_cls();
1541 BE_TIMER_POP(t_ra_color);
1543 /* we most probably constructed new Phis so liveness info is invalid
1545 /* TODO: test liveness_introduce */
1546 be_liveness_invalidate(lv);
1549 stat_ev_ctx_pop("regcls");
1552 BE_TIMER_PUSH(t_ra_spill_apply);
1553 be_abi_fix_stack_nodes(birg->abi);
1554 BE_TIMER_POP(t_ra_spill_apply);
1556 BE_TIMER_PUSH(t_verify);
1557 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1558 be_verify_register_allocation(birg);
1559 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1560 assert(be_verify_register_allocation(birg)
1561 && "Register allocation invalid");
1563 BE_TIMER_POP(t_verify);
1565 obstack_free(&obst, NULL);
1569 * Initializes this module.
1571 void be_init_straight_alloc(void)
1573 static be_ra_t be_ra_straight = {
1577 FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
1579 be_register_allocator("straight", &be_ra_straight);
1582 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);