4 * Copyright: (c) Universitaet Karlsruhe
5 * Licence: This file protected by GPL - GNU GENERAL PUBLIC LICENSE.
23 #include "irprintf_t.h"
28 #include "iredges_t.h"
34 #include "bespillbelady.h"
36 #include "besched_t.h"
40 #include "bechordal_t.h"
49 #define DBG_WORKSET 128
50 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
53 * An association between a node and a point in time.
55 typedef struct _loc_t {
56 ir_node *irn; /**< A node. */
57 unsigned time; /**< A use time (see beuses.h). */
60 typedef struct _workset_t {
61 int len; /**< current length */
62 loc_t vals[0]; /**< inlined array of the values/distances in this working set */
65 typedef struct _belady_env_t {
67 const be_chordal_env_t *cenv;
68 const arch_env_t *arch;
69 const arch_register_class_t *cls;
70 int n_regs; /** number of regs in this reg-class */
72 workset_t *ws; /**< the main workset used while processing a block. ob-allocated */
73 be_uses_t *uses; /**< env for the next-use magic */
74 ir_node *instr; /**< current instruction */
75 unsigned instr_nr; /**< current instruction number (relative to block start) */
78 spill_env_t *senv; /**< see bespill.h */
81 static int loc_compare(const void *a, const void *b)
85 return p->time - q->time;
88 void workset_print(const workset_t *w)
92 for(i = 0; i < w->len; ++i) {
93 ir_fprintf(stderr, "%+F %d\n", w->vals[i].irn, w->vals[i].time);
98 * Alloc a new workset on obstack @p ob with maximum size @p max
100 static INLINE workset_t *new_workset(belady_env_t *env, struct obstack *ob) {
102 size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
103 res = obstack_alloc(ob, size);
104 memset(res, 0, size);
109 * Alloc a new instance on obstack and make it equal to @param ws
111 static INLINE workset_t *workset_clone(belady_env_t *env, struct obstack *ob, workset_t *ws) {
113 size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
114 res = obstack_alloc(ob, size);
115 memcpy(res, ws, size);
120 * Do NOT alloc anything. Make @param tgt equal to @param src.
121 * returns @param tgt for convenience
123 static INLINE workset_t *workset_copy(belady_env_t *env, workset_t *tgt, workset_t *src) {
124 size_t size = sizeof(*src) + (env->n_regs)*sizeof(src->vals[0]);
125 memcpy(tgt, src, size);
130 * Overwrites the current content array of @param ws with the
131 * @param count locations given at memory @param locs.
132 * Set the length of @param ws to count.
134 static INLINE void workset_bulk_fill(workset_t *workset, int count, const loc_t *locs) {
135 workset->len = count;
136 memcpy(&(workset->vals[0]), locs, count * sizeof(locs[0]));
140 * Inserts the value @p val into the workset, iff it is not
141 * already contained. The workset must not be full.
143 static INLINE void workset_insert(belady_env_t *env, workset_t *ws, ir_node *val) {
145 /* check for current regclass */
146 if (!arch_irn_consider_in_reg_alloc(env->arch, env->cls, val)) {
147 DBG((dbg, DBG_WORKSET, "Dropped %+F\n", val));
151 /* check if val is already contained */
152 for(i=0; i<ws->len; ++i)
153 if (ws->vals[i].irn == val)
157 assert(ws->len < env->n_regs && "Workset already full!");
158 ws->vals[ws->len++].irn = val;
162 * Removes all entries from this workset
164 static INLINE void workset_clear(workset_t *ws) {
169 * Removes the value @p val from the workset if present.
171 static INLINE void workset_remove(workset_t *ws, ir_node *val) {
173 for(i=0; i<ws->len; ++i) {
174 if (ws->vals[i].irn == val) {
175 ws->vals[i] = ws->vals[--ws->len];
181 static INLINE int workset_contains(const workset_t *ws, const ir_node *val) {
183 for(i=0; i<ws->len; ++i) {
184 if (ws->vals[i].irn == val)
192 * Iterates over all values in the working set.
193 * @p ws The workset to iterate
194 * @p v A variable to put the current value in
195 * @p i An integer for internal use
197 #define workset_foreach(ws, v, i) for(i=0; \
198 v=(i < ws->len) ? ws->vals[i].irn : NULL, i < ws->len; \
201 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
202 #define workset_get_time(ws, i) (ws)->vals[i].time
203 #define workset_set_length(ws, length) (ws)->len = length
204 #define workset_get_length(ws) ((ws)->len)
205 #define workset_get_val(ws, i) ((ws)->vals[i].irn)
206 #define workset_sort(ws) qsort((ws)->vals, (ws)->len, sizeof((ws)->vals[0]), loc_compare);
208 typedef struct _block_info_t {
209 workset_t *ws_start, *ws_end;
214 static INLINE void *new_block_info(struct obstack *ob) {
215 block_info_t *res = obstack_alloc(ob, sizeof(*res));
216 res->ws_start = NULL;
223 #define get_block_info(blk) ((block_info_t *)get_irn_link(blk))
224 #define set_block_info(blk, info) set_irn_link(blk, info)
227 * @return The distance to the next use or 0 if irn has dont_spill flag set
229 static INLINE unsigned get_distance(belady_env_t *env, const ir_node *from, unsigned from_step, const ir_node *def, int skip_from_uses)
231 int flags = arch_irn_get_flags(env->arch, def);
234 assert(! (flags & arch_irn_flags_ignore));
236 /* We have to keep nonspillable nodes in the workingset */
237 if(flags & arch_irn_flags_dont_spill)
240 dist = be_get_next_use(env->uses, from, from_step, def, skip_from_uses);
242 if(USES_IS_INFINITE(dist))
243 dist = USES_INFINITY;
249 * Fix to remove dead nodes (especially don't spill nodes) from workset.
251 static void fix_dead_values(workset_t *ws, ir_node *irn) {
254 ir_node *block = get_nodes_block(irn);
256 DBG((dbg, DBG_DECIDE, "fixing dead values at %+F:\n", irn));
258 workset_foreach(ws, node, idx) {
259 const ir_edge_t *edge;
262 /* skip already fixed nodes */
263 if (workset_get_time(ws, idx) == INT_MAX)
266 /* check all users */
267 foreach_out_edge(node, edge) {
268 ir_node *user = get_edge_src_irn(edge);
270 if ((get_nodes_block(user) != block) || /* user is in a different block */
271 (sched_is_scheduled(user) && sched_comes_after(irn, user)) || /* user is scheduled after irn */
272 user == irn) /* irn is the user */
273 { /* => don't fix distance */
279 /* all users scheduled prior to current irn in in same block as irn -> fix */
281 workset_set_time(ws, idx, INT_MAX);
282 DBG((dbg, DBG_DECIDE, "\tfixing time for %+F to INT_MAX\n", node));
289 * Performs the actions necessary to grant the request that:
290 * - new_vals can be held in registers
291 * - as few as possible other values are disposed
292 * - the worst values get disposed
294 * @p is_usage indicates that the values in new_vals are used (not defined)
295 * In this case reloads must be performed
297 static void displace(belady_env_t *env, workset_t *new_vals, int is_usage) {
299 int i, len, max_allowed, demand, iter;
301 workset_t *ws = env->ws;
302 ir_node **to_insert = alloca(env->n_regs * sizeof(*to_insert));
305 1. Identify the number of needed slots and the values to reload
308 workset_foreach(new_vals, val, iter) {
309 /* mark value as used */
311 pset_insert_ptr(env->used, val);
313 if (! workset_contains(ws, val)) {
314 DBG((dbg, DBG_DECIDE, " insert %+F\n", val));
315 to_insert[demand++] = val;
317 DBG((dbg, DBG_SPILL, "Reload %+F before %+F\n", val, env->instr));
318 be_add_reload(env->senv, val, env->instr);
322 assert(is_usage || "Defined value already in workset?!?");
323 DBG((dbg, DBG_DECIDE, " skip %+F\n", val));
326 DBG((dbg, DBG_DECIDE, " demand = %d\n", demand));
329 2. Make room for at least 'demand' slots
331 len = workset_get_length(ws);
332 max_allowed = env->n_regs - demand;
334 DBG((dbg, DBG_DECIDE, " disposing %d values\n", ws->len - max_allowed));
336 /* Only make more free room if we do not have enough */
337 if (len > max_allowed) {
338 /* get current next-use distance */
339 for (i = 0; i < ws->len; ++i) {
340 unsigned dist = get_distance(env, env->instr, env->instr_nr, workset_get_val(ws, i), !is_usage);
341 workset_set_time(ws, i, dist);
345 FIX for don't spill nodes:
346 Problem is that get_distance always returns 0 for those nodes even if they are not
347 needed anymore (all their usages have already been visited).
348 Even if we change this behavior, get_distance doesn't distinguish between not
349 used anymore (dead) and live out of block.
350 Solution: Set distances of all nodes having all their usages in schedule prior to
351 current instruction to MAX_INT.
353 fix_dead_values(ws, env->instr);
355 /* sort entries by increasing nextuse-distance*/
359 Logic for not needed live-ins: If a value is disposed
360 before its first usage, remove it from start workset
361 We don't do this for phis though
363 for (i = max_allowed; i < ws->len; ++i) {
364 ir_node *irn = ws->vals[i].irn;
369 if (! pset_find_ptr(env->used, irn)) {
370 ir_node *curr_bb = get_nodes_block(env->instr);
371 workset_t *ws_start = get_block_info(curr_bb)->ws_start;
372 workset_remove(ws_start, irn);
374 DBG((dbg, DBG_DECIDE, " dispose %+F dumb\n", irn));
377 DBG((dbg, DBG_DECIDE, " dispose %+F\n", irn));
381 /* kill the last 'demand' entries in the array */
382 workset_set_length(ws, max_allowed);
386 3. Insert the new values into the workset
388 for (i = 0; i < demand; ++i)
389 workset_insert(env, env->ws, to_insert[i]);
392 static void belady(ir_node *blk, void *env);
395 * Computes set of live-ins for each block with multiple predecessors
396 * and notifies spill algorithm which phis need to be spilled
398 static void spill_phi_walker(ir_node *block, void *data) {
399 belady_env_t *env = data;
400 block_info_t *block_info;
401 ir_node *first, *irn;
402 loc_t loc, *starters;
403 int i, len, ws_count;
405 if(get_Block_n_cfgpreds(block) == 1 && get_irg_start_block(get_irn_irg(block)) != block)
408 block_info = new_block_info(&env->ob);
409 set_block_info(block, block_info);
411 /* Collect all values living at start of block */
412 starters = NEW_ARR_F(loc_t, 0);
414 /* rebuild schedule time information, because it seems to be broken */
415 sched_renumber(block);
417 DBG((dbg, DBG_START, "Living at start of %+F:\n", block));
418 first = sched_first(block);
419 sched_foreach(block, irn) {
422 if(!arch_irn_consider_in_reg_alloc(env->arch, env->cls, irn))
426 loc.time = get_distance(env, first, 0, irn, 0);
427 ARR_APP1(loc_t, starters, loc);
428 DBG((dbg, DBG_START, " %+F:\n", irn));
431 be_lv_foreach(env->cenv->lv, block, be_lv_state_in, i) {
432 ir_node *irn = be_lv_get_irn(env->cenv->lv, block, i);
433 if (!arch_irn_consider_in_reg_alloc(env->arch, env->cls, irn))
437 loc.time = get_distance(env, first, 0, irn, 0);
438 ARR_APP1(loc_t, starters, loc);
439 DBG((dbg, DBG_START, " %+F:\n", irn));
442 // Sort start values by first use
443 qsort(starters, ARR_LEN(starters), sizeof(starters[0]), loc_compare);
445 /* Copy the best ones from starters to start workset */
446 ws_count = MIN(ARR_LEN(starters), env->n_regs);
447 block_info->ws_start = new_workset(env, &env->ob);
448 workset_bulk_fill(block_info->ws_start, ws_count, starters);
450 /* The phis of this block which are not in the start set have to be spilled later. */
451 for (i = ws_count, len = ARR_LEN(starters); i < len; ++i) {
452 irn = starters[i].irn;
453 if (!is_Phi(irn) || get_nodes_block(irn) != block)
456 be_spill_phi(env->senv, irn);
463 * Collects all values live-in at block @p blk and all phi results in this block.
464 * Then it adds the best values (at most n_regs) to the blocks start_workset.
465 * The phis among the remaining values get spilled: Introduce psudo-copies of
466 * their args to break interference and make it possible to spill them to the
469 static block_info_t *compute_block_start_info(belady_env_t *env, ir_node *block) {
471 block_info_t *res, *pred_info;
473 /* Have we seen this block before? */
474 res = get_block_info(block);
478 /* Create the block info for this block. */
479 res = new_block_info(&env->ob);
480 set_block_info(block, res);
482 /* Use endset of predecessor block as startset */
483 assert(get_Block_n_cfgpreds(block) == 1 && block != get_irg_start_block(get_irn_irg(block)));
484 pred_block = get_Block_cfgpred_block(block, 0);
485 pred_info = get_block_info(pred_block);
487 /* if pred block has not been processed yet, do it now */
488 if (pred_info == NULL || pred_info->processed == 0) {
489 belady(pred_block, env);
490 pred_info = get_block_info(pred_block);
493 /* now we have an end_set of pred */
494 assert(pred_info->ws_end && "The recursive call (above) is supposed to compute an end_set");
495 res->ws_start = workset_clone(env, &env->ob, pred_info->ws_end);
502 * For the given block @p blk, decide for each values
503 * whether it is used from a register or is reloaded
506 static void belady(ir_node *block, void *data) {
507 belady_env_t *env = data;
511 block_info_t *block_info;
513 /* make sure we have blockinfo (with startset) */
514 block_info = get_block_info(block);
515 if (block_info == NULL)
516 block_info = compute_block_start_info(env, block);
518 /* Don't do a block twice */
519 if(block_info->processed)
522 /* get the starting workset for this block */
523 DBG((dbg, DBG_DECIDE, "\n"));
524 DBG((dbg, DBG_DECIDE, "Decide for %+F\n", block));
526 workset_copy(env, env->ws, block_info->ws_start);
527 DBG((dbg, DBG_WSETS, "Start workset for %+F:\n", block));
528 workset_foreach(env->ws, irn, iter)
529 DBG((dbg, DBG_WSETS, " %+F\n", irn));
531 /* process the block from start to end */
532 DBG((dbg, DBG_WSETS, "Processing...\n"));
533 env->used = pset_new_ptr_default();
535 new_vals = new_workset(env, &env->ob);
536 sched_foreach(block, irn) {
538 assert(workset_get_length(env->ws) <= env->n_regs && "Too much values in workset!");
540 /* projs are handled with the tuple value.
541 * Phis are no real instr (see insert_starters())
542 * instr_nr does not increase */
543 if (is_Proj(irn) || is_Phi(irn)) {
544 DBG((dbg, DBG_DECIDE, " ...%+F skipped\n", irn));
547 DBG((dbg, DBG_DECIDE, " ...%+F\n", irn));
549 /* set instruction in the workset */
552 /* allocate all values _used_ by this instruction */
553 workset_clear(new_vals);
554 for(i = 0, arity = get_irn_arity(irn); i < arity; ++i) {
555 workset_insert(env, new_vals, get_irn_n(irn, i));
557 displace(env, new_vals, 1);
559 /* allocate all values _defined_ by this instruction */
560 workset_clear(new_vals);
561 if (get_irn_mode(irn) == mode_T) { /* special handling for tuples and projs */
563 for(proj=sched_next(irn); is_Proj(proj); proj=sched_next(proj))
564 workset_insert(env, new_vals, proj);
566 workset_insert(env, new_vals, irn);
568 displace(env, new_vals, 0);
574 /* Remember end-workset for this block */
575 block_info->ws_end = workset_clone(env, &env->ob, env->ws);
576 block_info->processed = 1;
577 DBG((dbg, DBG_WSETS, "End workset for %+F:\n", block));
578 workset_foreach(block_info->ws_end, irn, iter)
579 DBG((dbg, DBG_WSETS, " %+F\n", irn));
583 * 'decide' is block-local and makes assumptions
584 * about the set of live-ins. Thus we must adapt the
585 * live-outs to the live-ins at each block-border.
587 static void fix_block_borders(ir_node *blk, void *data) {
588 belady_env_t *env = data;
590 int i, max, iter, iter2;
592 DBG((dbg, DBG_FIX, "\n"));
593 DBG((dbg, DBG_FIX, "Fixing %+F\n", blk));
595 wsb = get_block_info(blk)->ws_start;
597 /* process all pred blocks */
598 for (i=0, max=get_irn_arity(blk); i<max; ++i) {
599 ir_node *irnb, *irnp, *pred = get_Block_cfgpred_block(blk, i);
600 workset_t *wsp = get_block_info(pred)->ws_end;
602 DBG((dbg, DBG_FIX, " Pred %+F\n", pred));
604 workset_foreach(wsb, irnb, iter) {
605 /* if irnb is a phi of the current block we reload
606 * the corresponding argument, else irnb itself */
607 if(is_Phi(irnb) && blk == get_nodes_block(irnb)) {
608 irnb = get_irn_n(irnb, i);
610 // we might have unknowns as argument for the phi
611 if(!arch_irn_consider_in_reg_alloc(env->arch, env->cls, irnb))
615 /* Unknowns are available everywhere */
616 if(get_irn_opcode(irnb) == iro_Unknown)
619 /* check if irnb is in a register at end of pred */
620 workset_foreach(wsp, irnp, iter2) {
625 /* irnb is not in memory at the end of pred, so we have to reload it */
626 DBG((dbg, DBG_FIX, " reload %+F\n", irnb));
627 DBG((dbg, DBG_SPILL, "Reload %+F before %+F,%d\n", irnb, blk, i));
628 be_add_reload_on_edge(env->senv, irnb, blk, i);
631 /*epsilon statement :)*/;
636 void be_spill_belady(const be_chordal_env_t *chordal_env) {
637 be_spill_belady_spill_env(chordal_env, NULL);
640 void be_spill_belady_spill_env(const be_chordal_env_t *chordal_env, spill_env_t *spill_env) {
643 FIRM_DBG_REGISTER(dbg, "firm.be.spill.belady");
644 //firm_dbg_set_mask(dbg, DBG_SPILL);
646 /* init belady env */
647 obstack_init(&env.ob);
648 env.cenv = chordal_env;
649 env.arch = chordal_env->birg->main_env->arch_env;
650 env.cls = chordal_env->cls;
651 env.n_regs = env.cls->n_regs - be_put_ignore_regs(chordal_env->birg, chordal_env->cls, NULL);
652 env.ws = new_workset(&env, &env.ob);
653 env.uses = be_begin_uses(chordal_env->irg, chordal_env->exec_freq, chordal_env->lv);
654 if(spill_env == NULL) {
655 env.senv = be_new_spill_env(chordal_env);
657 env.senv = spill_env;
659 DEBUG_ONLY(be_set_spill_env_dbg_module(env.senv, dbg);)
661 be_clear_links(chordal_env->irg);
662 /* Decide which phi nodes will be spilled and place copies for them into the graph */
663 irg_block_walk_graph(chordal_env->irg, spill_phi_walker, NULL, &env);
664 /* Fix high register pressure with belady algorithm */
665 irg_block_walk_graph(chordal_env->irg, NULL, belady, &env);
666 /* belady was block-local, fix the global flow by adding reloads on the edges */
667 irg_block_walk_graph(chordal_env->irg, fix_block_borders, NULL, &env);
668 /* Insert spill/reload nodes into the graph and fix usages */
669 be_insert_spills_reloads(env.senv);
672 if(spill_env == NULL)
673 be_delete_spill_env(env.senv);
674 be_end_uses(env.uses);
675 obstack_free(&env.ob, NULL);