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