libcore wants int, not bool.
[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 #include <math.h>
53
54 #include "error.h"
55 #include "execfreq.h"
56 #include "ircons.h"
57 #include "irdom.h"
58 #include "iredges_t.h"
59 #include "irgraph_t.h"
60 #include "irgwalk.h"
61 #include "irnode_t.h"
62 #include "irprintf.h"
63 #include "obst.h"
64 #include "raw_bitset.h"
65 #include "unionfind.h"
66 #include "pdeq.h"
67 #include "hungarian.h"
68
69 #include "beabi.h"
70 #include "bechordal_t.h"
71 #include "be.h"
72 #include "beirg.h"
73 #include "belive_t.h"
74 #include "bemodule.h"
75 #include "benode_t.h"
76 #include "bera.h"
77 #include "besched.h"
78 #include "bespill.h"
79 #include "bespillutil.h"
80 #include "beverify.h"
81 #include "beutil.h"
82
83 #define USE_FACTOR                     1.0f
84 #define DEF_FACTOR                     1.0f
85 #define NEIGHBOR_FACTOR                0.2f
86 #define AFF_SHOULD_BE_SAME             0.5f
87 #define AFF_PHI                        1.0f
88 #define SPLIT_DELTA                    1.0f
89 #define MAX_OPTIMISTIC_SPLIT_RECURSION 0
90
91 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
92
93 static struct obstack               obst;
94 static be_irg_t                    *birg;
95 static ir_graph                    *irg;
96 static const arch_register_class_t *cls;
97 static const arch_register_req_t   *default_cls_req;
98 static be_lv_t                     *lv;
99 static const ir_exec_freq          *execfreqs;
100 static unsigned                     n_regs;
101 static unsigned                    *normal_regs;
102 static int                         *congruence_classes;
103 static ir_node                    **block_order;
104 static int                          n_block_order;
105 static int                          create_preferences        = true;
106 static int                          create_congruence_classes = true;
107 static int                          propagate_phi_registers   = true;
108
109 static const lc_opt_table_entry_t options[] = {
110         LC_OPT_ENT_BOOL("prefs", "use preference based coloring", &create_preferences),
111         LC_OPT_ENT_BOOL("congruences", "create congruence classes", &create_congruence_classes),
112         LC_OPT_ENT_BOOL("prop_phi", "propagate phi registers", &propagate_phi_registers),
113         LC_OPT_LAST
114 };
115
116 /** currently active assignments (while processing a basic block)
117  * maps registers to values(their current copies) */
118 static ir_node **assignments;
119
120 /**
121  * allocation information: last_uses, register preferences
122  * the information is per firm-node.
123  */
124 struct allocation_info_t {
125         unsigned  last_uses;      /**< bitset indicating last uses (input pos) */
126         ir_node  *current_value;  /**< copy of the value that should be used */
127         ir_node  *original_value; /**< for copies point to original value */
128         float     prefs[0];       /**< register preferences */
129 };
130 typedef struct allocation_info_t allocation_info_t;
131
132 /** helper datastructure used when sorting register preferences */
133 struct reg_pref_t {
134         unsigned num;
135         float    pref;
136 };
137 typedef struct reg_pref_t reg_pref_t;
138
139 /** per basic-block information */
140 struct block_info_t {
141         bool     processed;       /**< indicate wether block is processed */
142         ir_node *assignments[0];  /**< register assignments at end of block */
143 };
144 typedef struct block_info_t block_info_t;
145
146 /**
147  * Get the allocation info for a node.
148  * The info is allocated on the first visit of a node.
149  */
150 static allocation_info_t *get_allocation_info(ir_node *node)
151 {
152         allocation_info_t *info = get_irn_link(node);
153         if (info == NULL) {
154                 info = OALLOCFZ(&obst, allocation_info_t, prefs, n_regs);
155                 info->current_value  = node;
156                 info->original_value = node;
157                 set_irn_link(node, info);
158         }
159
160         return info;
161 }
162
163 /**
164  * Get allocation information for a basic block
165  */
166 static block_info_t *get_block_info(ir_node *block)
167 {
168         block_info_t *info = get_irn_link(block);
169
170         assert(is_Block(block));
171         if (info == NULL) {
172                 info = OALLOCFZ(&obst, block_info_t, assignments, n_regs);
173                 set_irn_link(block, info);
174         }
175
176         return info;
177 }
178
179 /**
180  * Get default register requirement for the current register class
181  */
182 static const arch_register_req_t *get_default_req_current_cls(void)
183 {
184         if (default_cls_req == NULL) {
185                 struct obstack      *obst = get_irg_obstack(irg);
186                 arch_register_req_t *req  = OALLOCZ(obst, arch_register_req_t);
187
188                 req->type = arch_register_req_type_normal;
189                 req->cls  = cls;
190
191                 default_cls_req = req;
192         }
193         return default_cls_req;
194 }
195
196 /**
197  * Link the allocation info of a node to a copy.
198  * Afterwards, both nodes uses the same allocation info.
199  * Copy must not have an allocation info assigned yet.
200  *
201  * @param copy   the node that gets the allocation info assigned
202  * @param value  the original node
203  */
204 static void mark_as_copy_of(ir_node *copy, ir_node *value)
205 {
206         ir_node           *original;
207         allocation_info_t *info      = get_allocation_info(value);
208         allocation_info_t *copy_info = get_allocation_info(copy);
209
210         /* find original value */
211         original = info->original_value;
212         if (original != value) {
213                 info = get_allocation_info(original);
214         }
215
216         assert(info->original_value == original);
217         info->current_value = copy;
218
219         /* the copy should not be linked to something else yet */
220         assert(copy_info->original_value == copy);
221         copy_info->original_value = original;
222
223         /* copy over allocation preferences */
224         memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
225 }
226
227 /**
228  * Calculate the penalties for every register on a node and its live neighbors.
229  *
230  * @param live_nodes  the set of live nodes at the current position, may be NULL
231  * @param penalty     the penalty to subtract from
232  * @param limited     a raw bitset containing the limited set for the node
233  * @param node        the node
234  */
235 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
236                                       float penalty, const unsigned* limited,
237                                       ir_node *node)
238 {
239         ir_nodeset_iterator_t iter;
240         unsigned              r;
241         unsigned              n_allowed;
242         allocation_info_t     *info = get_allocation_info(node);
243         ir_node               *neighbor;
244
245         /* give penalty for all forbidden regs */
246         for (r = 0; r < n_regs; ++r) {
247                 if (rbitset_is_set(limited, r))
248                         continue;
249
250                 info->prefs[r] -= penalty;
251         }
252
253         /* all other live values should get a penalty for allowed regs */
254         if (live_nodes == NULL)
255                 return;
256
257         penalty   *= NEIGHBOR_FACTOR;
258         n_allowed  = rbitset_popcnt(limited, n_regs);
259         if (n_allowed > 1) {
260                 /* only create a very weak penalty if multiple regs are allowed */
261                 penalty = (penalty * 0.8) / n_allowed;
262         }
263         foreach_ir_nodeset(live_nodes, neighbor, iter) {
264                 allocation_info_t *neighbor_info;
265
266                 /* TODO: if op is used on multiple inputs we might not do a
267                  * continue here */
268                 if (neighbor == node)
269                         continue;
270
271                 neighbor_info = get_allocation_info(neighbor);
272                 for (r = 0; r < n_regs; ++r) {
273                         if (!rbitset_is_set(limited, r))
274                                 continue;
275
276                         neighbor_info->prefs[r] -= penalty;
277                 }
278         }
279 }
280
281 /**
282  * Calculate the preferences of a definition for the current register class.
283  * If the definition uses a limited set of registers, reduce the preferences
284  * for the limited register on the node and its neighbors.
285  *
286  * @param live_nodes  the set of live nodes at the current node
287  * @param weight      the weight
288  * @param node        the current node
289  */
290 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
291                        ir_node *node)
292 {
293         const arch_register_req_t *req;
294
295         if (get_irn_mode(node) == mode_T) {
296                 const ir_edge_t *edge;
297                 foreach_out_edge(node, edge) {
298                         ir_node *proj = get_edge_src_irn(edge);
299                         check_defs(live_nodes, weight, proj);
300                 }
301                 return;
302         }
303
304         if (!arch_irn_consider_in_reg_alloc(cls, node))
305                 return;
306
307         req = arch_get_register_req_out(node);
308         if (req->type & arch_register_req_type_limited) {
309                 const unsigned *limited = req->limited;
310                 float           penalty = weight * DEF_FACTOR;
311                 give_penalties_for_limits(live_nodes, penalty, limited, node);
312         }
313
314         if (req->type & arch_register_req_type_should_be_same) {
315                 ir_node           *insn  = skip_Proj(node);
316                 allocation_info_t *info  = get_allocation_info(node);
317                 int                arity = get_irn_arity(insn);
318                 int                i;
319
320                 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
321                 for (i = 0; i < arity; ++i) {
322                         ir_node           *op;
323                         unsigned           r;
324                         allocation_info_t *op_info;
325
326                         if (!rbitset_is_set(&req->other_same, i))
327                                 continue;
328
329                         op = get_irn_n(insn, i);
330
331                         /* if we the value at the should_be_same input doesn't die at the
332                          * node, then it is no use to propagate the constraints (since a
333                          * copy will emerge anyway) */
334                         if (ir_nodeset_contains(live_nodes, op))
335                                 continue;
336
337                         op_info = get_allocation_info(op);
338                         for (r = 0; r < n_regs; ++r) {
339                                 op_info->prefs[r] += info->prefs[r] * factor;
340                         }
341                 }
342         }
343 }
344
345 /**
346  * Walker: Runs an a block calculates the preferences for any
347  * node and every register from the considered register class.
348  */
349 static void analyze_block(ir_node *block, void *data)
350 {
351         float         weight = get_block_execfreq(execfreqs, block);
352         ir_nodeset_t  live_nodes;
353         ir_node      *node;
354         (void) data;
355
356         ir_nodeset_init(&live_nodes);
357         be_liveness_end_of_block(lv, cls, block, &live_nodes);
358
359         sched_foreach_reverse(block, node) {
360                 allocation_info_t *info;
361                 int                i;
362                 int                arity;
363
364                 if (is_Phi(node))
365                         break;
366
367                 if (create_preferences)
368                         check_defs(&live_nodes, weight, node);
369
370                 /* mark last uses */
371                 arity = get_irn_arity(node);
372
373                 /* the allocation info node currently only uses 1 unsigned value
374                    to mark last used inputs. So we will fail for a node with more than
375                    32 inputs. */
376                 if (arity >= (int) sizeof(unsigned) * 8) {
377                         panic("Node with more than %d inputs not supported yet",
378                                         (int) sizeof(unsigned) * 8);
379                 }
380
381                 info = get_allocation_info(node);
382                 for (i = 0; i < arity; ++i) {
383                         ir_node *op = get_irn_n(node, i);
384                         if (!arch_irn_consider_in_reg_alloc(cls, op))
385                                 continue;
386
387                         /* last usage of a value? */
388                         if (!ir_nodeset_contains(&live_nodes, op)) {
389                                 rbitset_set(&info->last_uses, i);
390                         }
391                 }
392
393                 be_liveness_transfer(cls, node, &live_nodes);
394
395                 if (create_preferences) {
396                         /* update weights based on usage constraints */
397                         for (i = 0; i < arity; ++i) {
398                                 const arch_register_req_t *req;
399                                 const unsigned            *limited;
400                                 ir_node                   *op = get_irn_n(node, i);
401
402                                 if (!arch_irn_consider_in_reg_alloc(cls, op))
403                                         continue;
404
405                                 req = arch_get_register_req(node, i);
406                                 if (!(req->type & arch_register_req_type_limited))
407                                         continue;
408
409                                 limited = req->limited;
410                                 give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
411                                                                                   op);
412                         }
413                 }
414         }
415
416         ir_nodeset_destroy(&live_nodes);
417 }
418
419 static void congruence_def(ir_nodeset_t *live_nodes, ir_node *node)
420 {
421         const arch_register_req_t *req;
422
423         if (get_irn_mode(node) == mode_T) {
424                 const ir_edge_t *edge;
425                 foreach_out_edge(node, edge) {
426                         ir_node *def = get_edge_src_irn(edge);
427                         congruence_def(live_nodes, def);
428                 }
429                 return;
430         }
431
432         if (!arch_irn_consider_in_reg_alloc(cls, node))
433                 return;
434
435         /* should be same constraint? */
436         req = arch_get_register_req_out(node);
437         if (req->type & arch_register_req_type_should_be_same) {
438                 ir_node *insn  = skip_Proj(node);
439                 int      arity = get_irn_arity(insn);
440                 int      i;
441                 unsigned node_idx = get_irn_idx(node);
442                 node_idx          = uf_find(congruence_classes, node_idx);
443
444                 for (i = 0; i < arity; ++i) {
445                         ir_node               *live;
446                         ir_node               *op;
447                         int                    op_idx;
448                         ir_nodeset_iterator_t  iter;
449                         bool                   interferes = false;
450
451                         if (!rbitset_is_set(&req->other_same, i))
452                                 continue;
453
454                         op     = get_irn_n(insn, i);
455                         op_idx = get_irn_idx(op);
456                         op_idx = uf_find(congruence_classes, op_idx);
457
458                         /* do we interfere with the value */
459                         foreach_ir_nodeset(live_nodes, live, iter) {
460                                 int lv_idx = get_irn_idx(live);
461                                 lv_idx     = uf_find(congruence_classes, lv_idx);
462                                 if (lv_idx == op_idx) {
463                                         interferes = true;
464                                         break;
465                                 }
466                         }
467                         /* don't put in same affinity class if we interfere */
468                         if (interferes)
469                                 continue;
470
471                         node_idx = uf_union(congruence_classes, node_idx, op_idx);
472                         DB((dbg, LEVEL_3, "Merge %+F and %+F congruence classes\n",
473                             node, op));
474                         /* one should_be_same is enough... */
475                         break;
476                 }
477         }
478 }
479
480 static void create_congurence_class(ir_node *block, void *data)
481 {
482         ir_nodeset_t  live_nodes;
483         ir_node      *node;
484
485         (void) data;
486         ir_nodeset_init(&live_nodes);
487         be_liveness_end_of_block(lv, cls, block, &live_nodes);
488
489         /* check should be same constraints */
490         sched_foreach_reverse(block, node) {
491                 if (is_Phi(node))
492                         break;
493
494                 congruence_def(&live_nodes, node);
495                 be_liveness_transfer(cls, node, &live_nodes);
496         }
497
498         /* check phi congruence classes */
499         sched_foreach_reverse_from(node, node) {
500                 int i;
501                 int arity;
502                 int node_idx;
503                 assert(is_Phi(node));
504
505                 if (!arch_irn_consider_in_reg_alloc(cls, node))
506                         continue;
507
508                 node_idx = get_irn_idx(node);
509                 node_idx = uf_find(congruence_classes, node_idx);
510
511                 arity = get_irn_arity(node);
512                 for (i = 0; i < arity; ++i) {
513                         bool                  interferes = false;
514                         ir_nodeset_iterator_t iter;
515                         ir_node *live;
516                         ir_node *phi;
517                         ir_node *op     = get_Phi_pred(node, i);
518                         int      op_idx = get_irn_idx(op);
519                         op_idx = uf_find(congruence_classes, op_idx);
520
521                         /* do we interfere with the value */
522                         foreach_ir_nodeset(&live_nodes, live, iter) {
523                                 int lv_idx = get_irn_idx(live);
524                                 lv_idx     = uf_find(congruence_classes, lv_idx);
525                                 if (lv_idx == op_idx) {
526                                         interferes = true;
527                                         break;
528                                 }
529                         }
530                         /* don't put in same affinity class if we interfere */
531                         if (interferes)
532                                 continue;
533                         /* any other phi has the same input? */
534                         sched_foreach(block, phi) {
535                                 ir_node *oop;
536                                 int      oop_idx;
537                                 if (!is_Phi(phi))
538                                         break;
539                                 if (!arch_irn_consider_in_reg_alloc(cls, phi))
540                                         continue;
541                                 oop = get_Phi_pred(phi, i);
542                                 if (oop == op)
543                                         continue;
544                                 oop_idx = get_irn_idx(oop);
545                                 oop_idx = uf_find(congruence_classes, oop_idx);
546                                 if (oop_idx == op_idx) {
547                                         interferes = true;
548                                         break;
549                                 }
550                         }
551                         if (interferes)
552                                 continue;
553
554                         node_idx = uf_union(congruence_classes, node_idx, op_idx);
555                         DB((dbg, LEVEL_3, "Merge %+F and %+F congruence classes\n",
556                             node, op));
557                 }
558         }
559 }
560
561 static void merge_congruence_prefs(ir_node *node, void *data)
562 {
563         allocation_info_t *info;
564         allocation_info_t *head_info;
565         unsigned node_idx = get_irn_idx(node);
566         unsigned node_set = uf_find(congruence_classes, node_idx);
567         unsigned r;
568
569         (void) data;
570
571         /* head of congruence class or not in any class */
572         if (node_set == node_idx)
573                 return;
574
575         if (!arch_irn_consider_in_reg_alloc(cls, node))
576                 return;
577
578         head_info = get_allocation_info(get_idx_irn(irg, node_set));
579         info      = get_allocation_info(node);
580
581         for (r = 0; r < n_regs; ++r) {
582                 head_info->prefs[r] += info->prefs[r];
583         }
584 }
585
586 static void set_congruence_prefs(ir_node *node, void *data)
587 {
588         allocation_info_t *info;
589         allocation_info_t *head_info;
590         unsigned node_idx = get_irn_idx(node);
591         unsigned node_set = uf_find(congruence_classes, node_idx);
592
593         (void) data;
594
595         /* head of congruence class or not in any class */
596         if (node_set == node_idx)
597                 return;
598
599         if (!arch_irn_consider_in_reg_alloc(cls, node))
600                 return;
601
602         head_info = get_allocation_info(get_idx_irn(irg, node_set));
603         info      = get_allocation_info(node);
604
605         memcpy(info->prefs, head_info->prefs, n_regs * sizeof(info->prefs[0]));
606 }
607
608 static void combine_congruence_classes(void)
609 {
610         size_t n = get_irg_last_idx(irg);
611         congruence_classes = XMALLOCN(int, n);
612         uf_init(congruence_classes, n);
613
614         /* create congruence classes */
615         irg_block_walk_graph(irg, create_congurence_class, NULL, NULL);
616         /* merge preferences */
617         irg_walk_graph(irg, merge_congruence_prefs, NULL, NULL);
618         irg_walk_graph(irg, set_congruence_prefs, NULL, NULL);
619         free(congruence_classes);
620 }
621
622
623
624
625
626 /**
627  * Assign register reg to the given node.
628  *
629  * @param node  the node
630  * @param reg   the register
631  */
632 static void use_reg(ir_node *node, const arch_register_t *reg)
633 {
634         unsigned r = arch_register_get_index(reg);
635         assignments[r] = node;
636         arch_set_irn_register(node, reg);
637 }
638
639 static void free_reg_of_value(ir_node *node)
640 {
641         const arch_register_t *reg;
642         unsigned               r;
643
644         if (!arch_irn_consider_in_reg_alloc(cls, node))
645                 return;
646
647         reg        = arch_get_irn_register(node);
648         r          = arch_register_get_index(reg);
649         /* assignment->value may be NULL if a value is used at 2 inputs
650            so it gets freed twice. */
651         assert(assignments[r] == node || assignments[r] == NULL);
652         assignments[r] = NULL;
653 }
654
655 /**
656  * Compare two register preferences in decreasing order.
657  */
658 static int compare_reg_pref(const void *e1, const void *e2)
659 {
660         const reg_pref_t *rp1 = (const reg_pref_t*) e1;
661         const reg_pref_t *rp2 = (const reg_pref_t*) e2;
662         if (rp1->pref < rp2->pref)
663                 return 1;
664         if (rp1->pref > rp2->pref)
665                 return -1;
666         return 0;
667 }
668
669 static void fill_sort_candidates(reg_pref_t *regprefs,
670                                  const allocation_info_t *info)
671 {
672         unsigned r;
673
674         for (r = 0; r < n_regs; ++r) {
675                 float pref = info->prefs[r];
676                 regprefs[r].num  = r;
677                 regprefs[r].pref = pref;
678         }
679         /* TODO: use a stable sort here to avoid unnecessary register jumping */
680         qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
681 }
682
683 static bool try_optimistic_split(ir_node *to_split, ir_node *before,
684                                  float pref, float pref_delta,
685                                  unsigned *forbidden_regs, int recursion)
686 {
687         const arch_register_t *from_reg;
688         const arch_register_t *reg;
689         ir_node               *original_insn;
690         ir_node               *block;
691         ir_node               *copy;
692         unsigned               r;
693         unsigned               from_r;
694         unsigned               i;
695         allocation_info_t     *info = get_allocation_info(to_split);
696         reg_pref_t            *prefs;
697         float                  delta;
698         float                  split_threshold;
699
700         (void) pref;
701
702         /* stupid hack: don't optimisticallt split don't spill nodes...
703          * (so we don't split away the values produced because of
704          *  must_be_different constraints) */
705         original_insn = skip_Proj(info->original_value);
706         if (arch_irn_get_flags(original_insn) & arch_irn_flags_dont_spill)
707                 return false;
708
709         from_reg        = arch_get_irn_register(to_split);
710         from_r          = arch_register_get_index(from_reg);
711         block           = get_nodes_block(before);
712         split_threshold = get_block_execfreq(execfreqs, block) * SPLIT_DELTA;
713
714         if (pref_delta < split_threshold*0.5)
715                 return false;
716
717         /* find the best free position where we could move to */
718         prefs = ALLOCAN(reg_pref_t, n_regs);
719         fill_sort_candidates(prefs, info);
720         for (i = 0; i < n_regs; ++i) {
721                 float apref;
722                 float apref_delta;
723                 bool  res;
724                 bool  old_source_state;
725
726                 /* we need a normal register which is not an output register
727                    an different from the current register of to_split */
728                 r = prefs[i].num;
729                 if (!rbitset_is_set(normal_regs, r))
730                         continue;
731                 if (rbitset_is_set(forbidden_regs, r))
732                         continue;
733                 if (r == from_r)
734                         continue;
735
736                 /* is the split worth it? */
737                 delta = pref_delta + prefs[i].pref;
738                 if (delta < split_threshold) {
739                         DB((dbg, LEVEL_3, "Not doing optimistical split of %+F (depth %d), win %f too low\n",
740                                 to_split, recursion, delta));
741                         return false;
742                 }
743
744                 /* if the register is free then we can do the split */
745                 if (assignments[r] == NULL)
746                         break;
747
748                 /* otherwise we might try recursively calling optimistic_split */
749                 if (recursion+1 > MAX_OPTIMISTIC_SPLIT_RECURSION)
750                         continue;
751
752                 apref        = prefs[i].pref;
753                 apref_delta  = i+1 < n_regs ? apref - prefs[i+1].pref : 0;
754                 apref_delta += pref_delta - split_threshold;
755
756                 /* our source register isn't a usefull destination for recursive
757                    splits */
758                 old_source_state = rbitset_is_set(forbidden_regs, from_r);
759                 rbitset_set(forbidden_regs, from_r);
760                 /* try recursive split */
761                 res = try_optimistic_split(assignments[r], before, apref,
762                                            apref_delta, forbidden_regs, recursion+1);
763                 /* restore our destination */
764                 if (old_source_state) {
765                         rbitset_set(forbidden_regs, from_r);
766                 } else {
767                         rbitset_clear(forbidden_regs, from_r);
768                 }
769
770                 if (res)
771                         break;
772         }
773         if (i >= n_regs)
774                 return false;
775
776         reg  = arch_register_for_index(cls, r);
777         copy = be_new_Copy(cls, block, to_split);
778         mark_as_copy_of(copy, to_split);
779         /* hacky, but correct here */
780         if (assignments[arch_register_get_index(from_reg)] == to_split)
781                 free_reg_of_value(to_split);
782         use_reg(copy, reg);
783         sched_add_before(before, copy);
784
785         DB((dbg, LEVEL_3,
786             "Optimistic live-range split %+F move %+F(%s) -> %s before %+F (win %f, depth %d)\n",
787             copy, to_split, from_reg->name, reg->name, before, delta, recursion));
788         return true;
789 }
790
791 /**
792  * Determine and assign a register for node @p node
793  */
794 static void assign_reg(const ir_node *block, ir_node *node,
795                        unsigned *forbidden_regs)
796 {
797         const arch_register_t     *reg;
798         allocation_info_t         *info;
799         const arch_register_req_t *req;
800         reg_pref_t                *reg_prefs;
801         ir_node                   *in_node;
802         unsigned                   i;
803         const unsigned            *allowed_regs;
804         unsigned                   r;
805
806         assert(!is_Phi(node));
807         assert(arch_irn_consider_in_reg_alloc(cls, node));
808
809         /* preassigned register? */
810         reg = arch_get_irn_register(node);
811         if (reg != NULL) {
812                 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
813                 use_reg(node, reg);
814                 return;
815         }
816
817         /* give should_be_same boni */
818         info = get_allocation_info(node);
819         req  = arch_get_register_req_out(node);
820
821         in_node = skip_Proj(node);
822         if (req->type & arch_register_req_type_should_be_same) {
823                 float weight = get_block_execfreq(execfreqs, block);
824                 int   arity  = get_irn_arity(in_node);
825                 int   i;
826
827                 assert(arity <= (int) sizeof(req->other_same) * 8);
828                 for (i = 0; i < arity; ++i) {
829                         ir_node               *in;
830                         const arch_register_t *reg;
831                         unsigned               r;
832                         if (!rbitset_is_set(&req->other_same, i))
833                                 continue;
834
835                         in  = get_irn_n(in_node, i);
836                         reg = arch_get_irn_register(in);
837                         assert(reg != NULL);
838                         r = arch_register_get_index(reg);
839
840                         /* if the value didn't die here then we should not propagate the
841                          * should_be_same info */
842                         if (assignments[r] == in)
843                                 continue;
844
845                         info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
846                 }
847         }
848
849         /* create list of register candidates and sort by their preference */
850         DB((dbg, LEVEL_2, "Candidates for %+F:", node));
851         reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
852         fill_sort_candidates(reg_prefs, info);
853         for (i = 0; i < n_regs; ++i) {
854                 unsigned num = reg_prefs[i].num;
855                 const arch_register_t *reg;
856
857                 if (!rbitset_is_set(normal_regs, num))
858                         continue;
859
860                 reg = arch_register_for_index(cls, num);
861                 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
862         }
863         DB((dbg, LEVEL_2, "\n"));
864
865         allowed_regs = normal_regs;
866         if (req->type & arch_register_req_type_limited) {
867                 allowed_regs = req->limited;
868         }
869
870         for (i = 0; i < n_regs; ++i) {
871                 r = reg_prefs[i].num;
872                 if (!rbitset_is_set(allowed_regs, r))
873                         continue;
874                 if (assignments[r] == NULL)
875                         break;
876                 float    pref   = reg_prefs[i].pref;
877                 float    delta  = i+1 < n_regs ? pref - reg_prefs[i+1].pref : 0;
878                 ir_node *before = skip_Proj(node);
879                 bool     res    = try_optimistic_split(assignments[r], before,
880                                                                                            pref, delta, forbidden_regs, 0);
881                 if (res)
882                         break;
883         }
884         if (i >= n_regs) {
885                 panic("No register left for %+F\n", node);
886         }
887
888         reg = arch_register_for_index(cls, r);
889         DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
890         use_reg(node, reg);
891 }
892
893 /**
894  * Add an permutation in front of a node and change the assignments
895  * due to this permutation.
896  *
897  * To understand this imagine a permutation like this:
898  *
899  * 1 -> 2
900  * 2 -> 3
901  * 3 -> 1, 5
902  * 4 -> 6
903  * 5
904  * 6
905  * 7 -> 7
906  *
907  * First we count how many destinations a single value has. At the same time
908  * we can be sure that each destination register has at most 1 source register
909  * (it can have 0 which means we don't care what value is in it).
910  * We ignore all fullfilled permuations (like 7->7)
911  * In a first pass we create as much copy instructions as possible as they
912  * are generally cheaper than exchanges. We do this by counting into how many
913  * destinations a register has to be copied (in the example it's 2 for register
914  * 3, or 1 for the registers 1,2,4 and 7).
915  * We can then create a copy into every destination register when the usecount
916  * of that register is 0 (= noone else needs the value in the register).
917  *
918  * After this step we should have cycles left. We implement a cyclic permutation
919  * of n registers with n-1 transpositions.
920  *
921  * @param live_nodes   the set of live nodes, updated due to live range split
922  * @param before       the node before we add the permutation
923  * @param permutation  the permutation array indices are the destination
924  *                     registers, the values in the array are the source
925  *                     registers.
926  */
927 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
928                              unsigned *permutation)
929 {
930         unsigned  *n_used = ALLOCANZ(unsigned, n_regs);
931         ir_node   *block;
932         unsigned   r;
933
934         /* determine how often each source register needs to be read */
935         for (r = 0; r < n_regs; ++r) {
936                 unsigned  old_reg = permutation[r];
937                 ir_node  *value;
938
939                 value = assignments[old_reg];
940                 if (value == NULL) {
941                         /* nothing to do here, reg is not live. Mark it as fixpoint
942                          * so we ignore it in the next steps */
943                         permutation[r] = r;
944                         continue;
945                 }
946
947                 ++n_used[old_reg];
948         }
949
950         block = get_nodes_block(before);
951
952         /* step1: create copies where immediately possible */
953         for (r = 0; r < n_regs; /* empty */) {
954                 ir_node *copy;
955                 ir_node *src;
956                 const arch_register_t *reg;
957                 unsigned               old_r = permutation[r];
958
959                 /* - no need to do anything for fixed points.
960                    - we can't copy if the value in the dest reg is still needed */
961                 if (old_r == r || n_used[r] > 0) {
962                         ++r;
963                         continue;
964                 }
965
966                 /* create a copy */
967                 src  = assignments[old_r];
968                 copy = be_new_Copy(cls, block, src);
969                 sched_add_before(before, copy);
970                 reg = arch_register_for_index(cls, r);
971                 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
972                     copy, src, before, reg->name));
973                 mark_as_copy_of(copy, src);
974                 use_reg(copy, reg);
975
976                 if (live_nodes != NULL) {
977                         ir_nodeset_insert(live_nodes, copy);
978                 }
979
980                 /* old register has 1 user less, permutation is resolved */
981                 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
982                 permutation[r] = r;
983
984                 assert(n_used[old_r] > 0);
985                 --n_used[old_r];
986                 if (n_used[old_r] == 0) {
987                         if (live_nodes != NULL) {
988                                 ir_nodeset_remove(live_nodes, src);
989                         }
990                         free_reg_of_value(src);
991                 }
992
993                 /* advance or jump back (if this copy enabled another copy) */
994                 if (old_r < r && n_used[old_r] == 0) {
995                         r = old_r;
996                 } else {
997                         ++r;
998                 }
999         }
1000
1001         /* at this point we only have "cycles" left which we have to resolve with
1002          * perm instructions
1003          * TODO: if we have free registers left, then we should really use copy
1004          * instructions for any cycle longer than 2 registers...
1005          * (this is probably architecture dependent, there might be archs where
1006          *  copies are preferable even for 2-cycles) */
1007
1008         /* create perms with the rest */
1009         for (r = 0; r < n_regs; /* empty */) {
1010                 const arch_register_t *reg;
1011                 unsigned  old_r = permutation[r];
1012                 unsigned  r2;
1013                 ir_node  *in[2];
1014                 ir_node  *perm;
1015                 ir_node  *proj0;
1016                 ir_node  *proj1;
1017
1018                 if (old_r == r) {
1019                         ++r;
1020                         continue;
1021                 }
1022
1023                 /* we shouldn't have copies from 1 value to multiple destinations left*/
1024                 assert(n_used[old_r] == 1);
1025
1026                 /* exchange old_r and r2; after that old_r is a fixed point */
1027                 r2 = permutation[old_r];
1028
1029                 in[0] = assignments[r2];
1030                 in[1] = assignments[old_r];
1031                 perm = be_new_Perm(cls, block, 2, in);
1032                 sched_add_before(before, perm);
1033                 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
1034                     perm, in[0], in[1], before));
1035
1036                 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
1037                 mark_as_copy_of(proj0, in[0]);
1038                 reg = arch_register_for_index(cls, old_r);
1039                 use_reg(proj0, reg);
1040
1041                 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
1042                 mark_as_copy_of(proj1, in[1]);
1043                 reg = arch_register_for_index(cls, r2);
1044                 use_reg(proj1, reg);
1045
1046                 /* 1 value is now in the correct register */
1047                 permutation[old_r] = old_r;
1048                 /* the source of r changed to r2 */
1049                 permutation[r] = r2;
1050
1051                 /* if we have reached a fixpoint update data structures */
1052                 if (live_nodes != NULL) {
1053                         ir_nodeset_remove(live_nodes, in[0]);
1054                         ir_nodeset_remove(live_nodes, in[1]);
1055                         ir_nodeset_remove(live_nodes, proj0);
1056                         ir_nodeset_insert(live_nodes, proj1);
1057                 }
1058         }
1059
1060 #ifdef DEBUG_libfirm
1061         /* now we should only have fixpoints left */
1062         for (r = 0; r < n_regs; ++r) {
1063                 assert(permutation[r] == r);
1064         }
1065 #endif
1066 }
1067
1068 /**
1069  * Free regs for values last used.
1070  *
1071  * @param live_nodes   set of live nodes, will be updated
1072  * @param node         the node to consider
1073  */
1074 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
1075 {
1076         allocation_info_t     *info      = get_allocation_info(node);
1077         const unsigned        *last_uses = &info->last_uses;
1078         int                    arity     = get_irn_arity(node);
1079         int                    i;
1080
1081         for (i = 0; i < arity; ++i) {
1082                 ir_node *op;
1083
1084                 /* check if one operand is the last use */
1085                 if (!rbitset_is_set(last_uses, i))
1086                         continue;
1087
1088                 op = get_irn_n(node, i);
1089                 free_reg_of_value(op);
1090                 ir_nodeset_remove(live_nodes, op);
1091         }
1092 }
1093
1094 /**
1095  * change inputs of a node to the current value (copies/perms)
1096  */
1097 static void rewire_inputs(ir_node *node)
1098 {
1099         int i;
1100         int arity = get_irn_arity(node);
1101
1102         for (i = 0; i < arity; ++i) {
1103                 ir_node           *op = get_irn_n(node, i);
1104                 allocation_info_t *info;
1105
1106                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1107                         continue;
1108
1109                 info = get_allocation_info(op);
1110                 info = get_allocation_info(info->original_value);
1111                 if (info->current_value != op) {
1112                         set_irn_n(node, i, info->current_value);
1113                 }
1114         }
1115 }
1116
1117 /**
1118  * Create a bitset of registers occupied with value living through an
1119  * instruction
1120  */
1121 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
1122 {
1123         const allocation_info_t *info = get_allocation_info(node);
1124         unsigned r;
1125         int i;
1126         int arity;
1127
1128         /* mark all used registers as potentially live-through */
1129         for (r = 0; r < n_regs; ++r) {
1130                 if (assignments[r] == NULL)
1131                         continue;
1132                 if (!rbitset_is_set(normal_regs, r))
1133                         continue;
1134
1135                 rbitset_set(bitset, r);
1136         }
1137
1138         /* remove registers of value dying at the instruction */
1139         arity = get_irn_arity(node);
1140         for (i = 0; i < arity; ++i) {
1141                 ir_node               *op;
1142                 const arch_register_t *reg;
1143
1144                 if (!rbitset_is_set(&info->last_uses, i))
1145                         continue;
1146
1147                 op  = get_irn_n(node, i);
1148                 reg = arch_get_irn_register(op);
1149                 rbitset_clear(bitset, arch_register_get_index(reg));
1150         }
1151 }
1152
1153 /**
1154  * Enforce constraints at a node by live range splits.
1155  *
1156  * @param  live_nodes  the set of live nodes, might be changed
1157  * @param  node        the current node
1158  */
1159 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node,
1160                                 unsigned *forbidden_regs)
1161 {
1162         int arity = get_irn_arity(node);
1163         int i, res;
1164         hungarian_problem_t *bp;
1165         unsigned l, r;
1166         unsigned *assignment;
1167
1168         /* construct a list of register occupied by live-through values */
1169         unsigned *live_through_regs = NULL;
1170
1171         /* see if any use constraints are not met */
1172         bool good = true;
1173         for (i = 0; i < arity; ++i) {
1174                 ir_node                   *op = get_irn_n(node, i);
1175                 const arch_register_t     *reg;
1176                 const arch_register_req_t *req;
1177                 const unsigned            *limited;
1178                 unsigned                  r;
1179
1180                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1181                         continue;
1182
1183                 /* are there any limitations for the i'th operand? */
1184                 req = arch_get_register_req(node, i);
1185                 if (!(req->type & arch_register_req_type_limited))
1186                         continue;
1187
1188                 limited = req->limited;
1189                 reg     = arch_get_irn_register(op);
1190                 r       = arch_register_get_index(reg);
1191                 if (!rbitset_is_set(limited, r)) {
1192                         /* found an assignment outside the limited set */
1193                         good = false;
1194                         break;
1195                 }
1196         }
1197
1198         /* is any of the live-throughs using a constrained output register? */
1199         if (get_irn_mode(node) == mode_T) {
1200                 const ir_edge_t *edge;
1201
1202                 foreach_out_edge(node, edge) {
1203                         ir_node *proj = get_edge_src_irn(edge);
1204                         const arch_register_req_t *req;
1205
1206                         if (!arch_irn_consider_in_reg_alloc(cls, proj))
1207                                 continue;
1208
1209                         req = arch_get_register_req_out(proj);
1210                         if (!(req->type & arch_register_req_type_limited))
1211                                 continue;
1212
1213                         if (live_through_regs == NULL) {
1214                                 rbitset_alloca(live_through_regs, n_regs);
1215                                 determine_live_through_regs(live_through_regs, node);
1216                         }
1217
1218                         rbitset_or(forbidden_regs, req->limited, n_regs);
1219                         if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
1220                                 good = false;
1221                         }
1222                 }
1223         } else {
1224                 if (arch_irn_consider_in_reg_alloc(cls, node)) {
1225                         const arch_register_req_t *req = arch_get_register_req_out(node);
1226                         if (req->type & arch_register_req_type_limited) {
1227                                 rbitset_alloca(live_through_regs, n_regs);
1228                                 determine_live_through_regs(live_through_regs, node);
1229                                 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
1230                                         good = false;
1231                                         rbitset_or(forbidden_regs, req->limited, n_regs);
1232                                 }
1233                         }
1234                 }
1235         }
1236
1237         if (good)
1238                 return;
1239
1240         /* create these arrays if we haven't yet */
1241         if (live_through_regs == NULL) {
1242                 rbitset_alloca(live_through_regs, n_regs);
1243         }
1244
1245         /* at this point we have to construct a bipartite matching problem to see
1246          * which values should go to which registers
1247          * Note: We're building the matrix in "reverse" - source registers are
1248          *       right, destinations left because this will produce the solution
1249          *       in the format required for permute_values.
1250          */
1251         bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
1252
1253         /* add all combinations, then remove not allowed ones */
1254         for (l = 0; l < n_regs; ++l) {
1255                 if (!rbitset_is_set(normal_regs, l)) {
1256                         hungarian_add(bp, l, l, 1);
1257                         continue;
1258                 }
1259
1260                 for (r = 0; r < n_regs; ++r) {
1261                         if (!rbitset_is_set(normal_regs, r))
1262                                 continue;
1263                         /* livethrough values may not use constrainted output registers */
1264                         if (rbitset_is_set(live_through_regs, l)
1265                                         && rbitset_is_set(forbidden_regs, r))
1266                                 continue;
1267
1268                         hungarian_add(bp, r, l, l == r ? 9 : 8);
1269                 }
1270         }
1271
1272         for (i = 0; i < arity; ++i) {
1273                 ir_node                   *op = get_irn_n(node, i);
1274                 const arch_register_t     *reg;
1275                 const arch_register_req_t *req;
1276                 const unsigned            *limited;
1277                 unsigned                   current_reg;
1278
1279                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1280                         continue;
1281
1282                 req = arch_get_register_req(node, i);
1283                 if (!(req->type & arch_register_req_type_limited))
1284                         continue;
1285
1286                 limited     = req->limited;
1287                 reg         = arch_get_irn_register(op);
1288                 current_reg = arch_register_get_index(reg);
1289                 for (r = 0; r < n_regs; ++r) {
1290                         if (rbitset_is_set(limited, r))
1291                                 continue;
1292                         hungarian_remv(bp, r, current_reg);
1293                 }
1294         }
1295
1296         //hungarian_print_cost_matrix(bp, 1);
1297         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1298
1299         assignment = ALLOCAN(unsigned, n_regs);
1300         res = hungarian_solve(bp, (int*) assignment, NULL, 0);
1301         assert(res == 0);
1302
1303 #if 0
1304         fprintf(stderr, "Swap result:");
1305         for (i = 0; i < (int) n_regs; ++i) {
1306                 fprintf(stderr, " %d", assignment[i]);
1307         }
1308         fprintf(stderr, "\n");
1309 #endif
1310
1311         hungarian_free(bp);
1312
1313         permute_values(live_nodes, node, assignment);
1314 }
1315
1316 /** test wether a node @p n is a copy of the value of node @p of */
1317 static bool is_copy_of(ir_node *value, ir_node *test_value)
1318 {
1319         allocation_info_t *test_info;
1320         allocation_info_t *info;
1321
1322         if (value == test_value)
1323                 return true;
1324
1325         info      = get_allocation_info(value);
1326         test_info = get_allocation_info(test_value);
1327         return test_info->original_value == info->original_value;
1328 }
1329
1330 /**
1331  * find a value in the end-assignment of a basic block
1332  * @returns the index into the assignment array if found
1333  *          -1 if not found
1334  */
1335 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1336 {
1337         unsigned   r;
1338         ir_node  **assignments = info->assignments;
1339         for (r = 0; r < n_regs; ++r) {
1340                 ir_node *a_value = assignments[r];
1341
1342                 if (a_value == NULL)
1343                         continue;
1344                 if (is_copy_of(a_value, value))
1345                         return (int) r;
1346         }
1347
1348         return -1;
1349 }
1350
1351 /**
1352  * Create the necessary permutations at the end of a basic block to fullfill
1353  * the register assignment for phi-nodes in the next block
1354  */
1355 static void add_phi_permutations(ir_node *block, int p)
1356 {
1357         unsigned   r;
1358         unsigned  *permutation;
1359         ir_node  **old_assignments;
1360         bool       need_permutation;
1361         ir_node   *node;
1362         ir_node   *pred = get_Block_cfgpred_block(block, p);
1363
1364         block_info_t *pred_info = get_block_info(pred);
1365
1366         /* predecessor not processed yet? nothing to do */
1367         if (!pred_info->processed)
1368                 return;
1369
1370         permutation = ALLOCAN(unsigned, n_regs);
1371         for (r = 0; r < n_regs; ++r) {
1372                 permutation[r] = r;
1373         }
1374
1375         /* check phi nodes */
1376         need_permutation = false;
1377         node = sched_first(block);
1378         for ( ; is_Phi(node); node = sched_next(node)) {
1379                 const arch_register_t *reg;
1380                 int                    regn;
1381                 int                    a;
1382                 ir_node               *op;
1383
1384                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1385                         continue;
1386
1387                 op = get_Phi_pred(node, p);
1388                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1389                         continue;
1390
1391                 a = find_value_in_block_info(pred_info, op);
1392                 assert(a >= 0);
1393
1394                 reg  = arch_get_irn_register(node);
1395                 regn = arch_register_get_index(reg);
1396                 if (regn != a) {
1397                         permutation[regn] = a;
1398                         need_permutation  = true;
1399                 }
1400         }
1401
1402         if (need_permutation) {
1403                 /* permute values at end of predecessor */
1404                 old_assignments = assignments;
1405                 assignments     = pred_info->assignments;
1406                 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1407                                                  permutation);
1408                 assignments = old_assignments;
1409         }
1410
1411         /* change phi nodes to use the copied values */
1412         node = sched_first(block);
1413         for ( ; is_Phi(node); node = sched_next(node)) {
1414                 int      a;
1415                 ir_node *op;
1416
1417                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1418                         continue;
1419
1420                 op = get_Phi_pred(node, p);
1421                 /* no need to do anything for Unknown inputs */
1422                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1423                         continue;
1424
1425                 /* we have permuted all values into the correct registers so we can
1426                    simply query which value occupies the phis register in the
1427                    predecessor */
1428                 a  = arch_register_get_index(arch_get_irn_register(node));
1429                 op = pred_info->assignments[a];
1430                 set_Phi_pred(node, p, op);
1431         }
1432 }
1433
1434 /**
1435  * Set preferences for a phis register based on the registers used on the
1436  * phi inputs.
1437  */
1438 static void adapt_phi_prefs(ir_node *phi)
1439 {
1440         int i;
1441         int arity = get_irn_arity(phi);
1442         ir_node           *block = get_nodes_block(phi);
1443         allocation_info_t *info  = get_allocation_info(phi);
1444
1445         for (i = 0; i < arity; ++i) {
1446                 ir_node               *op  = get_irn_n(phi, i);
1447                 const arch_register_t *reg = arch_get_irn_register(op);
1448                 ir_node               *pred_block;
1449                 block_info_t          *pred_block_info;
1450                 float                  weight;
1451                 unsigned               r;
1452
1453                 if (reg == NULL)
1454                         continue;
1455                 /* we only give the bonus if the predecessor already has registers
1456                  * assigned, otherwise we only see a dummy value
1457                  * and any conclusions about its register are useless */
1458                 pred_block = get_Block_cfgpred_block(block, i);
1459                 pred_block_info = get_block_info(pred_block);
1460                 if (!pred_block_info->processed)
1461                         continue;
1462
1463                 /* give bonus for already assigned register */
1464                 weight = get_block_execfreq(execfreqs, pred_block);
1465                 r      = arch_register_get_index(reg);
1466                 info->prefs[r] += weight * AFF_PHI;
1467         }
1468 }
1469
1470 /**
1471  * After a phi has been assigned a register propagate preference inputs
1472  * to the phi inputs.
1473  */
1474 static void propagate_phi_register(ir_node *phi, unsigned assigned_r)
1475 {
1476         int      i;
1477         ir_node *block = get_nodes_block(phi);
1478         int      arity = get_irn_arity(phi);
1479
1480         for (i = 0; i < arity; ++i) {
1481                 ir_node           *op         = get_Phi_pred(phi, i);
1482                 allocation_info_t *info       = get_allocation_info(op);
1483                 ir_node           *pred_block = get_Block_cfgpred_block(block, i);
1484                 unsigned           r;
1485                 float              weight
1486                         = get_block_execfreq(execfreqs, pred_block) * AFF_PHI;
1487
1488                 if (info->prefs[assigned_r] >= weight)
1489                         continue;
1490
1491                 /* promote the prefered register */
1492                 for (r = 0; r < n_regs; ++r) {
1493                         if (info->prefs[r] > -weight) {
1494                                 info->prefs[r] = -weight;
1495                         }
1496                 }
1497                 info->prefs[assigned_r] = weight;
1498
1499                 if (is_Phi(op))
1500                         propagate_phi_register(op, assigned_r);
1501         }
1502 }
1503
1504 static void assign_phi_registers(ir_node *block)
1505 {
1506         int                  n_phis = 0;
1507         int                  n;
1508         int                  res;
1509         int                 *assignment;
1510         ir_node             *node;
1511         hungarian_problem_t *bp;
1512
1513         /* count phi nodes */
1514         sched_foreach(block, node) {
1515                 if (!is_Phi(node))
1516                         break;
1517                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1518                         continue;
1519                 ++n_phis;
1520         }
1521
1522         if (n_phis == 0)
1523                 return;
1524
1525         /* build a bipartite matching problem for all phi nodes */
1526         bp = hungarian_new(n_phis, n_regs, HUNGARIAN_MATCH_PERFECT);
1527         n  = 0;
1528         sched_foreach(block, node) {
1529                 unsigned r;
1530
1531                 allocation_info_t *info;
1532                 if (!is_Phi(node))
1533                         break;
1534                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1535                         continue;
1536
1537                 /* give boni for predecessor colorings */
1538                 adapt_phi_prefs(node);
1539                 /* add stuff to bipartite problem */
1540                 info = get_allocation_info(node);
1541                 DB((dbg, LEVEL_3, "Prefs for %+F: ", node));
1542                 for (r = 0; r < n_regs; ++r) {
1543                         float costs;
1544
1545                         if (!rbitset_is_set(normal_regs, r))
1546                                 continue;
1547
1548                         costs = info->prefs[r];
1549                         costs = costs < 0 ? -logf(-costs+1) : logf(costs+1);
1550                         costs *= 100;
1551                         costs += 10000;
1552                         hungarian_add(bp, n, r, costs);
1553                         DB((dbg, LEVEL_3, " %s(%f)", arch_register_for_index(cls, r)->name,
1554                                                 info->prefs[r]));
1555                 }
1556                 DB((dbg, LEVEL_3, "\n"));
1557                 ++n;
1558         }
1559
1560         //hungarian_print_cost_matrix(bp, 7);
1561         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1562
1563         assignment = ALLOCAN(int, n_regs);
1564         res        = hungarian_solve(bp, assignment, NULL, 0);
1565         assert(res == 0);
1566
1567         /* apply results */
1568         n = 0;
1569         sched_foreach(block, node) {
1570                 unsigned               r;
1571                 const arch_register_t *reg;
1572
1573                 if (!is_Phi(node))
1574                         break;
1575                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1576                         continue;
1577
1578                 r   = assignment[n++];
1579                 assert(rbitset_is_set(normal_regs, r));
1580                 reg = arch_register_for_index(cls, r);
1581                 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
1582                 use_reg(node, reg);
1583
1584                 /* adapt preferences for phi inputs */
1585                 if (propagate_phi_registers)
1586                         propagate_phi_register(node, r);
1587         }
1588 }
1589
1590 /**
1591  * Walker: assign registers to all nodes of a block that
1592  * need registers from the currently considered register class.
1593  */
1594 static void allocate_coalesce_block(ir_node *block, void *data)
1595 {
1596         int                    i;
1597         ir_nodeset_t           live_nodes;
1598         ir_nodeset_iterator_t  iter;
1599         ir_node               *node;
1600         int                    n_preds;
1601         block_info_t          *block_info;
1602         block_info_t         **pred_block_infos;
1603         ir_node              **phi_ins;
1604         unsigned              *forbidden_regs; /**< collects registers which must
1605                                                 not be used for optimistic splits */
1606
1607         (void) data;
1608         DB((dbg, LEVEL_2, "* Block %+F\n", block));
1609
1610         /* clear assignments */
1611         block_info  = get_block_info(block);
1612         assignments = block_info->assignments;
1613
1614         ir_nodeset_init(&live_nodes);
1615
1616         /* gather regalloc infos of predecessor blocks */
1617         n_preds             = get_Block_n_cfgpreds(block);
1618         pred_block_infos    = ALLOCAN(block_info_t*, n_preds);
1619         for (i = 0; i < n_preds; ++i) {
1620                 ir_node      *pred      = get_Block_cfgpred_block(block, i);
1621                 block_info_t *pred_info = get_block_info(pred);
1622                 pred_block_infos[i]     = pred_info;
1623         }
1624
1625         phi_ins = ALLOCAN(ir_node*, n_preds);
1626
1627         /* collect live-in nodes and preassigned values */
1628         be_lv_foreach(lv, block, be_lv_state_in, i) {
1629                 const arch_register_t *reg;
1630                 int                    p;
1631                 bool                   need_phi = false;
1632
1633                 node = be_lv_get_irn(lv, block, i);
1634                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1635                         continue;
1636
1637                 /* check all predecessors for this value, if it is not everywhere the
1638                    same or unknown then we have to construct a phi
1639                    (we collect the potential phi inputs here) */
1640                 for (p = 0; p < n_preds; ++p) {
1641                         block_info_t *pred_info = pred_block_infos[p];
1642
1643                         if (!pred_info->processed) {
1644                                 /* use node for now, it will get fixed later */
1645                                 phi_ins[p] = node;
1646                                 need_phi   = true;
1647                         } else {
1648                                 int a = find_value_in_block_info(pred_info, node);
1649
1650                                 /* must live out of predecessor */
1651                                 assert(a >= 0);
1652                                 phi_ins[p] = pred_info->assignments[a];
1653                                 /* different value from last time? then we need a phi */
1654                                 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1655                                         need_phi = true;
1656                                 }
1657                         }
1658                 }
1659
1660                 if (need_phi) {
1661                         ir_mode                   *mode = get_irn_mode(node);
1662                         const arch_register_req_t *req  = get_default_req_current_cls();
1663                         ir_node                   *phi;
1664                         int                        i;
1665
1666                         phi = new_r_Phi(block, n_preds, phi_ins, mode);
1667                         be_set_phi_reg_req(phi, req);
1668
1669                         DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1670 #ifdef DEBUG_libfirm
1671                         for (i = 0; i < n_preds; ++i) {
1672                                 DB((dbg, LEVEL_3, " %+F", phi_ins[i]));
1673                         }
1674                         DB((dbg, LEVEL_3, "\n"));
1675 #endif
1676                         mark_as_copy_of(phi, node);
1677                         sched_add_after(block, phi);
1678
1679                         node = phi;
1680                 } else {
1681                         allocation_info_t *info = get_allocation_info(node);
1682                         info->current_value = phi_ins[0];
1683
1684                         /* Grab 1 of the inputs we constructed (might not be the same as
1685                          * "node" as we could see the same copy of the value in all
1686                          * predecessors */
1687                         node = phi_ins[0];
1688                 }
1689
1690                 /* if the node already has a register assigned use it */
1691                 reg = arch_get_irn_register(node);
1692                 if (reg != NULL) {
1693                         use_reg(node, reg);
1694                 }
1695
1696                 /* remember that this node is live at the beginning of the block */
1697                 ir_nodeset_insert(&live_nodes, node);
1698         }
1699
1700         rbitset_alloca(forbidden_regs, n_regs);
1701
1702         /* handle phis... */
1703         assign_phi_registers(block);
1704
1705         /* all live-ins must have a register */
1706 #ifdef DEBUG_libfirm
1707         foreach_ir_nodeset(&live_nodes, node, iter) {
1708                 const arch_register_t *reg = arch_get_irn_register(node);
1709                 assert(reg != NULL);
1710         }
1711 #endif
1712
1713         /* assign instructions in the block */
1714         sched_foreach(block, node) {
1715                 int i;
1716                 int arity;
1717
1718                 /* phis are already assigned */
1719                 if (is_Phi(node))
1720                         continue;
1721
1722                 rewire_inputs(node);
1723
1724                 /* enforce use constraints */
1725                 rbitset_clear_all(forbidden_regs, n_regs);
1726                 enforce_constraints(&live_nodes, node, forbidden_regs);
1727
1728                 rewire_inputs(node);
1729
1730                 /* we may not use registers used for inputs for optimistic splits */
1731                 arity = get_irn_arity(node);
1732                 for (i = 0; i < arity; ++i) {
1733                         ir_node *op = get_irn_n(node, i);
1734                         const arch_register_t *reg;
1735                         if (!arch_irn_consider_in_reg_alloc(cls, op))
1736                                 continue;
1737
1738                         reg = arch_get_irn_register(op);
1739                         rbitset_set(forbidden_regs, arch_register_get_index(reg));
1740                 }
1741
1742                 /* free registers of values last used at this instruction */
1743                 free_last_uses(&live_nodes, node);
1744
1745                 /* assign output registers */
1746                 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1747                 if (get_irn_mode(node) == mode_T) {
1748                         const ir_edge_t *edge;
1749                         foreach_out_edge(node, edge) {
1750                                 ir_node *proj = get_edge_src_irn(edge);
1751                                 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1752                                         continue;
1753                                 assign_reg(block, proj, forbidden_regs);
1754                         }
1755                 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1756                         assign_reg(block, node, forbidden_regs);
1757                 }
1758         }
1759
1760         ir_nodeset_destroy(&live_nodes);
1761         assignments = NULL;
1762
1763         block_info->processed = true;
1764
1765         /* permute values at end of predecessor blocks in case of phi-nodes */
1766         if (n_preds > 1) {
1767                 int p;
1768                 for (p = 0; p < n_preds; ++p) {
1769                         add_phi_permutations(block, p);
1770                 }
1771         }
1772
1773         /* if we have exactly 1 successor then we might be able to produce phi
1774            copies now */
1775         if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1776                 const ir_edge_t *edge
1777                         = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1778                 ir_node      *succ      = get_edge_src_irn(edge);
1779                 int           p         = get_edge_src_pos(edge);
1780                 block_info_t *succ_info = get_block_info(succ);
1781
1782                 if (succ_info->processed) {
1783                         add_phi_permutations(succ, p);
1784                 }
1785         }
1786 }
1787
1788 typedef struct block_costs_t block_costs_t;
1789 struct block_costs_t {
1790         float costs;   /**< costs of the block */
1791         int   dfs_num; /**< depth first search number (to detect backedges) */
1792 };
1793
1794 static int cmp_block_costs(const void *d1, const void *d2)
1795 {
1796         const ir_node       * const *block1 = d1;
1797         const ir_node       * const *block2 = d2;
1798         const block_costs_t *info1  = get_irn_link(*block1);
1799         const block_costs_t *info2  = get_irn_link(*block2);
1800         return QSORT_CMP(info2->costs, info1->costs);
1801 }
1802
1803 static void determine_block_order(void)
1804 {
1805         int i;
1806         ir_node **blocklist = be_get_cfgpostorder(irg);
1807         int       n_blocks  = ARR_LEN(blocklist);
1808         int       dfs_num   = 0;
1809         pdeq     *worklist  = new_pdeq();
1810         ir_node **order     = XMALLOCN(ir_node*, n_blocks);
1811         int       order_p   = 0;
1812
1813         /* clear block links... */
1814         for (i = 0; i < n_blocks; ++i) {
1815                 ir_node *block = blocklist[i];
1816                 set_irn_link(block, NULL);
1817         }
1818
1819         /* walk blocks in reverse postorder, the costs for each block are the
1820          * sum of the costs of its predecessors (excluding the costs on backedges
1821          * which we can't determine) */
1822         for (i = n_blocks-1; i >= 0; --i) {
1823                 block_costs_t *cost_info;
1824                 ir_node *block = blocklist[i];
1825
1826                 float execfreq   = get_block_execfreq(execfreqs, block);
1827                 float costs      = execfreq;
1828                 int   n_cfgpreds = get_Block_n_cfgpreds(block);
1829                 int   p;
1830                 for (p = 0; p < n_cfgpreds; ++p) {
1831                         ir_node       *pred_block = get_Block_cfgpred_block(block, p);
1832                         block_costs_t *pred_costs = get_irn_link(pred_block);
1833                         /* we don't have any info for backedges */
1834                         if (pred_costs == NULL)
1835                                 continue;
1836                         costs += pred_costs->costs;
1837                 }
1838
1839                 cost_info          = OALLOCZ(&obst, block_costs_t);
1840                 cost_info->costs   = costs;
1841                 cost_info->dfs_num = dfs_num++;
1842                 set_irn_link(block, cost_info);
1843         }
1844
1845         /* sort array by block costs */
1846         qsort(blocklist, n_blocks, sizeof(blocklist[0]), cmp_block_costs);
1847
1848         ir_reserve_resources(irg, IR_RESOURCE_BLOCK_VISITED);
1849         inc_irg_block_visited(irg);
1850
1851         for (i = 0; i < n_blocks; ++i) {
1852                 ir_node       *block = blocklist[i];
1853                 if (Block_block_visited(block))
1854                         continue;
1855
1856                 /* continually add predecessors with highest costs to worklist
1857                  * (without using backedges) */
1858                 do {
1859                         block_costs_t *info       = get_irn_link(block);
1860                         ir_node       *best_pred  = NULL;
1861                         float          best_costs = -1;
1862                         int            n_cfgpred  = get_Block_n_cfgpreds(block);
1863                         int            i;
1864
1865                         pdeq_putr(worklist, block);
1866                         mark_Block_block_visited(block);
1867                         for (i = 0; i < n_cfgpred; ++i) {
1868                                 ir_node       *pred_block = get_Block_cfgpred_block(block, i);
1869                                 block_costs_t *pred_info  = get_irn_link(pred_block);
1870
1871                                 /* ignore backedges */
1872                                 if (pred_info->dfs_num > info->dfs_num)
1873                                         continue;
1874
1875                                 if (info->costs > best_costs) {
1876                                         best_costs = info->costs;
1877                                         best_pred  = pred_block;
1878                                 }
1879                         }
1880                         block = best_pred;
1881                 } while(block != NULL && !Block_block_visited(block));
1882
1883                 /* now put all nodes in the worklist in our final order */
1884                 while (!pdeq_empty(worklist)) {
1885                         ir_node *pblock = pdeq_getr(worklist);
1886                         assert(order_p < n_blocks);
1887                         order[order_p++] = pblock;
1888                 }
1889         }
1890         assert(order_p == n_blocks);
1891         del_pdeq(worklist);
1892
1893         ir_free_resources(irg, IR_RESOURCE_BLOCK_VISITED);
1894
1895         DEL_ARR_F(blocklist);
1896
1897         obstack_free(&obst, NULL);
1898         obstack_init(&obst);
1899
1900         block_order   = order;
1901         n_block_order = n_blocks;
1902 }
1903
1904 /**
1905  * Run the register allocator for the current register class.
1906  */
1907 static void be_straight_alloc_cls(void)
1908 {
1909         int i;
1910
1911         lv = be_assure_liveness(birg);
1912         be_liveness_assure_sets(lv);
1913         be_liveness_assure_chk(lv);
1914
1915         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
1916
1917         DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1918
1919         be_clear_links(irg);
1920
1921         irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1922         if (create_congruence_classes)
1923                 combine_congruence_classes();
1924
1925         for (i = 0; i < n_block_order; ++i) {
1926                 ir_node *block = block_order[i];
1927                 allocate_coalesce_block(block, NULL);
1928         }
1929
1930         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
1931 }
1932
1933 static void dump(int mask, ir_graph *irg, const char *suffix,
1934                  void (*dumper)(ir_graph *, const char *))
1935 {
1936         if(birg->main_env->options->dump_flags & mask)
1937                 be_dump(irg, suffix, dumper);
1938 }
1939
1940 /**
1941  * Run the spiller on the current graph.
1942  */
1943 static void spill(void)
1944 {
1945         /* make sure all nodes show their real register pressure */
1946         BE_TIMER_PUSH(t_ra_constr);
1947         be_pre_spill_prepare_constr(birg, cls);
1948         BE_TIMER_POP(t_ra_constr);
1949
1950         dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1951
1952         /* spill */
1953         BE_TIMER_PUSH(t_ra_spill);
1954         be_do_spill(birg, cls);
1955         BE_TIMER_POP(t_ra_spill);
1956
1957         BE_TIMER_PUSH(t_ra_spill_apply);
1958         check_for_memory_operands(irg);
1959         BE_TIMER_POP(t_ra_spill_apply);
1960
1961         dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1962 }
1963
1964 /**
1965  * The straight register allocator for a whole procedure.
1966  */
1967 static void be_straight_alloc(be_irg_t *new_birg)
1968 {
1969         const arch_env_t *arch_env = new_birg->main_env->arch_env;
1970         int   n_cls                = arch_env_get_n_reg_class(arch_env);
1971         int   c;
1972
1973         obstack_init(&obst);
1974
1975         birg      = new_birg;
1976         irg       = be_get_birg_irg(birg);
1977         execfreqs = birg->exec_freq;
1978
1979         /* determine a good coloring order */
1980         determine_block_order();
1981
1982         for (c = 0; c < n_cls; ++c) {
1983                 cls             = arch_env_get_reg_class(arch_env, c);
1984                 default_cls_req = NULL;
1985                 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1986                         continue;
1987
1988                 stat_ev_ctx_push_str("regcls", cls->name);
1989
1990                 n_regs      = arch_register_class_n_regs(cls);
1991                 normal_regs = rbitset_malloc(n_regs);
1992                 be_abi_set_non_ignore_regs(birg->abi, cls, normal_regs);
1993
1994                 spill();
1995
1996                 /* verify schedule and register pressure */
1997                 BE_TIMER_PUSH(t_verify);
1998                 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1999                         be_verify_schedule(birg);
2000                         be_verify_register_pressure(birg, cls, irg);
2001                 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
2002                         assert(be_verify_schedule(birg) && "Schedule verification failed");
2003                         assert(be_verify_register_pressure(birg, cls, irg)
2004                                 && "Register pressure verification failed");
2005                 }
2006                 BE_TIMER_POP(t_verify);
2007
2008                 BE_TIMER_PUSH(t_ra_color);
2009                 be_straight_alloc_cls();
2010                 BE_TIMER_POP(t_ra_color);
2011
2012                 /* we most probably constructed new Phis so liveness info is invalid
2013                  * now */
2014                 /* TODO: test liveness_introduce */
2015                 be_liveness_invalidate(lv);
2016                 free(normal_regs);
2017
2018                 stat_ev_ctx_pop("regcls");
2019         }
2020
2021         BE_TIMER_PUSH(t_ra_spill_apply);
2022         be_abi_fix_stack_nodes(birg->abi);
2023         BE_TIMER_POP(t_ra_spill_apply);
2024
2025         BE_TIMER_PUSH(t_verify);
2026         if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
2027                 be_verify_register_allocation(birg);
2028         } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
2029                 assert(be_verify_register_allocation(birg)
2030                                 && "Register allocation invalid");
2031         }
2032         BE_TIMER_POP(t_verify);
2033
2034         obstack_free(&obst, NULL);
2035 }
2036
2037 /**
2038  * Initializes this module.
2039  */
2040 void be_init_straight_alloc(void)
2041 {
2042         static be_ra_t be_ra_straight = {
2043                 be_straight_alloc,
2044         };
2045         lc_opt_entry_t *be_grp              = lc_opt_get_grp(firm_opt_get_root(), "be");
2046         lc_opt_entry_t *straightalloc_group = lc_opt_get_grp(be_grp, "straightalloc");
2047         lc_opt_add_table(straightalloc_group, options);
2048
2049         be_register_allocator("straight", &be_ra_straight);
2050         FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
2051 }
2052
2053 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);