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