6f5b84024254cf12526937873fa8778e2a296c26
[libfirm] / ir / be / beprefalloc.c
1 /*
2  * Copyright (C) 1995-2011 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
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.
10  *
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.
14  *
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
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       Preference Guided Register Assignment
23  * @author      Matthias Braun
24  * @date        14.2.2009
25  * @version     $Id$
26  *
27  * The idea is to allocate registers in 2 passes:
28  * 1. A first pass to determine "preferred" registers for live-ranges. This
29  *    calculates for each register and each live-range a value indicating
30  *    the usefulness. (You can roughly think of the value as the negative
31  *    costs needed for copies when the value is in the specific registers...)
32  *
33  * 2. Walk blocks and assigns registers in a greedy fashion. Preferring
34  *    registers with high preferences. When register constraints are not met,
35  *    add copies and split live-ranges.
36  *
37  * TODO:
38  *  - make use of free registers in the permute_values code
39  */
40 #include "config.h"
41
42 #include <float.h>
43 #include <stdbool.h>
44 #include <math.h>
45 #include "lpp.h"
46
47 #include "error.h"
48 #include "execfreq.h"
49 #include "ircons.h"
50 #include "irdom.h"
51 #include "iredges_t.h"
52 #include "irgraph_t.h"
53 #include "irgwalk.h"
54 #include "irnode_t.h"
55 #include "irprintf.h"
56 #include "irdump.h"
57 #include "obst.h"
58 #include "raw_bitset.h"
59 #include "unionfind.h"
60 #include "pdeq.h"
61 #include "hungarian.h"
62
63 #include "beabi.h"
64 #include "bechordal_t.h"
65 #include "be.h"
66 #include "beirg.h"
67 #include "belive_t.h"
68 #include "bemodule.h"
69 #include "benode.h"
70 #include "bera.h"
71 #include "besched.h"
72 #include "bespill.h"
73 #include "bespillutil.h"
74 #include "beverify.h"
75 #include "beutil.h"
76 #include "bestack.h"
77
78 #define USE_FACTOR                     1.0f
79 #define DEF_FACTOR                     1.0f
80 #define NEIGHBOR_FACTOR                0.2f
81 #define AFF_SHOULD_BE_SAME             0.5f
82 #define AFF_PHI                        1.0f
83 #define SPLIT_DELTA                    1.0f
84 #define MAX_OPTIMISTIC_SPLIT_RECURSION 0
85
86 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
87
88 static struct obstack               obst;
89 static ir_graph                    *irg;
90 static const arch_register_class_t *cls;
91 static be_lv_t                     *lv;
92 static const ir_exec_freq          *execfreqs;
93 static unsigned                     n_regs;
94 static unsigned                    *normal_regs;
95 static int                         *congruence_classes;
96 static ir_node                    **block_order;
97 static size_t                       n_block_order;
98 static int                          create_preferences        = true;
99 static int                          create_congruence_classes = true;
100 static int                          propagate_phi_registers   = true;
101
102 static const lc_opt_table_entry_t options[] = {
103         LC_OPT_ENT_BOOL("prefs", "use preference based coloring", &create_preferences),
104         LC_OPT_ENT_BOOL("congruences", "create congruence classes", &create_congruence_classes),
105         LC_OPT_ENT_BOOL("prop_phi", "propagate phi registers", &propagate_phi_registers),
106         LC_OPT_LAST
107 };
108
109 /** currently active assignments (while processing a basic block)
110  * maps registers to values(their current copies) */
111 static ir_node **assignments;
112
113 /**
114  * allocation information: last_uses, register preferences
115  * the information is per firm-node.
116  */
117 struct allocation_info_t {
118         unsigned  last_uses[2];   /**< bitset indicating last uses (input pos) */
119         ir_node  *current_value;  /**< copy of the value that should be used */
120         ir_node  *original_value; /**< for copies point to original value */
121         float     prefs[0];       /**< register preferences */
122 };
123 typedef struct allocation_info_t allocation_info_t;
124
125 /** helper datastructure used when sorting register preferences */
126 struct reg_pref_t {
127         unsigned num;
128         float    pref;
129 };
130 typedef struct reg_pref_t reg_pref_t;
131
132 /** per basic-block information */
133 struct block_info_t {
134         bool     processed;       /**< indicate whether block is processed */
135         ir_node *assignments[0];  /**< register assignments at end of block */
136 };
137 typedef struct block_info_t block_info_t;
138
139 /**
140  * Get the allocation info for a node.
141  * The info is allocated on the first visit of a node.
142  */
143 static allocation_info_t *get_allocation_info(ir_node *node)
144 {
145         allocation_info_t *info = (allocation_info_t*)get_irn_link(node);
146         if (info == NULL) {
147                 info = OALLOCFZ(&obst, allocation_info_t, prefs, n_regs);
148                 info->current_value  = node;
149                 info->original_value = node;
150                 set_irn_link(node, info);
151         }
152
153         return info;
154 }
155
156 static allocation_info_t *try_get_allocation_info(const ir_node *node)
157 {
158         return (allocation_info_t*) get_irn_link(node);
159 }
160
161 /**
162  * Get allocation information for a basic block
163  */
164 static block_info_t *get_block_info(ir_node *block)
165 {
166         block_info_t *info = (block_info_t*)get_irn_link(block);
167
168         assert(is_Block(block));
169         if (info == NULL) {
170                 info = OALLOCFZ(&obst, block_info_t, assignments, n_regs);
171                 set_irn_link(block, info);
172         }
173
174         return info;
175 }
176
177 /**
178  * Link the allocation info of a node to a copy.
179  * Afterwards, both nodes uses the same allocation info.
180  * Copy must not have an allocation info assigned yet.
181  *
182  * @param copy   the node that gets the allocation info assigned
183  * @param value  the original node
184  */
185 static void mark_as_copy_of(ir_node *copy, ir_node *value)
186 {
187         ir_node           *original;
188         allocation_info_t *info      = get_allocation_info(value);
189         allocation_info_t *copy_info = get_allocation_info(copy);
190
191         /* find original value */
192         original = info->original_value;
193         if (original != value) {
194                 info = get_allocation_info(original);
195         }
196
197         assert(info->original_value == original);
198         info->current_value = copy;
199
200         /* the copy should not be linked to something else yet */
201         assert(copy_info->original_value == copy);
202         copy_info->original_value = original;
203
204         /* copy over allocation preferences */
205         memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
206 }
207
208 /**
209  * Calculate the penalties for every register on a node and its live neighbors.
210  *
211  * @param live_nodes  the set of live nodes at the current position, may be NULL
212  * @param penalty     the penalty to subtract from
213  * @param limited     a raw bitset containing the limited set for the node
214  * @param node        the node
215  */
216 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
217                                       float penalty, const unsigned* limited,
218                                       ir_node *node)
219 {
220         ir_nodeset_iterator_t iter;
221         unsigned              r;
222         size_t                n_allowed;
223         allocation_info_t     *info = get_allocation_info(node);
224         ir_node               *neighbor;
225
226         /* give penalty for all forbidden regs */
227         for (r = 0; r < n_regs; ++r) {
228                 if (rbitset_is_set(limited, r))
229                         continue;
230
231                 info->prefs[r] -= penalty;
232         }
233
234         /* all other live values should get a penalty for allowed regs */
235         if (live_nodes == NULL)
236                 return;
237
238         penalty   *= NEIGHBOR_FACTOR;
239         n_allowed  = rbitset_popcount(limited, n_regs);
240         if (n_allowed > 1) {
241                 /* only create a very weak penalty if multiple regs are allowed */
242                 penalty = (penalty * 0.8f) / n_allowed;
243         }
244         foreach_ir_nodeset(live_nodes, neighbor, iter) {
245                 allocation_info_t *neighbor_info;
246
247                 /* TODO: if op is used on multiple inputs we might not do a
248                  * continue here */
249                 if (neighbor == node)
250                         continue;
251
252                 neighbor_info = get_allocation_info(neighbor);
253                 for (r = 0; r < n_regs; ++r) {
254                         if (!rbitset_is_set(limited, r))
255                                 continue;
256
257                         neighbor_info->prefs[r] -= penalty;
258                 }
259         }
260 }
261
262 /**
263  * Calculate the preferences of a definition for the current register class.
264  * If the definition uses a limited set of registers, reduce the preferences
265  * for the limited register on the node and its neighbors.
266  *
267  * @param live_nodes  the set of live nodes at the current node
268  * @param weight      the weight
269  * @param node        the current node
270  */
271 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
272                        ir_node *node)
273 {
274         const arch_register_req_t *req = arch_get_register_req_out(node);
275         if (req->type & arch_register_req_type_limited) {
276                 const unsigned *limited = req->limited;
277                 float           penalty = weight * DEF_FACTOR;
278                 give_penalties_for_limits(live_nodes, penalty, limited, node);
279         }
280
281         if (req->type & arch_register_req_type_should_be_same) {
282                 ir_node           *insn  = skip_Proj(node);
283                 allocation_info_t *info  = get_allocation_info(node);
284                 int                arity = get_irn_arity(insn);
285                 int                i;
286
287                 float factor = 1.0f / rbitset_popcount(&req->other_same, arity);
288                 for (i = 0; i < arity; ++i) {
289                         ir_node           *op;
290                         unsigned           r;
291                         allocation_info_t *op_info;
292
293                         if (!rbitset_is_set(&req->other_same, i))
294                                 continue;
295
296                         op = get_irn_n(insn, i);
297
298                         /* if we the value at the should_be_same input doesn't die at the
299                          * node, then it is no use to propagate the constraints (since a
300                          * copy will emerge anyway) */
301                         if (ir_nodeset_contains(live_nodes, op))
302                                 continue;
303
304                         op_info = get_allocation_info(op);
305                         for (r = 0; r < n_regs; ++r) {
306                                 op_info->prefs[r] += info->prefs[r] * factor;
307                         }
308                 }
309         }
310 }
311
312 /**
313  * Walker: Runs an a block calculates the preferences for any
314  * node and every register from the considered register class.
315  */
316 static void analyze_block(ir_node *block, void *data)
317 {
318         float         weight = (float)get_block_execfreq(execfreqs, block);
319         ir_nodeset_t  live_nodes;
320         ir_node      *node;
321         (void) data;
322
323         ir_nodeset_init(&live_nodes);
324         be_liveness_end_of_block(lv, cls, block, &live_nodes);
325
326         sched_foreach_reverse(block, node) {
327                 allocation_info_t *info;
328                 int                i;
329                 int                arity;
330
331                 if (is_Phi(node))
332                         break;
333
334                 if (create_preferences) {
335                         ir_node *value;
336                         be_foreach_definition(node, cls, value,
337                                 check_defs(&live_nodes, weight, value);
338                         );
339                 }
340
341                 /* mark last uses */
342                 arity = get_irn_arity(node);
343
344                 /* the allocation info node currently only uses 1 unsigned value
345                    to mark last used inputs. So we will fail for a node with more than
346                    32 inputs. */
347                 if (arity >= (int) sizeof(info->last_uses) * 8) {
348                         panic("Node with more than %d inputs not supported yet",
349                                         (int) sizeof(info->last_uses) * 8);
350                 }
351
352                 info = get_allocation_info(node);
353                 for (i = 0; i < arity; ++i) {
354                         ir_node                   *op  = get_irn_n(node, i);
355                         const arch_register_req_t *req = arch_get_register_req_out(op);
356                         if (req->cls != cls)
357                                 continue;
358
359                         /* last usage of a value? */
360                         if (!ir_nodeset_contains(&live_nodes, op)) {
361                                 rbitset_set(info->last_uses, i);
362                         }
363                 }
364
365                 be_liveness_transfer(cls, node, &live_nodes);
366
367                 if (create_preferences) {
368                         /* update weights based on usage constraints */
369                         for (i = 0; i < arity; ++i) {
370                                 const arch_register_req_t *req;
371                                 const unsigned            *limited;
372                                 ir_node                   *op = get_irn_n(node, i);
373
374                                 if (!arch_irn_consider_in_reg_alloc(cls, op))
375                                         continue;
376
377                                 req = arch_get_register_req(node, i);
378                                 if (!(req->type & arch_register_req_type_limited))
379                                         continue;
380
381                                 limited = req->limited;
382                                 give_penalties_for_limits(&live_nodes, weight * USE_FACTOR,
383                                                           limited, op);
384                         }
385                 }
386         }
387
388         ir_nodeset_destroy(&live_nodes);
389 }
390
391 static void congruence_def(ir_nodeset_t *live_nodes, const ir_node *node)
392 {
393         const arch_register_req_t *req = arch_get_register_req_out(node);
394
395         /* should be same constraint? */
396         if (req->type & arch_register_req_type_should_be_same) {
397                 const ir_node *insn  = skip_Proj_const(node);
398                 int      arity = get_irn_arity(insn);
399                 int      i;
400                 unsigned node_idx = get_irn_idx(node);
401                 node_idx          = uf_find(congruence_classes, node_idx);
402
403                 for (i = 0; i < arity; ++i) {
404                         ir_node               *live;
405                         ir_node               *op;
406                         int                    op_idx;
407                         ir_nodeset_iterator_t  iter;
408                         bool                   interferes = false;
409
410                         if (!rbitset_is_set(&req->other_same, i))
411                                 continue;
412
413                         op     = get_irn_n(insn, i);
414                         op_idx = get_irn_idx(op);
415                         op_idx = uf_find(congruence_classes, op_idx);
416
417                         /* do we interfere with the value */
418                         foreach_ir_nodeset(live_nodes, live, iter) {
419                                 int lv_idx = get_irn_idx(live);
420                                 lv_idx     = uf_find(congruence_classes, lv_idx);
421                                 if (lv_idx == op_idx) {
422                                         interferes = true;
423                                         break;
424                                 }
425                         }
426                         /* don't put in same affinity class if we interfere */
427                         if (interferes)
428                                 continue;
429
430                         node_idx = uf_union(congruence_classes, node_idx, op_idx);
431                         DB((dbg, LEVEL_3, "Merge %+F and %+F congruence classes\n",
432                             node, op));
433                         /* one should_be_same is enough... */
434                         break;
435                 }
436         }
437 }
438
439 static void create_congruence_class(ir_node *block, void *data)
440 {
441         ir_nodeset_t  live_nodes;
442         ir_node      *node;
443
444         (void) data;
445         ir_nodeset_init(&live_nodes);
446         be_liveness_end_of_block(lv, cls, block, &live_nodes);
447
448         /* check should be same constraints */
449         sched_foreach_reverse(block, node) {
450                 ir_node *value;
451                 if (is_Phi(node))
452                         break;
453
454                 be_foreach_definition(node, cls, value,
455                         congruence_def(&live_nodes, value);
456                 );
457                 be_liveness_transfer(cls, node, &live_nodes);
458         }
459
460         /* check phi congruence classes */
461         sched_foreach_reverse_from(node, node) {
462                 int i;
463                 int arity;
464                 int node_idx;
465                 assert(is_Phi(node));
466
467                 if (!arch_irn_consider_in_reg_alloc(cls, node))
468                         continue;
469
470                 node_idx = get_irn_idx(node);
471                 node_idx = uf_find(congruence_classes, node_idx);
472
473                 arity = get_irn_arity(node);
474                 for (i = 0; i < arity; ++i) {
475                         bool                  interferes = false;
476                         ir_nodeset_iterator_t iter;
477                         unsigned              r;
478                         int                   old_node_idx;
479                         ir_node              *live;
480                         ir_node              *phi;
481                         allocation_info_t    *head_info;
482                         allocation_info_t    *other_info;
483                         ir_node              *op     = get_Phi_pred(node, i);
484                         int                   op_idx = get_irn_idx(op);
485                         op_idx = uf_find(congruence_classes, op_idx);
486
487                         /* do we interfere with the value */
488                         foreach_ir_nodeset(&live_nodes, live, iter) {
489                                 int lv_idx = get_irn_idx(live);
490                                 lv_idx     = uf_find(congruence_classes, lv_idx);
491                                 if (lv_idx == op_idx) {
492                                         interferes = true;
493                                         break;
494                                 }
495                         }
496                         /* don't put in same affinity class if we interfere */
497                         if (interferes)
498                                 continue;
499                         /* any other phi has the same input? */
500                         sched_foreach(block, phi) {
501                                 ir_node *oop;
502                                 int      oop_idx;
503                                 if (!is_Phi(phi))
504                                         break;
505                                 if (!arch_irn_consider_in_reg_alloc(cls, phi))
506                                         continue;
507                                 oop = get_Phi_pred(phi, i);
508                                 if (oop == op)
509                                         continue;
510                                 oop_idx = get_irn_idx(oop);
511                                 oop_idx = uf_find(congruence_classes, oop_idx);
512                                 if (oop_idx == op_idx) {
513                                         interferes = true;
514                                         break;
515                                 }
516                         }
517                         if (interferes)
518                                 continue;
519
520                         /* merge the 2 congruence classes and sum up their preferences */
521                         old_node_idx = node_idx;
522                         node_idx = uf_union(congruence_classes, node_idx, op_idx);
523                         DB((dbg, LEVEL_3, "Merge %+F and %+F congruence classes\n",
524                             node, op));
525
526                         old_node_idx = node_idx == old_node_idx ? op_idx : old_node_idx;
527                         head_info  = get_allocation_info(get_idx_irn(irg, node_idx));
528                         other_info = get_allocation_info(get_idx_irn(irg, old_node_idx));
529                         for (r = 0; r < n_regs; ++r) {
530                                 head_info->prefs[r] += other_info->prefs[r];
531                         }
532                 }
533         }
534 }
535
536 static void set_congruence_prefs(ir_node *node, void *data)
537 {
538         allocation_info_t *info;
539         allocation_info_t *head_info;
540         unsigned node_idx = get_irn_idx(node);
541         unsigned node_set = uf_find(congruence_classes, node_idx);
542
543         (void) data;
544
545         /* head of congruence class or not in any class */
546         if (node_set == node_idx)
547                 return;
548
549         if (!arch_irn_consider_in_reg_alloc(cls, node))
550                 return;
551
552         head_info = get_allocation_info(get_idx_irn(irg, node_set));
553         info      = get_allocation_info(node);
554
555         memcpy(info->prefs, head_info->prefs, n_regs * sizeof(info->prefs[0]));
556 }
557
558 static void combine_congruence_classes(void)
559 {
560         size_t n = get_irg_last_idx(irg);
561         congruence_classes = XMALLOCN(int, n);
562         uf_init(congruence_classes, n);
563
564         /* create congruence classes */
565         irg_block_walk_graph(irg, create_congruence_class, NULL, NULL);
566         /* merge preferences */
567         irg_walk_graph(irg, set_congruence_prefs, NULL, NULL);
568         free(congruence_classes);
569 }
570
571
572
573 /**
574  * Assign register reg to the given node.
575  *
576  * @param node  the node
577  * @param reg   the register
578  */
579 static void use_reg(ir_node *node, const arch_register_t *reg)
580 {
581         unsigned r = arch_register_get_index(reg);
582         assignments[r] = node;
583         arch_set_irn_register(node, reg);
584 }
585
586 static void free_reg_of_value(ir_node *node)
587 {
588         const arch_register_t *reg;
589         unsigned               r;
590
591         if (!arch_irn_consider_in_reg_alloc(cls, node))
592                 return;
593
594         reg        = arch_get_irn_register(node);
595         r          = arch_register_get_index(reg);
596         /* assignment->value may be NULL if a value is used at 2 inputs
597            so it gets freed twice. */
598         assert(assignments[r] == node || assignments[r] == NULL);
599         assignments[r] = NULL;
600 }
601
602 /**
603  * Compare two register preferences in decreasing order.
604  */
605 static int compare_reg_pref(const void *e1, const void *e2)
606 {
607         const reg_pref_t *rp1 = (const reg_pref_t*) e1;
608         const reg_pref_t *rp2 = (const reg_pref_t*) e2;
609         if (rp1->pref < rp2->pref)
610                 return 1;
611         if (rp1->pref > rp2->pref)
612                 return -1;
613         return 0;
614 }
615
616 static void fill_sort_candidates(reg_pref_t *regprefs,
617                                  const allocation_info_t *info)
618 {
619         unsigned r;
620
621         for (r = 0; r < n_regs; ++r) {
622                 float pref = info->prefs[r];
623                 regprefs[r].num  = r;
624                 regprefs[r].pref = pref;
625         }
626         /* TODO: use a stable sort here to avoid unnecessary register jumping */
627         qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
628 }
629
630 static bool try_optimistic_split(ir_node *to_split, ir_node *before,
631                                  float pref, float pref_delta,
632                                  unsigned *forbidden_regs, int recursion)
633 {
634         const arch_register_t *from_reg;
635         const arch_register_t *reg;
636         ir_node               *original_insn;
637         ir_node               *block;
638         ir_node               *copy;
639         unsigned               r = 0;
640         unsigned               from_r;
641         unsigned               i;
642         allocation_info_t     *info = get_allocation_info(to_split);
643         reg_pref_t            *prefs;
644         float                  delta = 0;
645         float                  split_threshold;
646
647         (void) pref;
648
649         /* stupid hack: don't optimisticallt split don't spill nodes...
650          * (so we don't split away the values produced because of
651          *  must_be_different constraints) */
652         original_insn = skip_Proj(info->original_value);
653         if (arch_irn_get_flags(original_insn) & arch_irn_flags_dont_spill)
654                 return false;
655
656         from_reg        = arch_get_irn_register(to_split);
657         from_r          = arch_register_get_index(from_reg);
658         block           = get_nodes_block(before);
659         split_threshold = (float)get_block_execfreq(execfreqs, block) * SPLIT_DELTA;
660
661         if (pref_delta < split_threshold*0.5)
662                 return false;
663
664         /* find the best free position where we could move to */
665         prefs = ALLOCAN(reg_pref_t, n_regs);
666         fill_sort_candidates(prefs, info);
667         for (i = 0; i < n_regs; ++i) {
668                 float apref;
669                 float apref_delta;
670                 bool  res;
671                 bool  old_source_state;
672
673                 /* we need a normal register which is not an output register
674                    an different from the current register of to_split */
675                 r = prefs[i].num;
676                 if (!rbitset_is_set(normal_regs, r))
677                         continue;
678                 if (rbitset_is_set(forbidden_regs, r))
679                         continue;
680                 if (r == from_r)
681                         continue;
682
683                 /* is the split worth it? */
684                 delta = pref_delta + prefs[i].pref;
685                 if (delta < split_threshold) {
686                         DB((dbg, LEVEL_3, "Not doing optimistical split of %+F (depth %d), win %f too low\n",
687                                 to_split, recursion, delta));
688                         return false;
689                 }
690
691                 /* if the register is free then we can do the split */
692                 if (assignments[r] == NULL)
693                         break;
694
695                 /* otherwise we might try recursively calling optimistic_split */
696                 if (recursion+1 > MAX_OPTIMISTIC_SPLIT_RECURSION)
697                         continue;
698
699                 apref        = prefs[i].pref;
700                 apref_delta  = i+1 < n_regs ? apref - prefs[i+1].pref : 0;
701                 apref_delta += pref_delta - split_threshold;
702
703                 /* our source register isn't a useful destination for recursive
704                    splits */
705                 old_source_state = rbitset_is_set(forbidden_regs, from_r);
706                 rbitset_set(forbidden_regs, from_r);
707                 /* try recursive split */
708                 res = try_optimistic_split(assignments[r], before, apref,
709                                            apref_delta, forbidden_regs, recursion+1);
710                 /* restore our destination */
711                 if (old_source_state) {
712                         rbitset_set(forbidden_regs, from_r);
713                 } else {
714                         rbitset_clear(forbidden_regs, from_r);
715                 }
716
717                 if (res)
718                         break;
719         }
720         if (i >= n_regs)
721                 return false;
722
723         reg  = arch_register_for_index(cls, r);
724         copy = be_new_Copy(cls, block, to_split);
725         mark_as_copy_of(copy, to_split);
726         /* hacky, but correct here */
727         if (assignments[arch_register_get_index(from_reg)] == to_split)
728                 free_reg_of_value(to_split);
729         use_reg(copy, reg);
730         sched_add_before(before, copy);
731
732         DB((dbg, LEVEL_3,
733             "Optimistic live-range split %+F move %+F(%s) -> %s before %+F (win %f, depth %d)\n",
734             copy, to_split, from_reg->name, reg->name, before, delta, recursion));
735         return true;
736 }
737
738 /**
739  * Determine and assign a register for node @p node
740  */
741 static void assign_reg(const ir_node *block, ir_node *node,
742                        unsigned *forbidden_regs)
743 {
744         const arch_register_t     *final_reg;
745         allocation_info_t         *info;
746         const arch_register_req_t *req;
747         reg_pref_t                *reg_prefs;
748         ir_node                   *in_node;
749         unsigned                   r;
750         const unsigned            *allowed_regs;
751         unsigned                   final_reg_index = 0;
752
753         assert(!is_Phi(node));
754         /* preassigned register? */
755         final_reg = arch_get_irn_register(node);
756         if (final_reg != NULL) {
757                 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, final_reg->name));
758                 use_reg(node, final_reg);
759                 return;
760         }
761
762         req = arch_get_register_req_out(node);
763         /* ignore reqs must be preassigned */
764         assert (! (req->type & arch_register_req_type_ignore));
765
766         /* give should_be_same boni */
767         info    = get_allocation_info(node);
768         in_node = skip_Proj(node);
769         if (req->type & arch_register_req_type_should_be_same) {
770                 float weight = (float)get_block_execfreq(execfreqs, block);
771                 int   arity  = get_irn_arity(in_node);
772                 int   i;
773
774                 assert(arity <= (int) sizeof(req->other_same) * 8);
775                 for (i = 0; i < arity; ++i) {
776                         ir_node               *in;
777                         const arch_register_t *reg;
778                         unsigned               reg_index;
779                         if (!rbitset_is_set(&req->other_same, i))
780                                 continue;
781
782                         in  = get_irn_n(in_node, i);
783                         reg = arch_get_irn_register(in);
784                         assert(reg != NULL);
785                         reg_index = arch_register_get_index(reg);
786
787                         /* if the value didn't die here then we should not propagate the
788                          * should_be_same info */
789                         if (assignments[reg_index] == in)
790                                 continue;
791
792                         info->prefs[reg_index] += weight * AFF_SHOULD_BE_SAME;
793                 }
794         }
795
796         /* create list of register candidates and sort by their preference */
797         DB((dbg, LEVEL_2, "Candidates for %+F:", node));
798         reg_prefs = ALLOCAN(reg_pref_t, n_regs);
799         fill_sort_candidates(reg_prefs, info);
800         for (r = 0; r < n_regs; ++r) {
801                 unsigned num = reg_prefs[r].num;
802                 const arch_register_t *reg;
803
804                 if (!rbitset_is_set(normal_regs, num))
805                         continue;
806                 reg = arch_register_for_index(cls, num);
807                 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[r].pref));
808         }
809         DB((dbg, LEVEL_2, "\n"));
810
811         allowed_regs = normal_regs;
812         if (req->type & arch_register_req_type_limited) {
813                 allowed_regs = req->limited;
814         }
815
816         for (r = 0; r < n_regs; ++r) {
817                 float   pref, delta;
818                 ir_node *before;
819                 bool    res;
820
821                 final_reg_index = reg_prefs[r].num;
822                 if (!rbitset_is_set(allowed_regs, final_reg_index))
823                         continue;
824                 /* alignment constraint? */
825                 if (req->width > 1 && (req->type & arch_register_req_type_aligned)
826                                 && (final_reg_index % req->width) != 0)
827                         continue;
828
829                 if (assignments[final_reg_index] == NULL)
830                         break;
831                 pref   = reg_prefs[r].pref;
832                 delta  = r+1 < n_regs ? pref - reg_prefs[r+1].pref : 0;
833                 before = skip_Proj(node);
834                 res    = try_optimistic_split(assignments[final_reg_index], before,
835                                               pref, delta, forbidden_regs, 0);
836                 if (res)
837                         break;
838         }
839         if (r >= n_regs) {
840                 /* the common reason to hit this panic is when 1 of your nodes is not
841                  * register pressure faithful */
842                 panic("No register left for %+F\n", node);
843         }
844
845         final_reg = arch_register_for_index(cls, final_reg_index);
846         DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, final_reg->name));
847         use_reg(node, final_reg);
848 }
849
850 /**
851  * Add an permutation in front of a node and change the assignments
852  * due to this permutation.
853  *
854  * To understand this imagine a permutation like this:
855  *
856  * 1 -> 2
857  * 2 -> 3
858  * 3 -> 1, 5
859  * 4 -> 6
860  * 5
861  * 6
862  * 7 -> 7
863  *
864  * First we count how many destinations a single value has. At the same time
865  * we can be sure that each destination register has at most 1 source register
866  * (it can have 0 which means we don't care what value is in it).
867  * We ignore all fulfilled permuations (like 7->7)
868  * In a first pass we create as much copy instructions as possible as they
869  * are generally cheaper than exchanges. We do this by counting into how many
870  * destinations a register has to be copied (in the example it's 2 for register
871  * 3, or 1 for the registers 1,2,4 and 7).
872  * We can then create a copy into every destination register when the usecount
873  * of that register is 0 (= noone else needs the value in the register).
874  *
875  * After this step we should only have cycles left. We implement a cyclic
876  * permutation of n registers with n-1 transpositions.
877  *
878  * @param live_nodes   the set of live nodes, updated due to live range split
879  * @param before       the node before we add the permutation
880  * @param permutation  the permutation array indices are the destination
881  *                     registers, the values in the array are the source
882  *                     registers.
883  */
884 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
885                            unsigned *permutation)
886 {
887         unsigned  *n_used = ALLOCANZ(unsigned, n_regs);
888         ir_node   *block;
889         unsigned   r;
890
891         /* determine how often each source register needs to be read */
892         for (r = 0; r < n_regs; ++r) {
893                 unsigned  old_reg = permutation[r];
894                 ir_node  *value;
895
896                 value = assignments[old_reg];
897                 if (value == NULL) {
898                         /* nothing to do here, reg is not live. Mark it as fixpoint
899                          * so we ignore it in the next steps */
900                         permutation[r] = r;
901                         continue;
902                 }
903
904                 ++n_used[old_reg];
905         }
906
907         block = get_nodes_block(before);
908
909         /* step1: create copies where immediately possible */
910         for (r = 0; r < n_regs; /* empty */) {
911                 ir_node *copy;
912                 ir_node *src;
913                 const arch_register_t *reg;
914                 unsigned               old_r = permutation[r];
915
916                 /* - no need to do anything for fixed points.
917                    - we can't copy if the value in the dest reg is still needed */
918                 if (old_r == r || n_used[r] > 0) {
919                         ++r;
920                         continue;
921                 }
922
923                 /* create a copy */
924                 src  = assignments[old_r];
925                 copy = be_new_Copy(cls, block, src);
926                 sched_add_before(before, copy);
927                 reg = arch_register_for_index(cls, r);
928                 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
929                     copy, src, before, reg->name));
930                 mark_as_copy_of(copy, src);
931                 use_reg(copy, reg);
932
933                 if (live_nodes != NULL) {
934                         ir_nodeset_insert(live_nodes, copy);
935                 }
936
937                 /* old register has 1 user less, permutation is resolved */
938                 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
939                 permutation[r] = r;
940
941                 assert(n_used[old_r] > 0);
942                 --n_used[old_r];
943                 if (n_used[old_r] == 0) {
944                         if (live_nodes != NULL) {
945                                 ir_nodeset_remove(live_nodes, src);
946                         }
947                         free_reg_of_value(src);
948                 }
949
950                 /* advance or jump back (if this copy enabled another copy) */
951                 if (old_r < r && n_used[old_r] == 0) {
952                         r = old_r;
953                 } else {
954                         ++r;
955                 }
956         }
957
958         /* at this point we only have "cycles" left which we have to resolve with
959          * perm instructions
960          * TODO: if we have free registers left, then we should really use copy
961          * instructions for any cycle longer than 2 registers...
962          * (this is probably architecture dependent, there might be archs where
963          *  copies are preferable even for 2-cycles) */
964
965         /* create perms with the rest */
966         for (r = 0; r < n_regs; /* empty */) {
967                 const arch_register_t *reg;
968                 unsigned  old_r = permutation[r];
969                 unsigned  r2;
970                 ir_node  *in[2];
971                 ir_node  *perm;
972                 ir_node  *proj0;
973                 ir_node  *proj1;
974
975                 if (old_r == r) {
976                         ++r;
977                         continue;
978                 }
979
980                 /* we shouldn't have copies from 1 value to multiple destinations left*/
981                 assert(n_used[old_r] == 1);
982
983                 /* exchange old_r and r2; after that old_r is a fixed point */
984                 r2 = permutation[old_r];
985
986                 in[0] = assignments[r2];
987                 in[1] = assignments[old_r];
988                 perm = be_new_Perm(cls, block, 2, in);
989                 sched_add_before(before, perm);
990                 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
991                     perm, in[0], in[1], before));
992
993                 proj0 = new_r_Proj(perm, get_irn_mode(in[0]), 0);
994                 mark_as_copy_of(proj0, in[0]);
995                 reg = arch_register_for_index(cls, old_r);
996                 use_reg(proj0, reg);
997
998                 proj1 = new_r_Proj(perm, get_irn_mode(in[1]), 1);
999                 mark_as_copy_of(proj1, in[1]);
1000                 reg = arch_register_for_index(cls, r2);
1001                 use_reg(proj1, reg);
1002
1003                 /* 1 value is now in the correct register */
1004                 permutation[old_r] = old_r;
1005                 /* the source of r changed to r2 */
1006                 permutation[r] = r2;
1007
1008                 /* if we have reached a fixpoint update data structures */
1009                 if (live_nodes != NULL) {
1010                         ir_nodeset_remove(live_nodes, in[0]);
1011                         ir_nodeset_remove(live_nodes, in[1]);
1012                         ir_nodeset_remove(live_nodes, proj0);
1013                         ir_nodeset_insert(live_nodes, proj1);
1014                 }
1015         }
1016
1017 #ifdef DEBUG_libfirm
1018         /* now we should only have fixpoints left */
1019         for (r = 0; r < n_regs; ++r) {
1020                 assert(permutation[r] == r);
1021         }
1022 #endif
1023 }
1024
1025 /**
1026  * Free regs for values last used.
1027  *
1028  * @param live_nodes   set of live nodes, will be updated
1029  * @param node         the node to consider
1030  */
1031 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
1032 {
1033         allocation_info_t *info      = get_allocation_info(node);
1034         const unsigned    *last_uses = info->last_uses;
1035         int                arity     = get_irn_arity(node);
1036         int                i;
1037
1038         for (i = 0; i < arity; ++i) {
1039                 ir_node *op;
1040
1041                 /* check if one operand is the last use */
1042                 if (!rbitset_is_set(last_uses, i))
1043                         continue;
1044
1045                 op = get_irn_n(node, i);
1046                 free_reg_of_value(op);
1047                 ir_nodeset_remove(live_nodes, op);
1048         }
1049 }
1050
1051 /**
1052  * change inputs of a node to the current value (copies/perms)
1053  */
1054 static void rewire_inputs(ir_node *node)
1055 {
1056         int i;
1057         int arity = get_irn_arity(node);
1058
1059         for (i = 0; i < arity; ++i) {
1060                 ir_node           *op = get_irn_n(node, i);
1061                 allocation_info_t *info = try_get_allocation_info(op);
1062
1063                 if (info == NULL)
1064                         continue;
1065
1066                 info = get_allocation_info(info->original_value);
1067                 if (info->current_value != op) {
1068                         set_irn_n(node, i, info->current_value);
1069                 }
1070         }
1071 }
1072
1073 /**
1074  * Create a bitset of registers occupied with value living through an
1075  * instruction
1076  */
1077 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
1078 {
1079         const allocation_info_t *info = get_allocation_info(node);
1080         unsigned r;
1081         int i;
1082         int arity;
1083
1084         /* mark all used registers as potentially live-through */
1085         for (r = 0; r < n_regs; ++r) {
1086                 if (assignments[r] == NULL)
1087                         continue;
1088                 if (!rbitset_is_set(normal_regs, r))
1089                         continue;
1090
1091                 rbitset_set(bitset, r);
1092         }
1093
1094         /* remove registers of value dying at the instruction */
1095         arity = get_irn_arity(node);
1096         for (i = 0; i < arity; ++i) {
1097                 ir_node               *op;
1098                 const arch_register_t *reg;
1099
1100                 if (!rbitset_is_set(info->last_uses, i))
1101                         continue;
1102
1103                 op  = get_irn_n(node, i);
1104                 reg = arch_get_irn_register(op);
1105                 rbitset_clear(bitset, arch_register_get_index(reg));
1106         }
1107 }
1108
1109 static void solve_lpp(ir_nodeset_t *live_nodes, ir_node *node,
1110                       unsigned *forbidden_regs, unsigned *live_through_regs)
1111 {
1112         unsigned *forbidden_edges = rbitset_malloc(n_regs * n_regs);
1113         int      *lpp_vars        = XMALLOCNZ(int, n_regs*n_regs);
1114         int       arity           = get_irn_arity(node);
1115         int       i;
1116         unsigned  l;
1117         unsigned  r;
1118
1119         lpp_t *lpp = lpp_new("prefalloc", lpp_minimize);
1120         //lpp_set_time_limit(lpp, 20);
1121         lpp_set_log(lpp, stdout);
1122
1123         /** mark some edges as forbidden */
1124         for (i = 0; i < arity; ++i) {
1125                 ir_node                   *op = get_irn_n(node, i);
1126                 const arch_register_t     *reg;
1127                 const arch_register_req_t *req;
1128                 const unsigned            *limited;
1129                 unsigned                   current_reg;
1130
1131                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1132                         continue;
1133
1134                 req = arch_get_register_req(node, i);
1135                 if (!(req->type & arch_register_req_type_limited))
1136                         continue;
1137
1138                 limited     = req->limited;
1139                 reg         = arch_get_irn_register(op);
1140                 current_reg = arch_register_get_index(reg);
1141                 for (r = 0; r < n_regs; ++r) {
1142                         if (rbitset_is_set(limited, r))
1143                                 continue;
1144
1145                         rbitset_set(forbidden_edges, current_reg*n_regs + r);
1146                 }
1147         }
1148
1149         /* add all combinations, except for not allowed ones */
1150         for (l = 0; l < n_regs; ++l) {
1151                 if (!rbitset_is_set(normal_regs, l)) {
1152                         char name[15];
1153                         snprintf(name, sizeof(name), "%u_to_%u", l, l);
1154                         lpp_vars[l*n_regs+l] = lpp_add_var(lpp, name, lpp_binary, 1);
1155                         continue;
1156                 }
1157
1158                 for (r = 0; r < n_regs; ++r) {
1159                         if (!rbitset_is_set(normal_regs, r))
1160                                 continue;
1161                         if (rbitset_is_set(forbidden_edges, l*n_regs + r))
1162                                 continue;
1163                         /* livethrough values may not use constrained output registers */
1164                         if (rbitset_is_set(live_through_regs, l)
1165                             && rbitset_is_set(forbidden_regs, r))
1166                                 continue;
1167
1168                         char name[15];
1169                         snprintf(name, sizeof(name), "%u_to_%u", l, r);
1170
1171                         double costs = l==r ? 9 : 8;
1172                         lpp_vars[l*n_regs+r]
1173                                 = lpp_add_var(lpp, name, lpp_binary, costs);
1174                         assert(lpp_vars[l*n_regs+r] > 0);
1175                 }
1176         }
1177         /* add constraints */
1178         for (l = 0; l < n_regs; ++l) {
1179                 int constraint;
1180                 /* only 1 destination per register */
1181                 constraint = -1;
1182                 for (r = 0; r < n_regs; ++r) {
1183                         int var = lpp_vars[l*n_regs+r];
1184                         if (var == 0)
1185                                 continue;
1186                         if (constraint < 0) {
1187                                 char name[64];
1188                                 snprintf(name, sizeof(name), "%u_to_dest", l);
1189                                 constraint = lpp_add_cst(lpp, name, lpp_equal, 1);
1190                         }
1191                         lpp_set_factor_fast(lpp, constraint, var, 1);
1192                 }
1193                 /* each destination used by at most 1 value */
1194                 constraint = -1;
1195                 for (r = 0; r < n_regs; ++r) {
1196                         int var = lpp_vars[r*n_regs+l];
1197                         if (var == 0)
1198                                 continue;
1199                         if (constraint < 0) {
1200                                 char name[64];
1201                                 snprintf(name, sizeof(name), "one_to_%u", l);
1202                                 constraint = lpp_add_cst(lpp, name, lpp_less_equal, 1);
1203                         }
1204                         lpp_set_factor_fast(lpp, constraint, var, 1);
1205                 }
1206         }
1207
1208         lpp_dump_plain(lpp, fopen("lppdump.txt", "w"));
1209
1210         /* solve lpp */
1211         {
1212                 ir_graph     *irg     = get_irn_irg(node);
1213                 be_options_t *options = be_get_irg_options(irg);
1214                 unsigned     *assignment;
1215                 lpp_solve(lpp, options->ilp_server, options->ilp_solver);
1216                 if (!lpp_is_sol_valid(lpp))
1217                         panic("ilp solution not valid!");
1218
1219                 assignment = ALLOCAN(unsigned, n_regs);
1220                 for (l = 0; l < n_regs; ++l) {
1221                         unsigned dest_reg = (unsigned)-1;
1222                         for (r = 0; r < n_regs; ++r) {
1223                                 int var = lpp_vars[l*n_regs+r];
1224                                 if (var == 0)
1225                                         continue;
1226                                 double val = lpp_get_var_sol(lpp, var);
1227                                 if (val == 1) {
1228                                         assert(dest_reg == (unsigned)-1);
1229                                         dest_reg = r;
1230                                 }
1231                         }
1232                         assert(dest_reg != (unsigned)-1);
1233                         assignment[dest_reg] = l;
1234                 }
1235
1236                 fprintf(stderr, "Assignment: ");
1237                 for (l = 0; l < n_regs; ++l) {
1238                         fprintf(stderr, "%u ", assignment[l]);
1239                 }
1240                 fprintf(stderr, "\n");
1241                 fflush(stdout);
1242                 permute_values(live_nodes, node, assignment);
1243         }
1244         lpp_free(lpp);
1245 }
1246
1247 /**
1248  * Enforce constraints at a node by live range splits.
1249  *
1250  * @param  live_nodes  the set of live nodes, might be changed
1251  * @param  node        the current node
1252  */
1253 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node,
1254                                 unsigned *forbidden_regs)
1255 {
1256         int arity = get_irn_arity(node);
1257         int i, res;
1258         hungarian_problem_t *bp;
1259         unsigned l, r;
1260         unsigned *assignment;
1261         ir_node  *value;
1262
1263         /* construct a list of register occupied by live-through values */
1264         unsigned *live_through_regs = NULL;
1265
1266         /* see if any use constraints are not met */
1267         bool double_width = false;
1268         bool good = true;
1269         for (i = 0; i < arity; ++i) {
1270                 ir_node                   *op = get_irn_n(node, i);
1271                 const arch_register_t     *reg;
1272                 const arch_register_req_t *req;
1273                 const unsigned            *limited;
1274                 unsigned                   reg_index;
1275
1276                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1277                         continue;
1278
1279                 /* are there any limitations for the i'th operand? */
1280                 req = arch_get_register_req(node, i);
1281                 if (req->width > 1)
1282                         double_width = true;
1283                 if (!(req->type & arch_register_req_type_limited))
1284                         continue;
1285
1286                 limited   = req->limited;
1287                 reg       = arch_get_irn_register(op);
1288                 reg_index = arch_register_get_index(reg);
1289                 if (!rbitset_is_set(limited, reg_index)) {
1290                         /* found an assignment outside the limited set */
1291                         good = false;
1292                         break;
1293                 }
1294         }
1295
1296         /* is any of the live-throughs using a constrained output register? */
1297         be_foreach_definition(node, cls, value,
1298                 if (req_->width > 1)
1299                         double_width = true;
1300                 if (! (req_->type & arch_register_req_type_limited))
1301                         continue;
1302                 if (live_through_regs == NULL) {
1303                         rbitset_alloca(live_through_regs, n_regs);
1304                         determine_live_through_regs(live_through_regs, node);
1305                 }
1306                 rbitset_or(forbidden_regs, req_->limited, n_regs);
1307                 if (rbitsets_have_common(req_->limited, live_through_regs, n_regs))
1308                         good = false;
1309         );
1310
1311         if (good)
1312                 return;
1313
1314         /* create these arrays if we haven't yet */
1315         if (live_through_regs == NULL) {
1316                 rbitset_alloca(live_through_regs, n_regs);
1317         }
1318
1319         if (double_width) {
1320                 /* only the ILP variant can solve this yet */
1321                 solve_lpp(live_nodes, node, forbidden_regs, live_through_regs);
1322                 return;
1323         }
1324
1325         /* at this point we have to construct a bipartite matching problem to see
1326          * which values should go to which registers
1327          * Note: We're building the matrix in "reverse" - source registers are
1328          *       right, destinations left because this will produce the solution
1329          *       in the format required for permute_values.
1330          */
1331         bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
1332
1333         /* add all combinations, then remove not allowed ones */
1334         for (l = 0; l < n_regs; ++l) {
1335                 if (!rbitset_is_set(normal_regs, l)) {
1336                         hungarian_add(bp, l, l, 1);
1337                         continue;
1338                 }
1339
1340                 for (r = 0; r < n_regs; ++r) {
1341                         if (!rbitset_is_set(normal_regs, r))
1342                                 continue;
1343                         /* livethrough values may not use constrainted output registers */
1344                         if (rbitset_is_set(live_through_regs, l)
1345                                         && rbitset_is_set(forbidden_regs, r))
1346                                 continue;
1347
1348                         hungarian_add(bp, r, l, l == r ? 9 : 8);
1349                 }
1350         }
1351
1352         for (i = 0; i < arity; ++i) {
1353                 ir_node                   *op = get_irn_n(node, i);
1354                 const arch_register_t     *reg;
1355                 const arch_register_req_t *req;
1356                 const unsigned            *limited;
1357                 unsigned                   current_reg;
1358
1359                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1360                         continue;
1361
1362                 req = arch_get_register_req(node, i);
1363                 if (!(req->type & arch_register_req_type_limited))
1364                         continue;
1365
1366                 limited     = req->limited;
1367                 reg         = arch_get_irn_register(op);
1368                 current_reg = arch_register_get_index(reg);
1369                 for (r = 0; r < n_regs; ++r) {
1370                         if (rbitset_is_set(limited, r))
1371                                 continue;
1372                         hungarian_remove(bp, r, current_reg);
1373                 }
1374         }
1375
1376         //hungarian_print_cost_matrix(bp, 1);
1377         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1378
1379         assignment = ALLOCAN(unsigned, n_regs);
1380         res = hungarian_solve(bp, assignment, NULL, 0);
1381         assert(res == 0);
1382
1383 #if 0
1384         fprintf(stderr, "Swap result:");
1385         for (i = 0; i < (int) n_regs; ++i) {
1386                 fprintf(stderr, " %d", assignment[i]);
1387         }
1388         fprintf(stderr, "\n");
1389 #endif
1390
1391         hungarian_free(bp);
1392
1393         permute_values(live_nodes, node, assignment);
1394 }
1395
1396 /** test whether a node @p n is a copy of the value of node @p of */
1397 static bool is_copy_of(ir_node *value, ir_node *test_value)
1398 {
1399         allocation_info_t *test_info;
1400         allocation_info_t *info;
1401
1402         if (value == test_value)
1403                 return true;
1404
1405         info      = get_allocation_info(value);
1406         test_info = get_allocation_info(test_value);
1407         return test_info->original_value == info->original_value;
1408 }
1409
1410 /**
1411  * find a value in the end-assignment of a basic block
1412  * @returns the index into the assignment array if found
1413  *          -1 if not found
1414  */
1415 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1416 {
1417         unsigned   r;
1418         ir_node  **end_assignments = info->assignments;
1419         for (r = 0; r < n_regs; ++r) {
1420                 ir_node *a_value = end_assignments[r];
1421
1422                 if (a_value == NULL)
1423                         continue;
1424                 if (is_copy_of(a_value, value))
1425                         return (int) r;
1426         }
1427
1428         return -1;
1429 }
1430
1431 /**
1432  * Create the necessary permutations at the end of a basic block to fullfill
1433  * the register assignment for phi-nodes in the next block
1434  */
1435 static void add_phi_permutations(ir_node *block, int p)
1436 {
1437         unsigned   r;
1438         unsigned  *permutation;
1439         ir_node  **old_assignments;
1440         bool       need_permutation;
1441         ir_node   *phi;
1442         ir_node   *pred = get_Block_cfgpred_block(block, p);
1443
1444         block_info_t *pred_info = get_block_info(pred);
1445
1446         /* predecessor not processed yet? nothing to do */
1447         if (!pred_info->processed)
1448                 return;
1449
1450         permutation = ALLOCAN(unsigned, n_regs);
1451         for (r = 0; r < n_regs; ++r) {
1452                 permutation[r] = r;
1453         }
1454
1455         /* check phi nodes */
1456         need_permutation = false;
1457         phi = sched_first(block);
1458         for ( ; is_Phi(phi); phi = sched_next(phi)) {
1459                 const arch_register_t *reg;
1460                 const arch_register_t *op_reg;
1461                 int                    regn;
1462                 int                    a;
1463                 ir_node               *op;
1464
1465                 if (!arch_irn_consider_in_reg_alloc(cls, phi))
1466                         continue;
1467
1468                 op = get_Phi_pred(phi, p);
1469                 a  = find_value_in_block_info(pred_info, op);
1470                 assert(a >= 0);
1471
1472                 reg  = arch_get_irn_register(phi);
1473                 regn = arch_register_get_index(reg);
1474                 /* same register? nothing to do */
1475                 if (regn == a)
1476                         continue;
1477
1478                 op     = pred_info->assignments[a];
1479                 op_reg = arch_get_irn_register(op);
1480                 /* virtual or joker registers are ok too */
1481                 if ((op_reg->type & arch_register_type_joker)
1482                                 || (op_reg->type & arch_register_type_virtual))
1483                         continue;
1484
1485                 permutation[regn] = a;
1486                 need_permutation  = true;
1487         }
1488
1489         if (need_permutation) {
1490                 /* permute values at end of predecessor */
1491                 old_assignments = assignments;
1492                 assignments     = pred_info->assignments;
1493                 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1494                                permutation);
1495                 assignments = old_assignments;
1496         }
1497
1498         /* change phi nodes to use the copied values */
1499         phi = sched_first(block);
1500         for ( ; is_Phi(phi); phi = sched_next(phi)) {
1501                 int      a;
1502                 ir_node *op;
1503
1504                 if (!arch_irn_consider_in_reg_alloc(cls, phi))
1505                         continue;
1506
1507                 op = get_Phi_pred(phi, p);
1508
1509                 /* we have permuted all values into the correct registers so we can
1510                    simply query which value occupies the phis register in the
1511                    predecessor */
1512                 a  = arch_register_get_index(arch_get_irn_register(phi));
1513                 op = pred_info->assignments[a];
1514                 set_Phi_pred(phi, p, op);
1515         }
1516 }
1517
1518 /**
1519  * Set preferences for a phis register based on the registers used on the
1520  * phi inputs.
1521  */
1522 static void adapt_phi_prefs(ir_node *phi)
1523 {
1524         int i;
1525         int arity = get_irn_arity(phi);
1526         ir_node           *block = get_nodes_block(phi);
1527         allocation_info_t *info  = get_allocation_info(phi);
1528
1529         for (i = 0; i < arity; ++i) {
1530                 ir_node               *op  = get_irn_n(phi, i);
1531                 const arch_register_t *reg = arch_get_irn_register(op);
1532                 ir_node               *pred_block;
1533                 block_info_t          *pred_block_info;
1534                 float                  weight;
1535                 unsigned               r;
1536
1537                 if (reg == NULL)
1538                         continue;
1539                 /* we only give the bonus if the predecessor already has registers
1540                  * assigned, otherwise we only see a dummy value
1541                  * and any conclusions about its register are useless */
1542                 pred_block = get_Block_cfgpred_block(block, i);
1543                 pred_block_info = get_block_info(pred_block);
1544                 if (!pred_block_info->processed)
1545                         continue;
1546
1547                 /* give bonus for already assigned register */
1548                 weight = (float)get_block_execfreq(execfreqs, pred_block);
1549                 r      = arch_register_get_index(reg);
1550                 info->prefs[r] += weight * AFF_PHI;
1551         }
1552 }
1553
1554 /**
1555  * After a phi has been assigned a register propagate preference inputs
1556  * to the phi inputs.
1557  */
1558 static void propagate_phi_register(ir_node *phi, unsigned assigned_r)
1559 {
1560         int      i;
1561         ir_node *block = get_nodes_block(phi);
1562         int      arity = get_irn_arity(phi);
1563
1564         for (i = 0; i < arity; ++i) {
1565                 ir_node           *op         = get_Phi_pred(phi, i);
1566                 allocation_info_t *info       = get_allocation_info(op);
1567                 ir_node           *pred_block = get_Block_cfgpred_block(block, i);
1568                 unsigned           r;
1569                 float              weight
1570                         = (float)get_block_execfreq(execfreqs, pred_block) * AFF_PHI;
1571
1572                 if (info->prefs[assigned_r] >= weight)
1573                         continue;
1574
1575                 /* promote the prefered register */
1576                 for (r = 0; r < n_regs; ++r) {
1577                         if (info->prefs[r] > -weight) {
1578                                 info->prefs[r] = -weight;
1579                         }
1580                 }
1581                 info->prefs[assigned_r] = weight;
1582
1583                 if (is_Phi(op))
1584                         propagate_phi_register(op, assigned_r);
1585         }
1586 }
1587
1588 static void assign_phi_registers(ir_node *block)
1589 {
1590         int                  n_phis = 0;
1591         int                  n;
1592         int                  res;
1593         unsigned            *assignment;
1594         ir_node             *node;
1595         hungarian_problem_t *bp;
1596
1597         /* count phi nodes */
1598         sched_foreach(block, node) {
1599                 if (!is_Phi(node))
1600                         break;
1601                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1602                         continue;
1603                 ++n_phis;
1604         }
1605
1606         if (n_phis == 0)
1607                 return;
1608
1609         /* build a bipartite matching problem for all phi nodes */
1610         bp = hungarian_new(n_phis, n_regs, HUNGARIAN_MATCH_PERFECT);
1611         n  = 0;
1612         sched_foreach(block, node) {
1613                 unsigned r;
1614
1615                 allocation_info_t *info;
1616                 if (!is_Phi(node))
1617                         break;
1618                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1619                         continue;
1620
1621                 /* give boni for predecessor colorings */
1622                 adapt_phi_prefs(node);
1623                 /* add stuff to bipartite problem */
1624                 info = get_allocation_info(node);
1625                 DB((dbg, LEVEL_3, "Prefs for %+F: ", node));
1626                 for (r = 0; r < n_regs; ++r) {
1627                         float costs;
1628
1629                         if (!rbitset_is_set(normal_regs, r))
1630                                 continue;
1631
1632                         costs = info->prefs[r];
1633                         costs = costs < 0 ? -logf(-costs+1) : logf(costs+1);
1634                         costs *= 100;
1635                         costs += 10000;
1636                         hungarian_add(bp, n, r, (int)costs);
1637                         DB((dbg, LEVEL_3, " %s(%f)", arch_register_for_index(cls, r)->name,
1638                                                 info->prefs[r]));
1639                 }
1640                 DB((dbg, LEVEL_3, "\n"));
1641                 ++n;
1642         }
1643
1644         //hungarian_print_cost_matrix(bp, 7);
1645         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1646
1647         assignment = ALLOCAN(unsigned, n_regs);
1648         res        = hungarian_solve(bp, assignment, NULL, 0);
1649         assert(res == 0);
1650
1651         /* apply results */
1652         n = 0;
1653         sched_foreach(block, node) {
1654                 unsigned               r;
1655                 const arch_register_t *reg;
1656
1657                 if (!is_Phi(node))
1658                         break;
1659                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1660                         continue;
1661
1662                 r = assignment[n++];
1663                 assert(rbitset_is_set(normal_regs, r));
1664                 reg = arch_register_for_index(cls, r);
1665                 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
1666                 use_reg(node, reg);
1667
1668                 /* adapt preferences for phi inputs */
1669                 if (propagate_phi_registers)
1670                         propagate_phi_register(node, r);
1671         }
1672 }
1673
1674 /**
1675  * Walker: assign registers to all nodes of a block that
1676  * need registers from the currently considered register class.
1677  */
1678 static void allocate_coalesce_block(ir_node *block, void *data)
1679 {
1680         int            i;
1681         ir_nodeset_t   live_nodes;
1682         ir_node       *node;
1683         int            n_preds;
1684         block_info_t  *block_info;
1685         block_info_t **pred_block_infos;
1686         ir_node      **phi_ins;
1687         unsigned      *forbidden_regs; /**< collects registers which must
1688                                                 not be used for optimistic splits */
1689
1690         (void) data;
1691         DB((dbg, LEVEL_2, "* Block %+F\n", block));
1692
1693         /* clear assignments */
1694         block_info  = get_block_info(block);
1695         assignments = block_info->assignments;
1696
1697         ir_nodeset_init(&live_nodes);
1698
1699         /* gather regalloc infos of predecessor blocks */
1700         n_preds          = get_Block_n_cfgpreds(block);
1701         pred_block_infos = ALLOCAN(block_info_t*, n_preds);
1702         for (i = 0; i < n_preds; ++i) {
1703                 ir_node      *pred      = get_Block_cfgpred_block(block, i);
1704                 block_info_t *pred_info = get_block_info(pred);
1705                 pred_block_infos[i]     = pred_info;
1706         }
1707
1708         phi_ins = ALLOCAN(ir_node*, n_preds);
1709
1710         /* collect live-in nodes and preassigned values */
1711         be_lv_foreach(lv, block, be_lv_state_in, i) {
1712                 bool                       need_phi = false;
1713                 const arch_register_req_t *req;
1714                 const arch_register_t     *reg;
1715                 int                        p;
1716
1717                 node = be_lv_get_irn(lv, block, i);
1718                 req  = arch_get_register_req_out(node);
1719                 if (req->cls != cls)
1720                         continue;
1721
1722                 if (req->type & arch_register_req_type_ignore) {
1723                         allocation_info_t *info = get_allocation_info(node);
1724                         info->current_value = node;
1725
1726                         reg = arch_get_irn_register(node);
1727                         assert(reg != NULL); /* ignore values must be preassigned */
1728                         use_reg(node, reg);
1729                         continue;
1730                 }
1731
1732                 /* check all predecessors for this value, if it is not everywhere the
1733                    same or unknown then we have to construct a phi
1734                    (we collect the potential phi inputs here) */
1735                 for (p = 0; p < n_preds; ++p) {
1736                         block_info_t *pred_info = pred_block_infos[p];
1737
1738                         if (!pred_info->processed) {
1739                                 /* use node for now, it will get fixed later */
1740                                 phi_ins[p] = node;
1741                                 need_phi   = true;
1742                         } else {
1743                                 int a = find_value_in_block_info(pred_info, node);
1744
1745                                 /* must live out of predecessor */
1746                                 assert(a >= 0);
1747                                 phi_ins[p] = pred_info->assignments[a];
1748                                 /* different value from last time? then we need a phi */
1749                                 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1750                                         need_phi = true;
1751                                 }
1752                         }
1753                 }
1754
1755                 if (need_phi) {
1756                         ir_mode *mode = get_irn_mode(node);
1757                         ir_node *phi  = be_new_Phi(block, n_preds, phi_ins, mode, cls);
1758
1759                         DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1760 #ifdef DEBUG_libfirm
1761                         {
1762                                 int pi;
1763                                 for (pi = 0; pi < n_preds; ++pi) {
1764                                         DB((dbg, LEVEL_3, " %+F", phi_ins[pi]));
1765                                 }
1766                                 DB((dbg, LEVEL_3, "\n"));
1767                         }
1768 #endif
1769                         mark_as_copy_of(phi, node);
1770                         sched_add_after(block, phi);
1771
1772                         node = phi;
1773                 } else {
1774                         allocation_info_t *info = get_allocation_info(node);
1775                         info->current_value = phi_ins[0];
1776
1777                         /* Grab 1 of the inputs we constructed (might not be the same as
1778                          * "node" as we could see the same copy of the value in all
1779                          * predecessors */
1780                         node = phi_ins[0];
1781                 }
1782
1783                 /* if the node already has a register assigned use it */
1784                 reg = arch_get_irn_register(node);
1785                 if (reg != NULL) {
1786                         use_reg(node, reg);
1787                 }
1788
1789                 /* remember that this node is live at the beginning of the block */
1790                 ir_nodeset_insert(&live_nodes, node);
1791         }
1792
1793         rbitset_alloca(forbidden_regs, n_regs);
1794
1795         /* handle phis... */
1796         assign_phi_registers(block);
1797
1798         /* all live-ins must have a register */
1799 #ifdef DEBUG_libfirm
1800         {
1801                 ir_nodeset_iterator_t  iter;
1802                 foreach_ir_nodeset(&live_nodes, node, iter) {
1803                         const arch_register_t *reg = arch_get_irn_register(node);
1804                         assert(reg != NULL);
1805                 }
1806         }
1807 #endif
1808
1809         /* assign instructions in the block */
1810         sched_foreach(block, node) {
1811                 int arity;
1812                 ir_node *value;
1813
1814                 /* phis are already assigned */
1815                 if (is_Phi(node))
1816                         continue;
1817
1818                 rewire_inputs(node);
1819
1820                 /* enforce use constraints */
1821                 rbitset_clear_all(forbidden_regs, n_regs);
1822                 enforce_constraints(&live_nodes, node, forbidden_regs);
1823
1824                 rewire_inputs(node);
1825
1826                 /* we may not use registers used for inputs for optimistic splits */
1827                 arity = get_irn_arity(node);
1828                 for (i = 0; i < arity; ++i) {
1829                         ir_node *op = get_irn_n(node, i);
1830                         const arch_register_t *reg;
1831                         if (!arch_irn_consider_in_reg_alloc(cls, op))
1832                                 continue;
1833
1834                         reg = arch_get_irn_register(op);
1835                         rbitset_set(forbidden_regs, arch_register_get_index(reg));
1836                 }
1837
1838                 /* free registers of values last used at this instruction */
1839                 free_last_uses(&live_nodes, node);
1840
1841                 /* assign output registers */
1842                 be_foreach_definition_(node, cls, value,
1843                         assign_reg(block, value, forbidden_regs);
1844                 );
1845         }
1846
1847         ir_nodeset_destroy(&live_nodes);
1848         assignments = NULL;
1849
1850         block_info->processed = true;
1851
1852         /* permute values at end of predecessor blocks in case of phi-nodes */
1853         if (n_preds > 1) {
1854                 int p;
1855                 for (p = 0; p < n_preds; ++p) {
1856                         add_phi_permutations(block, p);
1857                 }
1858         }
1859
1860         /* if we have exactly 1 successor then we might be able to produce phi
1861            copies now */
1862         if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1863                 const ir_edge_t *edge
1864                         = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1865                 ir_node      *succ      = get_edge_src_irn(edge);
1866                 int           p         = get_edge_src_pos(edge);
1867                 block_info_t *succ_info = get_block_info(succ);
1868
1869                 if (succ_info->processed) {
1870                         add_phi_permutations(succ, p);
1871                 }
1872         }
1873 }
1874
1875 typedef struct block_costs_t block_costs_t;
1876 struct block_costs_t {
1877         float costs;   /**< costs of the block */
1878         int   dfs_num; /**< depth first search number (to detect backedges) */
1879 };
1880
1881 static int cmp_block_costs(const void *d1, const void *d2)
1882 {
1883         const ir_node       * const *block1 = (const ir_node**)d1;
1884         const ir_node       * const *block2 = (const ir_node**)d2;
1885         const block_costs_t *info1  = (const block_costs_t*)get_irn_link(*block1);
1886         const block_costs_t *info2  = (const block_costs_t*)get_irn_link(*block2);
1887         return QSORT_CMP(info2->costs, info1->costs);
1888 }
1889
1890 static void determine_block_order(void)
1891 {
1892         size_t    p;
1893         ir_node **blocklist = be_get_cfgpostorder(irg);
1894         size_t    n_blocks  = ARR_LEN(blocklist);
1895         int       dfs_num   = 0;
1896         pdeq     *worklist  = new_pdeq();
1897         ir_node **order     = XMALLOCN(ir_node*, n_blocks);
1898         size_t    order_p   = 0;
1899
1900         /* clear block links... */
1901         for (p = 0; p < n_blocks; ++p) {
1902                 ir_node *block = blocklist[p];
1903                 set_irn_link(block, NULL);
1904         }
1905
1906         /* walk blocks in reverse postorder, the costs for each block are the
1907          * sum of the costs of its predecessors (excluding the costs on backedges
1908          * which we can't determine) */
1909         for (p = n_blocks; p > 0;) {
1910                 block_costs_t *cost_info;
1911                 ir_node *block = blocklist[--p];
1912
1913                 float execfreq   = (float)get_block_execfreq(execfreqs, block);
1914                 float costs      = execfreq;
1915                 int   n_cfgpreds = get_Block_n_cfgpreds(block);
1916                 int   p2;
1917                 for (p2 = 0; p2 < n_cfgpreds; ++p2) {
1918                         ir_node       *pred_block = get_Block_cfgpred_block(block, p2);
1919                         block_costs_t *pred_costs = (block_costs_t*)get_irn_link(pred_block);
1920                         /* we don't have any info for backedges */
1921                         if (pred_costs == NULL)
1922                                 continue;
1923                         costs += pred_costs->costs;
1924                 }
1925
1926                 cost_info          = OALLOCZ(&obst, block_costs_t);
1927                 cost_info->costs   = costs;
1928                 cost_info->dfs_num = dfs_num++;
1929                 set_irn_link(block, cost_info);
1930         }
1931
1932         /* sort array by block costs */
1933         qsort(blocklist, n_blocks, sizeof(blocklist[0]), cmp_block_costs);
1934
1935         ir_reserve_resources(irg, IR_RESOURCE_BLOCK_VISITED);
1936         inc_irg_block_visited(irg);
1937
1938         for (p = 0; p < n_blocks; ++p) {
1939                 ir_node       *block = blocklist[p];
1940                 if (Block_block_visited(block))
1941                         continue;
1942
1943                 /* continually add predecessors with highest costs to worklist
1944                  * (without using backedges) */
1945                 do {
1946                         block_costs_t *info       = (block_costs_t*)get_irn_link(block);
1947                         ir_node       *best_pred  = NULL;
1948                         float          best_costs = -1;
1949                         int            n_cfgpred  = get_Block_n_cfgpreds(block);
1950                         int            i;
1951
1952                         pdeq_putr(worklist, block);
1953                         mark_Block_block_visited(block);
1954                         for (i = 0; i < n_cfgpred; ++i) {
1955                                 ir_node       *pred_block = get_Block_cfgpred_block(block, i);
1956                                 block_costs_t *pred_info  = (block_costs_t*)get_irn_link(pred_block);
1957
1958                                 /* ignore backedges */
1959                                 if (pred_info->dfs_num > info->dfs_num)
1960                                         continue;
1961
1962                                 if (info->costs > best_costs) {
1963                                         best_costs = info->costs;
1964                                         best_pred  = pred_block;
1965                                 }
1966                         }
1967                         block = best_pred;
1968                 } while (block != NULL && !Block_block_visited(block));
1969
1970                 /* now put all nodes in the worklist in our final order */
1971                 while (!pdeq_empty(worklist)) {
1972                         ir_node *pblock = (ir_node*)pdeq_getr(worklist);
1973                         assert(order_p < n_blocks);
1974                         order[order_p++] = pblock;
1975                 }
1976         }
1977         assert(order_p == n_blocks);
1978         del_pdeq(worklist);
1979
1980         ir_free_resources(irg, IR_RESOURCE_BLOCK_VISITED);
1981
1982         DEL_ARR_F(blocklist);
1983
1984         obstack_free(&obst, NULL);
1985         obstack_init(&obst);
1986
1987         block_order   = order;
1988         n_block_order = n_blocks;
1989 }
1990
1991 /**
1992  * Run the register allocator for the current register class.
1993  */
1994 static void be_pref_alloc_cls(void)
1995 {
1996         size_t i;
1997
1998         lv = be_assure_liveness(irg);
1999         be_liveness_assure_sets(lv);
2000
2001         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
2002
2003         DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
2004
2005         be_clear_links(irg);
2006
2007         irg_block_walk_graph(irg, NULL, analyze_block, NULL);
2008         if (create_congruence_classes)
2009                 combine_congruence_classes();
2010
2011         for (i = 0; i < n_block_order; ++i) {
2012                 ir_node *block = block_order[i];
2013                 allocate_coalesce_block(block, NULL);
2014         }
2015
2016         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
2017 }
2018
2019 static void dump(int mask, ir_graph *irg, const char *suffix)
2020 {
2021         if (be_get_irg_options(irg)->dump_flags & mask)
2022                 dump_ir_graph(irg, suffix);
2023 }
2024
2025 /**
2026  * Run the spiller on the current graph.
2027  */
2028 static void spill(void)
2029 {
2030         /* make sure all nodes show their real register pressure */
2031         be_timer_push(T_RA_CONSTR);
2032         be_pre_spill_prepare_constr(irg, cls);
2033         be_timer_pop(T_RA_CONSTR);
2034
2035         dump(DUMP_RA, irg, "spillprepare");
2036
2037         /* spill */
2038         be_timer_push(T_RA_SPILL);
2039         be_do_spill(irg, cls);
2040         be_timer_pop(T_RA_SPILL);
2041
2042         be_timer_push(T_RA_SPILL_APPLY);
2043         check_for_memory_operands(irg);
2044         be_timer_pop(T_RA_SPILL_APPLY);
2045
2046         dump(DUMP_RA, irg, "spill");
2047 }
2048
2049 /**
2050  * The pref register allocator for a whole procedure.
2051  */
2052 static void be_pref_alloc(ir_graph *new_irg)
2053 {
2054         const arch_env_t *arch_env = be_get_irg_arch_env(new_irg);
2055         int   n_cls                = arch_env->n_register_classes;
2056         int   c;
2057
2058         obstack_init(&obst);
2059
2060         irg       = new_irg;
2061         execfreqs = be_get_irg_exec_freq(irg);
2062
2063         /* determine a good coloring order */
2064         determine_block_order();
2065
2066         for (c = 0; c < n_cls; ++c) {
2067                 cls = &arch_env->register_classes[c];
2068                 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
2069                         continue;
2070
2071                 stat_ev_ctx_push_str("regcls", cls->name);
2072
2073                 n_regs      = arch_register_class_n_regs(cls);
2074                 normal_regs = rbitset_malloc(n_regs);
2075                 be_set_allocatable_regs(irg, cls, normal_regs);
2076
2077                 spill();
2078
2079                 /* verify schedule and register pressure */
2080                 be_timer_push(T_VERIFY);
2081                 if (be_get_irg_options(irg)->verify_option == BE_VERIFY_WARN) {
2082                         be_verify_schedule(irg);
2083                         be_verify_register_pressure(irg, cls);
2084                 } else if (be_get_irg_options(irg)->verify_option == BE_VERIFY_ASSERT) {
2085                         assert(be_verify_schedule(irg) && "Schedule verification failed");
2086                         assert(be_verify_register_pressure(irg, cls)
2087                                 && "Register pressure verification failed");
2088                 }
2089                 be_timer_pop(T_VERIFY);
2090
2091                 be_timer_push(T_RA_COLOR);
2092                 be_pref_alloc_cls();
2093                 be_timer_pop(T_RA_COLOR);
2094
2095                 /* we most probably constructed new Phis so liveness info is invalid
2096                  * now */
2097                 /* TODO: test liveness_introduce */
2098                 be_liveness_invalidate(lv);
2099                 free(normal_regs);
2100
2101                 stat_ev_ctx_pop("regcls");
2102         }
2103
2104         be_timer_push(T_RA_SPILL_APPLY);
2105         be_abi_fix_stack_nodes(irg);
2106         be_timer_pop(T_RA_SPILL_APPLY);
2107
2108         be_timer_push(T_VERIFY);
2109         if (be_get_irg_options(irg)->verify_option == BE_VERIFY_WARN) {
2110                 be_verify_register_allocation(irg);
2111         } else if (be_get_irg_options(irg)->verify_option == BE_VERIFY_ASSERT) {
2112                 assert(be_verify_register_allocation(irg)
2113                        && "Register allocation invalid");
2114         }
2115         be_timer_pop(T_VERIFY);
2116
2117         obstack_free(&obst, NULL);
2118 }
2119
2120 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_pref_alloc)
2121 void be_init_pref_alloc(void)
2122 {
2123         static be_ra_t be_ra_pref = {
2124                 be_pref_alloc,
2125         };
2126         lc_opt_entry_t *be_grp              = lc_opt_get_grp(firm_opt_get_root(), "be");
2127         lc_opt_entry_t *prefalloc_group = lc_opt_get_grp(be_grp, "prefalloc");
2128         lc_opt_add_table(prefalloc_group, options);
2129
2130         be_register_allocator("pref", &be_ra_pref);
2131         FIRM_DBG_REGISTER(dbg, "firm.be.prefalloc");
2132 }