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