- implement output constraint enforcement for new register allocator
[libfirm] / ir / be / benewalloc.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       New approach to allocation and copy coalescing
23  * @author      Matthias Braun
24  * @date        14.2.2009
25  * @version     $Id$
26  *
27  * ... WE NEED A NAME FOR THIS ...
28  *
29  * Only a proof of concept at this moment...
30  *
31  * The idea is to allocate registers in 2 passes:
32  * 1. A first pass to determine "preferred" registers for live-ranges. This
33  *    calculates for each register and each live-range a value indicating
34  *    the usefulness. (You can roughly think of the value as the negative
35  *    costs needed for copies when the value is in the specific registers...)
36  *
37  * 2. Walk blocks and assigns registers in a greedy fashion. Preferring
38  *    registers with high preferences. When register constraints are not met,
39  *    add copies and split live-ranges.
40  *
41  * TODO:
42  *  - make use of free registers in the permutate_values code
43  *  - output constraints are not ensured. The algorithm fails to copy values
44  *    away, so the registers for constrained outputs are free.
45  *  - must_be_different constraint is not respected
46  *  - We have to pessimistically construct Phi_0s when not all predecessors
47  *    of a block are known.
48  *  - Phi color assignment should give bonus points towards registers already
49  *    assigned at predecessors.
50  *  - think about a smarter sequence of visiting the blocks. Sorted by
51  *    execfreq might be good, or looptree from inner to outermost loops going
52  *    over blocks in a reverse postorder
53  */
54 #include "config.h"
55
56 #include <float.h>
57
58 #include "obst.h"
59 #include "irnode_t.h"
60 #include "irgraph_t.h"
61 #include "iredges_t.h"
62 #include "ircons.h"
63 #include "irgwalk.h"
64 #include "execfreq.h"
65
66 #include "be.h"
67 #include "bera.h"
68 #include "belive_t.h"
69 #include "bemodule.h"
70 #include "bechordal_t.h"
71 #include "besched.h"
72 #include "beirg.h"
73 #include "benode_t.h"
74 #include "bespill.h"
75 #include "bespillutil.h"
76 #include "beverify.h"
77
78 #include "bipartite.h"
79 #include "hungarian.h"
80
81 #define USE_FACTOR       1.0f
82 #define DEF_FACTOR       1.0f
83 #define NEIGHBOR_FACTOR  0.2f
84 #define SHOULD_BE_SAME   1.0f
85
86 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
87
88 static struct obstack               obst;
89 static be_irg_t                    *birg;
90 static ir_graph                    *irg;
91 static const arch_register_class_t *cls;
92 static be_lv_t                     *lv;
93 static const ir_exec_freq          *execfreqs;
94 static unsigned                     n_regs;
95 static bitset_t                    *ignore_regs;
96
97 /** info about the current assignment for a register */
98 struct assignment_t {
99         ir_node *value;            /**< currently assigned value */
100 };
101 typedef struct assignment_t assignment_t;
102
103 /** currently active assignments (while processing a basic block) */
104 static assignment_t *assignments;
105
106 /**
107  * allocation information: last_uses, register preferences
108  * the information is per firm-node.
109  */
110 struct allocation_info_t {
111         unsigned      last_uses;   /**< bitset indicating last uses (input pos) */
112         assignment_t *current_assignment;
113         float         prefs[0];    /**< register preferences */
114 };
115 typedef struct allocation_info_t allocation_info_t;
116
117 /** helper datastructure used when sorting register preferences */
118 struct reg_pref_t {
119         unsigned num;
120         float    pref;
121 };
122 typedef struct reg_pref_t reg_pref_t;
123
124 /** per basic-block information */
125 struct block_info_t {
126         int          processed;       /**< indicate wether block is processed */
127         assignment_t assignments[0];  /**< register assignments at end of block */
128 };
129 typedef struct block_info_t block_info_t;
130
131 /**
132  * Get the allocation info for a node.
133  * The info is allocated on the first visit of a node.
134  */
135 static allocation_info_t *get_allocation_info(ir_node *node)
136 {
137         allocation_info_t *info;
138         if (!irn_visited(node)) {
139                 size_t size = sizeof(info[0]) + n_regs * sizeof(info->prefs[0]);
140                 info = obstack_alloc(&obst, size);
141                 memset(info, 0, size);
142                 set_irn_link(node, info);
143                 mark_irn_visited(node);
144         } else {
145                 info = get_irn_link(node);
146         }
147
148         return info;
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;
157
158         assert(is_Block(block));
159         if (!irn_visited(block)) {
160                 size_t size = sizeof(info[0]) + n_regs * sizeof(info->assignments[0]);
161                 info = obstack_alloc(&obst, size);
162                 memset(info, 0, size);
163                 set_irn_link(block, info);
164                 mark_irn_visited(block);
165         } else {
166                 info = get_irn_link(block);
167         }
168
169         return info;
170 }
171
172 /**
173  * Link the allocation info of a node to a copy.
174  * Afterwards, both nodes uses the same allocation info.
175  * Copy must not have an allocation info assigned yet.
176  *
177  * @param copy   the node that gets the allocation info assigned
178  * @param value  the original node
179  */
180 static void link_to(ir_node *copy, ir_node *value)
181 {
182         allocation_info_t *info = get_allocation_info(value);
183         assert(!irn_visited(copy));
184         set_irn_link(copy, info);
185         mark_irn_visited(copy);
186 }
187
188 /**
189  * Calculate the penalties for every register on a node and its live neighbors.
190  *
191  * @param live_nodes   the set of live nodes at the current position, may be NULL
192  * @param penalty      the penalty to subtract from
193  * @param limited      a raw bitset containing the limited set for the node
194  * @param node         the node
195  */
196 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
197                                       float penalty, const unsigned* limited,
198                                                                           ir_node *node)
199 {
200         ir_nodeset_iterator_t iter;
201         unsigned              r;
202         allocation_info_t     *info = get_allocation_info(node);
203         ir_node               *neighbor;
204
205         /* give penalty for all forbidden regs */
206         for (r = 0; r < n_regs; ++r) {
207                 if (rbitset_is_set(limited, r))
208                         continue;
209
210                 info->prefs[r] -= penalty;
211         }
212
213         /* all other live values should get a penalty for allowed regs */
214         if (live_nodes == NULL)
215                 return;
216
217         /* TODO: reduce penalty if there are multiple allowed registers... */
218         penalty *= NEIGHBOR_FACTOR;
219         foreach_ir_nodeset(live_nodes, neighbor, iter) {
220                 allocation_info_t *neighbor_info;
221
222                 /* TODO: if op is used on multiple inputs we might not do a
223                  * continue here */
224                 if (neighbor == node)
225                         continue;
226
227                 neighbor_info = get_allocation_info(neighbor);
228                 for (r = 0; r < n_regs; ++r) {
229                         if (!rbitset_is_set(limited, r))
230                                 continue;
231
232                         neighbor_info->prefs[r] -= penalty;
233                 }
234         }
235 }
236
237 /**
238  * Calculate the preferences of a definition for the current register class.
239  * If the definition uses a limited set of registers, reduce the preferences
240  * for the limited register on the node and its neighbors.
241  *
242  * @param live_nodes  the set of live nodes at the current node
243  * @param weight      the weight
244  * @param node        the current node
245  */
246 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
247                        ir_node *node)
248 {
249         const arch_register_req_t *req;
250
251         if (get_irn_mode(node) == mode_T) {
252                 const ir_edge_t *edge;
253                 foreach_out_edge(node, edge) {
254                         ir_node *proj = get_edge_src_irn(edge);
255                         check_defs(live_nodes, weight, proj);
256                 }
257                 return;
258         }
259
260         if (!arch_irn_consider_in_reg_alloc(cls, node))
261                 return;
262
263         req = arch_get_register_req_out(node);
264         if (req->type & arch_register_req_type_limited) {
265                 const unsigned *limited = req->limited;
266                 float           penalty = weight * DEF_FACTOR;
267                 give_penalties_for_limits(live_nodes, penalty, limited, node);
268         }
269
270         if (req->type & arch_register_req_type_should_be_same) {
271                 ir_node           *insn  = skip_Proj(node);
272                 allocation_info_t *info  = get_allocation_info(node);
273                 int                arity = get_irn_arity(insn);
274                 int                i;
275
276                 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
277                 for (i = 0; i < arity; ++i) {
278                         ir_node           *op;
279                         unsigned          r;
280                         allocation_info_t *op_info;
281
282                         if (!rbitset_is_set(&req->other_same, i))
283                                 continue;
284
285                         op      = get_irn_n(insn, i);
286                         op_info = get_allocation_info(op);
287                         for (r = 0; r < n_regs; ++r) {
288                                 if (bitset_is_set(ignore_regs, r))
289                                         continue;
290                                 op_info->prefs[r] += info->prefs[r] * factor;
291                         }
292                 }
293         }
294 }
295
296 /**
297  * Walker: Runs an a block calculates the preferences for any
298  * node and every register from the considered register class.
299  */
300 static void analyze_block(ir_node *block, void *data)
301 {
302         float         weight = get_block_execfreq(execfreqs, block);
303         ir_nodeset_t  live_nodes;
304         ir_node      *node;
305         (void) data;
306
307         ir_nodeset_init(&live_nodes);
308         be_liveness_end_of_block(lv, cls, block, &live_nodes);
309
310         sched_foreach_reverse(block, node) {
311                 allocation_info_t *info;
312                 int               i, arity;
313
314                 if (is_Phi(node)) {
315                         /* TODO: handle constrained phi-nodes */
316                         break;
317                 }
318
319                 /* TODO give/take penalties for should_be_same/different) */
320                 check_defs(&live_nodes, weight, node);
321
322                 /* mark last uses */
323                 arity = get_irn_arity(node);
324                 /* I was lazy, and only allocated 1 unsigned
325                    => maximum of 32 uses per node (rewrite if necessary) */
326                 assert(arity <= (int) sizeof(unsigned) * 8);
327
328                 info = get_allocation_info(node);
329                 for (i = 0; i < arity; ++i) {
330                         ir_node *op = get_irn_n(node, i);
331                         if (!arch_irn_consider_in_reg_alloc(cls, op))
332                                 continue;
333
334                         /* last usage of a value? */
335                         if (!ir_nodeset_contains(&live_nodes, op)) {
336                                 rbitset_set(&info->last_uses, i);
337                         }
338                 }
339
340                 be_liveness_transfer(cls, node, &live_nodes);
341
342                 /* update weights based on usage constraints */
343                 for (i = 0; i < arity; ++i) {
344                         const arch_register_req_t *req;
345                         const unsigned            *limited;
346                         ir_node                   *op = get_irn_n(node, i);
347
348                         if (!arch_irn_consider_in_reg_alloc(cls, op))
349                                 continue;
350
351                         req = arch_get_register_req(node, i);
352                         if ((req->type & arch_register_req_type_limited) == 0)
353                                 continue;
354
355                         /* TODO: give penalties to neighbors for precolored nodes! */
356
357                         limited = req->limited;
358                         give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
359                                                   op);
360                 }
361         }
362
363         ir_nodeset_destroy(&live_nodes);
364 }
365
366 /**
367  * Assign register reg to the given node.
368  *
369  * @param node  the node
370  * @param reg   the register
371  */
372 static void use_reg(ir_node *node, const arch_register_t *reg)
373 {
374         unsigned           r          = arch_register_get_index(reg);
375         assignment_t      *assignment = &assignments[r];
376         allocation_info_t *info;
377
378         assert(assignment->value == NULL);
379         assignment->value = node;
380
381         info = get_allocation_info(node);
382         info->current_assignment = assignment;
383
384         arch_set_irn_register(node, reg);
385 }
386
387 /**
388  * Compare two register preferences in decreasing order.
389  */
390 static int compare_reg_pref(const void *e1, const void *e2)
391 {
392         const reg_pref_t *rp1 = (const reg_pref_t*) e1;
393         const reg_pref_t *rp2 = (const reg_pref_t*) e2;
394         if (rp1->pref < rp2->pref)
395                 return 1;
396         if (rp1->pref > rp2->pref)
397                 return -1;
398         return 0;
399 }
400
401 static void fill_sort_candidates(reg_pref_t *regprefs,
402                                  const allocation_info_t *info)
403 {
404         unsigned r;
405
406         for (r = 0; r < n_regs; ++r) {
407                 float pref = info->prefs[r];
408                 if (bitset_is_set(ignore_regs, r)) {
409                         pref = -10000;
410                 }
411                 regprefs[r].num  = r;
412                 regprefs[r].pref = pref;
413         }
414         /* TODO: use a stable sort here to avoid unnecessary register jumping */
415         qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
416 }
417
418 /**
419  * Determine and assign a register for node @p node
420  */
421 static void assign_reg(const ir_node *block, ir_node *node)
422 {
423         const arch_register_t     *reg;
424         allocation_info_t         *info;
425         const arch_register_req_t *req;
426         reg_pref_t                *reg_prefs;
427         ir_node                   *in_node;
428         unsigned                  i;
429
430         assert(arch_irn_consider_in_reg_alloc(cls, node));
431
432         /* preassigned register? */
433         reg = arch_get_irn_register(node);
434         if (reg != NULL) {
435                 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
436                 use_reg(node, reg);
437                 return;
438         }
439
440         /* give should_be_same boni */
441         info = get_allocation_info(node);
442         req  = arch_get_register_req_out(node);
443
444         in_node = skip_Proj(node);
445         if (req->type & arch_register_req_type_should_be_same) {
446                 float weight = get_block_execfreq(execfreqs, block);
447                 int   arity  = get_irn_arity(in_node);
448                 int   i;
449
450                 assert(arity <= (int) sizeof(req->other_same) * 8);
451                 for (i = 0; i < arity; ++i) {
452                         ir_node               *in;
453                         const arch_register_t *reg;
454                         unsigned               r;
455                         if (!rbitset_is_set(&req->other_same, i))
456                                 continue;
457
458                         in  = get_irn_n(in_node, i);
459                         reg = arch_get_irn_register(in);
460                         assert(reg != NULL);
461                         r = arch_register_get_index(reg);
462                         if (bitset_is_set(ignore_regs, r))
463                                 continue;
464                         info->prefs[r] += weight * SHOULD_BE_SAME;
465                 }
466         }
467
468         /* TODO: handle must_be_different */
469
470         /*  */
471         DB((dbg, LEVEL_2, "Candidates for %+F:", node));
472         reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
473         fill_sort_candidates(reg_prefs, info);
474         for (i = 0; i < n_regs; ++i) {
475                 unsigned               num = reg_prefs[i].num;
476                 const arch_register_t *reg = arch_register_for_index(cls, num);
477                 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
478         }
479         DB((dbg, LEVEL_2, "\n"));
480
481         for (i = 0; i < n_regs; ++i) {
482                 unsigned r = reg_prefs[i].num;
483                 /* ignores should be last and we should have a non-ignore left */
484                 assert(!bitset_is_set(ignore_regs, r));
485                 /* already used?
486            TODO: It might be better to copy the value occupying the register around here, find out when... */
487                 if (assignments[r].value != NULL)
488                         continue;
489                 reg = arch_register_for_index(cls, r);
490                 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
491                 use_reg(node, reg);
492                 break;
493         }
494 }
495
496 static void free_reg_of_value(ir_node *node)
497 {
498         allocation_info_t *info;
499         assignment_t      *assignment;
500         unsigned          r;
501
502         if (!arch_irn_consider_in_reg_alloc(cls, node))
503                 return;
504
505         info       = get_allocation_info(node);
506         assignment = info->current_assignment;
507
508         assert(assignment != NULL);
509
510         r = assignment - assignments;
511         DB((dbg, LEVEL_2, "Value %+F ended, freeing %s\n",
512                 node, arch_register_for_index(cls, r)->name));
513         assignment->value        = NULL;
514         info->current_assignment = NULL;
515 }
516
517 /**
518  * Return the index of the currently assigned register of a node.
519  */
520 static unsigned get_current_reg(ir_node *node)
521 {
522         allocation_info_t *info       = get_allocation_info(node);
523         assignment_t      *assignment = info->current_assignment;
524         return assignment - assignments;
525 }
526
527 /**
528  * Return the currently assigned assignment of a node.
529  */
530 static assignment_t *get_current_assignment(ir_node *node)
531 {
532         allocation_info_t *info = get_allocation_info(node);
533         return info->current_assignment;
534 }
535
536 /**
537  * Add an permutation in front of a node and change the assignments
538  * due to this permutation.
539  *
540  * To understand this imagine a permutation like this:
541  *
542  * 1 -> 2
543  * 2 -> 3
544  * 3 -> 1, 5
545  * 4 -> 6
546  * 5
547  * 6
548  * 7 -> 7
549  *
550  * First we count how many destinations a single value has. At the same time
551  * we can be sure that each destination register has at most 1 source register
552  * (it can have 0 which means we don't care what value is in it).
553  * We ignore all fullfilled permuations (like 7->7)
554  * In a first pass we create as much copy instructions as possible as they
555  * are generally cheaper than exchanges. We do this by counting into how many
556  * destinations a register has to be copied (in the example it's 2 for register
557  * 3, or 1 for the registers 1,2,4 and 7).
558  * We can then create a copy into every destination register when the usecount
559  * of that register is 0 (= noone else needs the value in the register).
560  *
561  * After this step we should have cycles left. We implement a cyclic permutation
562  * of n registers with n-1 transpositions.
563  *
564  * @param live_nodes   the set of live nodes, updated due to live range split
565  * @param before       the node before we add the permutation
566  * @param permutation  the permutation array indices are the destination
567  *                     registers, the values in the array are the source
568  *                     registers.
569  */
570 static void permutate_values(ir_nodeset_t *live_nodes, ir_node *before,
571                              unsigned *permutation)
572 {
573         ir_node   *block;
574         ir_node  **ins    = ALLOCANZ(ir_node*, n_regs);
575         unsigned  *n_used = ALLOCANZ(unsigned, n_regs);
576         unsigned   r;
577
578         /* create a list of permutations. Leave out fix points. */
579         for (r = 0; r < n_regs; ++r) {
580                 unsigned      old_reg = permutation[r];
581                 assignment_t *assignment;
582                 ir_node      *value;
583
584                 /* no need to do anything for a fixpoint */
585                 if (old_reg == r)
586                         continue;
587
588                 assignment = &assignments[old_reg];
589                 value      = assignment->value;
590                 if (value == NULL) {
591                         /* nothing to do here, reg is not live. Mark it as fixpoint
592                          * so we ignore it in the next steps */
593                         permutation[r] = r;
594                         continue;
595                 }
596
597                 ins[old_reg] = value;
598                 ++n_used[old_reg];
599
600                 /* free occupation infos, we'll add the values back later */
601                 if (live_nodes != NULL) {
602                         free_reg_of_value(value);
603                         ir_nodeset_remove(live_nodes, value);
604                 }
605         }
606
607         block = get_nodes_block(before);
608
609         /* step1: create copies where immediately possible */
610         for (r = 0; r < n_regs; /* empty */) {
611                 ir_node *copy;
612                 ir_node *src;
613                 const arch_register_t *reg;
614                 unsigned               old_r = permutation[r];
615
616                 /* - no need to do anything for fixed points.
617                    - we can't copy if the value in the dest reg is still needed */
618                 if (old_r == r || n_used[r] > 0) {
619                         ++r;
620                         continue;
621                 }
622
623                 /* create a copy */
624                 src = ins[old_r];
625                 copy = be_new_Copy(cls, block, src);
626                 reg = arch_register_for_index(cls, r);
627                 DB((dbg, LEVEL_2, "Copy %+F (from %+F) -> %s\n", copy, src, reg->name));
628                 link_to(copy, src);
629                 use_reg(copy, reg);
630                 sched_add_before(before, copy);
631
632                 /* old register has 1 user less, permutation is resolved */
633                 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
634                 assert(n_used[old_r] > 0);
635                 --n_used[old_r];
636                 permutation[r] = r;
637
638                 /* advance or jump back (this copy could have enabled another copy) */
639                 if (old_r < r && n_used[old_r] == 0) {
640                         r = old_r;
641                 } else {
642                         ++r;
643                 }
644         }
645
646         /* at this point we only have "cycles" left which we have to resolve with
647          * perm instructions
648          * TODO: if we have free registers left, then we should really use copy
649          * instructions for any cycle longer than 2 registers...
650          * (this is probably architecture dependent, there might be archs where
651          *  copies are preferable even for 2 cycles)
652          */
653
654         /* create perms with the rest */
655         for (r = 0; r < n_regs; /* empty */) {
656                 const arch_register_t *reg;
657                 unsigned  old_r = permutation[r];
658                 unsigned  r2;
659                 ir_node  *in[2];
660                 ir_node  *perm;
661                 ir_node  *proj0;
662                 ir_node  *proj1;
663
664                 if (old_r == r) {
665                         ++r;
666                         continue;
667                 }
668
669                 /* we shouldn't have copies from 1 value to multiple destinations left*/
670                 assert(n_used[old_r] == 1);
671
672                 /* exchange old_r and r2; after that old_r is a fixed point */
673                 r2 = permutation[old_r];
674
675                 in[0] = ins[r2];
676                 in[1] = ins[old_r];
677                 perm = be_new_Perm(cls, block, 2, in);
678
679                 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
680                 link_to(proj0, in[0]);
681                 reg = arch_register_for_index(cls, old_r);
682                 use_reg(proj0, reg);
683
684                 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
685
686                 /* 1 value is now in the correct register */
687                 permutation[old_r] = old_r;
688                 /* the source of r changed to r2 */
689                 permutation[r] = r2;
690                 ins[r2] = in[1];
691                 reg = arch_register_for_index(cls, r2);
692                 if (r == r2) {
693                         /* if we have reached a fixpoint update data structures */
694                         link_to(proj1, in[1]);
695                         use_reg(proj1, reg);
696                 } else {
697                         arch_set_irn_register(proj1, reg);
698                 }
699         }
700
701 #ifdef DEBUG_libfirm
702         /* now we should only have fixpoints left */
703         for (r = 0; r < n_regs; ++r) {
704                 assert(permutation[r] == r);
705         }
706 #endif
707 }
708
709 /**
710  * Free regs for values last used.
711  *
712  * @param live_nodes   set of live nodes, will be updated
713  * @param node         the node to consider
714  */
715 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
716 {
717         allocation_info_t *info  = get_allocation_info(node);
718         int                arity = get_irn_arity(node);
719         int                i;
720         for (i = 0; i < arity; ++i) {
721                 ir_node *op;
722
723                 /* check if one operand is the last use */
724                 if (!rbitset_is_set(&info->last_uses, i))
725                         continue;
726
727                 op = get_irn_n(node, i);
728                 free_reg_of_value(op);
729                 ir_nodeset_remove(live_nodes, op);
730         }
731 }
732
733 /**
734  * Create a bitset of registers occupied with value living through an
735  * instruction
736  */
737 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
738 {
739         const allocation_info_t *info = get_allocation_info(node);
740         unsigned r;
741         int i;
742         int arity;
743
744         /* mark all used registers as potentially live-through */
745         for (r = 0; r < n_regs; ++r) {
746                 const assignment_t *assignment = &assignments[r];
747                 if (assignment->value == NULL)
748                         continue;
749
750                 rbitset_set(bitset, r);
751         }
752
753         /* remove registers of value dying at the instruction */
754         arity = get_irn_arity(node);
755         for (i = 0; i < arity; ++i) {
756                 ir_node               *op;
757                 const arch_register_t *reg;
758
759                 if (!rbitset_is_set(&info->last_uses, i))
760                         continue;
761
762                 op  = get_irn_n(node, i);
763                 reg = arch_get_irn_register(op);
764                 rbitset_clear(bitset, arch_register_get_index(reg));
765         }
766 }
767
768 /**
769  * Enforce constraints at a node by live range splits.
770  *
771  * @param live_nodes  the set of live nodes, might be changed
772  * @param node        the current node
773  */
774 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node)
775 {
776         int arity = get_irn_arity(node);
777         int i, dummy, res;
778         hungarian_problem_t *bp;
779         unsigned l, r, p;
780         unsigned *assignment;
781
782         /* see if any use constraints are not met */
783         bool good = true;
784         for (i = 0; i < arity; ++i) {
785                 ir_node                   *op = get_irn_n(node, i);
786                 const arch_register_req_t *req;
787                 const unsigned            *limited;
788                 unsigned                  r;
789
790                 if (!arch_irn_consider_in_reg_alloc(cls, op))
791                         continue;
792
793                 /* are there any limitations for the i'th operand? */
794                 req = arch_get_register_req(node, i);
795                 if ((req->type & arch_register_req_type_limited) == 0)
796                         continue;
797
798                 limited = req->limited;
799                 r       = get_current_reg(op);
800                 if (!rbitset_is_set(limited, r)) {
801                         /* found an assignement outside the limited set */
802                         good = false;
803                         break;
804                 }
805         }
806
807         /* construct a list of register occupied by live-through values */
808         unsigned *live_through_regs = NULL;
809         unsigned *output_regs       = NULL;
810
811         /* is any of the live-throughs using a constrainted output register? */
812         if (get_irn_mode(node) == mode_T) {
813                 const ir_edge_t *edge;
814
815                 foreach_out_edge(node, edge) {
816                         ir_node *proj = get_edge_src_irn(edge);
817                         const arch_register_req_t *req;
818
819                         if (!arch_irn_consider_in_reg_alloc(cls, proj))
820                                 continue;
821
822                         req = arch_get_register_req_out(proj);
823                         if (! (req->type & arch_register_req_type_limited))
824                                 continue;
825
826                         if (live_through_regs == NULL) {
827                                 rbitset_alloca(live_through_regs, n_regs);
828                                 determine_live_through_regs(live_through_regs, node);
829
830                                 rbitset_alloca(output_regs, n_regs);
831                         }
832
833                         rbitset_or(output_regs, req->limited, n_regs);
834                         if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
835                                 good = false;
836                                 break;
837                         }
838                 }
839         } else {
840                 if (arch_irn_consider_in_reg_alloc(cls, node)) {
841                         const arch_register_req_t *req = arch_get_register_req_out(node);
842                         if (req->type & arch_register_req_type_limited) {
843                                 rbitset_alloca(live_through_regs, n_regs);
844                                 determine_live_through_regs(live_through_regs, node);
845                                 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
846                                         good = false;
847
848                                         rbitset_alloca(output_regs, n_regs);
849                                         rbitset_or(output_regs, req->limited, n_regs);
850                                 }
851                         }
852                 }
853         }
854
855         if (good)
856                 return;
857
858         if (live_through_regs == NULL) {
859                 rbitset_alloca(live_through_regs, n_regs);
860                 rbitset_alloca(output_regs, n_regs);
861         }
862
863         /* swap values around */
864         bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
865
866         /* add all combinations, then remove not allowed ones */
867         for (l = 0; l < n_regs; ++l) {
868                 if (bitset_is_set(ignore_regs, l)) {
869                         hungarian_add(bp, l, l, 90);
870                         continue;
871                 }
872
873                 for (r = 0; r < n_regs; ++r) {
874                         if (bitset_is_set(ignore_regs, r))
875                                 continue;
876                         /* livethrough values may not use constrainted output registers */
877                         if (rbitset_is_set(live_through_regs, l)
878                                         && rbitset_is_set(output_regs, r))
879                                 continue;
880
881                         hungarian_add(bp, l, r, l == r ? 90 : 89);
882                 }
883         }
884
885         for (i = 0; i < arity; ++i) {
886                 ir_node                   *op = get_irn_n(node, i);
887                 const arch_register_req_t *req;
888                 const unsigned            *limited;
889                 unsigned                  current_reg;
890
891                 if (!arch_irn_consider_in_reg_alloc(cls, op))
892                         continue;
893
894                 req = arch_get_register_req(node, i);
895                 if ((req->type & arch_register_req_type_limited) == 0)
896                         continue;
897
898                 limited     = req->limited;
899                 current_reg = get_current_reg(op);
900                 for (r = 0; r < n_regs; ++r) {
901                         if (rbitset_is_set(limited, r))
902                                 continue;
903                         hungarian_remv(bp, current_reg, r);
904                 }
905         }
906
907         hungarian_print_costmatrix(bp, 1);
908         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
909
910         assignment = ALLOCAN(unsigned, n_regs);
911         res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
912         assert(res == 0);
913
914         printf("Swap result:");
915         for (p = 0; p < n_regs; ++p) {
916                 printf(" %d", assignment[p]);
917         }
918         printf("\n");
919
920         hungarian_free(bp);
921
922         permutate_values(live_nodes, node, assignment);
923 }
924
925 /** test wether a node @p n is a copy of the value of node @p of */
926 static int is_copy_of(ir_node *n, ir_node *of)
927 {
928         allocation_info_t *of_info;
929
930         if (n == NULL)
931                 return 0;
932
933         if (n == of)
934                 return 1;
935
936         of_info = get_allocation_info(of);
937         if (!irn_visited(n))
938                 return 0;
939
940         return of_info == get_irn_link(n);
941 }
942
943 /** find a value in the end-assignment of a basic block
944  * @returns the index into the assignment array if found
945  *          -1 if not found
946  */
947 static int find_value_in_block_info(block_info_t *info, ir_node *value)
948 {
949         unsigned      r;
950         assignment_t *assignments = info->assignments;
951         for (r = 0; r < n_regs; ++r) {
952                 const assignment_t *assignment = &assignments[r];
953                 if (is_copy_of(assignment->value, value))
954                         return (int) r;
955         }
956
957         return -1;
958 }
959
960 /**
961  * Create the necessary permutations at the end of a basic block to fullfill
962  * the register assignment for phi-nodes in the next block
963  */
964 static void add_phi_permutations(ir_node *block, int p)
965 {
966         unsigned  r;
967         unsigned *permutation;
968         assignment_t *old_assignments;
969         int       need_permutation;
970         ir_node  *node;
971         ir_node  *pred = get_Block_cfgpred_block(block, p);
972
973         block_info_t *pred_info = get_block_info(pred);
974
975         /* predecessor not processed yet? nothing to do */
976         if (!pred_info->processed)
977                 return;
978
979         permutation = ALLOCAN(unsigned, n_regs);
980         for (r = 0; r < n_regs; ++r) {
981                 permutation[r] = r;
982         }
983
984         /* check phi nodes */
985         need_permutation = 0;
986         node = sched_first(block);
987         for ( ; is_Phi(node); node = sched_next(node)) {
988                 const arch_register_t *reg;
989                 int                    regn;
990                 int                    a;
991                 ir_node               *op;
992
993                 if (!arch_irn_consider_in_reg_alloc(cls, node))
994                         continue;
995
996                 op = get_Phi_pred(node, p);
997                 a = find_value_in_block_info(pred_info, op);
998                 assert(a >= 0);
999
1000                 reg = arch_get_irn_register(node);
1001                 regn = arch_register_get_index(reg);
1002                 if (regn != a) {
1003                         permutation[regn] = a;
1004                         need_permutation = 1;
1005                 }
1006         }
1007
1008         old_assignments = assignments;
1009         assignments     = pred_info->assignments;
1010         permutate_values(NULL, be_get_end_of_block_insertion_point(pred),
1011                          permutation);
1012         assignments     = old_assignments;
1013
1014         node = sched_first(block);
1015         for ( ; is_Phi(node); node = sched_next(node)) {
1016                 int                    a;
1017                 ir_node               *op;
1018
1019                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1020                         continue;
1021
1022                 op = get_Phi_pred(node, p);
1023                 /* TODO: optimize */
1024                 a = find_value_in_block_info(pred_info, op);
1025                 assert(a >= 0);
1026
1027                 op = pred_info->assignments[a].value;
1028                 set_Phi_pred(node, p, op);
1029         }
1030 }
1031
1032 /**
1033  * Walker: assign registers to all nodes of a block that
1034  * needs registers from the currently considered register class.
1035  */
1036 static void allocate_coalesce_block(ir_node *block, void *data)
1037 {
1038         int                    i;
1039         unsigned               r;
1040         ir_nodeset_t           live_nodes;
1041         ir_nodeset_iterator_t  iter;
1042         ir_node               *node, *start;
1043         int                    n_preds;
1044         block_info_t          *block_info;
1045         block_info_t         **pred_block_infos;
1046
1047         (void) data;
1048         DB((dbg, LEVEL_2, "Allocating in block %+F\n",
1049                 block));
1050
1051         /* clear assignments */
1052         block_info  = get_block_info(block);
1053         assignments = block_info->assignments;
1054
1055         for (r = 0; r < n_regs; ++r) {
1056                 assignment_t       *assignment = &assignments[r];
1057                 ir_node            *value      = assignment->value;
1058                 allocation_info_t  *info;
1059
1060                 if (value == NULL)
1061                         continue;
1062
1063                 info                     = get_allocation_info(value);
1064                 info->current_assignment = assignment;
1065         }
1066
1067         ir_nodeset_init(&live_nodes);
1068
1069         /* gather regalloc infos of predecessor blocks */
1070         n_preds = get_Block_n_cfgpreds(block);
1071         pred_block_infos = ALLOCAN(block_info_t*, n_preds);
1072         for (i = 0; i < n_preds; ++i) {
1073                 ir_node *pred = get_Block_cfgpred_block(block, i);
1074                 pred_block_infos[i] = get_block_info(pred);
1075         }
1076
1077         /* collect live-in nodes and preassigned values */
1078         be_lv_foreach(lv, block, be_lv_state_in, i) {
1079                 const arch_register_t *reg;
1080
1081                 node = be_lv_get_irn(lv, block, i);
1082                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1083                         continue;
1084
1085                 /* remember that this node is live at the beginning of the block */
1086                 ir_nodeset_insert(&live_nodes, node);
1087
1088                 /* if the node already has a register assigned use it */
1089                 reg = arch_get_irn_register(node);
1090                 if (reg != NULL) {
1091                         /* TODO: consult pred-block infos here. The value could be copied
1092                            away in some/all predecessor blocks. We need to construct
1093                            phi-nodes in this case.
1094                            We even need to construct some Phi_0 like constructs in cases
1095                            where the predecessor allocation is not determined yet. */
1096                         use_reg(node, reg);
1097                 }
1098         }
1099
1100         /* handle phis... */
1101         node = sched_first(block);
1102         for ( ; is_Phi(node); node = sched_next(node)) {
1103                 const arch_register_t *reg;
1104
1105                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1106                         continue;
1107
1108                 /* fill in regs already assigned */
1109                 reg = arch_get_irn_register(node);
1110                 if (reg != NULL) {
1111                         use_reg(node, reg);
1112                 } else {
1113                         /* TODO: give boni for registers already assigned at the
1114                            predecessors */
1115                         assign_reg(block, node);
1116                 }
1117         }
1118         start = node;
1119
1120         /* assign regs for live-in values */
1121         foreach_ir_nodeset(&live_nodes, node, iter) {
1122                 const arch_register_t *reg = arch_get_irn_register(node);
1123                 if (reg != NULL)
1124                         continue;
1125
1126                 assign_reg(block, node);
1127         }
1128
1129         /* permutate values at end of predecessor blocks in case of phi-nodes */
1130         if (n_preds > 1) {
1131                 int p;
1132                 for (p = 0; p < n_preds; ++p) {
1133                         add_phi_permutations(block, p);
1134                 }
1135         }
1136
1137         /* assign instructions in the block */
1138         for (node = start; !sched_is_end(node); node = sched_next(node)) {
1139                 int arity = get_irn_arity(node);
1140                 int i;
1141
1142                 /* enforce use constraints */
1143                 enforce_constraints(&live_nodes, node);
1144
1145                 /* exchange values to copied values where needed */
1146                 for (i = 0; i < arity; ++i) {
1147                         ir_node      *op = get_irn_n(node, i);
1148                         assignment_t *assignment;
1149
1150                         if (!arch_irn_consider_in_reg_alloc(cls, op))
1151                                 continue;
1152                         assignment = get_current_assignment(op);
1153                         assert(assignment != NULL);
1154                         if (op != assignment->value) {
1155                                 set_irn_n(node, i, assignment->value);
1156                         }
1157                 }
1158
1159                 /* free registers of values last used at this instruction */
1160                 free_last_uses(&live_nodes, node);
1161
1162                 /* assign output registers */
1163                 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1164                 if (get_irn_mode(node) == mode_T) {
1165                         const ir_edge_t *edge;
1166                         foreach_out_edge(node, edge) {
1167                                 ir_node *proj = get_edge_src_irn(edge);
1168                                 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1169                                         continue;
1170                                 assign_reg(block, proj);
1171                         }
1172                 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1173                         assign_reg(block, node);
1174                 }
1175         }
1176
1177         ir_nodeset_destroy(&live_nodes);
1178         assignments = NULL;
1179
1180         block_info->processed = 1;
1181
1182         /* if we have exactly 1 successor then we might be able to produce phi
1183            copies now */
1184         if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1185                 const ir_edge_t *edge
1186                         = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1187                 ir_node      *succ      = get_edge_src_irn(edge);
1188                 int           p         = get_edge_src_pos(edge);
1189                 block_info_t *succ_info = get_block_info(succ);
1190
1191                 if (succ_info->processed) {
1192                         add_phi_permutations(succ, p);
1193                 }
1194         }
1195 }
1196
1197 /**
1198  * Run the register allocator for the current register class.
1199  */
1200 static void be_straight_alloc_cls(void)
1201 {
1202         n_regs         = arch_register_class_n_regs(cls);
1203         lv             = be_assure_liveness(birg);
1204         be_liveness_assure_sets(lv);
1205         be_liveness_assure_chk(lv);
1206
1207         assignments = NULL;
1208
1209         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1210         inc_irg_visited(irg);
1211
1212         DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1213
1214         irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1215         irg_block_walk_graph(irg, NULL, allocate_coalesce_block, NULL);
1216
1217         ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1218 }
1219
1220 /**
1221  * Run the spiller on the current graph.
1222  */
1223 static void spill(void)
1224 {
1225         /* make sure all nodes show their real register pressure */
1226         BE_TIMER_PUSH(t_ra_constr);
1227         be_pre_spill_prepare_constr(birg, cls);
1228         BE_TIMER_POP(t_ra_constr);
1229
1230         /* spill */
1231         BE_TIMER_PUSH(t_ra_spill);
1232         be_do_spill(birg, cls);
1233         BE_TIMER_POP(t_ra_spill);
1234
1235         BE_TIMER_PUSH(t_ra_spill_apply);
1236         check_for_memory_operands(irg);
1237         BE_TIMER_POP(t_ra_spill_apply);
1238 }
1239
1240 /**
1241  * The straight register allocator for a whole procedure.
1242  */
1243 static void be_straight_alloc(be_irg_t *new_birg)
1244 {
1245         const arch_env_t *arch_env = new_birg->main_env->arch_env;
1246         int   n_cls                = arch_env_get_n_reg_class(arch_env);
1247         int   c;
1248
1249         obstack_init(&obst);
1250
1251         birg      = new_birg;
1252         irg       = be_get_birg_irg(birg);
1253         execfreqs = birg->exec_freq;
1254
1255         /* TODO: extract some of the stuff from bechordal allocator, like
1256          * statistics, time measurements, etc. and use them here too */
1257
1258         for (c = 0; c < n_cls; ++c) {
1259                 cls = arch_env_get_reg_class(arch_env, c);
1260                 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1261                         continue;
1262
1263                 stat_ev_ctx_push_str("bestraight_cls", cls->name);
1264
1265                 n_regs      = cls->n_regs;
1266                 ignore_regs = bitset_malloc(n_regs);
1267                 be_put_ignore_regs(birg, cls, ignore_regs);
1268
1269                 spill();
1270
1271                 /* verify schedule and register pressure */
1272                 BE_TIMER_PUSH(t_verify);
1273                 if (birg->main_env->options->vrfy_option == BE_CH_VRFY_WARN) {
1274                         be_verify_schedule(birg);
1275                         be_verify_register_pressure(birg, cls, irg);
1276                 } else if (birg->main_env->options->vrfy_option == BE_CH_VRFY_ASSERT) {
1277                         assert(be_verify_schedule(birg) && "Schedule verification failed");
1278                         assert(be_verify_register_pressure(birg, cls, irg)
1279                                 && "Register pressure verification failed");
1280                 }
1281                 BE_TIMER_POP(t_verify);
1282
1283                 BE_TIMER_PUSH(t_ra_color);
1284                 be_straight_alloc_cls();
1285                 BE_TIMER_POP(t_ra_color);
1286
1287                 bitset_free(ignore_regs);
1288
1289                 stat_ev_ctx_pop("bestraight_cls");
1290         }
1291
1292         BE_TIMER_PUSH(t_verify);
1293         if (birg->main_env->options->vrfy_option == BE_CH_VRFY_WARN) {
1294                 be_verify_register_allocation(birg);
1295         } else if(birg->main_env->options->vrfy_option == BE_CH_VRFY_ASSERT) {
1296                 assert(be_verify_register_allocation(birg)
1297                                 && "Register allocation invalid");
1298         }
1299         BE_TIMER_POP(t_verify);
1300
1301         obstack_free(&obst, NULL);
1302 }
1303
1304 /**
1305  * Initializes this module.
1306  */
1307 void be_init_straight_alloc(void)
1308 {
1309         static be_ra_t be_ra_straight = {
1310                 be_straight_alloc,
1311         };
1312
1313         FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
1314
1315         be_register_allocator("straight", &be_ra_straight);
1316 }
1317
1318 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);