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