26f76f1f50cf85393eab5cec75637a82a79665a3
[libfirm] / ir / be / bechordal.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       Chordal register allocation.
23  * @author      Sebastian Hack
24  * @date        08.12.2004
25  * @version     $Id$
26  */
27 #include "config.h"
28
29 #include <ctype.h>
30
31 #include "obst.h"
32 #include "pset.h"
33 #include "list.h"
34 #include "bitset.h"
35 #include "raw_bitset.h"
36 #include "iterator.h"
37 #include "bipartite.h"
38 #include "hungarian.h"
39
40 #include "irmode_t.h"
41 #include "irgraph_t.h"
42 #include "irprintf_t.h"
43 #include "irgwalk.h"
44 #include "irdump.h"
45 #include "irdom.h"
46 #include "irtools.h"
47 #include "irbitset.h"
48 #include "debug.h"
49 #include "iredges.h"
50
51 #include "beutil.h"
52 #include "besched.h"
53 #include "besched.h"
54 #include "belive_t.h"
55 #include "benode.h"
56 #include "bearch.h"
57 #include "beirgmod.h"
58 #include "beifg.h"
59 #include "beinsn_t.h"
60 #include "bestatevent.h"
61 #include "beirg.h"
62 #include "beintlive_t.h"
63 #include "bera.h"
64 #include "bechordal_t.h"
65 #include "bechordal_draw.h"
66 #include "bemodule.h"
67 #include "bearch.h"
68 #include "bechordal_common.h"
69
70 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
71
72 #define NO_COLOR (-1)
73
74 #define DUMP_INTERVALS
75
76 typedef struct be_chordal_alloc_env_t {
77         be_chordal_env_t *chordal_env;
78
79         pset *pre_colored;     /**< Set of precolored nodes. */
80         bitset_t *live;        /**< A liveness bitset. */
81         bitset_t *tmp_colors;  /**< An auxiliary bitset which is as long as the number of colors in the class. */
82         bitset_t *colors;      /**< The color mask. */
83         bitset_t *in_colors;   /**< Colors used by live in values. */
84         int colors_n;          /**< The number of colors. */
85 } be_chordal_alloc_env_t;
86
87 static int get_next_free_reg(const be_chordal_alloc_env_t *alloc_env, bitset_t *colors)
88 {
89         bitset_t *tmp = alloc_env->tmp_colors;
90         bitset_copy(tmp, colors);
91         bitset_flip_all(tmp);
92         bitset_and(tmp, alloc_env->chordal_env->allocatable_regs);
93         return bitset_next_set(tmp, 0);
94 }
95
96 static bitset_t *get_decisive_partner_regs(bitset_t *bs, const be_operand_t *o1, const be_operand_t *o2)
97 {
98         bitset_t *res = bs;
99
100         if (!o1) {
101                 bitset_copy(bs, o2->regs);
102                 return bs;
103         }
104
105         if (!o2) {
106                 bitset_copy(bs, o1->regs);
107                 return bs;
108         }
109
110         assert(o1->req->cls == o2->req->cls || ! o1->req->cls || ! o2->req->cls);
111
112         if (bitset_contains(o1->regs, o2->regs)) {
113                 bitset_copy(bs, o1->regs);
114         } else if (bitset_contains(o2->regs, o1->regs)) {
115                 bitset_copy(bs, o2->regs);
116         } else {
117                 res = NULL;
118         }
119
120         return res;
121 }
122
123 static void pair_up_operands(const be_chordal_alloc_env_t *alloc_env, be_insn_t *insn)
124 {
125         const be_chordal_env_t *env = alloc_env->chordal_env;
126         bitset_t               *bs  = bitset_alloca(env->cls->n_regs);
127         int                     i;
128         int                     j;
129
130         /*
131          * For each out operand, try to find an in operand which can be assigned the
132          * same register as the out operand.
133          */
134         for (j = 0; j < insn->use_start; ++j) {
135                 be_operand_t *smallest        = NULL;
136                 int           smallest_n_regs = env->cls->n_regs + 1;
137                 be_operand_t *out_op          = &insn->ops[j];
138
139                 /* Try to find an in operand which has ... */
140                 for (i = insn->use_start; i < insn->n_ops; ++i) {
141                         int           n_total;
142                         be_operand_t *op = &insn->ops[i];
143                         be_lv_t      *lv;
144
145                         if (op->partner != NULL)
146                                 continue;
147                         lv = be_get_irg_liveness(env->irg);
148                         if (be_values_interfere(lv, op->irn, op->carrier))
149                                 continue;
150
151                         bitset_copy(bs, op->regs);
152                         bitset_and(bs, out_op->regs);
153                         n_total = bitset_popcount(op->regs);
154
155                         if (!bitset_is_empty(bs) && n_total < smallest_n_regs) {
156                                 smallest        = op;
157                                 smallest_n_regs = n_total;
158                         }
159                 }
160
161                 if (smallest != NULL) {
162                         for (i = insn->use_start; i < insn->n_ops; ++i) {
163                                 if (insn->ops[i].carrier == smallest->carrier)
164                                         insn->ops[i].partner = out_op;
165                         }
166
167                         out_op->partner   = smallest;
168                         smallest->partner = out_op;
169                 }
170         }
171 }
172
173 static ir_node *handle_constraints(be_chordal_alloc_env_t *alloc_env,
174                                    ir_node *irn, int *silent)
175 {
176         int n_regs;
177         bitset_t *bs;
178         ir_node **alloc_nodes;
179         //hungarian_problem_t *bp;
180         int *assignment;
181         pmap *partners;
182         int i, n_alloc;
183         unsigned col;
184         const ir_edge_t *edge;
185         ir_node *perm = NULL;
186         //int match_res, cost;
187         be_chordal_env_t *env  = alloc_env->chordal_env;
188         void *base             = obstack_base(env->obst);
189         be_insn_t *insn        = chordal_scan_insn(env, irn);
190         ir_node *res           = insn->next_insn;
191         int be_silent          = *silent;
192         bipartite_t *bp;
193
194         if (insn->pre_colored) {
195                 int i;
196                 for (i = 0; i < insn->use_start; ++i)
197                         pset_insert_ptr(alloc_env->pre_colored, insn->ops[i].carrier);
198         }
199
200         /*
201          * If the current node is a barrier toggle the silent flag.
202          * If we are in the start block, we are ought to be silent at the beginning,
203          * so the toggling activates the constraint handling but skips the barrier.
204          * If we are in the end block we handle the in requirements of the barrier
205          * and set the rest to silent.
206          */
207         if (be_is_Barrier(irn))
208                 *silent = !*silent;
209
210         if (be_silent)
211                 goto end;
212
213         /*
214          * Perms inserted before the constraint handling phase are considered to be
215          * correctly precolored. These Perms arise during the ABI handling phase.
216          */
217         if (!insn->has_constraints)
218                 goto end;
219
220         n_regs      = env->cls->n_regs;
221         bs          = bitset_alloca(n_regs);
222         alloc_nodes = ALLOCAN(ir_node*, n_regs);
223         //bp          = hungarian_new(n_regs, n_regs, 2, HUNGARIAN_MATCH_PERFECT);
224         bp          = bipartite_new(n_regs, n_regs);
225         assignment  = ALLOCAN(int, n_regs);
226         partners    = pmap_create();
227
228         /*
229          * prepare the constraint handling of this node.
230          * Perms are constructed and Copies are created for constrained values
231          * interfering with the instruction.
232          */
233         perm = pre_process_constraints(alloc_env->chordal_env, &insn);
234
235         /* find suitable in operands to the out operands of the node. */
236         pair_up_operands(alloc_env, insn);
237
238         /*
239          * look at the in/out operands and add each operand (and its possible partner)
240          * to a bipartite graph (left: nodes with partners, right: admissible colors).
241          */
242         for (i = 0, n_alloc = 0; i < insn->n_ops; ++i) {
243                 be_operand_t *op = &insn->ops[i];
244
245                 /*
246                  * If the operand has no partner or the partner has not been marked
247                  * for allocation, determine the admissible registers and mark it
248                  * for allocation by associating the node and its partner with the
249                  * set of admissible registers via a bipartite graph.
250                  */
251                 if (!op->partner || !pmap_contains(partners, op->partner->carrier)) {
252                         ir_node *partner = op->partner ? op->partner->carrier : NULL;
253                         int i;
254
255                         pmap_insert(partners, op->carrier, partner);
256                         if (partner != NULL)
257                                 pmap_insert(partners, partner, op->carrier);
258
259                         /* don't insert a node twice */
260                         for (i = 0; i < n_alloc; ++i) {
261                                 if (alloc_nodes[i] == op->carrier) {
262                                         break;
263                                 }
264                         }
265                         if (i < n_alloc)
266                                 continue;
267
268                         alloc_nodes[n_alloc] = op->carrier;
269
270                         DBG((dbg, LEVEL_2, "\tassociating %+F and %+F\n", op->carrier,
271                              partner));
272
273                         bitset_clear_all(bs);
274                         get_decisive_partner_regs(bs, op, op->partner);
275
276                         DBG((dbg, LEVEL_2, "\tallowed registers for %+F: %B\n", op->carrier,
277                              bs));
278
279                         bitset_foreach(bs, col) {
280                                 //hungarian_add(bp, n_alloc, col, 1);
281                                 bipartite_add(bp, n_alloc, col);
282                         }
283
284                         n_alloc++;
285                 }
286         }
287
288         /*
289          * Put all nodes which live through the constrained instruction also to the
290          * allocation bipartite graph. They are considered unconstrained.
291          */
292         if (perm != NULL) {
293                 foreach_out_edge(perm, edge) {
294                         int i;
295                         ir_node *proj = get_edge_src_irn(edge);
296                         be_lv_t *lv   = be_get_irg_liveness(env->irg);
297
298                         assert(is_Proj(proj));
299
300                         if (!be_values_interfere(lv, proj, irn)
301                             || pmap_contains(partners, proj))
302                                 continue;
303
304                         /* don't insert a node twice */
305                         for (i = 0; i < n_alloc; ++i) {
306                                 if (alloc_nodes[i] == proj) {
307                                         break;
308                                 }
309                         }
310                         if (i < n_alloc)
311                                 continue;
312
313
314                         assert(n_alloc < n_regs);
315
316                         alloc_nodes[n_alloc] = proj;
317                         pmap_insert(partners, proj, NULL);
318
319                         bitset_foreach(env->allocatable_regs, col) {
320                                 //hungarian_add(bp, n_alloc, col, 1);
321                                 bipartite_add(bp, n_alloc, col);
322                         }
323
324                         n_alloc++;
325                 }
326         }
327
328         /* Compute a valid register allocation. */
329 #if 0
330         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
331         match_res = hungarian_solve(bp, assignment, &cost, 1);
332         assert(match_res == 0 && "matching failed");
333 #else
334         /*bipartite_dump_f(stderr, bp);*/
335         bipartite_matching(bp, assignment);
336 #endif
337
338         /* Assign colors obtained from the matching. */
339         for (i = 0; i < n_alloc; ++i) {
340                 const arch_register_t *reg;
341                 ir_node *irn;
342
343                 assert(assignment[i] >= 0 && "there must have been a register assigned (node not register pressure faithful?)");
344                 reg = arch_register_for_index(env->cls, assignment[i]);
345                 assert(! (reg->type & arch_register_type_ignore));
346
347                 irn = alloc_nodes[i];
348                 if (irn != NULL) {
349                         arch_set_irn_register(irn, reg);
350                         (void) pset_hinsert_ptr(alloc_env->pre_colored, irn);
351                         DBG((dbg, LEVEL_2, "\tsetting %+F to register %s\n", irn, reg->name));
352                 }
353
354                 irn = pmap_get(partners, alloc_nodes[i]);
355                 if (irn != NULL) {
356                         arch_set_irn_register(irn, reg);
357                         (void) pset_hinsert_ptr(alloc_env->pre_colored, irn);
358                         DBG((dbg, LEVEL_2, "\tsetting %+F to register %s\n", irn, reg->name));
359                 }
360         }
361
362         /* Allocate the non-constrained Projs of the Perm. */
363         if (perm != NULL) {
364                 bitset_clear_all(bs);
365
366                 /* Put the colors of all Projs in a bitset. */
367                 foreach_out_edge(perm, edge) {
368                         ir_node *proj              = get_edge_src_irn(edge);
369                         const arch_register_t *reg = arch_get_irn_register(proj);
370
371                         if (reg != NULL)
372                                 bitset_set(bs, reg->index);
373                 }
374
375                 /* Assign the not yet assigned Projs of the Perm a suitable color. */
376                 foreach_out_edge(perm, edge) {
377                         ir_node *proj              = get_edge_src_irn(edge);
378                         const arch_register_t *reg = arch_get_irn_register(proj);
379
380                         DBG((dbg, LEVEL_2, "\tchecking reg of %+F: %s\n", proj, reg ? reg->name : "<none>"));
381
382                         if (reg == NULL) {
383                                 col = get_next_free_reg(alloc_env, bs);
384                                 reg = arch_register_for_index(env->cls, col);
385                                 bitset_set(bs, reg->index);
386                                 arch_set_irn_register(proj, reg);
387                                 pset_insert_ptr(alloc_env->pre_colored, proj);
388                                 DBG((dbg, LEVEL_2, "\tsetting %+F to register %s\n", proj, reg->name));
389                         }
390                 }
391         }
392
393         bipartite_free(bp);
394         //hungarian_free(bp);
395         pmap_destroy(partners);
396
397 end:
398         obstack_free(env->obst, base);
399         return res;
400 }
401
402 /**
403  * Handle constraint nodes in each basic block.
404  * handle_constraints() inserts Perm nodes which perm
405  * over all values live at the constrained node right in front
406  * of the constrained node. These Perms signal a constrained node.
407  * For further comments, refer to handle_constraints().
408  */
409 static void constraints(ir_node *bl, void *data)
410 {
411         /*
412          * Start silent in the start block.
413          * The silence remains until the first barrier is seen.
414          * Each other block is begun loud.
415          */
416         int                     silent = bl == get_irg_start_block(get_irn_irg(bl));
417         be_chordal_alloc_env_t *env    = data;
418         ir_node                *irn;
419
420         /*
421          * If the block is the start block search the barrier and
422          * start handling constraints from there.
423          */
424         for (irn = sched_first(bl); !sched_is_end(irn);) {
425                 irn = handle_constraints(env, irn, &silent);
426         }
427 }
428
429 static void assign(ir_node *block, void *env_ptr)
430 {
431         be_chordal_alloc_env_t *alloc_env = env_ptr;
432         be_chordal_env_t *env       = alloc_env->chordal_env;
433         bitset_t *live              = alloc_env->live;
434         bitset_t *colors            = alloc_env->colors;
435         bitset_t *in_colors         = alloc_env->in_colors;
436         struct list_head *head      = get_block_border_head(env, block);
437         be_lv_t *lv                 = be_get_irg_liveness(env->irg);
438
439         const ir_node *irn;
440         border_t *b;
441         int idx;
442
443         bitset_clear_all(colors);
444         bitset_clear_all(live);
445         bitset_clear_all(in_colors);
446
447         DBG((dbg, LEVEL_4, "Assigning colors for block %+F\n", block));
448         DBG((dbg, LEVEL_4, "\tusedef chain for block\n"));
449         list_for_each_entry(border_t, b, head, list) {
450                 DBG((dbg, LEVEL_4, "\t%s %+F/%d\n", b->is_def ? "def" : "use",
451                                         b->irn, get_irn_idx(b->irn)));
452         }
453
454         /*
455          * Add initial defs for all values live in.
456          * Since their colors have already been assigned (The dominators were
457          * allocated before), we have to mark their colors as used also.
458          */
459         be_lv_foreach(lv, block, be_lv_state_in, idx) {
460                 irn = be_lv_get_irn(lv, block, idx);
461                 if (has_reg_class(env, irn)) {
462                         const arch_register_t *reg = arch_get_irn_register(irn);
463                         int col;
464
465                         assert(reg && "Node must have been assigned a register");
466                         col = arch_register_get_index(reg);
467
468                         DBG((dbg, LEVEL_4, "%+F has reg %s\n", irn, reg->name));
469
470                         /* Mark the color of the live in value as used. */
471                         bitset_set(colors, col);
472                         bitset_set(in_colors, col);
473
474                         /* Mark the value live in. */
475                         bitset_set(live, get_irn_idx(irn));
476                 }
477         }
478
479         /*
480          * Mind that the sequence of defs from back to front defines a perfect
481          * elimination order. So, coloring the definitions from first to last
482          * will work.
483          */
484         list_for_each_entry_reverse(border_t, b, head, list) {
485                 ir_node *irn = b->irn;
486                 int nr       = get_irn_idx(irn);
487                 int ignore   = arch_irn_is_ignore(irn);
488
489                 /*
490                  * Assign a color, if it is a local def. Global defs already have a
491                  * color.
492                  */
493                 if (b->is_def && !be_is_live_in(lv, block, irn)) {
494                         const arch_register_t *reg;
495                         int col = NO_COLOR;
496
497                         if (ignore || pset_find_ptr(alloc_env->pre_colored, irn)) {
498                                 reg = arch_get_irn_register(irn);
499                                 col = reg->index;
500                                 assert(!bitset_is_set(colors, col) && "pre-colored register must be free");
501                         } else {
502                                 col = get_next_free_reg(alloc_env, colors);
503                                 reg = arch_register_for_index(env->cls, col);
504                                 assert(arch_get_irn_register(irn) == NULL && "This node must not have been assigned a register yet");
505                                 assert(!arch_register_type_is(reg, ignore) && "Must not assign ignore register");
506                         }
507
508                         bitset_set(colors, col);
509                         arch_set_irn_register(irn, reg);
510
511                         DBG((dbg, LEVEL_1, "\tassigning register %s(%d) to %+F\n", arch_register_get_name(reg), col, irn));
512
513                         assert(!bitset_is_set(live, nr) && "Value's definition must not have been encountered");
514                         bitset_set(live, nr);
515                 } else if (!b->is_def) {
516                         /* Clear the color upon a use. */
517                         const arch_register_t *reg = arch_get_irn_register(irn);
518                         int col;
519
520                         assert(reg && "Register must have been assigned");
521
522                         col = arch_register_get_index(reg);
523 #ifndef NDEBUG
524                         if (!arch_register_type_is(reg, ignore)) {
525                                 assert(bitset_is_set(live, nr) && "Cannot have a non live use");
526                         }
527 #endif
528
529                         bitset_clear(colors, col);
530                         bitset_clear(live, nr);
531                 }
532         }
533 }
534
535 void be_ra_chordal_color(be_chordal_env_t *chordal_env)
536 {
537         be_chordal_alloc_env_t env;
538         char buf[256];
539         be_lv_t *lv;
540         const arch_register_class_t *cls = chordal_env->cls;
541
542         int colors_n          = arch_register_class_n_regs(cls);
543         ir_graph *irg         = chordal_env->irg;
544
545         lv = be_assure_liveness(irg);
546         be_liveness_assure_sets(lv);
547         be_liveness_assure_chk(lv);
548
549         assure_doms(irg);
550
551         env.chordal_env   = chordal_env;
552         env.colors_n      = colors_n;
553         env.colors        = bitset_alloca(colors_n);
554         env.tmp_colors    = bitset_alloca(colors_n);
555         env.in_colors     = bitset_alloca(colors_n);
556         env.pre_colored   = pset_new_ptr_default();
557
558         be_timer_push(T_CONSTR);
559
560         /* Handle register targeting constraints */
561         dom_tree_walk_irg(irg, constraints, NULL, &env);
562
563         if (chordal_env->opts->dump_flags & BE_CH_DUMP_CONSTR) {
564                 snprintf(buf, sizeof(buf), "%s-constr", chordal_env->cls->name);
565                 dump_ir_graph(chordal_env->irg, buf);
566         }
567
568         be_timer_pop(T_CONSTR);
569
570         env.live = bitset_malloc(get_irg_last_idx(chordal_env->irg));
571
572         /* First, determine the pressure */
573         dom_tree_walk_irg(irg, create_borders, NULL, env.chordal_env);
574
575         /* Assign the colors */
576         dom_tree_walk_irg(irg, assign, NULL, &env);
577
578         if (chordal_env->opts->dump_flags & BE_CH_DUMP_TREE_INTV) {
579                 plotter_t *plotter;
580                 ir_snprintf(buf, sizeof(buf), "ifg_%s_%F.eps", chordal_env->cls->name, irg);
581                 plotter = new_plotter_ps(buf);
582                 draw_interval_tree(&draw_chordal_def_opts, chordal_env, plotter);
583                 plotter_free(plotter);
584         }
585
586         bitset_free(env.live);
587         del_pset(env.pre_colored);
588 }
589
590 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_chordal);
591 void be_init_chordal(void)
592 {
593         static be_ra_chordal_coloring_t coloring = {
594                 be_ra_chordal_color
595         };
596         FIRM_DBG_REGISTER(dbg, "firm.be.chordal");
597
598         be_register_chordal_coloring("default", &coloring);
599 }