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