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