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