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
58 #include "iredges_t.h"
59 #include "irgraph_t.h"
64 #include "raw_bitset.h"
65 #include "unionfind.h"
67 #include "hungarian.h"
70 #include "bechordal_t.h"
79 #include "bespillutil.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
89 #define MAX_OPTIMISTIC_SPLIT_RECURSION 0
91 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
93 static struct obstack obst;
94 static be_irg_t *birg;
96 static const arch_register_class_t *cls;
97 static const arch_register_req_t *default_cls_req;
99 static const ir_exec_freq *execfreqs;
100 static unsigned n_regs;
101 static unsigned *normal_regs;
102 static int *congruence_classes;
103 static ir_node **block_order;
104 static int n_block_order;
105 static int create_preferences = true;
106 static int create_congruence_classes = true;
107 static int propagate_phi_registers = true;
109 static const lc_opt_table_entry_t options[] = {
110 LC_OPT_ENT_BOOL("prefs", "use preference based coloring", &create_preferences),
111 LC_OPT_ENT_BOOL("congruences", "create congruence classes", &create_congruence_classes),
112 LC_OPT_ENT_BOOL("prop_phi", "propagate phi registers", &propagate_phi_registers),
116 /** currently active assignments (while processing a basic block)
117 * maps registers to values(their current copies) */
118 static ir_node **assignments;
121 * allocation information: last_uses, register preferences
122 * the information is per firm-node.
124 struct allocation_info_t {
125 unsigned last_uses; /**< bitset indicating last uses (input pos) */
126 ir_node *current_value; /**< copy of the value that should be used */
127 ir_node *original_value; /**< for copies point to original value */
128 float prefs[0]; /**< register preferences */
130 typedef struct allocation_info_t allocation_info_t;
132 /** helper datastructure used when sorting register preferences */
137 typedef struct reg_pref_t reg_pref_t;
139 /** per basic-block information */
140 struct block_info_t {
141 bool processed; /**< indicate wether block is processed */
142 ir_node *assignments[0]; /**< register assignments at end of block */
144 typedef struct block_info_t block_info_t;
147 * Get the allocation info for a node.
148 * The info is allocated on the first visit of a node.
150 static allocation_info_t *get_allocation_info(ir_node *node)
152 allocation_info_t *info = get_irn_link(node);
154 info = OALLOCFZ(&obst, allocation_info_t, prefs, n_regs);
155 info->current_value = node;
156 info->original_value = node;
157 set_irn_link(node, info);
163 static allocation_info_t *try_get_allocation_info(const ir_node *node)
165 return (allocation_info_t*) get_irn_link(node);
169 * Get allocation information for a basic block
171 static block_info_t *get_block_info(ir_node *block)
173 block_info_t *info = get_irn_link(block);
175 assert(is_Block(block));
177 info = OALLOCFZ(&obst, block_info_t, assignments, n_regs);
178 set_irn_link(block, info);
185 * Get default register requirement for the current register class
187 static const arch_register_req_t *get_default_req_current_cls(void)
189 if (default_cls_req == NULL) {
190 struct obstack *obst = get_irg_obstack(irg);
191 arch_register_req_t *req = OALLOCZ(obst, arch_register_req_t);
193 req->type = arch_register_req_type_normal;
196 default_cls_req = req;
198 return default_cls_req;
202 * Link the allocation info of a node to a copy.
203 * Afterwards, both nodes uses the same allocation info.
204 * Copy must not have an allocation info assigned yet.
206 * @param copy the node that gets the allocation info assigned
207 * @param value the original node
209 static void mark_as_copy_of(ir_node *copy, ir_node *value)
212 allocation_info_t *info = get_allocation_info(value);
213 allocation_info_t *copy_info = get_allocation_info(copy);
215 /* find original value */
216 original = info->original_value;
217 if (original != value) {
218 info = get_allocation_info(original);
221 assert(info->original_value == original);
222 info->current_value = copy;
224 /* the copy should not be linked to something else yet */
225 assert(copy_info->original_value == copy);
226 copy_info->original_value = original;
228 /* copy over allocation preferences */
229 memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
233 * Calculate the penalties for every register on a node and its live neighbors.
235 * @param live_nodes the set of live nodes at the current position, may be NULL
236 * @param penalty the penalty to subtract from
237 * @param limited a raw bitset containing the limited set for the node
238 * @param node the node
240 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
241 float penalty, const unsigned* limited,
244 ir_nodeset_iterator_t iter;
247 allocation_info_t *info = get_allocation_info(node);
250 /* give penalty for all forbidden regs */
251 for (r = 0; r < n_regs; ++r) {
252 if (rbitset_is_set(limited, r))
255 info->prefs[r] -= penalty;
258 /* all other live values should get a penalty for allowed regs */
259 if (live_nodes == NULL)
262 penalty *= NEIGHBOR_FACTOR;
263 n_allowed = rbitset_popcnt(limited, n_regs);
265 /* only create a very weak penalty if multiple regs are allowed */
266 penalty = (penalty * 0.8f) / n_allowed;
268 foreach_ir_nodeset(live_nodes, neighbor, iter) {
269 allocation_info_t *neighbor_info;
271 /* TODO: if op is used on multiple inputs we might not do a
273 if (neighbor == node)
276 neighbor_info = get_allocation_info(neighbor);
277 for (r = 0; r < n_regs; ++r) {
278 if (!rbitset_is_set(limited, r))
281 neighbor_info->prefs[r] -= penalty;
287 * Calculate the preferences of a definition for the current register class.
288 * If the definition uses a limited set of registers, reduce the preferences
289 * for the limited register on the node and its neighbors.
291 * @param live_nodes the set of live nodes at the current node
292 * @param weight the weight
293 * @param node the current node
295 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
298 const arch_register_req_t *req;
300 if (get_irn_mode(node) == mode_T) {
301 const ir_edge_t *edge;
302 foreach_out_edge(node, edge) {
303 ir_node *proj = get_edge_src_irn(edge);
304 check_defs(live_nodes, weight, proj);
309 if (!arch_irn_consider_in_reg_alloc(cls, node))
312 req = arch_get_register_req_out(node);
313 if (req->type & arch_register_req_type_limited) {
314 const unsigned *limited = req->limited;
315 float penalty = weight * DEF_FACTOR;
316 give_penalties_for_limits(live_nodes, penalty, limited, node);
319 if (req->type & arch_register_req_type_should_be_same) {
320 ir_node *insn = skip_Proj(node);
321 allocation_info_t *info = get_allocation_info(node);
322 int arity = get_irn_arity(insn);
325 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
326 for (i = 0; i < arity; ++i) {
329 allocation_info_t *op_info;
331 if (!rbitset_is_set(&req->other_same, i))
334 op = get_irn_n(insn, i);
336 /* if we the value at the should_be_same input doesn't die at the
337 * node, then it is no use to propagate the constraints (since a
338 * copy will emerge anyway) */
339 if (ir_nodeset_contains(live_nodes, op))
342 op_info = get_allocation_info(op);
343 for (r = 0; r < n_regs; ++r) {
344 op_info->prefs[r] += info->prefs[r] * factor;
351 * Walker: Runs an a block calculates the preferences for any
352 * node and every register from the considered register class.
354 static void analyze_block(ir_node *block, void *data)
356 float weight = get_block_execfreq(execfreqs, block);
357 ir_nodeset_t live_nodes;
361 ir_nodeset_init(&live_nodes);
362 be_liveness_end_of_block(lv, cls, block, &live_nodes);
364 sched_foreach_reverse(block, node) {
365 allocation_info_t *info;
372 if (create_preferences)
373 check_defs(&live_nodes, weight, node);
376 arity = get_irn_arity(node);
378 /* the allocation info node currently only uses 1 unsigned value
379 to mark last used inputs. So we will fail for a node with more than
381 if (arity >= (int) sizeof(unsigned) * 8) {
382 panic("Node with more than %d inputs not supported yet",
383 (int) sizeof(unsigned) * 8);
386 info = get_allocation_info(node);
387 for (i = 0; i < arity; ++i) {
388 ir_node *op = get_irn_n(node, i);
389 if (!arch_irn_consider_in_reg_alloc(cls, op))
392 /* last usage of a value? */
393 if (!ir_nodeset_contains(&live_nodes, op)) {
394 rbitset_set(&info->last_uses, i);
398 be_liveness_transfer(cls, node, &live_nodes);
400 if (create_preferences) {
401 /* update weights based on usage constraints */
402 for (i = 0; i < arity; ++i) {
403 const arch_register_req_t *req;
404 const unsigned *limited;
405 ir_node *op = get_irn_n(node, i);
407 if (!arch_irn_consider_in_reg_alloc(cls, op))
410 req = arch_get_register_req(node, i);
411 if (!(req->type & arch_register_req_type_limited))
414 limited = req->limited;
415 give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
421 ir_nodeset_destroy(&live_nodes);
424 static void congruence_def(ir_nodeset_t *live_nodes, ir_node *node)
426 const arch_register_req_t *req;
428 if (get_irn_mode(node) == mode_T) {
429 const ir_edge_t *edge;
430 foreach_out_edge(node, edge) {
431 ir_node *def = get_edge_src_irn(edge);
432 congruence_def(live_nodes, def);
437 if (!arch_irn_consider_in_reg_alloc(cls, node))
440 /* should be same constraint? */
441 req = arch_get_register_req_out(node);
442 if (req->type & arch_register_req_type_should_be_same) {
443 ir_node *insn = skip_Proj(node);
444 int arity = get_irn_arity(insn);
446 unsigned node_idx = get_irn_idx(node);
447 node_idx = uf_find(congruence_classes, node_idx);
449 for (i = 0; i < arity; ++i) {
453 ir_nodeset_iterator_t iter;
454 bool interferes = false;
456 if (!rbitset_is_set(&req->other_same, i))
459 op = get_irn_n(insn, i);
460 op_idx = get_irn_idx(op);
461 op_idx = uf_find(congruence_classes, op_idx);
463 /* do we interfere with the value */
464 foreach_ir_nodeset(live_nodes, live, iter) {
465 int lv_idx = get_irn_idx(live);
466 lv_idx = uf_find(congruence_classes, lv_idx);
467 if (lv_idx == op_idx) {
472 /* don't put in same affinity class if we interfere */
476 node_idx = uf_union(congruence_classes, node_idx, op_idx);
477 DB((dbg, LEVEL_3, "Merge %+F and %+F congruence classes\n",
479 /* one should_be_same is enough... */
485 static void create_congurence_class(ir_node *block, void *data)
487 ir_nodeset_t live_nodes;
491 ir_nodeset_init(&live_nodes);
492 be_liveness_end_of_block(lv, cls, block, &live_nodes);
494 /* check should be same constraints */
495 sched_foreach_reverse(block, node) {
499 congruence_def(&live_nodes, node);
500 be_liveness_transfer(cls, node, &live_nodes);
503 /* check phi congruence classes */
504 sched_foreach_reverse_from(node, node) {
508 assert(is_Phi(node));
510 if (!arch_irn_consider_in_reg_alloc(cls, node))
513 node_idx = get_irn_idx(node);
514 node_idx = uf_find(congruence_classes, node_idx);
516 arity = get_irn_arity(node);
517 for (i = 0; i < arity; ++i) {
518 bool interferes = false;
519 ir_nodeset_iterator_t iter;
522 ir_node *op = get_Phi_pred(node, i);
523 int op_idx = get_irn_idx(op);
524 op_idx = uf_find(congruence_classes, op_idx);
526 /* do we interfere with the value */
527 foreach_ir_nodeset(&live_nodes, live, iter) {
528 int lv_idx = get_irn_idx(live);
529 lv_idx = uf_find(congruence_classes, lv_idx);
530 if (lv_idx == op_idx) {
535 /* don't put in same affinity class if we interfere */
538 /* any other phi has the same input? */
539 sched_foreach(block, phi) {
544 if (!arch_irn_consider_in_reg_alloc(cls, phi))
546 oop = get_Phi_pred(phi, i);
549 oop_idx = get_irn_idx(oop);
550 oop_idx = uf_find(congruence_classes, oop_idx);
551 if (oop_idx == op_idx) {
559 node_idx = uf_union(congruence_classes, node_idx, op_idx);
560 DB((dbg, LEVEL_3, "Merge %+F and %+F congruence classes\n",
566 static void merge_congruence_prefs(ir_node *node, void *data)
568 allocation_info_t *info;
569 allocation_info_t *head_info;
570 unsigned node_idx = get_irn_idx(node);
571 unsigned node_set = uf_find(congruence_classes, node_idx);
576 /* head of congruence class or not in any class */
577 if (node_set == node_idx)
580 if (!arch_irn_consider_in_reg_alloc(cls, node))
583 head_info = get_allocation_info(get_idx_irn(irg, node_set));
584 info = get_allocation_info(node);
586 for (r = 0; r < n_regs; ++r) {
587 head_info->prefs[r] += info->prefs[r];
591 static void set_congruence_prefs(ir_node *node, void *data)
593 allocation_info_t *info;
594 allocation_info_t *head_info;
595 unsigned node_idx = get_irn_idx(node);
596 unsigned node_set = uf_find(congruence_classes, node_idx);
600 /* head of congruence class or not in any class */
601 if (node_set == node_idx)
604 if (!arch_irn_consider_in_reg_alloc(cls, node))
607 head_info = get_allocation_info(get_idx_irn(irg, node_set));
608 info = get_allocation_info(node);
610 memcpy(info->prefs, head_info->prefs, n_regs * sizeof(info->prefs[0]));
613 static void combine_congruence_classes(void)
615 size_t n = get_irg_last_idx(irg);
616 congruence_classes = XMALLOCN(int, n);
617 uf_init(congruence_classes, n);
619 /* create congruence classes */
620 irg_block_walk_graph(irg, create_congurence_class, NULL, NULL);
621 /* merge preferences */
622 irg_walk_graph(irg, merge_congruence_prefs, NULL, NULL);
623 irg_walk_graph(irg, set_congruence_prefs, NULL, NULL);
624 free(congruence_classes);
632 * Assign register reg to the given node.
634 * @param node the node
635 * @param reg the register
637 static void use_reg(ir_node *node, const arch_register_t *reg)
639 unsigned r = arch_register_get_index(reg);
640 assignments[r] = node;
641 arch_set_irn_register(node, reg);
644 static void free_reg_of_value(ir_node *node)
646 const arch_register_t *reg;
649 if (!arch_irn_consider_in_reg_alloc(cls, node))
652 reg = arch_get_irn_register(node);
653 r = arch_register_get_index(reg);
654 /* assignment->value may be NULL if a value is used at 2 inputs
655 so it gets freed twice. */
656 assert(assignments[r] == node || assignments[r] == NULL);
657 assignments[r] = NULL;
661 * Compare two register preferences in decreasing order.
663 static int compare_reg_pref(const void *e1, const void *e2)
665 const reg_pref_t *rp1 = (const reg_pref_t*) e1;
666 const reg_pref_t *rp2 = (const reg_pref_t*) e2;
667 if (rp1->pref < rp2->pref)
669 if (rp1->pref > rp2->pref)
674 static void fill_sort_candidates(reg_pref_t *regprefs,
675 const allocation_info_t *info)
679 for (r = 0; r < n_regs; ++r) {
680 float pref = info->prefs[r];
682 regprefs[r].pref = pref;
684 /* TODO: use a stable sort here to avoid unnecessary register jumping */
685 qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
688 static bool try_optimistic_split(ir_node *to_split, ir_node *before,
689 float pref, float pref_delta,
690 unsigned *forbidden_regs, int recursion)
692 const arch_register_t *from_reg;
693 const arch_register_t *reg;
694 ir_node *original_insn;
700 allocation_info_t *info = get_allocation_info(to_split);
703 float split_threshold;
707 /* stupid hack: don't optimisticallt split don't spill nodes...
708 * (so we don't split away the values produced because of
709 * must_be_different constraints) */
710 original_insn = skip_Proj(info->original_value);
711 if (arch_irn_get_flags(original_insn) & arch_irn_flags_dont_spill)
714 from_reg = arch_get_irn_register(to_split);
715 from_r = arch_register_get_index(from_reg);
716 block = get_nodes_block(before);
717 split_threshold = get_block_execfreq(execfreqs, block) * SPLIT_DELTA;
719 if (pref_delta < split_threshold*0.5)
722 /* find the best free position where we could move to */
723 prefs = ALLOCAN(reg_pref_t, n_regs);
724 fill_sort_candidates(prefs, info);
725 for (i = 0; i < n_regs; ++i) {
729 bool old_source_state;
731 /* we need a normal register which is not an output register
732 an different from the current register of to_split */
734 if (!rbitset_is_set(normal_regs, r))
736 if (rbitset_is_set(forbidden_regs, r))
741 /* is the split worth it? */
742 delta = pref_delta + prefs[i].pref;
743 if (delta < split_threshold) {
744 DB((dbg, LEVEL_3, "Not doing optimistical split of %+F (depth %d), win %f too low\n",
745 to_split, recursion, delta));
749 /* if the register is free then we can do the split */
750 if (assignments[r] == NULL)
753 /* otherwise we might try recursively calling optimistic_split */
754 if (recursion+1 > MAX_OPTIMISTIC_SPLIT_RECURSION)
757 apref = prefs[i].pref;
758 apref_delta = i+1 < n_regs ? apref - prefs[i+1].pref : 0;
759 apref_delta += pref_delta - split_threshold;
761 /* our source register isn't a usefull destination for recursive
763 old_source_state = rbitset_is_set(forbidden_regs, from_r);
764 rbitset_set(forbidden_regs, from_r);
765 /* try recursive split */
766 res = try_optimistic_split(assignments[r], before, apref,
767 apref_delta, forbidden_regs, recursion+1);
768 /* restore our destination */
769 if (old_source_state) {
770 rbitset_set(forbidden_regs, from_r);
772 rbitset_clear(forbidden_regs, from_r);
781 reg = arch_register_for_index(cls, r);
782 copy = be_new_Copy(cls, block, to_split);
783 mark_as_copy_of(copy, to_split);
784 /* hacky, but correct here */
785 if (assignments[arch_register_get_index(from_reg)] == to_split)
786 free_reg_of_value(to_split);
788 sched_add_before(before, copy);
791 "Optimistic live-range split %+F move %+F(%s) -> %s before %+F (win %f, depth %d)\n",
792 copy, to_split, from_reg->name, reg->name, before, delta, recursion));
797 * Determine and assign a register for node @p node
799 static void assign_reg(const ir_node *block, ir_node *node,
800 unsigned *forbidden_regs)
802 const arch_register_t *reg;
803 allocation_info_t *info;
804 const arch_register_req_t *req;
805 reg_pref_t *reg_prefs;
808 const unsigned *allowed_regs;
811 assert(!is_Phi(node));
812 assert(arch_irn_consider_in_reg_alloc(cls, node));
814 /* preassigned register? */
815 reg = arch_get_irn_register(node);
817 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
822 /* give should_be_same boni */
823 info = get_allocation_info(node);
824 req = arch_get_register_req_out(node);
826 in_node = skip_Proj(node);
827 if (req->type & arch_register_req_type_should_be_same) {
828 float weight = get_block_execfreq(execfreqs, block);
829 int arity = get_irn_arity(in_node);
832 assert(arity <= (int) sizeof(req->other_same) * 8);
833 for (i = 0; i < arity; ++i) {
835 const arch_register_t *reg;
837 if (!rbitset_is_set(&req->other_same, i))
840 in = get_irn_n(in_node, i);
841 reg = arch_get_irn_register(in);
843 r = arch_register_get_index(reg);
845 /* if the value didn't die here then we should not propagate the
846 * should_be_same info */
847 if (assignments[r] == in)
850 info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
854 /* create list of register candidates and sort by their preference */
855 DB((dbg, LEVEL_2, "Candidates for %+F:", node));
856 reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
857 fill_sort_candidates(reg_prefs, info);
858 for (i = 0; i < n_regs; ++i) {
859 unsigned num = reg_prefs[i].num;
860 const arch_register_t *reg;
862 if (!rbitset_is_set(normal_regs, num))
865 reg = arch_register_for_index(cls, num);
866 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
868 DB((dbg, LEVEL_2, "\n"));
870 allowed_regs = normal_regs;
871 if (req->type & arch_register_req_type_limited) {
872 allowed_regs = req->limited;
875 for (i = 0; i < n_regs; ++i) {
880 r = reg_prefs[i].num;
881 if (!rbitset_is_set(allowed_regs, r))
883 if (assignments[r] == NULL)
885 pref = reg_prefs[i].pref;
886 delta = i+1 < n_regs ? pref - reg_prefs[i+1].pref : 0;
887 before = skip_Proj(node);
888 res = try_optimistic_split(assignments[r], before,
889 pref, delta, forbidden_regs, 0);
894 panic("No register left for %+F\n", node);
897 reg = arch_register_for_index(cls, r);
898 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
903 * Add an permutation in front of a node and change the assignments
904 * due to this permutation.
906 * To understand this imagine a permutation like this:
916 * First we count how many destinations a single value has. At the same time
917 * we can be sure that each destination register has at most 1 source register
918 * (it can have 0 which means we don't care what value is in it).
919 * We ignore all fullfilled permuations (like 7->7)
920 * In a first pass we create as much copy instructions as possible as they
921 * are generally cheaper than exchanges. We do this by counting into how many
922 * destinations a register has to be copied (in the example it's 2 for register
923 * 3, or 1 for the registers 1,2,4 and 7).
924 * We can then create a copy into every destination register when the usecount
925 * of that register is 0 (= noone else needs the value in the register).
927 * After this step we should have cycles left. We implement a cyclic permutation
928 * of n registers with n-1 transpositions.
930 * @param live_nodes the set of live nodes, updated due to live range split
931 * @param before the node before we add the permutation
932 * @param permutation the permutation array indices are the destination
933 * registers, the values in the array are the source
936 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
937 unsigned *permutation)
939 unsigned *n_used = ALLOCANZ(unsigned, n_regs);
943 /* determine how often each source register needs to be read */
944 for (r = 0; r < n_regs; ++r) {
945 unsigned old_reg = permutation[r];
948 value = assignments[old_reg];
950 /* nothing to do here, reg is not live. Mark it as fixpoint
951 * so we ignore it in the next steps */
959 block = get_nodes_block(before);
961 /* step1: create copies where immediately possible */
962 for (r = 0; r < n_regs; /* empty */) {
965 const arch_register_t *reg;
966 unsigned old_r = permutation[r];
968 /* - no need to do anything for fixed points.
969 - we can't copy if the value in the dest reg is still needed */
970 if (old_r == r || n_used[r] > 0) {
976 src = assignments[old_r];
977 copy = be_new_Copy(cls, block, src);
978 sched_add_before(before, copy);
979 reg = arch_register_for_index(cls, r);
980 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
981 copy, src, before, reg->name));
982 mark_as_copy_of(copy, src);
985 if (live_nodes != NULL) {
986 ir_nodeset_insert(live_nodes, copy);
989 /* old register has 1 user less, permutation is resolved */
990 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
993 assert(n_used[old_r] > 0);
995 if (n_used[old_r] == 0) {
996 if (live_nodes != NULL) {
997 ir_nodeset_remove(live_nodes, src);
999 free_reg_of_value(src);
1002 /* advance or jump back (if this copy enabled another copy) */
1003 if (old_r < r && n_used[old_r] == 0) {
1010 /* at this point we only have "cycles" left which we have to resolve with
1012 * TODO: if we have free registers left, then we should really use copy
1013 * instructions for any cycle longer than 2 registers...
1014 * (this is probably architecture dependent, there might be archs where
1015 * copies are preferable even for 2-cycles) */
1017 /* create perms with the rest */
1018 for (r = 0; r < n_regs; /* empty */) {
1019 const arch_register_t *reg;
1020 unsigned old_r = permutation[r];
1032 /* we shouldn't have copies from 1 value to multiple destinations left*/
1033 assert(n_used[old_r] == 1);
1035 /* exchange old_r and r2; after that old_r is a fixed point */
1036 r2 = permutation[old_r];
1038 in[0] = assignments[r2];
1039 in[1] = assignments[old_r];
1040 perm = be_new_Perm(cls, block, 2, in);
1041 sched_add_before(before, perm);
1042 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
1043 perm, in[0], in[1], before));
1045 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
1046 mark_as_copy_of(proj0, in[0]);
1047 reg = arch_register_for_index(cls, old_r);
1048 use_reg(proj0, reg);
1050 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
1051 mark_as_copy_of(proj1, in[1]);
1052 reg = arch_register_for_index(cls, r2);
1053 use_reg(proj1, reg);
1055 /* 1 value is now in the correct register */
1056 permutation[old_r] = old_r;
1057 /* the source of r changed to r2 */
1058 permutation[r] = r2;
1060 /* if we have reached a fixpoint update data structures */
1061 if (live_nodes != NULL) {
1062 ir_nodeset_remove(live_nodes, in[0]);
1063 ir_nodeset_remove(live_nodes, in[1]);
1064 ir_nodeset_remove(live_nodes, proj0);
1065 ir_nodeset_insert(live_nodes, proj1);
1069 #ifdef DEBUG_libfirm
1070 /* now we should only have fixpoints left */
1071 for (r = 0; r < n_regs; ++r) {
1072 assert(permutation[r] == r);
1078 * Free regs for values last used.
1080 * @param live_nodes set of live nodes, will be updated
1081 * @param node the node to consider
1083 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
1085 allocation_info_t *info = get_allocation_info(node);
1086 const unsigned *last_uses = &info->last_uses;
1087 int arity = get_irn_arity(node);
1090 for (i = 0; i < arity; ++i) {
1093 /* check if one operand is the last use */
1094 if (!rbitset_is_set(last_uses, i))
1097 op = get_irn_n(node, i);
1098 free_reg_of_value(op);
1099 ir_nodeset_remove(live_nodes, op);
1104 * change inputs of a node to the current value (copies/perms)
1106 static void rewire_inputs(ir_node *node)
1109 int arity = get_irn_arity(node);
1111 for (i = 0; i < arity; ++i) {
1112 ir_node *op = get_irn_n(node, i);
1113 allocation_info_t *info = try_get_allocation_info(op);
1118 info = get_allocation_info(info->original_value);
1119 if (info->current_value != op) {
1120 set_irn_n(node, i, info->current_value);
1126 * Create a bitset of registers occupied with value living through an
1129 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
1131 const allocation_info_t *info = get_allocation_info(node);
1136 /* mark all used registers as potentially live-through */
1137 for (r = 0; r < n_regs; ++r) {
1138 if (assignments[r] == NULL)
1140 if (!rbitset_is_set(normal_regs, r))
1143 rbitset_set(bitset, r);
1146 /* remove registers of value dying at the instruction */
1147 arity = get_irn_arity(node);
1148 for (i = 0; i < arity; ++i) {
1150 const arch_register_t *reg;
1152 if (!rbitset_is_set(&info->last_uses, i))
1155 op = get_irn_n(node, i);
1156 reg = arch_get_irn_register(op);
1157 rbitset_clear(bitset, arch_register_get_index(reg));
1162 * Enforce constraints at a node by live range splits.
1164 * @param live_nodes the set of live nodes, might be changed
1165 * @param node the current node
1167 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node,
1168 unsigned *forbidden_regs)
1170 int arity = get_irn_arity(node);
1172 hungarian_problem_t *bp;
1174 unsigned *assignment;
1176 /* construct a list of register occupied by live-through values */
1177 unsigned *live_through_regs = NULL;
1179 /* see if any use constraints are not met */
1181 for (i = 0; i < arity; ++i) {
1182 ir_node *op = get_irn_n(node, i);
1183 const arch_register_t *reg;
1184 const arch_register_req_t *req;
1185 const unsigned *limited;
1188 if (!arch_irn_consider_in_reg_alloc(cls, op))
1191 /* are there any limitations for the i'th operand? */
1192 req = arch_get_register_req(node, i);
1193 if (!(req->type & arch_register_req_type_limited))
1196 limited = req->limited;
1197 reg = arch_get_irn_register(op);
1198 r = arch_register_get_index(reg);
1199 if (!rbitset_is_set(limited, r)) {
1200 /* found an assignment outside the limited set */
1206 /* is any of the live-throughs using a constrained output register? */
1207 if (get_irn_mode(node) == mode_T) {
1208 const ir_edge_t *edge;
1210 foreach_out_edge(node, edge) {
1211 ir_node *proj = get_edge_src_irn(edge);
1212 const arch_register_req_t *req;
1214 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1217 req = arch_get_register_req_out(proj);
1218 if (!(req->type & arch_register_req_type_limited))
1221 if (live_through_regs == NULL) {
1222 rbitset_alloca(live_through_regs, n_regs);
1223 determine_live_through_regs(live_through_regs, node);
1226 rbitset_or(forbidden_regs, req->limited, n_regs);
1227 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
1232 if (arch_irn_consider_in_reg_alloc(cls, node)) {
1233 const arch_register_req_t *req = arch_get_register_req_out(node);
1234 if (req->type & arch_register_req_type_limited) {
1235 rbitset_alloca(live_through_regs, n_regs);
1236 determine_live_through_regs(live_through_regs, node);
1237 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
1239 rbitset_or(forbidden_regs, req->limited, n_regs);
1248 /* create these arrays if we haven't yet */
1249 if (live_through_regs == NULL) {
1250 rbitset_alloca(live_through_regs, n_regs);
1253 /* at this point we have to construct a bipartite matching problem to see
1254 * which values should go to which registers
1255 * Note: We're building the matrix in "reverse" - source registers are
1256 * right, destinations left because this will produce the solution
1257 * in the format required for permute_values.
1259 bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
1261 /* add all combinations, then remove not allowed ones */
1262 for (l = 0; l < n_regs; ++l) {
1263 if (!rbitset_is_set(normal_regs, l)) {
1264 hungarian_add(bp, l, l, 1);
1268 for (r = 0; r < n_regs; ++r) {
1269 if (!rbitset_is_set(normal_regs, r))
1271 /* livethrough values may not use constrainted output registers */
1272 if (rbitset_is_set(live_through_regs, l)
1273 && rbitset_is_set(forbidden_regs, r))
1276 hungarian_add(bp, r, l, l == r ? 9 : 8);
1280 for (i = 0; i < arity; ++i) {
1281 ir_node *op = get_irn_n(node, i);
1282 const arch_register_t *reg;
1283 const arch_register_req_t *req;
1284 const unsigned *limited;
1285 unsigned current_reg;
1287 if (!arch_irn_consider_in_reg_alloc(cls, op))
1290 req = arch_get_register_req(node, i);
1291 if (!(req->type & arch_register_req_type_limited))
1294 limited = req->limited;
1295 reg = arch_get_irn_register(op);
1296 current_reg = arch_register_get_index(reg);
1297 for (r = 0; r < n_regs; ++r) {
1298 if (rbitset_is_set(limited, r))
1300 hungarian_remv(bp, r, current_reg);
1304 //hungarian_print_cost_matrix(bp, 1);
1305 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1307 assignment = ALLOCAN(unsigned, n_regs);
1308 res = hungarian_solve(bp, (int*) assignment, NULL, 0);
1312 fprintf(stderr, "Swap result:");
1313 for (i = 0; i < (int) n_regs; ++i) {
1314 fprintf(stderr, " %d", assignment[i]);
1316 fprintf(stderr, "\n");
1321 permute_values(live_nodes, node, assignment);
1324 /** test wether a node @p n is a copy of the value of node @p of */
1325 static bool is_copy_of(ir_node *value, ir_node *test_value)
1327 allocation_info_t *test_info;
1328 allocation_info_t *info;
1330 if (value == test_value)
1333 info = get_allocation_info(value);
1334 test_info = get_allocation_info(test_value);
1335 return test_info->original_value == info->original_value;
1339 * find a value in the end-assignment of a basic block
1340 * @returns the index into the assignment array if found
1343 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1346 ir_node **assignments = info->assignments;
1347 for (r = 0; r < n_regs; ++r) {
1348 ir_node *a_value = assignments[r];
1350 if (a_value == NULL)
1352 if (is_copy_of(a_value, value))
1360 * Create the necessary permutations at the end of a basic block to fullfill
1361 * the register assignment for phi-nodes in the next block
1363 static void add_phi_permutations(ir_node *block, int p)
1366 unsigned *permutation;
1367 ir_node **old_assignments;
1368 bool need_permutation;
1370 ir_node *pred = get_Block_cfgpred_block(block, p);
1372 block_info_t *pred_info = get_block_info(pred);
1374 /* predecessor not processed yet? nothing to do */
1375 if (!pred_info->processed)
1378 permutation = ALLOCAN(unsigned, n_regs);
1379 for (r = 0; r < n_regs; ++r) {
1383 /* check phi nodes */
1384 need_permutation = false;
1385 node = sched_first(block);
1386 for ( ; is_Phi(node); node = sched_next(node)) {
1387 const arch_register_t *reg;
1392 if (!arch_irn_consider_in_reg_alloc(cls, node))
1395 op = get_Phi_pred(node, p);
1396 if (!arch_irn_consider_in_reg_alloc(cls, op))
1399 a = find_value_in_block_info(pred_info, op);
1402 reg = arch_get_irn_register(node);
1403 regn = arch_register_get_index(reg);
1405 permutation[regn] = a;
1406 need_permutation = true;
1410 if (need_permutation) {
1411 /* permute values at end of predecessor */
1412 old_assignments = assignments;
1413 assignments = pred_info->assignments;
1414 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1416 assignments = old_assignments;
1419 /* change phi nodes to use the copied values */
1420 node = sched_first(block);
1421 for ( ; is_Phi(node); node = sched_next(node)) {
1425 if (!arch_irn_consider_in_reg_alloc(cls, node))
1428 op = get_Phi_pred(node, p);
1429 /* no need to do anything for Unknown inputs */
1430 if (!arch_irn_consider_in_reg_alloc(cls, op))
1433 /* we have permuted all values into the correct registers so we can
1434 simply query which value occupies the phis register in the
1436 a = arch_register_get_index(arch_get_irn_register(node));
1437 op = pred_info->assignments[a];
1438 set_Phi_pred(node, p, op);
1443 * Set preferences for a phis register based on the registers used on the
1446 static void adapt_phi_prefs(ir_node *phi)
1449 int arity = get_irn_arity(phi);
1450 ir_node *block = get_nodes_block(phi);
1451 allocation_info_t *info = get_allocation_info(phi);
1453 for (i = 0; i < arity; ++i) {
1454 ir_node *op = get_irn_n(phi, i);
1455 const arch_register_t *reg = arch_get_irn_register(op);
1456 ir_node *pred_block;
1457 block_info_t *pred_block_info;
1463 /* we only give the bonus if the predecessor already has registers
1464 * assigned, otherwise we only see a dummy value
1465 * and any conclusions about its register are useless */
1466 pred_block = get_Block_cfgpred_block(block, i);
1467 pred_block_info = get_block_info(pred_block);
1468 if (!pred_block_info->processed)
1471 /* give bonus for already assigned register */
1472 weight = get_block_execfreq(execfreqs, pred_block);
1473 r = arch_register_get_index(reg);
1474 info->prefs[r] += weight * AFF_PHI;
1479 * After a phi has been assigned a register propagate preference inputs
1480 * to the phi inputs.
1482 static void propagate_phi_register(ir_node *phi, unsigned assigned_r)
1485 ir_node *block = get_nodes_block(phi);
1486 int arity = get_irn_arity(phi);
1488 for (i = 0; i < arity; ++i) {
1489 ir_node *op = get_Phi_pred(phi, i);
1490 allocation_info_t *info = get_allocation_info(op);
1491 ir_node *pred_block = get_Block_cfgpred_block(block, i);
1494 = get_block_execfreq(execfreqs, pred_block) * AFF_PHI;
1496 if (info->prefs[assigned_r] >= weight)
1499 /* promote the prefered register */
1500 for (r = 0; r < n_regs; ++r) {
1501 if (info->prefs[r] > -weight) {
1502 info->prefs[r] = -weight;
1505 info->prefs[assigned_r] = weight;
1508 propagate_phi_register(op, assigned_r);
1512 static void assign_phi_registers(ir_node *block)
1519 hungarian_problem_t *bp;
1521 /* count phi nodes */
1522 sched_foreach(block, node) {
1525 if (!arch_irn_consider_in_reg_alloc(cls, node))
1533 /* build a bipartite matching problem for all phi nodes */
1534 bp = hungarian_new(n_phis, n_regs, HUNGARIAN_MATCH_PERFECT);
1536 sched_foreach(block, node) {
1539 allocation_info_t *info;
1542 if (!arch_irn_consider_in_reg_alloc(cls, node))
1545 /* give boni for predecessor colorings */
1546 adapt_phi_prefs(node);
1547 /* add stuff to bipartite problem */
1548 info = get_allocation_info(node);
1549 DB((dbg, LEVEL_3, "Prefs for %+F: ", node));
1550 for (r = 0; r < n_regs; ++r) {
1553 if (!rbitset_is_set(normal_regs, r))
1556 costs = info->prefs[r];
1557 costs = costs < 0 ? -logf(-costs+1) : logf(costs+1);
1560 hungarian_add(bp, n, r, costs);
1561 DB((dbg, LEVEL_3, " %s(%f)", arch_register_for_index(cls, r)->name,
1564 DB((dbg, LEVEL_3, "\n"));
1568 //hungarian_print_cost_matrix(bp, 7);
1569 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1571 assignment = ALLOCAN(int, n_regs);
1572 res = hungarian_solve(bp, assignment, NULL, 0);
1577 sched_foreach(block, node) {
1579 const arch_register_t *reg;
1583 if (!arch_irn_consider_in_reg_alloc(cls, node))
1586 r = assignment[n++];
1587 assert(rbitset_is_set(normal_regs, r));
1588 reg = arch_register_for_index(cls, r);
1589 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
1592 /* adapt preferences for phi inputs */
1593 if (propagate_phi_registers)
1594 propagate_phi_register(node, r);
1599 * Walker: assign registers to all nodes of a block that
1600 * need registers from the currently considered register class.
1602 static void allocate_coalesce_block(ir_node *block, void *data)
1605 ir_nodeset_t live_nodes;
1608 block_info_t *block_info;
1609 block_info_t **pred_block_infos;
1611 unsigned *forbidden_regs; /**< collects registers which must
1612 not be used for optimistic splits */
1615 DB((dbg, LEVEL_2, "* Block %+F\n", block));
1617 /* clear assignments */
1618 block_info = get_block_info(block);
1619 assignments = block_info->assignments;
1621 ir_nodeset_init(&live_nodes);
1623 /* gather regalloc infos of predecessor blocks */
1624 n_preds = get_Block_n_cfgpreds(block);
1625 pred_block_infos = ALLOCAN(block_info_t*, n_preds);
1626 for (i = 0; i < n_preds; ++i) {
1627 ir_node *pred = get_Block_cfgpred_block(block, i);
1628 block_info_t *pred_info = get_block_info(pred);
1629 pred_block_infos[i] = pred_info;
1632 phi_ins = ALLOCAN(ir_node*, n_preds);
1634 /* collect live-in nodes and preassigned values */
1635 be_lv_foreach(lv, block, be_lv_state_in, i) {
1636 const arch_register_t *reg;
1638 bool need_phi = false;
1640 node = be_lv_get_irn(lv, block, i);
1641 if (!arch_irn_consider_in_reg_alloc(cls, node))
1644 /* check all predecessors for this value, if it is not everywhere the
1645 same or unknown then we have to construct a phi
1646 (we collect the potential phi inputs here) */
1647 for (p = 0; p < n_preds; ++p) {
1648 block_info_t *pred_info = pred_block_infos[p];
1650 if (!pred_info->processed) {
1651 /* use node for now, it will get fixed later */
1655 int a = find_value_in_block_info(pred_info, node);
1657 /* must live out of predecessor */
1659 phi_ins[p] = pred_info->assignments[a];
1660 /* different value from last time? then we need a phi */
1661 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1668 ir_mode *mode = get_irn_mode(node);
1669 const arch_register_req_t *req = get_default_req_current_cls();
1672 phi = new_r_Phi(block, n_preds, phi_ins, mode);
1673 be_set_phi_reg_req(phi, req);
1675 DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1676 #ifdef DEBUG_libfirm
1679 for (i = 0; i < n_preds; ++i) {
1680 DB((dbg, LEVEL_3, " %+F", phi_ins[i]));
1682 DB((dbg, LEVEL_3, "\n"));
1685 mark_as_copy_of(phi, node);
1686 sched_add_after(block, phi);
1690 allocation_info_t *info = get_allocation_info(node);
1691 info->current_value = phi_ins[0];
1693 /* Grab 1 of the inputs we constructed (might not be the same as
1694 * "node" as we could see the same copy of the value in all
1699 /* if the node already has a register assigned use it */
1700 reg = arch_get_irn_register(node);
1705 /* remember that this node is live at the beginning of the block */
1706 ir_nodeset_insert(&live_nodes, node);
1709 rbitset_alloca(forbidden_regs, n_regs);
1711 /* handle phis... */
1712 assign_phi_registers(block);
1714 /* all live-ins must have a register */
1715 #ifdef DEBUG_libfirm
1717 ir_nodeset_iterator_t iter;
1718 foreach_ir_nodeset(&live_nodes, node, iter) {
1719 const arch_register_t *reg = arch_get_irn_register(node);
1720 assert(reg != NULL);
1725 /* assign instructions in the block */
1726 sched_foreach(block, node) {
1730 /* phis are already assigned */
1734 rewire_inputs(node);
1736 /* enforce use constraints */
1737 rbitset_clear_all(forbidden_regs, n_regs);
1738 enforce_constraints(&live_nodes, node, forbidden_regs);
1740 rewire_inputs(node);
1742 /* we may not use registers used for inputs for optimistic splits */
1743 arity = get_irn_arity(node);
1744 for (i = 0; i < arity; ++i) {
1745 ir_node *op = get_irn_n(node, i);
1746 const arch_register_t *reg;
1747 if (!arch_irn_consider_in_reg_alloc(cls, op))
1750 reg = arch_get_irn_register(op);
1751 rbitset_set(forbidden_regs, arch_register_get_index(reg));
1754 /* free registers of values last used at this instruction */
1755 free_last_uses(&live_nodes, node);
1757 /* assign output registers */
1758 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1759 if (get_irn_mode(node) == mode_T) {
1760 const ir_edge_t *edge;
1761 foreach_out_edge(node, edge) {
1762 ir_node *proj = get_edge_src_irn(edge);
1763 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1765 assign_reg(block, proj, forbidden_regs);
1767 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1768 assign_reg(block, node, forbidden_regs);
1772 ir_nodeset_destroy(&live_nodes);
1775 block_info->processed = true;
1777 /* permute values at end of predecessor blocks in case of phi-nodes */
1780 for (p = 0; p < n_preds; ++p) {
1781 add_phi_permutations(block, p);
1785 /* if we have exactly 1 successor then we might be able to produce phi
1787 if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1788 const ir_edge_t *edge
1789 = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1790 ir_node *succ = get_edge_src_irn(edge);
1791 int p = get_edge_src_pos(edge);
1792 block_info_t *succ_info = get_block_info(succ);
1794 if (succ_info->processed) {
1795 add_phi_permutations(succ, p);
1800 typedef struct block_costs_t block_costs_t;
1801 struct block_costs_t {
1802 float costs; /**< costs of the block */
1803 int dfs_num; /**< depth first search number (to detect backedges) */
1806 static int cmp_block_costs(const void *d1, const void *d2)
1808 const ir_node * const *block1 = d1;
1809 const ir_node * const *block2 = d2;
1810 const block_costs_t *info1 = get_irn_link(*block1);
1811 const block_costs_t *info2 = get_irn_link(*block2);
1812 return QSORT_CMP(info2->costs, info1->costs);
1815 static void determine_block_order(void)
1818 ir_node **blocklist = be_get_cfgpostorder(irg);
1819 int n_blocks = ARR_LEN(blocklist);
1821 pdeq *worklist = new_pdeq();
1822 ir_node **order = XMALLOCN(ir_node*, n_blocks);
1825 /* clear block links... */
1826 for (i = 0; i < n_blocks; ++i) {
1827 ir_node *block = blocklist[i];
1828 set_irn_link(block, NULL);
1831 /* walk blocks in reverse postorder, the costs for each block are the
1832 * sum of the costs of its predecessors (excluding the costs on backedges
1833 * which we can't determine) */
1834 for (i = n_blocks-1; i >= 0; --i) {
1835 block_costs_t *cost_info;
1836 ir_node *block = blocklist[i];
1838 float execfreq = get_block_execfreq(execfreqs, block);
1839 float costs = execfreq;
1840 int n_cfgpreds = get_Block_n_cfgpreds(block);
1842 for (p = 0; p < n_cfgpreds; ++p) {
1843 ir_node *pred_block = get_Block_cfgpred_block(block, p);
1844 block_costs_t *pred_costs = get_irn_link(pred_block);
1845 /* we don't have any info for backedges */
1846 if (pred_costs == NULL)
1848 costs += pred_costs->costs;
1851 cost_info = OALLOCZ(&obst, block_costs_t);
1852 cost_info->costs = costs;
1853 cost_info->dfs_num = dfs_num++;
1854 set_irn_link(block, cost_info);
1857 /* sort array by block costs */
1858 qsort(blocklist, n_blocks, sizeof(blocklist[0]), cmp_block_costs);
1860 ir_reserve_resources(irg, IR_RESOURCE_BLOCK_VISITED);
1861 inc_irg_block_visited(irg);
1863 for (i = 0; i < n_blocks; ++i) {
1864 ir_node *block = blocklist[i];
1865 if (Block_block_visited(block))
1868 /* continually add predecessors with highest costs to worklist
1869 * (without using backedges) */
1871 block_costs_t *info = get_irn_link(block);
1872 ir_node *best_pred = NULL;
1873 float best_costs = -1;
1874 int n_cfgpred = get_Block_n_cfgpreds(block);
1877 pdeq_putr(worklist, block);
1878 mark_Block_block_visited(block);
1879 for (i = 0; i < n_cfgpred; ++i) {
1880 ir_node *pred_block = get_Block_cfgpred_block(block, i);
1881 block_costs_t *pred_info = get_irn_link(pred_block);
1883 /* ignore backedges */
1884 if (pred_info->dfs_num > info->dfs_num)
1887 if (info->costs > best_costs) {
1888 best_costs = info->costs;
1889 best_pred = pred_block;
1893 } while(block != NULL && !Block_block_visited(block));
1895 /* now put all nodes in the worklist in our final order */
1896 while (!pdeq_empty(worklist)) {
1897 ir_node *pblock = pdeq_getr(worklist);
1898 assert(order_p < n_blocks);
1899 order[order_p++] = pblock;
1902 assert(order_p == n_blocks);
1905 ir_free_resources(irg, IR_RESOURCE_BLOCK_VISITED);
1907 DEL_ARR_F(blocklist);
1909 obstack_free(&obst, NULL);
1910 obstack_init(&obst);
1912 block_order = order;
1913 n_block_order = n_blocks;
1917 * Run the register allocator for the current register class.
1919 static void be_straight_alloc_cls(void)
1923 lv = be_assure_liveness(birg);
1924 be_liveness_assure_sets(lv);
1926 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
1928 DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1930 be_clear_links(irg);
1932 irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1933 if (create_congruence_classes)
1934 combine_congruence_classes();
1936 for (i = 0; i < n_block_order; ++i) {
1937 ir_node *block = block_order[i];
1938 allocate_coalesce_block(block, NULL);
1941 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
1944 static void dump(int mask, ir_graph *irg, const char *suffix,
1945 void (*dumper)(ir_graph *, const char *))
1947 if(birg->main_env->options->dump_flags & mask)
1948 be_dump(irg, suffix, dumper);
1952 * Run the spiller on the current graph.
1954 static void spill(void)
1956 /* make sure all nodes show their real register pressure */
1957 BE_TIMER_PUSH(t_ra_constr);
1958 be_pre_spill_prepare_constr(birg, cls);
1959 BE_TIMER_POP(t_ra_constr);
1961 dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1964 BE_TIMER_PUSH(t_ra_spill);
1965 be_do_spill(birg, cls);
1966 BE_TIMER_POP(t_ra_spill);
1968 BE_TIMER_PUSH(t_ra_spill_apply);
1969 check_for_memory_operands(irg);
1970 BE_TIMER_POP(t_ra_spill_apply);
1972 dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1976 * The straight register allocator for a whole procedure.
1978 static void be_straight_alloc(be_irg_t *new_birg)
1980 const arch_env_t *arch_env = new_birg->main_env->arch_env;
1981 int n_cls = arch_env_get_n_reg_class(arch_env);
1984 obstack_init(&obst);
1987 irg = be_get_birg_irg(birg);
1988 execfreqs = birg->exec_freq;
1990 /* determine a good coloring order */
1991 determine_block_order();
1993 for (c = 0; c < n_cls; ++c) {
1994 cls = arch_env_get_reg_class(arch_env, c);
1995 default_cls_req = NULL;
1996 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1999 stat_ev_ctx_push_str("regcls", cls->name);
2001 n_regs = arch_register_class_n_regs(cls);
2002 normal_regs = rbitset_malloc(n_regs);
2003 be_abi_set_non_ignore_regs(birg->abi, cls, normal_regs);
2007 /* verify schedule and register pressure */
2008 BE_TIMER_PUSH(t_verify);
2009 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
2010 be_verify_schedule(birg);
2011 be_verify_register_pressure(birg, cls, irg);
2012 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
2013 assert(be_verify_schedule(birg) && "Schedule verification failed");
2014 assert(be_verify_register_pressure(birg, cls, irg)
2015 && "Register pressure verification failed");
2017 BE_TIMER_POP(t_verify);
2019 BE_TIMER_PUSH(t_ra_color);
2020 be_straight_alloc_cls();
2021 BE_TIMER_POP(t_ra_color);
2023 /* we most probably constructed new Phis so liveness info is invalid
2025 /* TODO: test liveness_introduce */
2026 be_liveness_invalidate(lv);
2029 stat_ev_ctx_pop("regcls");
2032 BE_TIMER_PUSH(t_ra_spill_apply);
2033 be_abi_fix_stack_nodes(birg->abi);
2034 BE_TIMER_POP(t_ra_spill_apply);
2036 BE_TIMER_PUSH(t_verify);
2037 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
2038 be_verify_register_allocation(birg);
2039 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
2040 assert(be_verify_register_allocation(birg)
2041 && "Register allocation invalid");
2043 BE_TIMER_POP(t_verify);
2045 obstack_free(&obst, NULL);
2049 * Initializes this module.
2051 void be_init_straight_alloc(void)
2053 static be_ra_t be_ra_straight = {
2056 lc_opt_entry_t *be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
2057 lc_opt_entry_t *straightalloc_group = lc_opt_get_grp(be_grp, "straightalloc");
2058 lc_opt_add_table(straightalloc_group, options);
2060 be_register_allocator("straight", &be_ra_straight);
2061 FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
2064 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);