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