fix a bug in constraint enforcement; improve phi handling and phi0 construction ...
[libfirm] / ir / be / benewalloc.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       New approach to allocation and copy coalescing
23  * @author      Matthias Braun
24  * @date        14.2.2009
25  * @version     $Id$
26  *
27  * ... WE NEED A NAME FOR THIS ...
28  *
29  * Only a proof of concept at this moment...
30  *
31  * The idea is to allocate registers in 2 passes:
32  * 1. A first pass to determine "preferred" registers for live-ranges. This
33  *    calculates for each register and each live-range a value indicating
34  *    the usefulness. (You can roughly think of the value as the negative
35  *    costs needed for copies when the value is in the specific registers...)
36  *
37  * 2. Walk blocks and assigns registers in a greedy fashion. Preferring
38  *    registers with high preferences. When register constraints are not met,
39  *    add copies and split live-ranges.
40  *
41  * TODO:
42  *  - make use of free registers in the permutate_values code
43  *  - We have to pessimistically construct Phi_0s when not all predecessors
44  *    of a block are known.
45  *  - Phi color assignment should give bonus points towards registers already
46  *    assigned at predecessors.
47  *  - think about a smarter sequence of visiting the blocks. Sorted by
48  *    execfreq might be good, or looptree from inner to outermost loops going
49  *    over blocks in a reverse postorder
50  */
51 #include "config.h"
52
53 #include <float.h>
54 #include <stdbool.h>
55
56 #include "obst.h"
57 #include "irnode_t.h"
58 #include "irgraph_t.h"
59 #include "iredges_t.h"
60 #include "ircons.h"
61 #include "irgwalk.h"
62 #include "irdom.h"
63 #include "execfreq.h"
64 #include "error.h"
65
66 #include "be.h"
67 #include "bera.h"
68 #include "belive_t.h"
69 #include "bemodule.h"
70 #include "bechordal_t.h"
71 #include "besched.h"
72 #include "beirg.h"
73 #include "benode_t.h"
74 #include "bespill.h"
75 #include "bespillutil.h"
76 #include "beverify.h"
77
78 #include "bipartite.h"
79 #include "hungarian.h"
80
81 #define USE_FACTOR         1.0f
82 #define DEF_FACTOR         1.0f
83 #define NEIGHBOR_FACTOR    0.2f
84 #define AFF_SHOULD_BE_SAME 1.0f
85 #define AFF_PHI            1.0f
86
87 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
88
89 static struct obstack               obst;
90 static be_irg_t                    *birg;
91 static ir_graph                    *irg;
92 static const arch_register_class_t *cls;
93 static const arch_register_req_t   *default_cls_req;
94 static be_lv_t                     *lv;
95 static const ir_exec_freq          *execfreqs;
96 static unsigned                     n_regs;
97 static bitset_t                    *ignore_regs;
98
99 /** info about the current assignment for a register */
100 struct assignment_t {
101         ir_node *value;            /**< currently assigned value */
102 };
103 typedef struct assignment_t assignment_t;
104
105 /** currently active assignments (while processing a basic block) */
106 static assignment_t *assignments;
107
108 /**
109  * allocation information: last_uses, register preferences
110  * the information is per firm-node.
111  */
112 struct allocation_info_t {
113         unsigned  last_uses;      /**< bitset indicating last uses (input pos) */
114         ir_node  *current_value;  /**< copy of the value that should be used */
115         ir_node  *original_value; /**< for copies point to original value */
116         float     prefs[0];       /**< register preferences */
117 };
118 typedef struct allocation_info_t allocation_info_t;
119
120 /** helper datastructure used when sorting register preferences */
121 struct reg_pref_t {
122         unsigned num;
123         float    pref;
124 };
125 typedef struct reg_pref_t reg_pref_t;
126
127 /** per basic-block information */
128 struct block_info_t {
129         bool         processed;       /**< indicate wether block is processed */
130         assignment_t assignments[0];  /**< register assignments at end of block */
131 };
132 typedef struct block_info_t block_info_t;
133
134 /**
135  * Get the allocation info for a node.
136  * The info is allocated on the first visit of a node.
137  */
138 static allocation_info_t *get_allocation_info(ir_node *node)
139 {
140         allocation_info_t *info;
141         if (!irn_visited_else_mark(node)) {
142                 size_t size = sizeof(info[0]) + n_regs * sizeof(info->prefs[0]);
143                 info = obstack_alloc(&obst, size);
144                 memset(info, 0, size);
145                 info->current_value  = node;
146                 info->original_value = node;
147                 set_irn_link(node, info);
148         } else {
149                 info = get_irn_link(node);
150         }
151
152         return info;
153 }
154
155 /**
156  * Get allocation information for a basic block
157  */
158 static block_info_t *get_block_info(ir_node *block)
159 {
160         block_info_t *info;
161
162         assert(is_Block(block));
163         if (!irn_visited_else_mark(block)) {
164                 size_t size = sizeof(info[0]) + n_regs * sizeof(info->assignments[0]);
165                 info = obstack_alloc(&obst, size);
166                 memset(info, 0, size);
167                 set_irn_link(block, info);
168         } else {
169                 info = get_irn_link(block);
170         }
171
172         return info;
173 }
174
175 /**
176  * Get default register requirement for the current register class
177  */
178 static const arch_register_req_t *get_default_req_current_cls(void)
179 {
180         if (default_cls_req == NULL) {
181                 struct obstack      *obst = get_irg_obstack(irg);
182                 arch_register_req_t *req  = obstack_alloc(obst, sizeof(*req));
183                 memset(req, 0, sizeof(*req));
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 over allocation preferences */
219         memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
220         copy_info->original_value = original;
221 }
222
223 /**
224  * Calculate the penalties for every register on a node and its live neighbors.
225  *
226  * @param live_nodes  the set of live nodes at the current position, may be NULL
227  * @param penalty     the penalty to subtract from
228  * @param limited     a raw bitset containing the limited set for the node
229  * @param node        the node
230  */
231 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
232                                       float penalty, const unsigned* limited,
233                                       ir_node *node)
234 {
235         ir_nodeset_iterator_t iter;
236         unsigned              r;
237         allocation_info_t     *info = get_allocation_info(node);
238         ir_node               *neighbor;
239
240         /* give penalty for all forbidden regs */
241         for (r = 0; r < n_regs; ++r) {
242                 if (rbitset_is_set(limited, r))
243                         continue;
244
245                 info->prefs[r] -= penalty;
246         }
247
248         /* all other live values should get a penalty for allowed regs */
249         if (live_nodes == NULL)
250                 return;
251
252         /* TODO: reduce penalty if there are multiple allowed registers... */
253         penalty *= NEIGHBOR_FACTOR;
254         foreach_ir_nodeset(live_nodes, neighbor, iter) {
255                 allocation_info_t *neighbor_info;
256
257                 /* TODO: if op is used on multiple inputs we might not do a
258                  * continue here */
259                 if (neighbor == node)
260                         continue;
261
262                 neighbor_info = get_allocation_info(neighbor);
263                 for (r = 0; r < n_regs; ++r) {
264                         if (!rbitset_is_set(limited, r))
265                                 continue;
266
267                         neighbor_info->prefs[r] -= penalty;
268                 }
269         }
270 }
271
272 /**
273  * Calculate the preferences of a definition for the current register class.
274  * If the definition uses a limited set of registers, reduce the preferences
275  * for the limited register on the node and its neighbors.
276  *
277  * @param live_nodes  the set of live nodes at the current node
278  * @param weight      the weight
279  * @param node        the current node
280  */
281 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
282                        ir_node *node)
283 {
284         const arch_register_req_t *req;
285
286         if (get_irn_mode(node) == mode_T) {
287                 const ir_edge_t *edge;
288                 foreach_out_edge(node, edge) {
289                         ir_node *proj = get_edge_src_irn(edge);
290                         check_defs(live_nodes, weight, proj);
291                 }
292                 return;
293         }
294
295         if (!arch_irn_consider_in_reg_alloc(cls, node))
296                 return;
297
298         req = arch_get_register_req_out(node);
299         if (req->type & arch_register_req_type_limited) {
300                 const unsigned *limited = req->limited;
301                 float           penalty = weight * DEF_FACTOR;
302                 give_penalties_for_limits(live_nodes, penalty, limited, node);
303         }
304
305         if (req->type & arch_register_req_type_should_be_same) {
306                 ir_node           *insn  = skip_Proj(node);
307                 allocation_info_t *info  = get_allocation_info(node);
308                 int                arity = get_irn_arity(insn);
309                 int                i;
310
311                 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
312                 for (i = 0; i < arity; ++i) {
313                         ir_node           *op;
314                         unsigned           r;
315                         allocation_info_t *op_info;
316
317                         if (!rbitset_is_set(&req->other_same, i))
318                                 continue;
319
320                         op      = get_irn_n(insn, i);
321                         op_info = get_allocation_info(op);
322                         for (r = 0; r < n_regs; ++r) {
323                                 if (bitset_is_set(ignore_regs, r))
324                                         continue;
325                                 op_info->prefs[r] += info->prefs[r] * factor;
326                         }
327                 }
328         }
329 }
330
331 /**
332  * Walker: Runs an a block calculates the preferences for any
333  * node and every register from the considered register class.
334  */
335 static void analyze_block(ir_node *block, void *data)
336 {
337         float         weight = get_block_execfreq(execfreqs, block);
338         ir_nodeset_t  live_nodes;
339         ir_node      *node;
340         (void) data;
341
342         ir_nodeset_init(&live_nodes);
343         be_liveness_end_of_block(lv, cls, block, &live_nodes);
344
345         sched_foreach_reverse(block, node) {
346                 allocation_info_t *info;
347                 int                i;
348                 int                arity;
349
350                 if (is_Phi(node))
351                         break;
352
353                 /* TODO give/take penalties for should_be_same/different) */
354                 check_defs(&live_nodes, weight, node);
355
356                 /* mark last uses */
357                 arity = get_irn_arity(node);
358
359                 /* the allocation info node currently only uses 1 unsigned value
360                    to mark last used inputs. So we will fail for a node with more than
361                    32 inputs. */
362                 if (arity >= (int) sizeof(unsigned) * 8) {
363                         panic("Node with more than %d inputs not supported yet",
364                                         (int) sizeof(unsigned) * 8);
365                 }
366
367                 info = get_allocation_info(node);
368                 for (i = 0; i < arity; ++i) {
369                         ir_node *op = get_irn_n(node, i);
370                         if (!arch_irn_consider_in_reg_alloc(cls, op))
371                                 continue;
372
373                         /* last usage of a value? */
374                         if (!ir_nodeset_contains(&live_nodes, op)) {
375                                 rbitset_set(&info->last_uses, i);
376                         }
377                 }
378
379                 be_liveness_transfer(cls, node, &live_nodes);
380
381                 /* update weights based on usage constraints */
382                 for (i = 0; i < arity; ++i) {
383                         const arch_register_req_t *req;
384                         const unsigned            *limited;
385                         ir_node                   *op = get_irn_n(node, i);
386
387                         if (!arch_irn_consider_in_reg_alloc(cls, op))
388                                 continue;
389
390                         req = arch_get_register_req(node, i);
391                         if (!(req->type & arch_register_req_type_limited))
392                                 continue;
393
394                         /* TODO: give penalties to neighbors for precolored nodes! */
395
396                         limited = req->limited;
397                         give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
398                                                   op);
399                 }
400         }
401
402         ir_nodeset_destroy(&live_nodes);
403 }
404
405 /**
406  * Assign register reg to the given node.
407  *
408  * @param node  the node
409  * @param reg   the register
410  */
411 static void use_reg(ir_node *node, const arch_register_t *reg)
412 {
413         unsigned      r          = arch_register_get_index(reg);
414         assignment_t *assignment = &assignments[r];
415
416         assert(assignment->value == NULL);
417         assignment->value = node;
418
419         arch_set_irn_register(node, reg);
420 }
421
422 /**
423  * Compare two register preferences in decreasing order.
424  */
425 static int compare_reg_pref(const void *e1, const void *e2)
426 {
427         const reg_pref_t *rp1 = (const reg_pref_t*) e1;
428         const reg_pref_t *rp2 = (const reg_pref_t*) e2;
429         if (rp1->pref < rp2->pref)
430                 return 1;
431         if (rp1->pref > rp2->pref)
432                 return -1;
433         return 0;
434 }
435
436 static void fill_sort_candidates(reg_pref_t *regprefs,
437                                  const allocation_info_t *info)
438 {
439         unsigned r;
440
441         for (r = 0; r < n_regs; ++r) {
442                 float pref = info->prefs[r];
443                 if (bitset_is_set(ignore_regs, r)) {
444                         pref = -10000;
445                 }
446                 regprefs[r].num  = r;
447                 regprefs[r].pref = pref;
448         }
449         /* TODO: use a stable sort here to avoid unnecessary register jumping */
450         qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
451 }
452
453 /**
454  * Determine and assign a register for node @p node
455  */
456 static void assign_reg(const ir_node *block, ir_node *node)
457 {
458         const arch_register_t     *reg;
459         allocation_info_t         *info;
460         const arch_register_req_t *req;
461         reg_pref_t                *reg_prefs;
462         ir_node                   *in_node;
463         unsigned                  i;
464
465         assert(arch_irn_consider_in_reg_alloc(cls, node));
466
467         /* preassigned register? */
468         reg = arch_get_irn_register(node);
469         if (reg != NULL) {
470                 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
471                 use_reg(node, reg);
472                 return;
473         }
474
475         /* give should_be_same boni */
476         info = get_allocation_info(node);
477         req  = arch_get_register_req_out(node);
478
479         in_node = skip_Proj(node);
480         if (req->type & arch_register_req_type_should_be_same) {
481                 float weight = get_block_execfreq(execfreqs, block);
482                 int   arity  = get_irn_arity(in_node);
483                 int   i;
484
485                 assert(arity <= (int) sizeof(req->other_same) * 8);
486                 for (i = 0; i < arity; ++i) {
487                         ir_node               *in;
488                         const arch_register_t *reg;
489                         unsigned               r;
490                         if (!rbitset_is_set(&req->other_same, i))
491                                 continue;
492
493                         in  = get_irn_n(in_node, i);
494                         reg = arch_get_irn_register(in);
495                         assert(reg != NULL);
496                         r = arch_register_get_index(reg);
497                         if (bitset_is_set(ignore_regs, r))
498                                 continue;
499                         info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
500                 }
501         }
502
503         DB((dbg, LEVEL_2, "Candidates for %+F:", node));
504         reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
505         fill_sort_candidates(reg_prefs, info);
506         for (i = 0; i < n_regs; ++i) {
507                 unsigned               num = reg_prefs[i].num;
508                 const arch_register_t *reg = arch_register_for_index(cls, num);
509                 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
510         }
511         DB((dbg, LEVEL_2, "\n"));
512
513         for (i = 0; i < n_regs; ++i) {
514                 unsigned r = reg_prefs[i].num;
515                 /* ignores are last and we should have at least 1 non-ignore left */
516                 assert(!bitset_is_set(ignore_regs, r));
517                 /* already used?
518                    TODO: It might be better to copy the value occupying the register
519                    around here instead of trying the next one, find out when... */
520                 if (assignments[r].value != NULL)
521                         continue;
522                 reg = arch_register_for_index(cls, r);
523                 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
524                 use_reg(node, reg);
525                 break;
526         }
527 }
528
529 static void free_reg_of_value(ir_node *node)
530 {
531         assignment_t          *assignment;
532         const arch_register_t *reg;
533         unsigned               r;
534
535         if (!arch_irn_consider_in_reg_alloc(cls, node))
536                 return;
537
538         reg               = arch_get_irn_register(node);
539         r                 = arch_register_get_index(reg);
540         assignment        = &assignments[r];
541         assert(assignment->value == node);
542         assignment->value = NULL;
543 }
544
545 /**
546  * Add an permutation in front of a node and change the assignments
547  * due to this permutation.
548  *
549  * To understand this imagine a permutation like this:
550  *
551  * 1 -> 2
552  * 2 -> 3
553  * 3 -> 1, 5
554  * 4 -> 6
555  * 5
556  * 6
557  * 7 -> 7
558  *
559  * First we count how many destinations a single value has. At the same time
560  * we can be sure that each destination register has at most 1 source register
561  * (it can have 0 which means we don't care what value is in it).
562  * We ignore all fullfilled permuations (like 7->7)
563  * In a first pass we create as much copy instructions as possible as they
564  * are generally cheaper than exchanges. We do this by counting into how many
565  * destinations a register has to be copied (in the example it's 2 for register
566  * 3, or 1 for the registers 1,2,4 and 7).
567  * We can then create a copy into every destination register when the usecount
568  * of that register is 0 (= noone else needs the value in the register).
569  *
570  * After this step we should have cycles left. We implement a cyclic permutation
571  * of n registers with n-1 transpositions.
572  *
573  * @param live_nodes   the set of live nodes, updated due to live range split
574  * @param before       the node before we add the permutation
575  * @param permutation  the permutation array indices are the destination
576  *                     registers, the values in the array are the source
577  *                     registers.
578  */
579 static void permutate_values(ir_nodeset_t *live_nodes, ir_node *before,
580                              unsigned *permutation)
581 {
582         ir_node   *block;
583         ir_node  **ins    = ALLOCANZ(ir_node*, n_regs);
584         unsigned  *n_used = ALLOCANZ(unsigned, n_regs);
585         unsigned   r;
586
587         /* create a list of permutations. Leave out fix points. */
588         for (r = 0; r < n_regs; ++r) {
589                 unsigned      old_reg = permutation[r];
590                 assignment_t *assignment;
591                 ir_node      *value;
592
593                 /* no need to do anything for a fixpoint */
594                 if (old_reg == r)
595                         continue;
596
597                 assignment = &assignments[old_reg];
598                 value      = assignment->value;
599                 if (value == NULL) {
600                         /* nothing to do here, reg is not live. Mark it as fixpoint
601                          * so we ignore it in the next steps */
602                         permutation[r] = r;
603                         continue;
604                 }
605
606                 ins[old_reg] = value;
607                 ++n_used[old_reg];
608                 free_reg_of_value(value);
609
610                 /* free occupation infos, we'll add the values back later */
611                 if (live_nodes != NULL) {
612                         ir_nodeset_remove(live_nodes, value);
613                 }
614         }
615
616         block = get_nodes_block(before);
617
618         /* step1: create copies where immediately possible */
619         for (r = 0; r < n_regs; /* empty */) {
620                 ir_node *copy;
621                 ir_node *src;
622                 const arch_register_t *reg;
623                 unsigned               old_r = permutation[r];
624
625                 /* - no need to do anything for fixed points.
626                    - we can't copy if the value in the dest reg is still needed */
627                 if (old_r == r || n_used[r] > 0) {
628                         ++r;
629                         continue;
630                 }
631
632                 /* create a copy */
633                 src = ins[old_r];
634                 copy = be_new_Copy(cls, block, src);
635                 sched_add_before(before, copy);
636                 reg = arch_register_for_index(cls, r);
637                 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
638                     copy, src, before, reg->name));
639                 mark_as_copy_of(copy, src);
640                 use_reg(copy, reg);
641
642                 if (live_nodes != NULL) {
643                         ir_nodeset_insert(live_nodes, copy);
644                 }
645
646                 /* old register has 1 user less, permutation is resolved */
647                 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
648                 assert(n_used[old_r] > 0);
649                 --n_used[old_r];
650                 permutation[r] = r;
651
652                 /* advance or jump back (if this copy enabled another copy) */
653                 if (old_r < r && n_used[old_r] == 0) {
654                         r = old_r;
655                 } else {
656                         ++r;
657                 }
658         }
659
660         /* at this point we only have "cycles" left which we have to resolve with
661          * perm instructions
662          * TODO: if we have free registers left, then we should really use copy
663          * instructions for any cycle longer than 2 registers...
664          * (this is probably architecture dependent, there might be archs where
665          *  copies are preferable even for 2-cycles) */
666
667         /* create perms with the rest */
668         for (r = 0; r < n_regs; /* empty */) {
669                 const arch_register_t *reg;
670                 unsigned  old_r = permutation[r];
671                 unsigned  r2;
672                 ir_node  *in[2];
673                 ir_node  *perm;
674                 ir_node  *proj0;
675                 ir_node  *proj1;
676
677                 if (old_r == r) {
678                         ++r;
679                         continue;
680                 }
681
682                 /* we shouldn't have copies from 1 value to multiple destinations left*/
683                 assert(n_used[old_r] == 1);
684
685                 /* exchange old_r and r2; after that old_r is a fixed point */
686                 r2 = permutation[old_r];
687
688                 in[0] = ins[r2];
689                 in[1] = ins[old_r];
690                 perm = be_new_Perm(cls, block, 2, in);
691                 sched_add_before(before, perm);
692                 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
693                     perm, in[0], in[1], before));
694
695                 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
696                 mark_as_copy_of(proj0, in[0]);
697                 reg = arch_register_for_index(cls, old_r);
698                 use_reg(proj0, reg);
699                 if (live_nodes != NULL) {
700                         ir_nodeset_insert(live_nodes, proj0);
701                 }
702
703                 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
704
705                 /* 1 value is now in the correct register */
706                 permutation[old_r] = old_r;
707                 /* the source of r changed to r2 */
708                 permutation[r] = r2;
709                 ins[r2] = in[1];
710                 reg = arch_register_for_index(cls, r2);
711                 if (r == r2) {
712                         /* if we have reached a fixpoint update data structures */
713                         mark_as_copy_of(proj1, in[1]);
714                         use_reg(proj1, reg);
715                         if (live_nodes != NULL) {
716                                 ir_nodeset_insert(live_nodes, proj1);
717                         }
718                 } else {
719                         arch_set_irn_register(proj1, reg);
720                 }
721         }
722
723 #ifdef DEBUG_libfirm
724         /* now we should only have fixpoints left */
725         for (r = 0; r < n_regs; ++r) {
726                 assert(permutation[r] == r);
727         }
728 #endif
729 }
730
731 /**
732  * Free regs for values last used.
733  *
734  * @param live_nodes   set of live nodes, will be updated
735  * @param node         the node to consider
736  */
737 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
738 {
739         allocation_info_t *info      = get_allocation_info(node);
740         const unsigned    *last_uses = &info->last_uses;
741         int                arity     = get_irn_arity(node);
742         int                i;
743         for (i = 0; i < arity; ++i) {
744                 ir_node *op;
745
746                 /* check if one operand is the last use */
747                 if (!rbitset_is_set(last_uses, i))
748                         continue;
749
750                 op = get_irn_n(node, i);
751                 free_reg_of_value(op);
752                 ir_nodeset_remove(live_nodes, op);
753         }
754 }
755
756 /**
757  * Create a bitset of registers occupied with value living through an
758  * instruction
759  */
760 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
761 {
762         const allocation_info_t *info = get_allocation_info(node);
763         unsigned r;
764         int i;
765         int arity;
766
767         /* mark all used registers as potentially live-through */
768         for (r = 0; r < n_regs; ++r) {
769                 const assignment_t *assignment = &assignments[r];
770                 if (assignment->value == NULL)
771                         continue;
772
773                 rbitset_set(bitset, r);
774         }
775
776         /* remove registers of value dying at the instruction */
777         arity = get_irn_arity(node);
778         for (i = 0; i < arity; ++i) {
779                 ir_node               *op;
780                 const arch_register_t *reg;
781
782                 if (!rbitset_is_set(&info->last_uses, i))
783                         continue;
784
785                 op  = get_irn_n(node, i);
786                 reg = arch_get_irn_register(op);
787                 rbitset_clear(bitset, arch_register_get_index(reg));
788         }
789 }
790
791 /**
792  * Enforce constraints at a node by live range splits.
793  *
794  * @param live_nodes  the set of live nodes, might be changed
795  * @param node        the current node
796  */
797 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node)
798 {
799         int arity = get_irn_arity(node);
800         int i, dummy, res;
801         hungarian_problem_t *bp;
802         unsigned l, r;
803         unsigned *assignment;
804
805         /* see if any use constraints are not met */
806         bool good = true;
807         for (i = 0; i < arity; ++i) {
808                 ir_node                   *op = get_irn_n(node, i);
809                 const arch_register_t     *reg;
810                 const arch_register_req_t *req;
811                 const unsigned            *limited;
812                 unsigned                  r;
813
814                 if (!arch_irn_consider_in_reg_alloc(cls, op))
815                         continue;
816
817                 /* are there any limitations for the i'th operand? */
818                 req = arch_get_register_req(node, i);
819                 if (!(req->type & arch_register_req_type_limited))
820                         continue;
821
822                 limited = req->limited;
823                 reg     = arch_get_irn_register(op);
824                 r       = arch_register_get_index(reg);
825                 if (!rbitset_is_set(limited, r)) {
826                         /* found an assignement outside the limited set */
827                         good = false;
828                         break;
829                 }
830         }
831
832         /* construct a list of register occupied by live-through values */
833         unsigned *live_through_regs = NULL;
834         unsigned *output_regs       = NULL;
835
836         /* is any of the live-throughs using a constrainted output register? */
837         if (get_irn_mode(node) == mode_T) {
838                 const ir_edge_t *edge;
839
840                 foreach_out_edge(node, edge) {
841                         ir_node *proj = get_edge_src_irn(edge);
842                         const arch_register_req_t *req;
843
844                         if (!arch_irn_consider_in_reg_alloc(cls, proj))
845                                 continue;
846
847                         req = arch_get_register_req_out(proj);
848                         if (!(req->type & arch_register_req_type_limited))
849                                 continue;
850
851                         if (live_through_regs == NULL) {
852                                 rbitset_alloca(live_through_regs, n_regs);
853                                 determine_live_through_regs(live_through_regs, node);
854
855                                 rbitset_alloca(output_regs, n_regs);
856                         }
857
858                         rbitset_or(output_regs, req->limited, n_regs);
859                         if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
860                                 good = false;
861                         }
862                 }
863         } else {
864                 if (arch_irn_consider_in_reg_alloc(cls, node)) {
865                         const arch_register_req_t *req = arch_get_register_req_out(node);
866                         if (req->type & arch_register_req_type_limited) {
867                                 rbitset_alloca(live_through_regs, n_regs);
868                                 determine_live_through_regs(live_through_regs, node);
869                                 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
870                                         good = false;
871
872                                         rbitset_alloca(output_regs, n_regs);
873                                         rbitset_or(output_regs, req->limited, n_regs);
874                                 }
875                         }
876                 }
877         }
878
879         if (good)
880                 return;
881
882         /* create these arrays if we haven't yet */
883         if (output_regs == NULL) {
884                 if (live_through_regs == NULL) {
885                         rbitset_alloca(live_through_regs, n_regs);
886                 }
887                 rbitset_alloca(output_regs, n_regs);
888         }
889
890         /* at this point we have to construct a bipartite matching problem to see
891            which values should go to which registers */
892         bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
893
894         /* add all combinations, then remove not allowed ones */
895         for (l = 0; l < n_regs; ++l) {
896                 if (bitset_is_set(ignore_regs, l)) {
897                         hungarian_add(bp, l, l, 1);
898                         continue;
899                 }
900
901                 for (r = 0; r < n_regs; ++r) {
902                         if (bitset_is_set(ignore_regs, r))
903                                 continue;
904                         /* livethrough values may not use constrainted output registers */
905                         if (rbitset_is_set(live_through_regs, l)
906                                         && rbitset_is_set(output_regs, r))
907                                 continue;
908
909                         hungarian_add(bp, l, r, l == r ? 9 : 8);
910                 }
911         }
912
913         for (i = 0; i < arity; ++i) {
914                 ir_node                   *op = get_irn_n(node, i);
915                 const arch_register_t     *reg;
916                 const arch_register_req_t *req;
917                 const unsigned            *limited;
918                 unsigned                   current_reg;
919
920                 if (!arch_irn_consider_in_reg_alloc(cls, op))
921                         continue;
922
923                 req = arch_get_register_req(node, i);
924                 if (!(req->type & arch_register_req_type_limited))
925                         continue;
926
927                 limited     = req->limited;
928                 reg         = arch_get_irn_register(op);
929                 current_reg = arch_register_get_index(reg);
930                 for (r = 0; r < n_regs; ++r) {
931                         if (rbitset_is_set(limited, r))
932                                 continue;
933                         hungarian_remv(bp, current_reg, r);
934                 }
935         }
936
937         hungarian_print_costmatrix(bp, 1);
938         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
939
940         assignment = ALLOCAN(unsigned, n_regs);
941         res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
942         assert(res == 0);
943
944 #if 1
945         printf("Swap result:");
946         for (i = 0; i < (int) n_regs; ++i) {
947                 printf(" %d", assignment[i]);
948         }
949         printf("\n");
950 #endif
951
952         hungarian_free(bp);
953
954         permutate_values(live_nodes, node, assignment);
955 }
956
957 /** test wether a node @p n is a copy of the value of node @p of */
958 static bool is_copy_of(ir_node *value, ir_node *test_value)
959 {
960         allocation_info_t *test_info;
961
962         if (value == NULL)
963                 return false;
964         if (value == test_value)
965                 return true;
966
967         test_info = get_allocation_info(test_value);
968         return test_info->original_value == value;
969 }
970
971 /**
972  * find a value in the end-assignment of a basic block
973  * @returns the index into the assignment array if found
974  *          -1 if not found
975  */
976 static int find_value_in_block_info(block_info_t *info, ir_node *value)
977 {
978         unsigned      r;
979         assignment_t *assignments = info->assignments;
980         for (r = 0; r < n_regs; ++r) {
981                 const assignment_t *assignment = &assignments[r];
982                 if (is_copy_of(assignment->value, value))
983                         return (int) r;
984         }
985
986         return -1;
987 }
988
989 /**
990  * Create the necessary permutations at the end of a basic block to fullfill
991  * the register assignment for phi-nodes in the next block
992  */
993 static void add_phi_permutations(ir_node *block, int p)
994 {
995         unsigned  r;
996         unsigned *permutation;
997         assignment_t *old_assignments;
998         bool      need_permutation;
999         ir_node  *node;
1000         ir_node  *pred = get_Block_cfgpred_block(block, p);
1001
1002         block_info_t *pred_info = get_block_info(pred);
1003
1004         /* predecessor not processed yet? nothing to do */
1005         if (!pred_info->processed)
1006                 return;
1007
1008         permutation = ALLOCAN(unsigned, n_regs);
1009         for (r = 0; r < n_regs; ++r) {
1010                 permutation[r] = r;
1011         }
1012
1013         /* check phi nodes */
1014         need_permutation = false;
1015         node = sched_first(block);
1016         for ( ; is_Phi(node); node = sched_next(node)) {
1017                 const arch_register_t *reg;
1018                 int                    regn;
1019                 int                    a;
1020                 ir_node               *op;
1021
1022                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1023                         continue;
1024
1025                 op = get_Phi_pred(node, p);
1026                 a = find_value_in_block_info(pred_info, op);
1027                 assert(a >= 0);
1028
1029                 reg = arch_get_irn_register(node);
1030                 regn = arch_register_get_index(reg);
1031                 if (regn != a) {
1032                         permutation[regn] = a;
1033                         need_permutation = true;
1034                 }
1035         }
1036
1037         if (!need_permutation)
1038                 return;
1039
1040         /* permutate values at end of predecessor */
1041         old_assignments = assignments;
1042         assignments     = pred_info->assignments;
1043         permutate_values(NULL, be_get_end_of_block_insertion_point(pred),
1044                          permutation);
1045         assignments = old_assignments;
1046
1047         /* change phi nodes to use the copied values */
1048         node = sched_first(block);
1049         for ( ; is_Phi(node); node = sched_next(node)) {
1050                 int      a;
1051                 ir_node *op;
1052
1053                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1054                         continue;
1055
1056                 /* we have permutated all values into the correct registers so we can
1057                    simply query which value occupies the phis register in the
1058                    predecessor */
1059                 a  = arch_register_get_index(arch_get_irn_register(node));
1060                 op = pred_info->assignments[a].value;
1061                 set_Phi_pred(node, p, op);
1062         }
1063 }
1064
1065 static void handle_phi_prefs(ir_node *phi)
1066 {
1067         int i;
1068         int arity = get_irn_arity(phi);
1069         ir_node           *block = get_nodes_block(phi);
1070         allocation_info_t *info  = get_allocation_info(phi);
1071
1072         for (i = 0; i < arity; ++i) {
1073                 ir_node               *op  = get_irn_n(phi, i);
1074                 const arch_register_t *reg = arch_get_irn_register(op);
1075                 ir_node               *pred;
1076                 float                  weight;
1077                 unsigned               r;
1078
1079                 if (reg == NULL)
1080                         continue;
1081
1082                 /* give bonus for already assigned register */
1083                 pred   = get_Block_cfgpred_block(block, i);
1084                 weight = get_block_execfreq(execfreqs, pred);
1085                 r      = arch_register_get_index(reg);
1086                 info->prefs[r] += weight * AFF_PHI;
1087         }
1088 }
1089
1090 /**
1091  * Walker: assign registers to all nodes of a block that
1092  * need registers from the currently considered register class.
1093  */
1094 static void allocate_coalesce_block(ir_node *block, void *data)
1095 {
1096         int                    i;
1097         ir_nodeset_t           live_nodes;
1098         ir_nodeset_iterator_t  iter;
1099         ir_node               *node, *start;
1100         int                    n_preds;
1101         block_info_t          *block_info;
1102         block_info_t          *processed_pred_info;
1103         block_info_t         **pred_block_infos;
1104         bool                   all_preds_processed;
1105
1106         (void) data;
1107         DB((dbg, LEVEL_2, "* Block %+F\n", block));
1108
1109         /* clear assignments */
1110         block_info  = get_block_info(block);
1111         assignments = block_info->assignments;
1112
1113         ir_nodeset_init(&live_nodes);
1114
1115         /* gather regalloc infos of predecessor blocks */
1116         n_preds             = get_Block_n_cfgpreds(block);
1117         pred_block_infos    = ALLOCAN(block_info_t*, n_preds);
1118         all_preds_processed = true;
1119         for (i = 0; i < n_preds; ++i) {
1120                 ir_node      *pred      = get_Block_cfgpred_block(block, i);
1121                 block_info_t *pred_info = get_block_info(pred);
1122                 pred_block_infos[i]     = pred_info;
1123
1124                 if (!pred_info->processed) {
1125                         all_preds_processed = false;
1126                 } else {
1127                         /* we need 1 (arbitrary) processed predecessor */
1128                         processed_pred_info = pred_info;
1129                 }
1130         }
1131
1132         /* collect live-in nodes and preassigned values */
1133         be_lv_foreach(lv, block, be_lv_state_in, i) {
1134                 const arch_register_t *reg;
1135
1136                 node = be_lv_get_irn(lv, block, i);
1137                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1138                         continue;
1139
1140                 /* if we don't know all predecessors, then we have no idea which values
1141                    are copied, so we have to pessimistically construct phi-nodes for all
1142                    of them */
1143                 if (!all_preds_processed) {
1144                         ir_mode                   *mode = get_irn_mode(node);
1145                         ir_node                   **ins = ALLOCAN(ir_node*, n_preds);
1146                         const arch_register_req_t *req  = get_default_req_current_cls();
1147                         ir_node                   *phi;
1148                         int                        i2;
1149
1150                         for (i2 = 0; i2 < n_preds; ++i2) {
1151                                 ins[i2] = node;
1152                         }
1153                         phi = new_r_Phi(block, n_preds, ins, mode);
1154                         be_set_phi_reg_req(phi, req);
1155
1156                         DB((dbg, LEVEL_3, "Pessimistic Phi %+F (for %+F)\n", phi, node));
1157
1158                         /* TODO: if node had a register assigned use that as a strong
1159                            preference */
1160                         mark_as_copy_of(phi, node);
1161                         sched_add_after(block, phi);
1162
1163                         node = phi;
1164                 } else {
1165                         /* check wether the value is the same in all predecessors,
1166                            if not construct a phi node */
1167                 }
1168
1169                 /* if the node already has a register assigned use it */
1170                 reg = arch_get_irn_register(node);
1171                 if (reg != NULL) {
1172                         /* TODO: consult pred-block infos here. The value could be copied
1173                            away in some/all predecessor blocks. We need to construct
1174                            phi-nodes in this case.
1175                            We even need to construct some Phi_0 like constructs in cases
1176                            where the predecessor allocation is not determined yet. */
1177                         use_reg(node, reg);
1178                 }
1179
1180                 /* remember that this node is live at the beginning of the block */
1181                 ir_nodeset_insert(&live_nodes, node);
1182         }
1183
1184         /* handle phis... */
1185         node = sched_first(block);
1186         for ( ; is_Phi(node); node = sched_next(node)) {
1187                 const arch_register_t *reg;
1188
1189                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1190                         continue;
1191
1192                 /* fill in regs already assigned */
1193                 reg = arch_get_irn_register(node);
1194                 if (reg != NULL) {
1195                         use_reg(node, reg);
1196                 } else {
1197                         /* TODO: give boni for registers already assigned at the
1198                            predecessors */
1199                         handle_phi_prefs(node);
1200                         assign_reg(block, node);
1201                 }
1202         }
1203         start = node;
1204
1205         /* assign regs for live-in values */
1206         foreach_ir_nodeset(&live_nodes, node, iter) {
1207                 const arch_register_t *reg = arch_get_irn_register(node);
1208                 if (reg != NULL)
1209                         continue;
1210
1211                 assign_reg(block, node);
1212         }
1213
1214         /* assign instructions in the block */
1215         for (node = start; !sched_is_end(node); node = sched_next(node)) {
1216                 int arity = get_irn_arity(node);
1217                 int i;
1218
1219                 /* enforce use constraints */
1220                 enforce_constraints(&live_nodes, node);
1221
1222                 /* exchange values to copied values where needed */
1223                 for (i = 0; i < arity; ++i) {
1224                         ir_node           *op = get_irn_n(node, i);
1225                         allocation_info_t *info;
1226
1227                         if (!arch_irn_consider_in_reg_alloc(cls, op))
1228                                 continue;
1229
1230                         info = get_allocation_info(op);
1231                         if (info->current_value != op) {
1232                                 set_irn_n(node, i, info->current_value);
1233                         }
1234                 }
1235
1236                 /* free registers of values last used at this instruction */
1237                 free_last_uses(&live_nodes, node);
1238
1239                 /* assign output registers */
1240                 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1241                 if (get_irn_mode(node) == mode_T) {
1242                         const ir_edge_t *edge;
1243                         foreach_out_edge(node, edge) {
1244                                 ir_node *proj = get_edge_src_irn(edge);
1245                                 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1246                                         continue;
1247                                 assign_reg(block, proj);
1248                         }
1249                 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1250                         assign_reg(block, node);
1251                 }
1252         }
1253
1254         ir_nodeset_destroy(&live_nodes);
1255         assignments = NULL;
1256
1257         block_info->processed = true;
1258
1259         /* permutate values at end of predecessor blocks in case of phi-nodes */
1260         if (n_preds > 1) {
1261                 int p;
1262                 for (p = 0; p < n_preds; ++p) {
1263                         add_phi_permutations(block, p);
1264                 }
1265         }
1266
1267         /* if we have exactly 1 successor then we might be able to produce phi
1268            copies now */
1269         if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1270                 const ir_edge_t *edge
1271                         = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1272                 ir_node      *succ      = get_edge_src_irn(edge);
1273                 int           p         = get_edge_src_pos(edge);
1274                 block_info_t *succ_info = get_block_info(succ);
1275
1276                 if (succ_info->processed) {
1277                         add_phi_permutations(succ, p);
1278                 }
1279         }
1280 }
1281
1282 /**
1283  * Run the register allocator for the current register class.
1284  */
1285 static void be_straight_alloc_cls(void)
1286 {
1287         lv = be_assure_liveness(birg);
1288         be_liveness_assure_sets(lv);
1289         be_liveness_assure_chk(lv);
1290
1291         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1292         inc_irg_visited(irg);
1293
1294         DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1295
1296         irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1297         /* we need some dominance pre-order walk to ensure we see all
1298          *  definitions/create copies before we encounter their users */
1299         dom_tree_walk_irg(irg, allocate_coalesce_block, NULL, NULL);
1300
1301         ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1302 }
1303
1304 static void dump(int mask, ir_graph *irg, const char *suffix,
1305                  void (*dumper)(ir_graph *, const char *))
1306 {
1307         if(birg->main_env->options->dump_flags & mask)
1308                 be_dump(irg, suffix, dumper);
1309 }
1310
1311 /**
1312  * Run the spiller on the current graph.
1313  */
1314 static void spill(void)
1315 {
1316         /* make sure all nodes show their real register pressure */
1317         BE_TIMER_PUSH(t_ra_constr);
1318         be_pre_spill_prepare_constr(birg, cls);
1319         BE_TIMER_POP(t_ra_constr);
1320
1321         dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1322
1323         /* spill */
1324         BE_TIMER_PUSH(t_ra_spill);
1325         be_do_spill(birg, cls);
1326         BE_TIMER_POP(t_ra_spill);
1327
1328         BE_TIMER_PUSH(t_ra_spill_apply);
1329         check_for_memory_operands(irg);
1330         BE_TIMER_POP(t_ra_spill_apply);
1331
1332         dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1333 }
1334
1335 /**
1336  * The straight register allocator for a whole procedure.
1337  */
1338 static void be_straight_alloc(be_irg_t *new_birg)
1339 {
1340         const arch_env_t *arch_env = new_birg->main_env->arch_env;
1341         int   n_cls                = arch_env_get_n_reg_class(arch_env);
1342         int   c;
1343
1344         obstack_init(&obst);
1345
1346         birg      = new_birg;
1347         irg       = be_get_birg_irg(birg);
1348         execfreqs = birg->exec_freq;
1349
1350         /* TODO: extract some of the stuff from bechordal allocator, like
1351          * statistics, time measurements, etc. and use them here too */
1352
1353         for (c = 0; c < n_cls; ++c) {
1354                 cls             = arch_env_get_reg_class(arch_env, c);
1355                 default_cls_req = NULL;
1356                 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1357                         continue;
1358
1359                 stat_ev_ctx_push_str("regcls", cls->name);
1360
1361                 n_regs      = arch_register_class_n_regs(cls);
1362                 ignore_regs = bitset_malloc(n_regs);
1363                 be_put_ignore_regs(birg, cls, ignore_regs);
1364
1365                 spill();
1366
1367                 /* verify schedule and register pressure */
1368                 BE_TIMER_PUSH(t_verify);
1369                 if (birg->main_env->options->vrfy_option == BE_CH_VRFY_WARN) {
1370                         be_verify_schedule(birg);
1371                         be_verify_register_pressure(birg, cls, irg);
1372                 } else if (birg->main_env->options->vrfy_option == BE_CH_VRFY_ASSERT) {
1373                         assert(be_verify_schedule(birg) && "Schedule verification failed");
1374                         assert(be_verify_register_pressure(birg, cls, irg)
1375                                 && "Register pressure verification failed");
1376                 }
1377                 BE_TIMER_POP(t_verify);
1378
1379                 BE_TIMER_PUSH(t_ra_color);
1380                 be_straight_alloc_cls();
1381                 BE_TIMER_POP(t_ra_color);
1382
1383                 bitset_free(ignore_regs);
1384
1385                 stat_ev_ctx_pop("regcls");
1386         }
1387
1388         BE_TIMER_PUSH(t_verify);
1389         if (birg->main_env->options->vrfy_option == BE_CH_VRFY_WARN) {
1390                 be_verify_register_allocation(birg);
1391         } else if(birg->main_env->options->vrfy_option == BE_CH_VRFY_ASSERT) {
1392                 assert(be_verify_register_allocation(birg)
1393                                 && "Register allocation invalid");
1394         }
1395         BE_TIMER_POP(t_verify);
1396
1397         obstack_free(&obst, NULL);
1398 }
1399
1400 /**
1401  * Initializes this module.
1402  */
1403 void be_init_straight_alloc(void)
1404 {
1405         static be_ra_t be_ra_straight = {
1406                 be_straight_alloc,
1407         };
1408
1409         FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
1410
1411         be_register_allocator("straight", &be_ra_straight);
1412 }
1413
1414 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);