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