Add OALLOC*() to make allocating from obstacks a bit nicer.
[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 permute_values code
43  *  - think about a smarter sequence of visiting the blocks. Sorted by
44  *    execfreq might be good, or looptree from inner to outermost loops going
45  *    over blocks in a reverse postorder
46  *  - propagate preferences through Phis
47  */
48 #include "config.h"
49
50 #include <float.h>
51 #include <stdbool.h>
52
53 #include "error.h"
54 #include "execfreq.h"
55 #include "ircons.h"
56 #include "irdom.h"
57 #include "iredges_t.h"
58 #include "irgraph_t.h"
59 #include "irgwalk.h"
60 #include "irnode_t.h"
61 #include "obst.h"
62 #include "raw_bitset.h"
63
64 #include "beabi.h"
65 #include "bechordal_t.h"
66 #include "be.h"
67 #include "beirg.h"
68 #include "belive_t.h"
69 #include "bemodule.h"
70 #include "benode_t.h"
71 #include "bera.h"
72 #include "besched.h"
73 #include "bespill.h"
74 #include "bespillutil.h"
75 #include "beverify.h"
76
77 #include "hungarian.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
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 const arch_register_req_t   *default_cls_req;
93 static be_lv_t                     *lv;
94 static const ir_exec_freq          *execfreqs;
95 static unsigned                     n_regs;
96 static unsigned                    *normal_regs;
97
98 /** currently active assignments (while processing a basic block)
99  * maps registers to values(their current copies) */
100 static ir_node **assignments;
101
102 /**
103  * allocation information: last_uses, register preferences
104  * the information is per firm-node.
105  */
106 struct allocation_info_t {
107         unsigned  last_uses;      /**< bitset indicating last uses (input pos) */
108         ir_node  *current_value;  /**< copy of the value that should be used */
109         ir_node  *original_value; /**< for copies point to original value */
110         float     prefs[0];       /**< register preferences */
111 };
112 typedef struct allocation_info_t allocation_info_t;
113
114 /** helper datastructure used when sorting register preferences */
115 struct reg_pref_t {
116         unsigned num;
117         float    pref;
118 };
119 typedef struct reg_pref_t reg_pref_t;
120
121 /** per basic-block information */
122 struct block_info_t {
123         bool     processed;       /**< indicate wether block is processed */
124         ir_node *assignments[0];  /**< register assignments at end of block */
125 };
126 typedef struct block_info_t block_info_t;
127
128 /**
129  * Get the allocation info for a node.
130  * The info is allocated on the first visit of a node.
131  */
132 static allocation_info_t *get_allocation_info(ir_node *node)
133 {
134         allocation_info_t *info;
135         if (!irn_visited_else_mark(node)) {
136                 info = OALLOCFZ(&obst, allocation_info_t, prefs, n_regs);
137                 info->current_value  = node;
138                 info->original_value = node;
139                 set_irn_link(node, info);
140         } else {
141                 info = get_irn_link(node);
142         }
143
144         return info;
145 }
146
147 /**
148  * Get allocation information for a basic block
149  */
150 static block_info_t *get_block_info(ir_node *block)
151 {
152         block_info_t *info;
153
154         assert(is_Block(block));
155         if (!irn_visited_else_mark(block)) {
156                 info = OALLOCFZ(&obst, block_info_t, assignments, n_regs);
157                 set_irn_link(block, info);
158         } else {
159                 info = get_irn_link(block);
160         }
161
162         return info;
163 }
164
165 /**
166  * Get default register requirement for the current register class
167  */
168 static const arch_register_req_t *get_default_req_current_cls(void)
169 {
170         if (default_cls_req == NULL) {
171                 struct obstack      *obst = get_irg_obstack(irg);
172                 arch_register_req_t *req  = OALLOCZ(obst, arch_register_req_t);
173
174                 req->type = arch_register_req_type_normal;
175                 req->cls  = cls;
176
177                 default_cls_req = req;
178         }
179         return default_cls_req;
180 }
181
182 /**
183  * Link the allocation info of a node to a copy.
184  * Afterwards, both nodes uses the same allocation info.
185  * Copy must not have an allocation info assigned yet.
186  *
187  * @param copy   the node that gets the allocation info assigned
188  * @param value  the original node
189  */
190 static void mark_as_copy_of(ir_node *copy, ir_node *value)
191 {
192         ir_node           *original;
193         allocation_info_t *info      = get_allocation_info(value);
194         allocation_info_t *copy_info = get_allocation_info(copy);
195
196         /* find original value */
197         original = info->original_value;
198         if (original != value) {
199                 info = get_allocation_info(original);
200         }
201
202         assert(info->original_value == original);
203         info->current_value = copy;
204
205         /* the copy should not be linked to something else yet */
206         assert(copy_info->original_value == copy);
207         /* copy over allocation preferences */
208         memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
209         copy_info->original_value = original;
210 }
211
212 /**
213  * Calculate the penalties for every register on a node and its live neighbors.
214  *
215  * @param live_nodes  the set of live nodes at the current position, may be NULL
216  * @param penalty     the penalty to subtract from
217  * @param limited     a raw bitset containing the limited set for the node
218  * @param node        the node
219  */
220 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
221                                       float penalty, const unsigned* limited,
222                                       ir_node *node)
223 {
224         ir_nodeset_iterator_t iter;
225         unsigned              r;
226         allocation_info_t     *info = get_allocation_info(node);
227         ir_node               *neighbor;
228
229         /* give penalty for all forbidden regs */
230         for (r = 0; r < n_regs; ++r) {
231                 if (rbitset_is_set(limited, r))
232                         continue;
233
234                 info->prefs[r] -= penalty;
235         }
236
237         /* all other live values should get a penalty for allowed regs */
238         if (live_nodes == NULL)
239                 return;
240
241         /* TODO: reduce penalty if there are multiple allowed registers... */
242         penalty *= NEIGHBOR_FACTOR;
243         foreach_ir_nodeset(live_nodes, neighbor, iter) {
244                 allocation_info_t *neighbor_info;
245
246                 /* TODO: if op is used on multiple inputs we might not do a
247                  * continue here */
248                 if (neighbor == node)
249                         continue;
250
251                 neighbor_info = get_allocation_info(neighbor);
252                 for (r = 0; r < n_regs; ++r) {
253                         if (!rbitset_is_set(limited, r))
254                                 continue;
255
256                         neighbor_info->prefs[r] -= penalty;
257                 }
258         }
259 }
260
261 /**
262  * Calculate the preferences of a definition for the current register class.
263  * If the definition uses a limited set of registers, reduce the preferences
264  * for the limited register on the node and its neighbors.
265  *
266  * @param live_nodes  the set of live nodes at the current node
267  * @param weight      the weight
268  * @param node        the current node
269  */
270 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
271                        ir_node *node)
272 {
273         const arch_register_req_t *req;
274
275         if (get_irn_mode(node) == mode_T) {
276                 const ir_edge_t *edge;
277                 foreach_out_edge(node, edge) {
278                         ir_node *proj = get_edge_src_irn(edge);
279                         check_defs(live_nodes, weight, proj);
280                 }
281                 return;
282         }
283
284         if (!arch_irn_consider_in_reg_alloc(cls, node))
285                 return;
286
287         req = arch_get_register_req_out(node);
288         if (req->type & arch_register_req_type_limited) {
289                 const unsigned *limited = req->limited;
290                 float           penalty = weight * DEF_FACTOR;
291                 give_penalties_for_limits(live_nodes, penalty, limited, node);
292         }
293
294         if (req->type & arch_register_req_type_should_be_same) {
295                 ir_node           *insn  = skip_Proj(node);
296                 allocation_info_t *info  = get_allocation_info(node);
297                 int                arity = get_irn_arity(insn);
298                 int                i;
299
300                 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
301                 for (i = 0; i < arity; ++i) {
302                         ir_node           *op;
303                         unsigned           r;
304                         allocation_info_t *op_info;
305
306                         if (!rbitset_is_set(&req->other_same, i))
307                                 continue;
308
309                         op = get_irn_n(insn, i);
310
311                         /* if we the value at the should_be_same input doesn't die at the
312                          * node, then it is no use to propagate the constraints (since a
313                          * copy will emerge anyway) */
314                         if (ir_nodeset_contains(live_nodes, op))
315                                 continue;
316
317                         op_info = get_allocation_info(op);
318                         for (r = 0; r < n_regs; ++r) {
319                                 op_info->prefs[r] += info->prefs[r] * factor;
320                         }
321                 }
322         }
323 }
324
325 /**
326  * Walker: Runs an a block calculates the preferences for any
327  * node and every register from the considered register class.
328  */
329 static void analyze_block(ir_node *block, void *data)
330 {
331         float         weight = get_block_execfreq(execfreqs, block);
332         ir_nodeset_t  live_nodes;
333         ir_node      *node;
334         (void) data;
335
336         ir_nodeset_init(&live_nodes);
337         be_liveness_end_of_block(lv, cls, block, &live_nodes);
338
339         sched_foreach_reverse(block, node) {
340                 allocation_info_t *info;
341                 int                i;
342                 int                arity;
343
344                 if (is_Phi(node))
345                         break;
346
347                 check_defs(&live_nodes, weight, node);
348
349                 /* mark last uses */
350                 arity = get_irn_arity(node);
351
352                 /* the allocation info node currently only uses 1 unsigned value
353                    to mark last used inputs. So we will fail for a node with more than
354                    32 inputs. */
355                 if (arity >= (int) sizeof(unsigned) * 8) {
356                         panic("Node with more than %d inputs not supported yet",
357                                         (int) sizeof(unsigned) * 8);
358                 }
359
360                 info = get_allocation_info(node);
361                 for (i = 0; i < arity; ++i) {
362                         ir_node *op = get_irn_n(node, i);
363                         if (!arch_irn_consider_in_reg_alloc(cls, op))
364                                 continue;
365
366                         /* last usage of a value? */
367                         if (!ir_nodeset_contains(&live_nodes, op)) {
368                                 rbitset_set(&info->last_uses, i);
369                         }
370                 }
371
372                 be_liveness_transfer(cls, node, &live_nodes);
373
374                 /* update weights based on usage constraints */
375                 for (i = 0; i < arity; ++i) {
376                         const arch_register_req_t *req;
377                         const unsigned            *limited;
378                         ir_node                   *op = get_irn_n(node, i);
379
380                         if (!arch_irn_consider_in_reg_alloc(cls, op))
381                                 continue;
382
383                         req = arch_get_register_req(node, i);
384                         if (!(req->type & arch_register_req_type_limited))
385                                 continue;
386
387                         limited = req->limited;
388                         give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
389                                                   op);
390                 }
391         }
392
393         ir_nodeset_destroy(&live_nodes);
394 }
395
396 /**
397  * Assign register reg to the given node.
398  *
399  * @param node  the node
400  * @param reg   the register
401  */
402 static void use_reg(ir_node *node, const arch_register_t *reg)
403 {
404         unsigned r = arch_register_get_index(reg);
405         assignments[r] = node;
406         arch_set_irn_register(node, reg);
407 }
408
409 static void free_reg_of_value(ir_node *node)
410 {
411         const arch_register_t *reg;
412         unsigned               r;
413
414         if (!arch_irn_consider_in_reg_alloc(cls, node))
415                 return;
416
417         reg        = arch_get_irn_register(node);
418         r          = arch_register_get_index(reg);
419         /* assignment->value may be NULL if a value is used at 2 inputs
420            so it gets freed twice. */
421         assert(assignments[r] == node || assignments[r] == NULL);
422         assignments[r] = NULL;
423 }
424
425 /**
426  * Compare two register preferences in decreasing order.
427  */
428 static int compare_reg_pref(const void *e1, const void *e2)
429 {
430         const reg_pref_t *rp1 = (const reg_pref_t*) e1;
431         const reg_pref_t *rp2 = (const reg_pref_t*) e2;
432         if (rp1->pref < rp2->pref)
433                 return 1;
434         if (rp1->pref > rp2->pref)
435                 return -1;
436         return 0;
437 }
438
439 static void fill_sort_candidates(reg_pref_t *regprefs,
440                                  const allocation_info_t *info)
441 {
442         unsigned r;
443
444         for (r = 0; r < n_regs; ++r) {
445                 float pref = info->prefs[r];
446                 regprefs[r].num  = r;
447                 regprefs[r].pref = pref;
448         }
449         /* TODO: use a stable sort here to avoid unnecessary register jumping */
450         qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
451 }
452
453 static bool try_optimistic_split(ir_node *to_split, ir_node *before,
454                                  float pref, float pref_delta,
455                                  unsigned *output_regs)
456 {
457         const arch_register_t *reg;
458         ir_node               *block;
459         ir_node               *copy;
460         unsigned               r;
461         unsigned               i;
462         allocation_info_t     *info = get_allocation_info(to_split);
463         reg_pref_t            *prefs;
464         float                  delta;
465
466         (void) pref;
467
468         /* find the best free position where we could move to */
469         prefs = ALLOCAN(reg_pref_t, n_regs);
470         fill_sort_candidates(prefs, info);
471         for (i = 0; i < n_regs; ++i) {
472                 r = prefs[i].num;
473                 if (!rbitset_is_set(normal_regs, r))
474                         continue;
475                 if (rbitset_is_set(output_regs, r))
476                         continue;
477                 if (assignments[r] == NULL)
478                         break;
479         }
480         if (i >= n_regs) {
481                 return false;
482         }
483         /* TODO: use execfreq somehow... */
484         delta = pref_delta + prefs[i].pref;
485         if (delta < SPLIT_DELTA) {
486                 DB((dbg, LEVEL_3, "Not doing optimistical split, win %f too low\n",
487                     delta));
488                 return false;
489         }
490
491         reg   = arch_register_for_index(cls, r);
492         block = get_nodes_block(before);
493         copy = be_new_Copy(cls, block, to_split);
494         mark_as_copy_of(copy, to_split);
495         free_reg_of_value(to_split);
496         use_reg(copy, reg);
497         sched_add_before(before, copy);
498
499         DB((dbg, LEVEL_3,
500             "Optimistic live-range split %+F move %+F -> %s before %+F (win %f)\n",
501             copy, to_split, reg->name, before, delta));
502         return true;
503 }
504
505 /**
506  * Determine and assign a register for node @p node
507  */
508 static void assign_reg(const ir_node *block, ir_node *node,
509                        unsigned *output_regs)
510 {
511         const arch_register_t     *reg;
512         allocation_info_t         *info;
513         const arch_register_req_t *req;
514         reg_pref_t                *reg_prefs;
515         ir_node                   *in_node;
516         unsigned                   i;
517         const unsigned            *allowed_regs;
518         unsigned                   r;
519
520         assert(arch_irn_consider_in_reg_alloc(cls, node));
521
522         /* preassigned register? */
523         reg = arch_get_irn_register(node);
524         if (reg != NULL) {
525                 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
526                 use_reg(node, reg);
527                 return;
528         }
529
530         /* give should_be_same boni */
531         info = get_allocation_info(node);
532         req  = arch_get_register_req_out(node);
533
534         in_node = skip_Proj(node);
535         if (req->type & arch_register_req_type_should_be_same) {
536                 float weight = get_block_execfreq(execfreqs, block);
537                 int   arity  = get_irn_arity(in_node);
538                 int   i;
539
540                 assert(arity <= (int) sizeof(req->other_same) * 8);
541                 for (i = 0; i < arity; ++i) {
542                         ir_node               *in;
543                         const arch_register_t *reg;
544                         unsigned               r;
545                         if (!rbitset_is_set(&req->other_same, i))
546                                 continue;
547
548                         in  = get_irn_n(in_node, i);
549                         reg = arch_get_irn_register(in);
550                         assert(reg != NULL);
551                         r = arch_register_get_index(reg);
552
553                         /* if the value didn't die here then we should not propagate the
554                          * should_be_same info */
555                         if (assignments[r] == in)
556                                 continue;
557
558                         info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
559                 }
560         }
561
562         /* create list of register candidates and sort by their preference */
563         DB((dbg, LEVEL_2, "Candidates for %+F:", node));
564         reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
565         fill_sort_candidates(reg_prefs, info);
566         for (i = 0; i < n_regs; ++i) {
567                 unsigned num = reg_prefs[i].num;
568                 const arch_register_t *reg;
569
570                 if (!rbitset_is_set(normal_regs, num))
571                         continue;
572
573                 reg = arch_register_for_index(cls, num);
574                 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
575         }
576         DB((dbg, LEVEL_2, "\n"));
577
578         allowed_regs = normal_regs;
579         if (req->type & arch_register_req_type_limited) {
580                 allowed_regs = req->limited;
581         }
582
583         for (i = 0; i < n_regs; ++i) {
584                 r = reg_prefs[i].num;
585                 if (!rbitset_is_set(allowed_regs, r))
586                         continue;
587                 if (assignments[r] == NULL)
588                         break;
589                 if (!is_Phi(node)) {
590                         float    pref   = reg_prefs[i].pref;
591                         float    delta  = i+1 < n_regs ? pref - reg_prefs[i+1].pref : 0;
592                         ir_node *before = skip_Proj(node);
593                         bool     res    = try_optimistic_split(assignments[r], before,
594                                                                pref, delta,
595                                                                output_regs);
596                         if (res)
597                                 break;
598                 }
599         }
600         if (i >= n_regs) {
601                 panic("No register left for %+F\n", node);
602         }
603
604         reg = arch_register_for_index(cls, r);
605         DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
606         use_reg(node, reg);
607 }
608
609 /**
610  * Add an permutation in front of a node and change the assignments
611  * due to this permutation.
612  *
613  * To understand this imagine a permutation like this:
614  *
615  * 1 -> 2
616  * 2 -> 3
617  * 3 -> 1, 5
618  * 4 -> 6
619  * 5
620  * 6
621  * 7 -> 7
622  *
623  * First we count how many destinations a single value has. At the same time
624  * we can be sure that each destination register has at most 1 source register
625  * (it can have 0 which means we don't care what value is in it).
626  * We ignore all fullfilled permuations (like 7->7)
627  * In a first pass we create as much copy instructions as possible as they
628  * are generally cheaper than exchanges. We do this by counting into how many
629  * destinations a register has to be copied (in the example it's 2 for register
630  * 3, or 1 for the registers 1,2,4 and 7).
631  * We can then create a copy into every destination register when the usecount
632  * of that register is 0 (= noone else needs the value in the register).
633  *
634  * After this step we should have cycles left. We implement a cyclic permutation
635  * of n registers with n-1 transpositions.
636  *
637  * @param live_nodes   the set of live nodes, updated due to live range split
638  * @param before       the node before we add the permutation
639  * @param permutation  the permutation array indices are the destination
640  *                     registers, the values in the array are the source
641  *                     registers.
642  */
643 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
644                              unsigned *permutation)
645 {
646         unsigned  *n_used = ALLOCANZ(unsigned, n_regs);
647         ir_node   *block;
648         unsigned   r;
649
650         /* determine how often each source register needs to be read */
651         for (r = 0; r < n_regs; ++r) {
652                 unsigned  old_reg = permutation[r];
653                 ir_node  *value;
654
655                 value = assignments[old_reg];
656                 if (value == NULL) {
657                         /* nothing to do here, reg is not live. Mark it as fixpoint
658                          * so we ignore it in the next steps */
659                         permutation[r] = r;
660                         continue;
661                 }
662
663                 ++n_used[old_reg];
664         }
665
666         block = get_nodes_block(before);
667
668         /* step1: create copies where immediately possible */
669         for (r = 0; r < n_regs; /* empty */) {
670                 ir_node *copy;
671                 ir_node *src;
672                 const arch_register_t *reg;
673                 unsigned               old_r = permutation[r];
674
675                 /* - no need to do anything for fixed points.
676                    - we can't copy if the value in the dest reg is still needed */
677                 if (old_r == r || n_used[r] > 0) {
678                         ++r;
679                         continue;
680                 }
681
682                 /* create a copy */
683                 src  = assignments[old_r];
684                 copy = be_new_Copy(cls, block, src);
685                 sched_add_before(before, copy);
686                 reg = arch_register_for_index(cls, r);
687                 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
688                     copy, src, before, reg->name));
689                 mark_as_copy_of(copy, src);
690                 use_reg(copy, reg);
691
692                 if (live_nodes != NULL) {
693                         ir_nodeset_insert(live_nodes, copy);
694                 }
695
696                 /* old register has 1 user less, permutation is resolved */
697                 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
698                 permutation[r] = r;
699
700                 assert(n_used[old_r] > 0);
701                 --n_used[old_r];
702                 if (n_used[old_r] == 0) {
703                         if (live_nodes != NULL) {
704                                 ir_nodeset_remove(live_nodes, src);
705                         }
706                         free_reg_of_value(src);
707                 }
708
709                 /* advance or jump back (if this copy enabled another copy) */
710                 if (old_r < r && n_used[old_r] == 0) {
711                         r = old_r;
712                 } else {
713                         ++r;
714                 }
715         }
716
717         /* at this point we only have "cycles" left which we have to resolve with
718          * perm instructions
719          * TODO: if we have free registers left, then we should really use copy
720          * instructions for any cycle longer than 2 registers...
721          * (this is probably architecture dependent, there might be archs where
722          *  copies are preferable even for 2-cycles) */
723
724         /* create perms with the rest */
725         for (r = 0; r < n_regs; /* empty */) {
726                 const arch_register_t *reg;
727                 unsigned  old_r = permutation[r];
728                 unsigned  r2;
729                 ir_node  *in[2];
730                 ir_node  *perm;
731                 ir_node  *proj0;
732                 ir_node  *proj1;
733
734                 if (old_r == r) {
735                         ++r;
736                         continue;
737                 }
738
739                 /* we shouldn't have copies from 1 value to multiple destinations left*/
740                 assert(n_used[old_r] == 1);
741
742                 /* exchange old_r and r2; after that old_r is a fixed point */
743                 r2 = permutation[old_r];
744
745                 in[0] = assignments[r2];
746                 in[1] = assignments[old_r];
747                 perm = be_new_Perm(cls, block, 2, in);
748                 sched_add_before(before, perm);
749                 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
750                     perm, in[0], in[1], before));
751
752                 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
753                 mark_as_copy_of(proj0, in[0]);
754                 reg = arch_register_for_index(cls, old_r);
755                 use_reg(proj0, reg);
756
757                 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
758                 mark_as_copy_of(proj1, in[1]);
759                 reg = arch_register_for_index(cls, r2);
760                 use_reg(proj1, reg);
761
762                 /* 1 value is now in the correct register */
763                 permutation[old_r] = old_r;
764                 /* the source of r changed to r2 */
765                 permutation[r] = r2;
766
767                 /* if we have reached a fixpoint update data structures */
768                 if (live_nodes != NULL) {
769                         ir_nodeset_remove(live_nodes, in[0]);
770                         ir_nodeset_remove(live_nodes, in[1]);
771                         ir_nodeset_remove(live_nodes, proj0);
772                         ir_nodeset_insert(live_nodes, proj1);
773                 }
774         }
775
776 #ifdef DEBUG_libfirm
777         /* now we should only have fixpoints left */
778         for (r = 0; r < n_regs; ++r) {
779                 assert(permutation[r] == r);
780         }
781 #endif
782 }
783
784 /**
785  * Free regs for values last used.
786  *
787  * @param live_nodes   set of live nodes, will be updated
788  * @param node         the node to consider
789  */
790 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
791 {
792         allocation_info_t     *info      = get_allocation_info(node);
793         const unsigned        *last_uses = &info->last_uses;
794         int                    arity     = get_irn_arity(node);
795         int                    i;
796
797         for (i = 0; i < arity; ++i) {
798                 ir_node *op;
799
800                 /* check if one operand is the last use */
801                 if (!rbitset_is_set(last_uses, i))
802                         continue;
803
804                 op = get_irn_n(node, i);
805                 free_reg_of_value(op);
806                 ir_nodeset_remove(live_nodes, op);
807         }
808 }
809
810 /**
811  * change inputs of a node to the current value (copies/perms)
812  */
813 static void rewire_inputs(ir_node *node)
814 {
815         int i;
816         int arity = get_irn_arity(node);
817
818         for (i = 0; i < arity; ++i) {
819                 ir_node           *op = get_irn_n(node, i);
820                 allocation_info_t *info;
821
822                 if (!arch_irn_consider_in_reg_alloc(cls, op))
823                         continue;
824
825                 info = get_allocation_info(op);
826                 info = get_allocation_info(info->original_value);
827                 if (info->current_value != op) {
828                         set_irn_n(node, i, info->current_value);
829                 }
830         }
831 }
832
833 /**
834  * Create a bitset of registers occupied with value living through an
835  * instruction
836  */
837 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
838 {
839         const allocation_info_t *info = get_allocation_info(node);
840         unsigned r;
841         int i;
842         int arity;
843
844         /* mark all used registers as potentially live-through */
845         for (r = 0; r < n_regs; ++r) {
846                 if (assignments[r] == NULL)
847                         continue;
848                 if (!rbitset_is_set(normal_regs, r))
849                         continue;
850
851                 rbitset_set(bitset, r);
852         }
853
854         /* remove registers of value dying at the instruction */
855         arity = get_irn_arity(node);
856         for (i = 0; i < arity; ++i) {
857                 ir_node               *op;
858                 const arch_register_t *reg;
859
860                 if (!rbitset_is_set(&info->last_uses, i))
861                         continue;
862
863                 op  = get_irn_n(node, i);
864                 reg = arch_get_irn_register(op);
865                 rbitset_clear(bitset, arch_register_get_index(reg));
866         }
867 }
868
869 /**
870  * Enforce constraints at a node by live range splits.
871  *
872  * @param  live_nodes  the set of live nodes, might be changed
873  * @param  node        the current node
874  */
875 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node,
876                                 unsigned *output_regs)
877 {
878         int arity = get_irn_arity(node);
879         int i, dummy, res;
880         hungarian_problem_t *bp;
881         unsigned l, r;
882         unsigned *assignment;
883
884         /* construct a list of register occupied by live-through values */
885         unsigned *live_through_regs = NULL;
886
887         /* see if any use constraints are not met */
888         bool good = true;
889         for (i = 0; i < arity; ++i) {
890                 ir_node                   *op = get_irn_n(node, i);
891                 const arch_register_t     *reg;
892                 const arch_register_req_t *req;
893                 const unsigned            *limited;
894                 unsigned                  r;
895
896                 if (!arch_irn_consider_in_reg_alloc(cls, op))
897                         continue;
898
899                 /* are there any limitations for the i'th operand? */
900                 req = arch_get_register_req(node, i);
901                 if (!(req->type & arch_register_req_type_limited))
902                         continue;
903
904                 limited = req->limited;
905                 reg     = arch_get_irn_register(op);
906                 r       = arch_register_get_index(reg);
907                 if (!rbitset_is_set(limited, r)) {
908                         /* found an assignment outside the limited set */
909                         good = false;
910                         break;
911                 }
912         }
913
914         /* is any of the live-throughs using a constrained output register? */
915         if (get_irn_mode(node) == mode_T) {
916                 const ir_edge_t *edge;
917
918                 foreach_out_edge(node, edge) {
919                         ir_node *proj = get_edge_src_irn(edge);
920                         const arch_register_req_t *req;
921
922                         if (!arch_irn_consider_in_reg_alloc(cls, proj))
923                                 continue;
924
925                         req = arch_get_register_req_out(proj);
926                         if (!(req->type & arch_register_req_type_limited))
927                                 continue;
928
929                         if (live_through_regs == NULL) {
930                                 rbitset_alloca(live_through_regs, n_regs);
931                                 determine_live_through_regs(live_through_regs, node);
932                         }
933
934                         rbitset_or(output_regs, req->limited, n_regs);
935                         if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
936                                 good = false;
937                         }
938                 }
939         } else {
940                 if (arch_irn_consider_in_reg_alloc(cls, node)) {
941                         const arch_register_req_t *req = arch_get_register_req_out(node);
942                         if (req->type & arch_register_req_type_limited) {
943                                 rbitset_alloca(live_through_regs, n_regs);
944                                 determine_live_through_regs(live_through_regs, node);
945                                 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
946                                         good = false;
947                                         rbitset_or(output_regs, req->limited, n_regs);
948                                 }
949                         }
950                 }
951         }
952
953         if (good)
954                 return;
955
956         /* create these arrays if we haven't yet */
957         if (live_through_regs == NULL) {
958                 rbitset_alloca(live_through_regs, n_regs);
959         }
960
961         /* at this point we have to construct a bipartite matching problem to see
962          * which values should go to which registers
963          * Note: We're building the matrix in "reverse" - source registers are
964          *       right, destinations left because this will produce the solution
965          *       in the format required for permute_values.
966          */
967         bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
968
969         /* add all combinations, then remove not allowed ones */
970         for (l = 0; l < n_regs; ++l) {
971                 if (!rbitset_is_set(normal_regs, l)) {
972                         hungarian_add(bp, l, l, 1);
973                         continue;
974                 }
975
976                 for (r = 0; r < n_regs; ++r) {
977                         if (!rbitset_is_set(normal_regs, r))
978                                 continue;
979                         /* livethrough values may not use constrainted output registers */
980                         if (rbitset_is_set(live_through_regs, l)
981                                         && rbitset_is_set(output_regs, r))
982                                 continue;
983
984                         hungarian_add(bp, r, l, l == r ? 9 : 8);
985                 }
986         }
987
988         for (i = 0; i < arity; ++i) {
989                 ir_node                   *op = get_irn_n(node, i);
990                 const arch_register_t     *reg;
991                 const arch_register_req_t *req;
992                 const unsigned            *limited;
993                 unsigned                   current_reg;
994
995                 if (!arch_irn_consider_in_reg_alloc(cls, op))
996                         continue;
997
998                 req = arch_get_register_req(node, i);
999                 if (!(req->type & arch_register_req_type_limited))
1000                         continue;
1001
1002                 limited     = req->limited;
1003                 reg         = arch_get_irn_register(op);
1004                 current_reg = arch_register_get_index(reg);
1005                 for (r = 0; r < n_regs; ++r) {
1006                         if (rbitset_is_set(limited, r))
1007                                 continue;
1008                         hungarian_remv(bp, r, current_reg);
1009                 }
1010         }
1011
1012         //hungarian_print_costmatrix(bp, 1);
1013         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1014
1015         assignment = ALLOCAN(unsigned, n_regs);
1016         res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
1017         assert(res == 0);
1018
1019 #if 0
1020         fprintf(stderr, "Swap result:");
1021         for (i = 0; i < (int) n_regs; ++i) {
1022                 fprintf(stderr, " %d", assignment[i]);
1023         }
1024         fprintf(stderr, "\n");
1025 #endif
1026
1027         hungarian_free(bp);
1028
1029         permute_values(live_nodes, node, assignment);
1030 }
1031
1032 /** test wether a node @p n is a copy of the value of node @p of */
1033 static bool is_copy_of(ir_node *value, ir_node *test_value)
1034 {
1035         allocation_info_t *test_info;
1036         allocation_info_t *info;
1037
1038         if (value == test_value)
1039                 return true;
1040
1041         info      = get_allocation_info(value);
1042         test_info = get_allocation_info(test_value);
1043         return test_info->original_value == info->original_value;
1044 }
1045
1046 /**
1047  * find a value in the end-assignment of a basic block
1048  * @returns the index into the assignment array if found
1049  *          -1 if not found
1050  */
1051 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1052 {
1053         unsigned   r;
1054         ir_node  **assignments = info->assignments;
1055         for (r = 0; r < n_regs; ++r) {
1056                 ir_node *a_value = assignments[r];
1057
1058                 if (a_value == NULL)
1059                         continue;
1060                 if (is_copy_of(a_value, value))
1061                         return (int) r;
1062         }
1063
1064         return -1;
1065 }
1066
1067 /**
1068  * Create the necessary permutations at the end of a basic block to fullfill
1069  * the register assignment for phi-nodes in the next block
1070  */
1071 static void add_phi_permutations(ir_node *block, int p)
1072 {
1073         unsigned   r;
1074         unsigned  *permutation;
1075         ir_node  **old_assignments;
1076         bool       need_permutation;
1077         ir_node   *node;
1078         ir_node   *pred = get_Block_cfgpred_block(block, p);
1079
1080         block_info_t *pred_info = get_block_info(pred);
1081
1082         /* predecessor not processed yet? nothing to do */
1083         if (!pred_info->processed)
1084                 return;
1085
1086         permutation = ALLOCAN(unsigned, n_regs);
1087         for (r = 0; r < n_regs; ++r) {
1088                 permutation[r] = r;
1089         }
1090
1091         /* check phi nodes */
1092         need_permutation = false;
1093         node = sched_first(block);
1094         for ( ; is_Phi(node); node = sched_next(node)) {
1095                 const arch_register_t *reg;
1096                 int                    regn;
1097                 int                    a;
1098                 ir_node               *op;
1099
1100                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1101                         continue;
1102
1103                 op = get_Phi_pred(node, p);
1104                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1105                         continue;
1106
1107                 a  = find_value_in_block_info(pred_info, op);
1108                 assert(a >= 0);
1109
1110                 reg  = arch_get_irn_register(node);
1111                 regn = arch_register_get_index(reg);
1112                 if (regn != a) {
1113                         permutation[regn] = a;
1114                         need_permutation  = true;
1115                 }
1116         }
1117
1118         if (need_permutation) {
1119                 /* permute values at end of predecessor */
1120                 old_assignments = assignments;
1121                 assignments     = pred_info->assignments;
1122                 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1123                                                  permutation);
1124                 assignments = old_assignments;
1125         }
1126
1127         /* change phi nodes to use the copied values */
1128         node = sched_first(block);
1129         for ( ; is_Phi(node); node = sched_next(node)) {
1130                 int      a;
1131                 ir_node *op;
1132
1133                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1134                         continue;
1135
1136                 op = get_Phi_pred(node, p);
1137                 /* no need to do anything for Unknown inputs */
1138                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1139                         continue;
1140
1141                 /* we have permuted all values into the correct registers so we can
1142                    simply query which value occupies the phis register in the
1143                    predecessor */
1144                 a  = arch_register_get_index(arch_get_irn_register(node));
1145                 op = pred_info->assignments[a];
1146                 set_Phi_pred(node, p, op);
1147         }
1148 }
1149
1150 /**
1151  * Set preferences for a phis register based on the registers used on the
1152  * phi inputs.
1153  */
1154 static void adapt_phi_prefs(ir_node *phi)
1155 {
1156         int i;
1157         int arity = get_irn_arity(phi);
1158         ir_node           *block = get_nodes_block(phi);
1159         allocation_info_t *info  = get_allocation_info(phi);
1160
1161         for (i = 0; i < arity; ++i) {
1162                 ir_node               *op  = get_irn_n(phi, i);
1163                 const arch_register_t *reg = arch_get_irn_register(op);
1164                 ir_node               *pred;
1165                 ir_node               *pred_block;
1166                 block_info_t          *pred_block_info;
1167                 float                  weight;
1168                 unsigned               r;
1169
1170                 if (reg == NULL)
1171                         continue;
1172                 /* we only give the bonus if the predecessor already has register
1173                  * assigned, otherwise we only see a dummy value
1174                  * and any conclusions about its register are useless */
1175                 pred_block = get_Block_cfgpred_block(block, i);
1176                 pred_block_info = get_block_info(pred_block);
1177                 if (!pred_block_info->processed)
1178                         continue;
1179
1180                 /* give bonus for already assigned register */
1181                 pred   = get_Block_cfgpred_block(block, i);
1182                 weight = get_block_execfreq(execfreqs, pred);
1183                 r      = arch_register_get_index(reg);
1184                 info->prefs[r] += weight * AFF_PHI;
1185         }
1186 }
1187
1188 /**
1189  * After a phi has been assigned a register propagate preference inputs
1190  * to the phi inputs.
1191  */
1192 static void propagate_phi_register(ir_node *phi, unsigned r)
1193 {
1194         int                    i;
1195         ir_node               *block = get_nodes_block(phi);
1196         int                    arity = get_irn_arity(phi);
1197
1198         for (i = 0; i < arity; ++i) {
1199                 ir_node           *op   = get_Phi_pred(phi, i);
1200                 allocation_info_t *info = get_allocation_info(op);
1201                 ir_node           *pred;
1202                 float              weight;
1203
1204                 pred   = get_Block_cfgpred_block(block, i);
1205                 weight = get_block_execfreq(execfreqs, pred);
1206                 weight *= AFF_PHI;
1207
1208                 if (info->prefs[r] >= weight)
1209                         continue;
1210
1211                 /* promote the prefered register */
1212                 info->prefs[r] += AFF_PHI * weight;
1213                 if (is_Phi(op))
1214                         propagate_phi_register(op, r);
1215         }
1216 }
1217
1218 /**
1219  * Walker: assign registers to all nodes of a block that
1220  * need registers from the currently considered register class.
1221  */
1222 static void allocate_coalesce_block(ir_node *block, void *data)
1223 {
1224         int                    i;
1225         ir_nodeset_t           live_nodes;
1226         ir_nodeset_iterator_t  iter;
1227         ir_node               *node, *start;
1228         int                    n_preds;
1229         block_info_t          *block_info;
1230         block_info_t         **pred_block_infos;
1231         ir_node              **phi_ins;
1232         unsigned              *output_regs; /**< collects registers which must not
1233                                                                                      be used for optimistic splits */
1234
1235         (void) data;
1236         DB((dbg, LEVEL_2, "* Block %+F\n", block));
1237
1238         /* clear assignments */
1239         block_info  = get_block_info(block);
1240         assignments = block_info->assignments;
1241
1242         ir_nodeset_init(&live_nodes);
1243
1244         /* gather regalloc infos of predecessor blocks */
1245         n_preds             = get_Block_n_cfgpreds(block);
1246         pred_block_infos    = ALLOCAN(block_info_t*, n_preds);
1247         for (i = 0; i < n_preds; ++i) {
1248                 ir_node      *pred      = get_Block_cfgpred_block(block, i);
1249                 block_info_t *pred_info = get_block_info(pred);
1250                 pred_block_infos[i]     = pred_info;
1251         }
1252
1253         phi_ins = ALLOCAN(ir_node*, n_preds);
1254
1255         /* collect live-in nodes and preassigned values */
1256         be_lv_foreach(lv, block, be_lv_state_in, i) {
1257                 const arch_register_t *reg;
1258                 int                    p;
1259                 bool                   need_phi = false;
1260
1261                 node = be_lv_get_irn(lv, block, i);
1262                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1263                         continue;
1264
1265                 /* check all predecessors for this value, if it is not everywhere the
1266                    same or unknown then we have to construct a phi
1267                    (we collect the potential phi inputs here) */
1268                 for (p = 0; p < n_preds; ++p) {
1269                         block_info_t *pred_info = pred_block_infos[p];
1270
1271                         if (!pred_info->processed) {
1272                                 /* use node for now, it will get fixed later */
1273                                 phi_ins[p] = node;
1274                                 need_phi   = true;
1275                         } else {
1276                                 int a = find_value_in_block_info(pred_info, node);
1277
1278                                 /* must live out of predecessor */
1279                                 assert(a >= 0);
1280                                 phi_ins[p] = pred_info->assignments[a];
1281                                 /* different value from last time? then we need a phi */
1282                                 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1283                                         need_phi = true;
1284                                 }
1285                         }
1286                 }
1287
1288                 if (need_phi) {
1289                         ir_mode                   *mode = get_irn_mode(node);
1290                         const arch_register_req_t *req  = get_default_req_current_cls();
1291                         ir_node                   *phi;
1292                         int                        i;
1293
1294                         phi = new_r_Phi(block, n_preds, phi_ins, mode);
1295                         be_set_phi_reg_req(phi, req);
1296
1297                         DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1298 #ifdef DEBUG_libfirm
1299                         for (i = 0; i < n_preds; ++i) {
1300                                 DB((dbg, LEVEL_3, " %+F", phi_ins[i]));
1301                         }
1302                         DB((dbg, LEVEL_3, "\n"));
1303 #endif
1304                         mark_as_copy_of(phi, node);
1305                         sched_add_after(block, phi);
1306
1307                         node = phi;
1308                 } else {
1309                         allocation_info_t *info = get_allocation_info(node);
1310                         info->current_value = phi_ins[0];
1311
1312                         /* Grab 1 of the inputs we constructed (might not be the same as
1313                          * "node" as we could see the same copy of the value in all
1314                          * predecessors */
1315                         node = phi_ins[0];
1316                 }
1317
1318                 /* if the node already has a register assigned use it */
1319                 reg = arch_get_irn_register(node);
1320                 if (reg != NULL) {
1321                         /* TODO: consult pred-block infos here. The value could be copied
1322                            away in some/all predecessor blocks. We need to construct
1323                            phi-nodes in this case.
1324                            We even need to construct some Phi_0 like constructs in cases
1325                            where the predecessor allocation is not determined yet. */
1326                         use_reg(node, reg);
1327                 }
1328
1329                 /* remember that this node is live at the beginning of the block */
1330                 ir_nodeset_insert(&live_nodes, node);
1331         }
1332
1333         rbitset_alloca(output_regs, n_regs);
1334
1335         /* handle phis... */
1336         node = sched_first(block);
1337         for ( ; is_Phi(node); node = sched_next(node)) {
1338                 const arch_register_t *reg;
1339
1340                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1341                         continue;
1342
1343                 /* fill in regs already assigned */
1344                 reg = arch_get_irn_register(node);
1345                 if (reg != NULL) {
1346                         use_reg(node, reg);
1347                 } else {
1348                         adapt_phi_prefs(node);
1349                         assign_reg(block, node, output_regs);
1350
1351                         reg = arch_get_irn_register(node);
1352                         propagate_phi_register(node, arch_register_get_index(reg));
1353                 }
1354         }
1355         start = node;
1356
1357         /* assign regs for live-in values */
1358         foreach_ir_nodeset(&live_nodes, node, iter) {
1359                 const arch_register_t *reg = arch_get_irn_register(node);
1360                 if (reg != NULL)
1361                         continue;
1362
1363                 assign_reg(block, node, output_regs);
1364                 /* shouldn't happen if we color in dominance order */
1365                 assert (!is_Phi(node));
1366         }
1367
1368         /* assign instructions in the block */
1369         for (node = start; !sched_is_end(node); node = sched_next(node)) {
1370                 unsigned r;
1371
1372                 rewire_inputs(node);
1373
1374                 /* enforce use constraints */
1375                 rbitset_clear_all(output_regs, n_regs);
1376                 enforce_constraints(&live_nodes, node, output_regs);
1377                 /* we may not use registers occupied here for optimistic splits */
1378                 for (r = 0; r < n_regs; ++r) {
1379                         if (assignments[r] != NULL)
1380                                 rbitset_set(output_regs, r);
1381                 }
1382
1383                 rewire_inputs(node);
1384
1385                 /* free registers of values last used at this instruction */
1386                 free_last_uses(&live_nodes, node);
1387
1388                 /* assign output registers */
1389                 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1390                 if (get_irn_mode(node) == mode_T) {
1391                         const ir_edge_t *edge;
1392                         foreach_out_edge(node, edge) {
1393                                 ir_node *proj = get_edge_src_irn(edge);
1394                                 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1395                                         continue;
1396                                 assign_reg(block, proj, output_regs);
1397                         }
1398                 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1399                         assign_reg(block, node, output_regs);
1400                 }
1401         }
1402
1403         ir_nodeset_destroy(&live_nodes);
1404         assignments = NULL;
1405
1406         block_info->processed = true;
1407
1408         /* permute values at end of predecessor blocks in case of phi-nodes */
1409         if (n_preds > 1) {
1410                 int p;
1411                 for (p = 0; p < n_preds; ++p) {
1412                         add_phi_permutations(block, p);
1413                 }
1414         }
1415
1416         /* if we have exactly 1 successor then we might be able to produce phi
1417            copies now */
1418         if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1419                 const ir_edge_t *edge
1420                         = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1421                 ir_node      *succ      = get_edge_src_irn(edge);
1422                 int           p         = get_edge_src_pos(edge);
1423                 block_info_t *succ_info = get_block_info(succ);
1424
1425                 if (succ_info->processed) {
1426                         add_phi_permutations(succ, p);
1427                 }
1428         }
1429 }
1430
1431 /**
1432  * Run the register allocator for the current register class.
1433  */
1434 static void be_straight_alloc_cls(void)
1435 {
1436         lv = be_assure_liveness(birg);
1437         be_liveness_assure_sets(lv);
1438         be_liveness_assure_chk(lv);
1439
1440         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1441         inc_irg_visited(irg);
1442
1443         DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1444
1445         irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1446         /* we need some dominance pre-order walk to ensure we see all
1447          *  definitions/create copies before we encounter their users */
1448         dom_tree_walk_irg(irg, allocate_coalesce_block, NULL, NULL);
1449
1450         ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1451 }
1452
1453 static void dump(int mask, ir_graph *irg, const char *suffix,
1454                  void (*dumper)(ir_graph *, const char *))
1455 {
1456         if(birg->main_env->options->dump_flags & mask)
1457                 be_dump(irg, suffix, dumper);
1458 }
1459
1460 /**
1461  * Run the spiller on the current graph.
1462  */
1463 static void spill(void)
1464 {
1465         /* make sure all nodes show their real register pressure */
1466         BE_TIMER_PUSH(t_ra_constr);
1467         be_pre_spill_prepare_constr(birg, cls);
1468         BE_TIMER_POP(t_ra_constr);
1469
1470         dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1471
1472         /* spill */
1473         BE_TIMER_PUSH(t_ra_spill);
1474         be_do_spill(birg, cls);
1475         BE_TIMER_POP(t_ra_spill);
1476
1477         BE_TIMER_PUSH(t_ra_spill_apply);
1478         check_for_memory_operands(irg);
1479         BE_TIMER_POP(t_ra_spill_apply);
1480
1481         dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1482 }
1483
1484 /**
1485  * The straight register allocator for a whole procedure.
1486  */
1487 static void be_straight_alloc(be_irg_t *new_birg)
1488 {
1489         const arch_env_t *arch_env = new_birg->main_env->arch_env;
1490         int   n_cls                = arch_env_get_n_reg_class(arch_env);
1491         int   c;
1492
1493         obstack_init(&obst);
1494
1495         birg      = new_birg;
1496         irg       = be_get_birg_irg(birg);
1497         execfreqs = birg->exec_freq;
1498
1499         /* TODO: extract some of the stuff from bechordal allocator, like
1500          * statistics, time measurements, etc. and use them here too */
1501
1502         for (c = 0; c < n_cls; ++c) {
1503                 cls             = arch_env_get_reg_class(arch_env, c);
1504                 default_cls_req = NULL;
1505                 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1506                         continue;
1507
1508                 stat_ev_ctx_push_str("regcls", cls->name);
1509
1510                 n_regs      = arch_register_class_n_regs(cls);
1511                 normal_regs = rbitset_malloc(n_regs);
1512                 be_abi_set_non_ignore_regs(birg->abi, cls, normal_regs);
1513
1514                 spill();
1515
1516                 /* verify schedule and register pressure */
1517                 BE_TIMER_PUSH(t_verify);
1518                 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1519                         be_verify_schedule(birg);
1520                         be_verify_register_pressure(birg, cls, irg);
1521                 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1522                         assert(be_verify_schedule(birg) && "Schedule verification failed");
1523                         assert(be_verify_register_pressure(birg, cls, irg)
1524                                 && "Register pressure verification failed");
1525                 }
1526                 BE_TIMER_POP(t_verify);
1527
1528                 BE_TIMER_PUSH(t_ra_color);
1529                 be_straight_alloc_cls();
1530                 BE_TIMER_POP(t_ra_color);
1531
1532                 /* we most probably constructed new Phis so liveness info is invalid
1533                  * now */
1534                 /* TODO: test liveness_introduce */
1535                 be_liveness_invalidate(lv);
1536                 free(normal_regs);
1537
1538                 stat_ev_ctx_pop("regcls");
1539         }
1540
1541         BE_TIMER_PUSH(t_ra_spill_apply);
1542         be_abi_fix_stack_nodes(birg->abi);
1543         BE_TIMER_POP(t_ra_spill_apply);
1544
1545         BE_TIMER_PUSH(t_verify);
1546         if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1547                 be_verify_register_allocation(birg);
1548         } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1549                 assert(be_verify_register_allocation(birg)
1550                                 && "Register allocation invalid");
1551         }
1552         BE_TIMER_POP(t_verify);
1553
1554         obstack_free(&obst, NULL);
1555 }
1556
1557 /**
1558  * Initializes this module.
1559  */
1560 void be_init_straight_alloc(void)
1561 {
1562         static be_ra_t be_ra_straight = {
1563                 be_straight_alloc,
1564         };
1565
1566         FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
1567
1568         be_register_allocator("straight", &be_ra_straight);
1569 }
1570
1571 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);