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