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