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