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