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