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"
63 #include "unionfind.h"
66 #include "bechordal_t.h"
75 #include "bespillutil.h"
78 #include "hungarian.h"
80 #define USE_FACTOR 1.0f
81 #define DEF_FACTOR 1.0f
82 #define NEIGHBOR_FACTOR 0.2f
83 #define AFF_SHOULD_BE_SAME 0.5f
85 #define SPLIT_DELTA 1.0f
87 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
89 static struct obstack obst;
90 static be_irg_t *birg;
92 static const arch_register_class_t *cls;
93 static const arch_register_req_t *default_cls_req;
95 static const ir_exec_freq *execfreqs;
96 static unsigned n_regs;
97 static unsigned *normal_regs;
98 static int *congruence_classes;
100 /** currently active assignments (while processing a basic block)
101 * maps registers to values(their current copies) */
102 static ir_node **assignments;
105 * allocation information: last_uses, register preferences
106 * the information is per firm-node.
108 struct allocation_info_t {
109 unsigned last_uses; /**< bitset indicating last uses (input pos) */
110 ir_node *current_value; /**< copy of the value that should be used */
111 ir_node *original_value; /**< for copies point to original value */
112 unsigned char should_be_same[2];
113 float prefs[0]; /**< register preferences */
115 typedef struct allocation_info_t allocation_info_t;
117 /** helper datastructure used when sorting register preferences */
122 typedef struct reg_pref_t reg_pref_t;
124 /** per basic-block information */
125 struct block_info_t {
126 bool processed; /**< indicate wether block is processed */
127 ir_node *assignments[0]; /**< register assignments at end of block */
129 typedef struct block_info_t block_info_t;
132 * Get the allocation info for a node.
133 * The info is allocated on the first visit of a node.
135 static allocation_info_t *get_allocation_info(ir_node *node)
137 allocation_info_t *info = get_irn_link(node);
139 info = OALLOCFZ(&obst, allocation_info_t, prefs, n_regs);
140 info->current_value = node;
141 info->original_value = node;
142 set_irn_link(node, info);
149 * Get allocation information for a basic block
151 static block_info_t *get_block_info(ir_node *block)
153 block_info_t *info = get_irn_link(block);
155 assert(is_Block(block));
157 info = OALLOCFZ(&obst, block_info_t, assignments, n_regs);
158 set_irn_link(block, info);
165 * Get default register requirement for the current register class
167 static const arch_register_req_t *get_default_req_current_cls(void)
169 if (default_cls_req == NULL) {
170 struct obstack *obst = get_irg_obstack(irg);
171 arch_register_req_t *req = OALLOCZ(obst, arch_register_req_t);
173 req->type = arch_register_req_type_normal;
176 default_cls_req = req;
178 return default_cls_req;
182 * Link the allocation info of a node to a copy.
183 * Afterwards, both nodes uses the same allocation info.
184 * Copy must not have an allocation info assigned yet.
186 * @param copy the node that gets the allocation info assigned
187 * @param value the original node
189 static void mark_as_copy_of(ir_node *copy, ir_node *value)
192 allocation_info_t *info = get_allocation_info(value);
193 allocation_info_t *copy_info = get_allocation_info(copy);
195 /* find original value */
196 original = info->original_value;
197 if (original != value) {
198 info = get_allocation_info(original);
201 assert(info->original_value == original);
202 info->current_value = copy;
204 /* the copy should not be linked to something else yet */
205 assert(copy_info->original_value == copy);
206 copy_info->original_value = original;
208 /* copy over allocation preferences */
209 memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
213 * Calculate the penalties for every register on a node and its live neighbors.
215 * @param live_nodes the set of live nodes at the current position, may be NULL
216 * @param penalty the penalty to subtract from
217 * @param limited a raw bitset containing the limited set for the node
218 * @param node the node
220 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
221 float penalty, const unsigned* limited,
224 ir_nodeset_iterator_t iter;
226 allocation_info_t *info = get_allocation_info(node);
229 /* give penalty for all forbidden regs */
230 for (r = 0; r < n_regs; ++r) {
231 if (rbitset_is_set(limited, r))
234 info->prefs[r] -= penalty;
237 /* all other live values should get a penalty for allowed regs */
238 if (live_nodes == NULL)
241 /* TODO: reduce penalty if there are multiple allowed registers... */
242 penalty *= NEIGHBOR_FACTOR;
243 foreach_ir_nodeset(live_nodes, neighbor, iter) {
244 allocation_info_t *neighbor_info;
246 /* TODO: if op is used on multiple inputs we might not do a
248 if (neighbor == node)
251 neighbor_info = get_allocation_info(neighbor);
252 for (r = 0; r < n_regs; ++r) {
253 if (!rbitset_is_set(limited, r))
256 neighbor_info->prefs[r] -= penalty;
262 * Calculate the preferences of a definition for the current register class.
263 * If the definition uses a limited set of registers, reduce the preferences
264 * for the limited register on the node and its neighbors.
266 * @param live_nodes the set of live nodes at the current node
267 * @param weight the weight
268 * @param node the current node
270 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
273 const arch_register_req_t *req;
275 if (get_irn_mode(node) == mode_T) {
276 const ir_edge_t *edge;
277 foreach_out_edge(node, edge) {
278 ir_node *proj = get_edge_src_irn(edge);
279 check_defs(live_nodes, weight, proj);
284 if (!arch_irn_consider_in_reg_alloc(cls, node))
287 req = arch_get_register_req_out(node);
288 if (req->type & arch_register_req_type_limited) {
289 const unsigned *limited = req->limited;
290 float penalty = weight * DEF_FACTOR;
291 give_penalties_for_limits(live_nodes, penalty, limited, node);
294 if (req->type & arch_register_req_type_should_be_same) {
295 ir_node *insn = skip_Proj(node);
296 allocation_info_t *info = get_allocation_info(node);
297 int arity = get_irn_arity(insn);
300 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
301 for (i = 0; i < arity; ++i) {
304 allocation_info_t *op_info;
306 if (!rbitset_is_set(&req->other_same, i))
309 op = get_irn_n(insn, i);
311 /* if we the value at the should_be_same input doesn't die at the
312 * node, then it is no use to propagate the constraints (since a
313 * copy will emerge anyway) */
314 if (ir_nodeset_contains(live_nodes, op))
317 op_info = get_allocation_info(op);
318 for (r = 0; r < n_regs; ++r) {
319 op_info->prefs[r] += info->prefs[r] * factor;
326 * Walker: Runs an a block calculates the preferences for any
327 * node and every register from the considered register class.
329 static void analyze_block(ir_node *block, void *data)
331 float weight = get_block_execfreq(execfreqs, block);
332 ir_nodeset_t live_nodes;
336 ir_nodeset_init(&live_nodes);
337 be_liveness_end_of_block(lv, cls, block, &live_nodes);
339 sched_foreach_reverse(block, node) {
340 allocation_info_t *info;
347 check_defs(&live_nodes, weight, node);
350 arity = get_irn_arity(node);
352 /* the allocation info node currently only uses 1 unsigned value
353 to mark last used inputs. So we will fail for a node with more than
355 if (arity >= (int) sizeof(unsigned) * 8) {
356 panic("Node with more than %d inputs not supported yet",
357 (int) sizeof(unsigned) * 8);
360 info = get_allocation_info(node);
361 for (i = 0; i < arity; ++i) {
362 ir_node *op = get_irn_n(node, i);
363 if (!arch_irn_consider_in_reg_alloc(cls, op))
366 /* last usage of a value? */
367 if (!ir_nodeset_contains(&live_nodes, op)) {
368 rbitset_set(&info->last_uses, i);
372 be_liveness_transfer(cls, node, &live_nodes);
374 /* update weights based on usage constraints */
375 for (i = 0; i < arity; ++i) {
376 const arch_register_req_t *req;
377 const unsigned *limited;
378 ir_node *op = get_irn_n(node, i);
380 if (!arch_irn_consider_in_reg_alloc(cls, op))
383 req = arch_get_register_req(node, i);
384 if (!(req->type & arch_register_req_type_limited))
387 limited = req->limited;
388 give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
393 ir_nodeset_destroy(&live_nodes);
396 static void create_congurence_class(ir_node *node, void *data)
401 int arity = get_irn_arity(node);
402 unsigned phi_idx = get_irn_idx(node);
403 phi_idx = uf_find(congruence_classes, phi_idx);
404 for (i = 0; i < arity; ++i) {
405 ir_node *op = get_Phi_pred(node, i);
406 int op_idx = get_irn_idx(op);
407 op_idx = uf_find(congruence_classes, op_idx);
408 phi_idx = uf_union(congruence_classes, phi_idx, op_idx);
412 /* should be same constraint? */
414 const arch_register_req_t *req = arch_get_register_req_out(node);
415 if (req->type & arch_register_req_type_should_be_same) {
416 ir_node *pred = get_Proj_pred(node);
417 int arity = get_irn_arity(pred);
419 unsigned node_idx = get_irn_idx(node);
420 node_idx = uf_find(congruence_classes, node_idx);
422 for (i = 0; i < arity; ++i) {
426 if (!rbitset_is_set(&req->other_same, i))
429 op = get_irn_n(pred, i);
430 op_idx = get_irn_idx(op);
431 op_idx = uf_find(congruence_classes, op_idx);
432 node_idx = uf_union(congruence_classes, node_idx, op_idx);
439 static void merge_congruence_prefs(ir_node *node, void *data)
441 allocation_info_t *info;
442 allocation_info_t *head_info;
443 unsigned node_idx = get_irn_idx(node);
444 unsigned node_set = uf_find(congruence_classes, node_idx);
449 /* head of congruence class or not in any class */
450 if (node_set == node_idx)
453 if (!arch_irn_consider_in_reg_alloc(cls, node))
456 head_info = get_allocation_info(get_idx_irn(irg, node_set));
457 info = get_allocation_info(node);
459 for (r = 0; r < n_regs; ++r) {
460 head_info->prefs[r] += info->prefs[r];
464 static void set_congruence_prefs(ir_node *node, void *data)
466 allocation_info_t *info;
467 allocation_info_t *head_info;
468 unsigned node_idx = get_irn_idx(node);
469 unsigned node_set = uf_find(congruence_classes, node_idx);
473 /* head of congruence class or not in any class */
474 if (node_set == node_idx)
477 if (!arch_irn_consider_in_reg_alloc(cls, node))
480 head_info = get_allocation_info(get_idx_irn(irg, node_set));
481 info = get_allocation_info(node);
483 memcpy(info->prefs, head_info->prefs, n_regs * sizeof(info->prefs[0]));
486 static void combine_congruence_classes(void)
488 size_t n = get_irg_last_idx(irg);
489 congruence_classes = XMALLOCN(int, n);
490 uf_init(congruence_classes, n);
492 /* create congruence classes */
493 irg_walk_graph(irg, create_congurence_class, NULL, NULL);
494 /* merge preferences */
495 irg_walk_graph(irg, merge_congruence_prefs, NULL, NULL);
496 irg_walk_graph(irg, set_congruence_prefs, NULL, NULL);
504 * Assign register reg to the given node.
506 * @param node the node
507 * @param reg the register
509 static void use_reg(ir_node *node, const arch_register_t *reg)
511 unsigned r = arch_register_get_index(reg);
512 assignments[r] = node;
513 arch_set_irn_register(node, reg);
516 static void free_reg_of_value(ir_node *node)
518 const arch_register_t *reg;
521 if (!arch_irn_consider_in_reg_alloc(cls, node))
524 reg = arch_get_irn_register(node);
525 r = arch_register_get_index(reg);
526 /* assignment->value may be NULL if a value is used at 2 inputs
527 so it gets freed twice. */
528 assert(assignments[r] == node || assignments[r] == NULL);
529 assignments[r] = NULL;
533 * Compare two register preferences in decreasing order.
535 static int compare_reg_pref(const void *e1, const void *e2)
537 const reg_pref_t *rp1 = (const reg_pref_t*) e1;
538 const reg_pref_t *rp2 = (const reg_pref_t*) e2;
539 if (rp1->pref < rp2->pref)
541 if (rp1->pref > rp2->pref)
546 static void fill_sort_candidates(reg_pref_t *regprefs,
547 const allocation_info_t *info)
551 for (r = 0; r < n_regs; ++r) {
552 float pref = info->prefs[r];
554 regprefs[r].pref = pref;
556 /* TODO: use a stable sort here to avoid unnecessary register jumping */
557 qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
560 static bool try_optimistic_split(ir_node *to_split, ir_node *before,
561 float pref, float pref_delta,
562 unsigned *output_regs)
564 const arch_register_t *reg;
570 allocation_info_t *info = get_allocation_info(to_split);
576 /* stupid hack: don't optimisticallt split don't spill nodes...
577 * (so we don't split away the values produced because of
578 * must_be_different constraints) */
579 insn = skip_Proj(to_split);
580 if (arch_irn_get_flags(insn) & arch_irn_flags_dont_spill)
583 /* find the best free position where we could move to */
584 prefs = ALLOCAN(reg_pref_t, n_regs);
585 fill_sort_candidates(prefs, info);
586 for (i = 0; i < n_regs; ++i) {
588 if (!rbitset_is_set(normal_regs, r))
590 if (rbitset_is_set(output_regs, r))
592 if (assignments[r] == NULL)
598 /* TODO: use execfreq somehow... */
599 delta = pref_delta + prefs[i].pref;
600 if (delta < SPLIT_DELTA) {
601 DB((dbg, LEVEL_3, "Not doing optimistical split, win %f too low\n",
606 reg = arch_register_for_index(cls, r);
607 block = get_nodes_block(before);
608 copy = be_new_Copy(cls, block, to_split);
609 mark_as_copy_of(copy, to_split);
610 free_reg_of_value(to_split);
612 sched_add_before(before, copy);
615 "Optimistic live-range split %+F move %+F -> %s before %+F (win %f)\n",
616 copy, to_split, reg->name, before, delta));
621 * Determine and assign a register for node @p node
623 static void assign_reg(const ir_node *block, ir_node *node,
624 unsigned *output_regs)
626 const arch_register_t *reg;
627 allocation_info_t *info;
628 const arch_register_req_t *req;
629 reg_pref_t *reg_prefs;
632 const unsigned *allowed_regs;
635 assert(arch_irn_consider_in_reg_alloc(cls, node));
637 /* preassigned register? */
638 reg = arch_get_irn_register(node);
640 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
645 /* give should_be_same boni */
646 info = get_allocation_info(node);
647 req = arch_get_register_req_out(node);
649 in_node = skip_Proj(node);
650 if (req->type & arch_register_req_type_should_be_same) {
651 float weight = get_block_execfreq(execfreqs, block);
652 int arity = get_irn_arity(in_node);
655 assert(arity <= (int) sizeof(req->other_same) * 8);
656 for (i = 0; i < arity; ++i) {
658 const arch_register_t *reg;
660 if (!rbitset_is_set(&req->other_same, i))
663 in = get_irn_n(in_node, i);
664 reg = arch_get_irn_register(in);
666 r = arch_register_get_index(reg);
668 /* if the value didn't die here then we should not propagate the
669 * should_be_same info */
670 if (assignments[r] == in)
673 info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
677 /* create list of register candidates and sort by their preference */
678 DB((dbg, LEVEL_2, "Candidates for %+F:", node));
679 reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
680 fill_sort_candidates(reg_prefs, info);
681 for (i = 0; i < n_regs; ++i) {
682 unsigned num = reg_prefs[i].num;
683 const arch_register_t *reg;
685 if (!rbitset_is_set(normal_regs, num))
688 reg = arch_register_for_index(cls, num);
689 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
691 DB((dbg, LEVEL_2, "\n"));
693 allowed_regs = normal_regs;
694 if (req->type & arch_register_req_type_limited) {
695 allowed_regs = req->limited;
698 for (i = 0; i < n_regs; ++i) {
699 r = reg_prefs[i].num;
700 if (!rbitset_is_set(allowed_regs, r))
702 if (assignments[r] == NULL)
705 float pref = reg_prefs[i].pref;
706 float delta = i+1 < n_regs ? pref - reg_prefs[i+1].pref : 0;
707 ir_node *before = skip_Proj(node);
708 bool res = try_optimistic_split(assignments[r], before,
716 panic("No register left for %+F\n", node);
719 reg = arch_register_for_index(cls, r);
720 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
725 * Add an permutation in front of a node and change the assignments
726 * due to this permutation.
728 * To understand this imagine a permutation like this:
738 * First we count how many destinations a single value has. At the same time
739 * we can be sure that each destination register has at most 1 source register
740 * (it can have 0 which means we don't care what value is in it).
741 * We ignore all fullfilled permuations (like 7->7)
742 * In a first pass we create as much copy instructions as possible as they
743 * are generally cheaper than exchanges. We do this by counting into how many
744 * destinations a register has to be copied (in the example it's 2 for register
745 * 3, or 1 for the registers 1,2,4 and 7).
746 * We can then create a copy into every destination register when the usecount
747 * of that register is 0 (= noone else needs the value in the register).
749 * After this step we should have cycles left. We implement a cyclic permutation
750 * of n registers with n-1 transpositions.
752 * @param live_nodes the set of live nodes, updated due to live range split
753 * @param before the node before we add the permutation
754 * @param permutation the permutation array indices are the destination
755 * registers, the values in the array are the source
758 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
759 unsigned *permutation)
761 unsigned *n_used = ALLOCANZ(unsigned, n_regs);
765 /* determine how often each source register needs to be read */
766 for (r = 0; r < n_regs; ++r) {
767 unsigned old_reg = permutation[r];
770 value = assignments[old_reg];
772 /* nothing to do here, reg is not live. Mark it as fixpoint
773 * so we ignore it in the next steps */
781 block = get_nodes_block(before);
783 /* step1: create copies where immediately possible */
784 for (r = 0; r < n_regs; /* empty */) {
787 const arch_register_t *reg;
788 unsigned old_r = permutation[r];
790 /* - no need to do anything for fixed points.
791 - we can't copy if the value in the dest reg is still needed */
792 if (old_r == r || n_used[r] > 0) {
798 src = assignments[old_r];
799 copy = be_new_Copy(cls, block, src);
800 sched_add_before(before, copy);
801 reg = arch_register_for_index(cls, r);
802 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
803 copy, src, before, reg->name));
804 mark_as_copy_of(copy, src);
807 if (live_nodes != NULL) {
808 ir_nodeset_insert(live_nodes, copy);
811 /* old register has 1 user less, permutation is resolved */
812 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
815 assert(n_used[old_r] > 0);
817 if (n_used[old_r] == 0) {
818 if (live_nodes != NULL) {
819 ir_nodeset_remove(live_nodes, src);
821 free_reg_of_value(src);
824 /* advance or jump back (if this copy enabled another copy) */
825 if (old_r < r && n_used[old_r] == 0) {
832 /* at this point we only have "cycles" left which we have to resolve with
834 * TODO: if we have free registers left, then we should really use copy
835 * instructions for any cycle longer than 2 registers...
836 * (this is probably architecture dependent, there might be archs where
837 * copies are preferable even for 2-cycles) */
839 /* create perms with the rest */
840 for (r = 0; r < n_regs; /* empty */) {
841 const arch_register_t *reg;
842 unsigned old_r = permutation[r];
854 /* we shouldn't have copies from 1 value to multiple destinations left*/
855 assert(n_used[old_r] == 1);
857 /* exchange old_r and r2; after that old_r is a fixed point */
858 r2 = permutation[old_r];
860 in[0] = assignments[r2];
861 in[1] = assignments[old_r];
862 perm = be_new_Perm(cls, block, 2, in);
863 sched_add_before(before, perm);
864 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
865 perm, in[0], in[1], before));
867 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
868 mark_as_copy_of(proj0, in[0]);
869 reg = arch_register_for_index(cls, old_r);
872 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
873 mark_as_copy_of(proj1, in[1]);
874 reg = arch_register_for_index(cls, r2);
877 /* 1 value is now in the correct register */
878 permutation[old_r] = old_r;
879 /* the source of r changed to r2 */
882 /* if we have reached a fixpoint update data structures */
883 if (live_nodes != NULL) {
884 ir_nodeset_remove(live_nodes, in[0]);
885 ir_nodeset_remove(live_nodes, in[1]);
886 ir_nodeset_remove(live_nodes, proj0);
887 ir_nodeset_insert(live_nodes, proj1);
892 /* now we should only have fixpoints left */
893 for (r = 0; r < n_regs; ++r) {
894 assert(permutation[r] == r);
900 * Free regs for values last used.
902 * @param live_nodes set of live nodes, will be updated
903 * @param node the node to consider
905 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
907 allocation_info_t *info = get_allocation_info(node);
908 const unsigned *last_uses = &info->last_uses;
909 int arity = get_irn_arity(node);
912 for (i = 0; i < arity; ++i) {
915 /* check if one operand is the last use */
916 if (!rbitset_is_set(last_uses, i))
919 op = get_irn_n(node, i);
920 free_reg_of_value(op);
921 ir_nodeset_remove(live_nodes, op);
926 * change inputs of a node to the current value (copies/perms)
928 static void rewire_inputs(ir_node *node)
931 int arity = get_irn_arity(node);
933 for (i = 0; i < arity; ++i) {
934 ir_node *op = get_irn_n(node, i);
935 allocation_info_t *info;
937 if (!arch_irn_consider_in_reg_alloc(cls, op))
940 info = get_allocation_info(op);
941 info = get_allocation_info(info->original_value);
942 if (info->current_value != op) {
943 set_irn_n(node, i, info->current_value);
949 * Create a bitset of registers occupied with value living through an
952 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
954 const allocation_info_t *info = get_allocation_info(node);
959 /* mark all used registers as potentially live-through */
960 for (r = 0; r < n_regs; ++r) {
961 if (assignments[r] == NULL)
963 if (!rbitset_is_set(normal_regs, r))
966 rbitset_set(bitset, r);
969 /* remove registers of value dying at the instruction */
970 arity = get_irn_arity(node);
971 for (i = 0; i < arity; ++i) {
973 const arch_register_t *reg;
975 if (!rbitset_is_set(&info->last_uses, i))
978 op = get_irn_n(node, i);
979 reg = arch_get_irn_register(op);
980 rbitset_clear(bitset, arch_register_get_index(reg));
985 * Enforce constraints at a node by live range splits.
987 * @param live_nodes the set of live nodes, might be changed
988 * @param node the current node
990 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node,
991 unsigned *output_regs)
993 int arity = get_irn_arity(node);
995 hungarian_problem_t *bp;
997 unsigned *assignment;
999 /* construct a list of register occupied by live-through values */
1000 unsigned *live_through_regs = NULL;
1002 /* see if any use constraints are not met */
1004 for (i = 0; i < arity; ++i) {
1005 ir_node *op = get_irn_n(node, i);
1006 const arch_register_t *reg;
1007 const arch_register_req_t *req;
1008 const unsigned *limited;
1011 if (!arch_irn_consider_in_reg_alloc(cls, op))
1014 /* are there any limitations for the i'th operand? */
1015 req = arch_get_register_req(node, i);
1016 if (!(req->type & arch_register_req_type_limited))
1019 limited = req->limited;
1020 reg = arch_get_irn_register(op);
1021 r = arch_register_get_index(reg);
1022 if (!rbitset_is_set(limited, r)) {
1023 /* found an assignment outside the limited set */
1029 /* is any of the live-throughs using a constrained output register? */
1030 if (get_irn_mode(node) == mode_T) {
1031 const ir_edge_t *edge;
1033 foreach_out_edge(node, edge) {
1034 ir_node *proj = get_edge_src_irn(edge);
1035 const arch_register_req_t *req;
1037 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1040 req = arch_get_register_req_out(proj);
1041 if (!(req->type & arch_register_req_type_limited))
1044 if (live_through_regs == NULL) {
1045 rbitset_alloca(live_through_regs, n_regs);
1046 determine_live_through_regs(live_through_regs, node);
1049 rbitset_or(output_regs, req->limited, n_regs);
1050 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
1055 if (arch_irn_consider_in_reg_alloc(cls, node)) {
1056 const arch_register_req_t *req = arch_get_register_req_out(node);
1057 if (req->type & arch_register_req_type_limited) {
1058 rbitset_alloca(live_through_regs, n_regs);
1059 determine_live_through_regs(live_through_regs, node);
1060 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
1062 rbitset_or(output_regs, req->limited, n_regs);
1071 /* create these arrays if we haven't yet */
1072 if (live_through_regs == NULL) {
1073 rbitset_alloca(live_through_regs, n_regs);
1076 /* at this point we have to construct a bipartite matching problem to see
1077 * which values should go to which registers
1078 * Note: We're building the matrix in "reverse" - source registers are
1079 * right, destinations left because this will produce the solution
1080 * in the format required for permute_values.
1082 bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
1084 /* add all combinations, then remove not allowed ones */
1085 for (l = 0; l < n_regs; ++l) {
1086 if (!rbitset_is_set(normal_regs, l)) {
1087 hungarian_add(bp, l, l, 1);
1091 for (r = 0; r < n_regs; ++r) {
1092 if (!rbitset_is_set(normal_regs, r))
1094 /* livethrough values may not use constrainted output registers */
1095 if (rbitset_is_set(live_through_regs, l)
1096 && rbitset_is_set(output_regs, r))
1099 hungarian_add(bp, r, l, l == r ? 9 : 8);
1103 for (i = 0; i < arity; ++i) {
1104 ir_node *op = get_irn_n(node, i);
1105 const arch_register_t *reg;
1106 const arch_register_req_t *req;
1107 const unsigned *limited;
1108 unsigned current_reg;
1110 if (!arch_irn_consider_in_reg_alloc(cls, op))
1113 req = arch_get_register_req(node, i);
1114 if (!(req->type & arch_register_req_type_limited))
1117 limited = req->limited;
1118 reg = arch_get_irn_register(op);
1119 current_reg = arch_register_get_index(reg);
1120 for (r = 0; r < n_regs; ++r) {
1121 if (rbitset_is_set(limited, r))
1123 hungarian_remv(bp, r, current_reg);
1127 //hungarian_print_costmatrix(bp, 1);
1128 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1130 assignment = ALLOCAN(unsigned, n_regs);
1131 res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
1135 fprintf(stderr, "Swap result:");
1136 for (i = 0; i < (int) n_regs; ++i) {
1137 fprintf(stderr, " %d", assignment[i]);
1139 fprintf(stderr, "\n");
1144 permute_values(live_nodes, node, assignment);
1147 /** test wether a node @p n is a copy of the value of node @p of */
1148 static bool is_copy_of(ir_node *value, ir_node *test_value)
1150 allocation_info_t *test_info;
1151 allocation_info_t *info;
1153 if (value == test_value)
1156 info = get_allocation_info(value);
1157 test_info = get_allocation_info(test_value);
1158 return test_info->original_value == info->original_value;
1162 * find a value in the end-assignment of a basic block
1163 * @returns the index into the assignment array if found
1166 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1169 ir_node **assignments = info->assignments;
1170 for (r = 0; r < n_regs; ++r) {
1171 ir_node *a_value = assignments[r];
1173 if (a_value == NULL)
1175 if (is_copy_of(a_value, value))
1183 * Create the necessary permutations at the end of a basic block to fullfill
1184 * the register assignment for phi-nodes in the next block
1186 static void add_phi_permutations(ir_node *block, int p)
1189 unsigned *permutation;
1190 ir_node **old_assignments;
1191 bool need_permutation;
1193 ir_node *pred = get_Block_cfgpred_block(block, p);
1195 block_info_t *pred_info = get_block_info(pred);
1197 /* predecessor not processed yet? nothing to do */
1198 if (!pred_info->processed)
1201 permutation = ALLOCAN(unsigned, n_regs);
1202 for (r = 0; r < n_regs; ++r) {
1206 /* check phi nodes */
1207 need_permutation = false;
1208 node = sched_first(block);
1209 for ( ; is_Phi(node); node = sched_next(node)) {
1210 const arch_register_t *reg;
1215 if (!arch_irn_consider_in_reg_alloc(cls, node))
1218 op = get_Phi_pred(node, p);
1219 if (!arch_irn_consider_in_reg_alloc(cls, op))
1222 a = find_value_in_block_info(pred_info, op);
1225 reg = arch_get_irn_register(node);
1226 regn = arch_register_get_index(reg);
1228 permutation[regn] = a;
1229 need_permutation = true;
1233 if (need_permutation) {
1234 /* permute values at end of predecessor */
1235 old_assignments = assignments;
1236 assignments = pred_info->assignments;
1237 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1239 assignments = old_assignments;
1242 /* change phi nodes to use the copied values */
1243 node = sched_first(block);
1244 for ( ; is_Phi(node); node = sched_next(node)) {
1248 if (!arch_irn_consider_in_reg_alloc(cls, node))
1251 op = get_Phi_pred(node, p);
1252 /* no need to do anything for Unknown inputs */
1253 if (!arch_irn_consider_in_reg_alloc(cls, op))
1256 /* we have permuted all values into the correct registers so we can
1257 simply query which value occupies the phis register in the
1259 a = arch_register_get_index(arch_get_irn_register(node));
1260 op = pred_info->assignments[a];
1261 set_Phi_pred(node, p, op);
1266 * Set preferences for a phis register based on the registers used on the
1269 static void adapt_phi_prefs(ir_node *phi)
1272 int arity = get_irn_arity(phi);
1273 ir_node *block = get_nodes_block(phi);
1274 allocation_info_t *info = get_allocation_info(phi);
1276 for (i = 0; i < arity; ++i) {
1277 ir_node *op = get_irn_n(phi, i);
1278 const arch_register_t *reg = arch_get_irn_register(op);
1279 ir_node *pred_block;
1280 block_info_t *pred_block_info;
1286 /* we only give the bonus if the predecessor already has registers
1287 * assigned, otherwise we only see a dummy value
1288 * and any conclusions about its register are useless */
1289 pred_block = get_Block_cfgpred_block(block, i);
1290 pred_block_info = get_block_info(pred_block);
1291 if (!pred_block_info->processed)
1294 /* give bonus for already assigned register */
1295 weight = get_block_execfreq(execfreqs, pred_block);
1296 r = arch_register_get_index(reg);
1297 info->prefs[r] += weight * AFF_PHI;
1302 * After a phi has been assigned a register propagate preference inputs
1303 * to the phi inputs.
1305 static void propagate_phi_register(ir_node *phi, unsigned r)
1308 ir_node *block = get_nodes_block(phi);
1309 int arity = get_irn_arity(phi);
1311 for (i = 0; i < arity; ++i) {
1312 ir_node *op = get_Phi_pred(phi, i);
1313 allocation_info_t *info = get_allocation_info(op);
1314 ir_node *pred_block = get_Block_cfgpred_block(block, i);
1316 = get_block_execfreq(execfreqs, pred_block) * AFF_PHI;
1318 if (info->prefs[r] >= weight)
1321 /* promote the prefered register */
1322 info->prefs[r] = AFF_PHI * weight;
1324 propagate_phi_register(op, r);
1329 * Walker: assign registers to all nodes of a block that
1330 * need registers from the currently considered register class.
1332 static void allocate_coalesce_block(ir_node *block, void *data)
1335 ir_nodeset_t live_nodes;
1336 ir_nodeset_iterator_t iter;
1337 ir_node *node, *start;
1339 block_info_t *block_info;
1340 block_info_t **pred_block_infos;
1342 unsigned *output_regs; /**< collects registers which must not
1343 be used for optimistic splits */
1346 DB((dbg, LEVEL_2, "* Block %+F\n", block));
1348 /* clear assignments */
1349 block_info = get_block_info(block);
1350 assignments = block_info->assignments;
1352 ir_nodeset_init(&live_nodes);
1354 /* gather regalloc infos of predecessor blocks */
1355 n_preds = get_Block_n_cfgpreds(block);
1356 pred_block_infos = ALLOCAN(block_info_t*, n_preds);
1357 for (i = 0; i < n_preds; ++i) {
1358 ir_node *pred = get_Block_cfgpred_block(block, i);
1359 block_info_t *pred_info = get_block_info(pred);
1360 pred_block_infos[i] = pred_info;
1363 phi_ins = ALLOCAN(ir_node*, n_preds);
1365 /* collect live-in nodes and preassigned values */
1366 be_lv_foreach(lv, block, be_lv_state_in, i) {
1367 const arch_register_t *reg;
1369 bool need_phi = false;
1371 node = be_lv_get_irn(lv, block, i);
1372 if (!arch_irn_consider_in_reg_alloc(cls, node))
1375 /* check all predecessors for this value, if it is not everywhere the
1376 same or unknown then we have to construct a phi
1377 (we collect the potential phi inputs here) */
1378 for (p = 0; p < n_preds; ++p) {
1379 block_info_t *pred_info = pred_block_infos[p];
1381 if (!pred_info->processed) {
1382 /* use node for now, it will get fixed later */
1386 int a = find_value_in_block_info(pred_info, node);
1388 /* must live out of predecessor */
1390 phi_ins[p] = pred_info->assignments[a];
1391 /* different value from last time? then we need a phi */
1392 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1399 ir_mode *mode = get_irn_mode(node);
1400 const arch_register_req_t *req = get_default_req_current_cls();
1404 phi = new_r_Phi(block, n_preds, phi_ins, mode);
1405 be_set_phi_reg_req(phi, req);
1407 DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1408 #ifdef DEBUG_libfirm
1409 for (i = 0; i < n_preds; ++i) {
1410 DB((dbg, LEVEL_3, " %+F", phi_ins[i]));
1412 DB((dbg, LEVEL_3, "\n"));
1414 mark_as_copy_of(phi, node);
1415 sched_add_after(block, phi);
1419 allocation_info_t *info = get_allocation_info(node);
1420 info->current_value = phi_ins[0];
1422 /* Grab 1 of the inputs we constructed (might not be the same as
1423 * "node" as we could see the same copy of the value in all
1428 /* if the node already has a register assigned use it */
1429 reg = arch_get_irn_register(node);
1431 /* TODO: consult pred-block infos here. The value could be copied
1432 away in some/all predecessor blocks. We need to construct
1433 phi-nodes in this case.
1434 We even need to construct some Phi_0 like constructs in cases
1435 where the predecessor allocation is not determined yet. */
1439 /* remember that this node is live at the beginning of the block */
1440 ir_nodeset_insert(&live_nodes, node);
1443 rbitset_alloca(output_regs, n_regs);
1445 /* handle phis... */
1446 node = sched_first(block);
1447 for ( ; is_Phi(node); node = sched_next(node)) {
1448 const arch_register_t *reg;
1450 if (!arch_irn_consider_in_reg_alloc(cls, node))
1453 /* fill in regs already assigned */
1454 reg = arch_get_irn_register(node);
1458 adapt_phi_prefs(node);
1459 assign_reg(block, node, output_regs);
1461 reg = arch_get_irn_register(node);
1462 propagate_phi_register(node, arch_register_get_index(reg));
1467 /* assign regs for live-in values */
1468 foreach_ir_nodeset(&live_nodes, node, iter) {
1469 const arch_register_t *reg = arch_get_irn_register(node);
1473 assign_reg(block, node, output_regs);
1474 /* shouldn't happen if we color in dominance order */
1475 assert (!is_Phi(node));
1478 /* assign instructions in the block */
1479 for (node = start; !sched_is_end(node); node = sched_next(node)) {
1482 rewire_inputs(node);
1484 /* enforce use constraints */
1485 rbitset_clear_all(output_regs, n_regs);
1486 enforce_constraints(&live_nodes, node, output_regs);
1487 /* we may not use registers occupied here for optimistic splits */
1488 for (r = 0; r < n_regs; ++r) {
1489 if (assignments[r] != NULL)
1490 rbitset_set(output_regs, r);
1493 rewire_inputs(node);
1495 /* free registers of values last used at this instruction */
1496 free_last_uses(&live_nodes, node);
1498 /* assign output registers */
1499 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1500 if (get_irn_mode(node) == mode_T) {
1501 const ir_edge_t *edge;
1502 foreach_out_edge(node, edge) {
1503 ir_node *proj = get_edge_src_irn(edge);
1504 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1506 assign_reg(block, proj, output_regs);
1508 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1509 assign_reg(block, node, output_regs);
1513 ir_nodeset_destroy(&live_nodes);
1516 block_info->processed = true;
1518 /* permute values at end of predecessor blocks in case of phi-nodes */
1521 for (p = 0; p < n_preds; ++p) {
1522 add_phi_permutations(block, p);
1526 /* if we have exactly 1 successor then we might be able to produce phi
1528 if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1529 const ir_edge_t *edge
1530 = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1531 ir_node *succ = get_edge_src_irn(edge);
1532 int p = get_edge_src_pos(edge);
1533 block_info_t *succ_info = get_block_info(succ);
1535 if (succ_info->processed) {
1536 add_phi_permutations(succ, p);
1542 * Run the register allocator for the current register class.
1544 static void be_straight_alloc_cls(void)
1546 lv = be_assure_liveness(birg);
1547 be_liveness_assure_sets(lv);
1548 be_liveness_assure_chk(lv);
1550 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
1552 DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1554 be_clear_links(irg);
1555 irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1556 combine_congruence_classes();
1557 /* we need some dominance pre-order walk to ensure we see all
1558 * definitions/create copies before we encounter their users */
1559 dom_tree_walk_irg(irg, allocate_coalesce_block, NULL, NULL);
1561 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
1564 static void dump(int mask, ir_graph *irg, const char *suffix,
1565 void (*dumper)(ir_graph *, const char *))
1567 if(birg->main_env->options->dump_flags & mask)
1568 be_dump(irg, suffix, dumper);
1572 * Run the spiller on the current graph.
1574 static void spill(void)
1576 /* make sure all nodes show their real register pressure */
1577 BE_TIMER_PUSH(t_ra_constr);
1578 be_pre_spill_prepare_constr(birg, cls);
1579 BE_TIMER_POP(t_ra_constr);
1581 dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1584 BE_TIMER_PUSH(t_ra_spill);
1585 be_do_spill(birg, cls);
1586 BE_TIMER_POP(t_ra_spill);
1588 BE_TIMER_PUSH(t_ra_spill_apply);
1589 check_for_memory_operands(irg);
1590 BE_TIMER_POP(t_ra_spill_apply);
1592 dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1596 * The straight register allocator for a whole procedure.
1598 static void be_straight_alloc(be_irg_t *new_birg)
1600 const arch_env_t *arch_env = new_birg->main_env->arch_env;
1601 int n_cls = arch_env_get_n_reg_class(arch_env);
1604 obstack_init(&obst);
1607 irg = be_get_birg_irg(birg);
1608 execfreqs = birg->exec_freq;
1610 /* TODO: extract some of the stuff from bechordal allocator, like
1611 * statistics, time measurements, etc. and use them here too */
1613 for (c = 0; c < n_cls; ++c) {
1614 cls = arch_env_get_reg_class(arch_env, c);
1615 default_cls_req = NULL;
1616 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1619 stat_ev_ctx_push_str("regcls", cls->name);
1621 n_regs = arch_register_class_n_regs(cls);
1622 normal_regs = rbitset_malloc(n_regs);
1623 be_abi_set_non_ignore_regs(birg->abi, cls, normal_regs);
1627 /* verify schedule and register pressure */
1628 BE_TIMER_PUSH(t_verify);
1629 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1630 be_verify_schedule(birg);
1631 be_verify_register_pressure(birg, cls, irg);
1632 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1633 assert(be_verify_schedule(birg) && "Schedule verification failed");
1634 assert(be_verify_register_pressure(birg, cls, irg)
1635 && "Register pressure verification failed");
1637 BE_TIMER_POP(t_verify);
1639 BE_TIMER_PUSH(t_ra_color);
1640 be_straight_alloc_cls();
1641 BE_TIMER_POP(t_ra_color);
1643 /* we most probably constructed new Phis so liveness info is invalid
1645 /* TODO: test liveness_introduce */
1646 be_liveness_invalidate(lv);
1649 stat_ev_ctx_pop("regcls");
1652 BE_TIMER_PUSH(t_ra_spill_apply);
1653 be_abi_fix_stack_nodes(birg->abi);
1654 BE_TIMER_POP(t_ra_spill_apply);
1656 BE_TIMER_PUSH(t_verify);
1657 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1658 be_verify_register_allocation(birg);
1659 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1660 assert(be_verify_register_allocation(birg)
1661 && "Register allocation invalid");
1663 BE_TIMER_POP(t_verify);
1665 obstack_free(&obst, NULL);
1669 * Initializes this module.
1671 void be_init_straight_alloc(void)
1673 static be_ra_t be_ra_straight = {
1677 FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
1679 be_register_allocator("straight", &be_ra_straight);
1682 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);