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