2 * Copyright (C) 1995-2007 University of Karlsruhe. All right reserved.
4 * This file is part of libFirm.
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.
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.
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
22 * @brief Beladys spillalgorithm.
23 * @author Daniel Grund, Matthias Braun
34 #include "irprintf_t.h"
40 #include "iredges_t.h"
47 #include "bespillbelady.h"
49 #include "besched_t.h"
53 #include "bechordal_t.h"
54 #include "bespilloptions.h"
55 #include "beloopana.h"
66 #define DBG_WORKSET 128
67 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
70 * An association between a node and a point in time.
72 typedef struct _loc_t {
73 ir_node *irn; /**< A node. */
74 unsigned time; /**< A use time (see beuses.h). */
77 typedef struct _workset_t {
78 int len; /**< current length */
79 loc_t vals[0]; /**< inlined array of the values/distances in this working set */
82 typedef struct _belady_env_t {
84 const arch_env_t *arch;
85 const arch_register_class_t *cls;
87 be_loopana_t *loop_ana;
88 int n_regs; /** number of regs in this reg-class */
90 workset_t *ws; /**< the main workset used while processing a block. ob-allocated */
91 be_uses_t *uses; /**< env for the next-use magic */
92 ir_node *instr; /**< current instruction */
93 unsigned instr_nr; /**< current instruction number (relative to block start) */
96 spill_env_t *senv; /**< see bespill.h */
99 static int loc_compare(const void *a, const void *b)
103 return p->time - q->time;
106 static INLINE void workset_print(const workset_t *w)
110 for(i = 0; i < w->len; ++i) {
111 ir_fprintf(stderr, "%+F %d\n", w->vals[i].irn, w->vals[i].time);
116 * Alloc a new workset on obstack @p ob with maximum size @p max
118 static INLINE workset_t *new_workset(belady_env_t *env, struct obstack *ob) {
120 size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
121 res = obstack_alloc(ob, size);
122 memset(res, 0, size);
127 * Alloc a new instance on obstack and make it equal to @param ws
129 static INLINE workset_t *workset_clone(belady_env_t *env, struct obstack *ob, workset_t *ws) {
131 size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
132 res = obstack_alloc(ob, size);
133 memcpy(res, ws, size);
138 * Do NOT alloc anything. Make @param tgt equal to @param src.
139 * returns @param tgt for convenience
141 static INLINE workset_t *workset_copy(belady_env_t *env, workset_t *tgt, workset_t *src) {
142 size_t size = sizeof(*src) + (env->n_regs)*sizeof(src->vals[0]);
143 memcpy(tgt, src, size);
148 * Overwrites the current content array of @param ws with the
149 * @param count locations given at memory @param locs.
150 * Set the length of @param ws to count.
152 static INLINE void workset_bulk_fill(workset_t *workset, int count, const loc_t *locs) {
153 workset->len = count;
154 memcpy(&(workset->vals[0]), locs, count * sizeof(locs[0]));
158 * Inserts the value @p val into the workset, iff it is not
159 * already contained. The workset must not be full.
161 static INLINE void workset_insert(belady_env_t *env, workset_t *ws, ir_node *val) {
163 /* check for current regclass */
164 if (!arch_irn_consider_in_reg_alloc(env->arch, env->cls, val)) {
165 DBG((dbg, DBG_WORKSET, "Skipped %+F\n", val));
169 /* check if val is already contained */
170 for(i=0; i<ws->len; ++i)
171 if (ws->vals[i].irn == val)
175 assert(ws->len < env->n_regs && "Workset already full!");
176 ws->vals[ws->len++].irn = val;
180 * Removes all entries from this workset
182 static INLINE void workset_clear(workset_t *ws) {
187 * Removes the value @p val from the workset if present.
189 static INLINE void workset_remove(workset_t *ws, ir_node *val) {
191 for(i=0; i<ws->len; ++i) {
192 if (ws->vals[i].irn == val) {
193 ws->vals[i] = ws->vals[--ws->len];
199 static INLINE int workset_contains(const workset_t *ws, const ir_node *val) {
201 for(i=0; i<ws->len; ++i) {
202 if (ws->vals[i].irn == val)
210 * Iterates over all values in the working set.
211 * @p ws The workset to iterate
212 * @p v A variable to put the current value in
213 * @p i An integer for internal use
215 #define workset_foreach(ws, v, i) for(i=0; \
216 v=(i < ws->len) ? ws->vals[i].irn : NULL, i < ws->len; \
219 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
220 #define workset_get_time(ws, i) (ws)->vals[i].time
221 #define workset_set_length(ws, length) (ws)->len = length
222 #define workset_get_length(ws) ((ws)->len)
223 #define workset_get_val(ws, i) ((ws)->vals[i].irn)
224 #define workset_sort(ws) qsort((ws)->vals, (ws)->len, sizeof((ws)->vals[0]), loc_compare);
226 typedef struct _block_info_t {
227 workset_t *ws_start, *ws_end;
232 static INLINE void *new_block_info(struct obstack *ob) {
233 block_info_t *res = obstack_alloc(ob, sizeof(*res));
234 res->ws_start = NULL;
241 #define get_block_info(block) ((block_info_t *)get_irn_link(block))
242 #define set_block_info(block, info) set_irn_link(block, info)
245 * @return The distance to the next use or 0 if irn has dont_spill flag set
247 static INLINE unsigned get_distance(belady_env_t *env, ir_node *from, unsigned from_step, const ir_node *def, int skip_from_uses)
250 int flags = arch_irn_get_flags(env->arch, def);
252 assert(! (flags & arch_irn_flags_ignore));
254 use = be_get_next_use(env->uses, from, from_step, def, skip_from_uses);
255 if(USES_IS_INFINITE(use.time))
256 return USES_INFINITY;
258 /* We have to keep nonspillable nodes in the workingset */
259 if(flags & arch_irn_flags_dont_spill)
266 * Performs the actions necessary to grant the request that:
267 * - new_vals can be held in registers
268 * - as few as possible other values are disposed
269 * - the worst values get disposed
271 * @p is_usage indicates that the values in new_vals are used (not defined)
272 * In this case reloads must be performed
274 static void displace(belady_env_t *env, workset_t *new_vals, int is_usage) {
276 int i, len, max_allowed, demand, iter;
278 workset_t *ws = env->ws;
279 ir_node **to_insert = alloca(env->n_regs * sizeof(*to_insert));
282 1. Identify the number of needed slots and the values to reload
285 workset_foreach(new_vals, val, iter) {
286 /* mark value as used */
288 pset_insert_ptr(env->used, val);
290 if (! workset_contains(ws, val)) {
291 DBG((dbg, DBG_DECIDE, " insert %+F\n", val));
292 to_insert[demand++] = val;
294 DBG((dbg, DBG_SPILL, "Reload %+F before %+F\n", val, env->instr));
295 be_add_reload(env->senv, val, env->instr, env->cls, 1);
299 assert(is_usage || "Defined value already in workset?!?");
300 DBG((dbg, DBG_DECIDE, " skip %+F\n", val));
303 DBG((dbg, DBG_DECIDE, " demand = %d\n", demand));
306 2. Make room for at least 'demand' slots
308 len = workset_get_length(ws);
309 max_allowed = env->n_regs - demand;
311 DBG((dbg, DBG_DECIDE, " disposing %d values\n", ws->len - max_allowed));
313 /* Only make more free room if we do not have enough */
314 if (len > max_allowed) {
315 /* get current next-use distance */
316 for (i = 0; i < ws->len; ++i) {
317 unsigned dist = get_distance(env, env->instr, env->instr_nr, workset_get_val(ws, i), !is_usage);
318 workset_set_time(ws, i, dist);
321 /* sort entries by increasing nextuse-distance*/
325 Logic for not needed live-ins: If a value is disposed
326 before its first usage, remove it from start workset
327 We don't do this for phis though
329 for (i = max_allowed; i < ws->len; ++i) {
330 ir_node *irn = ws->vals[i].irn;
332 DBG((dbg, DBG_DECIDE, " disposing %+F (%u)\n", irn, workset_get_time(ws, i)));
337 if (! pset_find_ptr(env->used, irn)) {
338 ir_node *curr_bb = get_nodes_block(env->instr);
339 workset_t *ws_start = get_block_info(curr_bb)->ws_start;
340 workset_remove(ws_start, irn);
342 DBG((dbg, DBG_DECIDE, " (and removing %+F from start workset)\n", irn));
346 /* kill the last 'demand' entries in the array */
347 workset_set_length(ws, max_allowed);
351 3. Insert the new values into the workset
353 for (i = 0; i < demand; ++i)
354 workset_insert(env, env->ws, to_insert[i]);
357 static void belady(ir_node *block, void *env);
359 /** Decides whether a specific node should be in the start workset or not
361 * @param env belady environment
363 * @param node the node to test
364 * @param block the block of the node
365 * @param loop the loop of the node
367 static loc_t to_take_or_not_to_take(belady_env_t *env, ir_node* first,
368 ir_node *node, ir_node *block,
371 be_next_use_t next_use;
373 loc.time = USES_INFINITY;
376 if (!arch_irn_consider_in_reg_alloc(env->arch, env->cls, node)) {
377 loc.time = USES_INFINITY;
381 /* We have to keep nonspillable nodes in the workingset */
382 if(arch_irn_get_flags(env->arch, node) & arch_irn_flags_dont_spill) {
384 DBG((dbg, DBG_START, " %+F taken (dontspill node)\n", node, loc.time));
388 next_use = be_get_next_use(env->uses, first, 0, node, 0);
389 if(USES_IS_INFINITE(next_use.time)) {
390 // the nodes marked as live in shouldn't be dead, so it must be a phi
391 assert(is_Phi(node));
392 loc.time = USES_INFINITY;
393 DBG((dbg, DBG_START, " %+F not taken (dead)\n", node));
395 be_spill_phi(env->senv, node);
400 loc.time = next_use.time;
402 if(next_use.outermost_loop >= get_loop_depth(loop)) {
403 DBG((dbg, DBG_START, " %+F taken (%u, loop %d)\n", node, loc.time, next_use.outermost_loop));
405 loc.time = USES_PENDING;
406 DBG((dbg, DBG_START, " %+F delayed (outerloopdepth %d < loopdetph %d)\n", node, next_use.outermost_loop, get_loop_depth(loop)));
412 * Computes set of live-ins for each block with multiple predecessors
413 * and notifies spill algorithm which phis need to be spilled
415 static void compute_live_ins(ir_node *block, void *data) {
416 belady_env_t *env = data;
417 ir_loop *loop = get_irn_loop(block);
418 const be_lv_t *lv = env->lv;
419 block_info_t *block_info;
420 ir_node *first, *irn;
421 loc_t loc, *starters, *delayed;
422 int i, len, ws_count;
423 int free_slots, free_pressure_slots;
426 if (get_Block_n_cfgpreds(block) == 1 && get_irg_start_block(get_irn_irg(block)) != block)
429 block_info = new_block_info(&env->ob);
430 set_block_info(block, block_info);
432 /* Collect all values living at start of block */
433 starters = NEW_ARR_F(loc_t, 0);
434 delayed = NEW_ARR_F(loc_t, 0);
436 DBG((dbg, DBG_START, "Living at start of %+F:\n", block));
437 first = sched_first(block);
439 /* check all Phis first */
440 sched_foreach(block, irn) {
444 loc = to_take_or_not_to_take(env, first, irn, block, loop);
446 if (! USES_IS_INFINITE(loc.time)) {
447 if (USES_IS_PENDING(loc.time))
448 ARR_APP1(loc_t, delayed, loc);
450 ARR_APP1(loc_t, starters, loc);
454 /* check all Live-Ins */
455 be_lv_foreach(lv, block, be_lv_state_in, i) {
456 ir_node *node = be_lv_get_irn(lv, block, i);
458 loc = to_take_or_not_to_take(env, first, node, block, loop);
460 if (! USES_IS_INFINITE(loc.time)) {
461 if (USES_IS_PENDING(loc.time))
462 ARR_APP1(loc_t, delayed, loc);
464 ARR_APP1(loc_t, starters, loc);
468 pressure = be_get_loop_pressure(env->loop_ana, env->cls, loop);
469 assert(ARR_LEN(delayed) <= (signed)pressure);
470 free_slots = env->n_regs - ARR_LEN(starters);
471 free_pressure_slots = env->n_regs - (pressure - ARR_LEN(delayed));
472 free_slots = MIN(free_slots, free_pressure_slots);
473 /* append nodes delayed due to loop structure until start set is full */
474 for (i = 0; i < ARR_LEN(delayed) && i < free_slots; ++i) {
475 DBG((dbg, DBG_START, " delayed %+F taken\n", delayed[i].irn));
476 ARR_APP1(loc_t, starters, delayed[i]);
477 delayed[i].irn = NULL;
480 /* spill all delayed phis which didn't make it into start workset */
481 for (i = ARR_LEN(delayed) - 1; i >= 0; --i) {
482 ir_node *irn = delayed[i].irn;
483 if (irn && is_Phi(irn)) {
484 DBG((dbg, DBG_START, " spilling delayed phi %+F\n", irn));
485 be_spill_phi(env->senv, irn);
490 /* Sort start values by first use */
491 qsort(starters, ARR_LEN(starters), sizeof(starters[0]), loc_compare);
493 /* Copy the best ones from starters to start workset */
494 ws_count = MIN(ARR_LEN(starters), env->n_regs);
495 block_info->ws_start = new_workset(env, &env->ob);
496 workset_bulk_fill(block_info->ws_start, ws_count, starters);
498 /* The phis of this block which are not in the start set have to be spilled later. */
499 len = ARR_LEN(starters);
500 for (i = ws_count; i < len; ++i) {
501 irn = starters[i].irn;
502 if (! is_Phi(irn) || get_nodes_block(irn) != block)
505 be_spill_phi(env->senv, irn);
512 * Collects all values live-in at block @p block and all phi results in this block.
513 * Then it adds the best values (at most n_regs) to the blocks start_workset.
514 * The phis among the remaining values get spilled: Introduce psudo-copies of
515 * their args to break interference and make it possible to spill them to the
518 static block_info_t *compute_block_start_info(belady_env_t *env, ir_node *block) {
520 block_info_t *res, *pred_info;
522 /* Have we seen this block before? */
523 res = get_block_info(block);
527 /* Create the block info for this block. */
528 res = new_block_info(&env->ob);
529 set_block_info(block, res);
531 /* Use endset of predecessor block as startset */
532 assert(get_Block_n_cfgpreds(block) == 1 && block != get_irg_start_block(get_irn_irg(block)));
533 pred_block = get_Block_cfgpred_block(block, 0);
534 pred_info = get_block_info(pred_block);
536 /* if pred block has not been processed yet, do it now */
537 if (pred_info == NULL || pred_info->processed == 0) {
538 belady(pred_block, env);
539 pred_info = get_block_info(pred_block);
542 /* now we have an end_set of pred */
543 assert(pred_info->ws_end && "The recursive call (above) is supposed to compute an end_set");
544 res->ws_start = workset_clone(env, &env->ob, pred_info->ws_end);
551 * For the given block @p block, decide for each values
552 * whether it is used from a register or is reloaded
555 static void belady(ir_node *block, void *data) {
556 belady_env_t *env = data;
560 block_info_t *block_info;
562 /* make sure we have blockinfo (with startset) */
563 block_info = get_block_info(block);
564 if (block_info == NULL)
565 block_info = compute_block_start_info(env, block);
567 /* Don't do a block twice */
568 if(block_info->processed)
571 /* get the starting workset for this block */
572 DBG((dbg, DBG_DECIDE, "\n"));
573 DBG((dbg, DBG_DECIDE, "Decide for %+F\n", block));
575 workset_copy(env, env->ws, block_info->ws_start);
576 DBG((dbg, DBG_WSETS, "Start workset for %+F:\n", block));
577 workset_foreach(env->ws, irn, iter)
578 DBG((dbg, DBG_WSETS, " %+F (%u)\n", irn, workset_get_time(env->ws, iter)));
580 /* process the block from start to end */
581 DBG((dbg, DBG_WSETS, "Processing...\n"));
582 env->used = pset_new_ptr_default();
584 new_vals = new_workset(env, &env->ob);
585 sched_foreach(block, irn) {
587 assert(workset_get_length(env->ws) <= env->n_regs && "Too much values in workset!");
589 /* projs are handled with the tuple value.
590 * Phis are no real instr (see insert_starters())
591 * instr_nr does not increase */
592 if (is_Proj(irn) || is_Phi(irn)) {
593 DBG((dbg, DBG_DECIDE, " ...%+F skipped\n", irn));
596 DBG((dbg, DBG_DECIDE, " ...%+F\n", irn));
598 /* set instruction in the workset */
601 /* allocate all values _used_ by this instruction */
602 workset_clear(new_vals);
603 for(i = 0, arity = get_irn_arity(irn); i < arity; ++i) {
604 workset_insert(env, new_vals, get_irn_n(irn, i));
606 displace(env, new_vals, 1);
608 /* allocate all values _defined_ by this instruction */
609 workset_clear(new_vals);
610 if (get_irn_mode(irn) == mode_T) { /* special handling for tuples and projs */
612 for(proj=sched_next(irn); is_Proj(proj); proj=sched_next(proj))
613 workset_insert(env, new_vals, proj);
615 workset_insert(env, new_vals, irn);
617 displace(env, new_vals, 0);
623 /* Remember end-workset for this block */
624 block_info->ws_end = workset_clone(env, &env->ob, env->ws);
625 block_info->processed = 1;
626 DBG((dbg, DBG_WSETS, "End workset for %+F:\n", block));
627 workset_foreach(block_info->ws_end, irn, iter)
628 DBG((dbg, DBG_WSETS, " %+F (%u)\n", irn, workset_get_time(block_info->ws_end, iter)));
632 * 'decide' is block-local and makes assumptions
633 * about the set of live-ins. Thus we must adapt the
634 * live-outs to the live-ins at each block-border.
636 static void fix_block_borders(ir_node *block, void *data) {
637 belady_env_t *env = data;
639 ir_graph *irg = get_irn_irg(block);
640 ir_node *startblock = get_irg_start_block(irg);
641 int i, max, iter, iter2;
643 if(block == startblock)
646 DBG((dbg, DBG_FIX, "\n"));
647 DBG((dbg, DBG_FIX, "Fixing %+F\n", block));
649 wsb = get_block_info(block)->ws_start;
651 /* process all pred blocks */
652 for (i=0, max=get_irn_arity(block); i<max; ++i) {
653 ir_node *irnb, *irnp, *pred = get_Block_cfgpred_block(block, i);
654 workset_t *wsp = get_block_info(pred)->ws_end;
656 DBG((dbg, DBG_FIX, " Pred %+F\n", pred));
658 workset_foreach(wsb, irnb, iter) {
659 /* if irnb is a phi of the current block we reload
660 * the corresponding argument, else irnb itself */
661 if(is_Phi(irnb) && block == get_nodes_block(irnb)) {
662 irnb = get_irn_n(irnb, i);
664 // we might have unknowns as argument for the phi
665 if(!arch_irn_consider_in_reg_alloc(env->arch, env->cls, irnb))
669 /* Unknowns are available everywhere */
670 if(get_irn_opcode(irnb) == iro_Unknown)
673 /* check if irnb is in a register at end of pred */
674 workset_foreach(wsp, irnp, iter2) {
679 /* irnb is not in memory at the end of pred, so we have to reload it */
680 DBG((dbg, DBG_FIX, " reload %+F\n", irnb));
681 DBG((dbg, DBG_SPILL, "Reload %+F before %+F,%d\n", irnb, block, i));
682 be_add_reload_on_edge(env->senv, irnb, block, i, env->cls, 1);
685 /*epsilon statement :)*/;
691 * Do spilling for a register class on a graph using the belady heuristic.
692 * In the transformed graph, the register pressure never exceeds the number
693 * of available registers.
695 * @param birg The backend graph
696 * @param cls The register class to spill
698 static void be_spill_belady(be_irg_t *birg, const arch_register_class_t *cls) {
699 be_spill_belady_spill_env(birg, cls, NULL);
702 void be_spill_belady_spill_env(be_irg_t *birg, const arch_register_class_t *cls, spill_env_t *spill_env) {
704 ir_graph *irg = be_get_birg_irg(birg);
707 /* some special classes contain only ignore regs, nothing to do then */
708 n_regs = cls->n_regs - be_put_ignore_regs(birg, cls, NULL);
712 be_invalidate_liveness(birg);
713 be_assure_liveness(birg);
714 /* construct control flow loop tree */
715 if(! (get_irg_loopinfo_state(irg) & loopinfo_cf_consistent)) {
716 construct_cf_backedges(irg);
719 /* init belady env */
720 obstack_init(&env.ob);
721 env.arch = birg->main_env->arch_env;
723 env.lv = be_get_birg_liveness(birg);
725 env.ws = new_workset(&env, &env.ob);
726 env.uses = be_begin_uses(irg, env.lv);
727 env.loop_ana = be_new_loop_pressure(birg);
728 if(spill_env == NULL) {
729 env.senv = be_new_spill_env(birg);
731 env.senv = spill_env;
735 /* Decide which phi nodes will be spilled and place copies for them into the graph */
736 irg_block_walk_graph(irg, compute_live_ins, NULL, &env);
737 /* Fix high register pressure with belady algorithm */
738 irg_block_walk_graph(irg, NULL, belady, &env);
739 /* belady was block-local, fix the global flow by adding reloads on the edges */
740 irg_block_walk_graph(irg, fix_block_borders, NULL, &env);
741 /* Insert spill/reload nodes into the graph and fix usages */
742 be_insert_spills_reloads(env.senv);
745 if(spill_env == NULL)
746 be_delete_spill_env(env.senv);
747 be_end_uses(env.uses);
748 be_free_loop_pressure(env.loop_ana);
749 obstack_free(&env.ob, NULL);
752 void be_init_spillbelady(void)
754 static be_spiller_t belady_spiller = {
758 be_register_spiller("belady", &belady_spiller);
759 FIRM_DBG_REGISTER(dbg, "firm.be.spill.belady");
762 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spillbelady);