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