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