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