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