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). */
75 int reloaded_value; /**< the value is a reloaded value */
78 typedef struct _workset_t {
79 int len; /**< current length */
80 loc_t vals[0]; /**< inlined array of the values/distances in this working set */
83 typedef struct _belady_env_t {
85 const arch_env_t *arch;
86 const arch_register_class_t *cls;
88 be_loopana_t *loop_ana;
89 int n_regs; /** number of regs in this reg-class */
91 workset_t *ws; /**< the main workset used while processing a block. ob-allocated */
92 be_uses_t *uses; /**< env for the next-use magic */
93 ir_node *instr; /**< current instruction */
94 unsigned instr_nr; /**< current instruction number (relative to block start) */
97 spill_env_t *senv; /**< see bespill.h */
100 static int loc_compare(const void *a, const void *b)
104 return p->time - q->time;
108 static void workset_print(const workset_t *w)
112 for(i = 0; i < w->len; ++i) {
113 ir_fprintf(stderr, "%+F %d (%d)\n", w->vals[i].irn, w->vals[i].time, w->vals[i].reloaded_value);
115 /* avoid unused warning */
116 (void) workset_print;
120 * Alloc a new workset on obstack @p ob with maximum size @p max
122 static INLINE workset_t *new_workset(belady_env_t *env, struct obstack *ob) {
124 size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
125 res = obstack_alloc(ob, size);
126 memset(res, 0, size);
131 * Alloc a new instance on obstack and make it equal to @param ws
133 static INLINE workset_t *workset_clone(belady_env_t *env, struct obstack *ob, workset_t *ws) {
135 size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
136 res = obstack_alloc(ob, size);
137 memcpy(res, ws, size);
142 * Do NOT alloc anything. Make @param tgt equal to @param src.
143 * returns @param tgt for convenience
145 static INLINE workset_t *workset_copy(belady_env_t *env, workset_t *tgt, workset_t *src) {
146 size_t size = sizeof(*src) + (env->n_regs)*sizeof(src->vals[0]);
147 memcpy(tgt, src, size);
152 * Overwrites the current content array of @param ws with the
153 * @param count locations given at memory @param locs.
154 * Set the length of @param ws to count.
156 static INLINE void workset_bulk_fill(workset_t *workset, int count, const loc_t *locs) {
157 workset->len = count;
158 memcpy(&(workset->vals[0]), locs, count * sizeof(locs[0]));
162 * Inserts the value @p val into the workset, iff it is not
163 * already contained. The workset must not be full.
165 static INLINE void workset_insert(belady_env_t *env, workset_t *ws,
166 ir_node *val, int reloaded_value)
169 /* check for current regclass */
170 if (!arch_irn_consider_in_reg_alloc(env->arch, env->cls, val)) {
171 //DBG((dbg, DBG_WORKSET, "Skipped %+F\n", val));
175 /* check if val is already contained */
176 for(i=0; i<ws->len; ++i) {
177 if (ws->vals[i].irn == val) {
178 if(!ws->vals[i].reloaded_value)
179 ws->vals[i].reloaded_value = reloaded_value;
185 assert(ws->len < env->n_regs && "Workset already full!");
186 ws->vals[ws->len].irn = val;
187 ws->vals[ws->len].reloaded_value = reloaded_value;
192 * Removes all entries from this workset
194 static INLINE void workset_clear(workset_t *ws) {
199 * Removes the value @p val from the workset if present.
201 static INLINE void workset_remove(workset_t *ws, ir_node *val) {
203 for(i=0; i<ws->len; ++i) {
204 if (ws->vals[i].irn == val) {
205 ws->vals[i] = ws->vals[--ws->len];
211 static INLINE int workset_contains(const workset_t *ws, const ir_node *val) {
213 for(i=0; i<ws->len; ++i) {
214 if (ws->vals[i].irn == val)
222 * Iterates over all values in the working set.
223 * @p ws The workset to iterate
224 * @p v A variable to put the current value in
225 * @p i An integer for internal use
227 #define workset_foreach(ws, v, i) for(i=0; \
228 v=(i < ws->len) ? ws->vals[i].irn : NULL, i < ws->len; \
231 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
232 #define workset_get_time(ws, i) (ws)->vals[i].time
233 #define workset_set_length(ws, length) (ws)->len = length
234 #define workset_get_length(ws) ((ws)->len)
235 #define workset_get_val(ws, i) ((ws)->vals[i].irn)
236 #define workset_sort(ws) qsort((ws)->vals, (ws)->len, sizeof((ws)->vals[0]), loc_compare);
238 typedef struct _block_info_t {
239 workset_t *ws_start, *ws_end;
244 static INLINE void *new_block_info(struct obstack *ob) {
245 block_info_t *res = obstack_alloc(ob, sizeof(*res));
246 res->ws_start = NULL;
253 #define get_block_info(block) ((block_info_t *)get_irn_link(block))
254 #define set_block_info(block, info) set_irn_link(block, info)
257 * @return The distance to the next use or 0 if irn has dont_spill flag set
259 static INLINE unsigned get_distance(belady_env_t *env, ir_node *from, unsigned from_step, const ir_node *def, int skip_from_uses)
262 int flags = arch_irn_get_flags(env->arch, def);
264 assert(! (flags & arch_irn_flags_ignore));
266 use = be_get_next_use(env->uses, from, from_step, def, skip_from_uses);
267 if(USES_IS_INFINITE(use.time))
268 return USES_INFINITY;
270 /* We have to keep nonspillable nodes in the workingset */
271 if(flags & arch_irn_flags_dont_spill)
278 * Performs the actions necessary to grant the request that:
279 * - new_vals can be held in registers
280 * - as few as possible other values are disposed
281 * - the worst values get disposed
283 * @p is_usage indicates that the values in new_vals are used (not defined)
284 * In this case reloads must be performed
286 static void displace(belady_env_t *env, workset_t *new_vals, int is_usage) {
288 int i, len, max_allowed, demand, iter;
290 workset_t *ws = env->ws;
291 ir_node **to_insert = alloca(env->n_regs * sizeof(*to_insert));
294 1. Identify the number of needed slots and the values to reload
297 workset_foreach(new_vals, val, iter) {
298 /* mark value as used */
300 pset_insert_ptr(env->used, val);
302 if (! workset_contains(ws, val)) {
303 DBG((dbg, DBG_DECIDE, " insert %+F\n", val));
305 to_insert[demand++] = val;
307 DBG((dbg, DBG_SPILL, "Reload %+F before %+F\n", val, env->instr));
308 be_add_reload(env->senv, val, env->instr, env->cls, 1);
311 DBG((dbg, DBG_DECIDE, " %+F already in workset\n", val));
315 //DBG((dbg, DBG_DECIDE, " demand = %d\n", demand));
318 2. Make room for at least 'demand' slots
320 len = workset_get_length(ws);
321 max_allowed = env->n_regs - demand;
323 /* Only make more free room if we do not have enough */
324 if (len > max_allowed) {
325 DBG((dbg, DBG_DECIDE, " disposing %d values\n", ws->len - max_allowed));
327 /* get current next-use distance */
328 for (i = 0; i < ws->len; ++i) {
329 unsigned dist = get_distance(env, env->instr, env->instr_nr, workset_get_val(ws, i), !is_usage);
330 workset_set_time(ws, i, dist);
333 /* sort entries by increasing nextuse-distance*/
337 Logic for not needed live-ins: If a value is disposed
338 before its first usage, remove it from start workset
339 We don't do this for phis though
341 for (i = max_allowed; i < ws->len; ++i) {
342 ir_node *irn = ws->vals[i].irn;
344 DBG((dbg, DBG_DECIDE, " disposing %+F (%u)\n", irn,
345 workset_get_time(ws, i)));
347 if(!USES_IS_INFINITE(ws->vals[i].time)
348 && !ws->vals[i].reloaded_value) {
349 be_add_spill(env->senv, irn, env->instr);
355 if (! pset_find_ptr(env->used, irn)) {
356 ir_node *curr_bb = get_nodes_block(env->instr);
357 workset_t *ws_start = get_block_info(curr_bb)->ws_start;
358 workset_remove(ws_start, irn);
360 DBG((dbg, DBG_DECIDE, " (and removing %+F from start workset)\n", irn));
364 /* kill the last 'demand' entries in the array */
365 workset_set_length(ws, max_allowed);
369 3. Insert the new values into the workset
371 for (i = 0; i < demand; ++i) {
372 workset_insert(env, env->ws, to_insert[i], 1);
376 static void belady(ir_node *block, void *env);
378 /** Decides whether a specific node should be in the start workset or not
380 * @param env belady environment
382 * @param node the node to test
383 * @param block the block of the node
384 * @param loop the loop of the node
386 static loc_t to_take_or_not_to_take(belady_env_t *env, ir_node* first,
387 ir_node *node, ir_node *block,
390 be_next_use_t next_use;
392 loc.time = USES_INFINITY;
396 if (!arch_irn_consider_in_reg_alloc(env->arch, env->cls, node)) {
397 loc.time = USES_INFINITY;
401 /* We have to keep nonspillable nodes in the workingset */
402 if(arch_irn_get_flags(env->arch, node) & arch_irn_flags_dont_spill) {
404 DBG((dbg, DBG_START, " %+F taken (dontspill node)\n", node, loc.time));
408 next_use = be_get_next_use(env->uses, first, 0, node, 0);
409 if(USES_IS_INFINITE(next_use.time)) {
410 // the nodes marked as live in shouldn't be dead, so it must be a phi
411 assert(is_Phi(node));
412 loc.time = USES_INFINITY;
413 DBG((dbg, DBG_START, " %+F not taken (dead)\n", node));
415 be_spill_phi(env->senv, node);
420 loc.time = next_use.time;
422 if(next_use.outermost_loop >= get_loop_depth(loop)) {
423 DBG((dbg, DBG_START, " %+F taken (%u, loop %d)\n", node, loc.time, next_use.outermost_loop));
425 loc.time = USES_PENDING;
426 DBG((dbg, DBG_START, " %+F delayed (outerloopdepth %d < loopdetph %d)\n", node, next_use.outermost_loop, get_loop_depth(loop)));
432 * Computes set of live-ins for each block with multiple predecessors
433 * and notifies spill algorithm which phis need to be spilled
435 static void compute_live_ins(ir_node *block, void *data) {
436 belady_env_t *env = data;
437 ir_loop *loop = get_irn_loop(block);
438 const be_lv_t *lv = env->lv;
439 block_info_t *block_info;
440 ir_node *first, *irn;
441 loc_t loc, *starters, *delayed;
442 int i, len, ws_count;
443 int free_slots, free_pressure_slots;
446 if (get_Block_n_cfgpreds(block) == 1 && get_irg_start_block(get_irn_irg(block)) != block)
449 block_info = new_block_info(&env->ob);
450 set_block_info(block, block_info);
452 /* Collect all values living at start of block */
453 starters = NEW_ARR_F(loc_t, 0);
454 delayed = NEW_ARR_F(loc_t, 0);
456 DBG((dbg, DBG_START, "Living at start of %+F:\n", block));
457 first = sched_first(block);
459 /* check all Phis first */
460 sched_foreach(block, irn) {
464 loc = to_take_or_not_to_take(env, first, irn, block, loop);
466 if (! USES_IS_INFINITE(loc.time)) {
467 if (USES_IS_PENDING(loc.time))
468 ARR_APP1(loc_t, delayed, loc);
470 ARR_APP1(loc_t, starters, loc);
474 /* check all Live-Ins */
475 be_lv_foreach(lv, block, be_lv_state_in, i) {
476 ir_node *node = be_lv_get_irn(lv, block, i);
478 loc = to_take_or_not_to_take(env, first, node, block, loop);
480 if (! USES_IS_INFINITE(loc.time)) {
481 if (USES_IS_PENDING(loc.time))
482 ARR_APP1(loc_t, delayed, loc);
484 ARR_APP1(loc_t, starters, loc);
488 pressure = be_get_loop_pressure(env->loop_ana, env->cls, loop);
489 assert(ARR_LEN(delayed) <= (signed)pressure);
490 free_slots = env->n_regs - ARR_LEN(starters);
491 free_pressure_slots = env->n_regs - (pressure - ARR_LEN(delayed));
492 free_slots = MIN(free_slots, free_pressure_slots);
493 /* append nodes delayed due to loop structure until start set is full */
494 for (i = 0; i < ARR_LEN(delayed) && i < free_slots; ++i) {
495 DBG((dbg, DBG_START, " delayed %+F taken\n", delayed[i].irn));
496 ARR_APP1(loc_t, starters, delayed[i]);
497 delayed[i].irn = NULL;
500 /* spill all delayed phis which didn't make it into start workset */
501 for ( ; i < ARR_LEN(delayed); ++i) {
502 ir_node *irn = delayed[i].irn;
503 if (irn && is_Phi(irn) && get_nodes_block(irn) == block) {
504 DBG((dbg, DBG_START, " spilling delayed phi %+F\n", irn));
505 be_spill_phi(env->senv, irn);
510 /* Sort start values by first use */
511 qsort(starters, ARR_LEN(starters), sizeof(starters[0]), loc_compare);
513 /* Copy the best ones from starters to start workset */
514 ws_count = MIN(ARR_LEN(starters), env->n_regs);
515 block_info->ws_start = new_workset(env, &env->ob);
516 workset_bulk_fill(block_info->ws_start, ws_count, starters);
518 /* The phis of this block which are not in the start set have to be spilled later. */
519 len = ARR_LEN(starters);
520 for (i = ws_count; i < len; ++i) {
521 irn = starters[i].irn;
522 if (! is_Phi(irn) || get_nodes_block(irn) != block)
525 be_spill_phi(env->senv, irn);
532 * Collects all values live-in at block @p block and all phi results in this block.
533 * Then it adds the best values (at most n_regs) to the blocks start_workset.
534 * The phis among the remaining values get spilled: Introduce psudo-copies of
535 * their args to break interference and make it possible to spill them to the
538 static block_info_t *compute_block_start_info(belady_env_t *env, ir_node *block) {
540 block_info_t *res, *pred_info;
542 /* Have we seen this block before? */
543 res = get_block_info(block);
547 /* Create the block info for this block. */
548 res = new_block_info(&env->ob);
549 set_block_info(block, res);
551 /* Use endset of predecessor block as startset */
552 assert(get_Block_n_cfgpreds(block) == 1 && block != get_irg_start_block(get_irn_irg(block)));
553 pred_block = get_Block_cfgpred_block(block, 0);
554 pred_info = get_block_info(pred_block);
556 /* if pred block has not been processed yet, do it now */
557 if (pred_info == NULL || pred_info->processed == 0) {
558 belady(pred_block, env);
559 pred_info = get_block_info(pred_block);
562 /* now we have an end_set of pred */
563 assert(pred_info->ws_end && "The recursive call (above) is supposed to compute an end_set");
564 res->ws_start = workset_clone(env, &env->ob, pred_info->ws_end);
571 * For the given block @p block, decide for each values
572 * whether it is used from a register or is reloaded
575 static void belady(ir_node *block, void *data) {
576 belady_env_t *env = data;
580 block_info_t *block_info;
582 /* make sure we have blockinfo (with startset) */
583 block_info = get_block_info(block);
584 if (block_info == NULL)
585 block_info = compute_block_start_info(env, block);
587 /* Don't do a block twice */
588 if(block_info->processed)
591 /* get the starting workset for this block */
592 DBG((dbg, DBG_DECIDE, "\n"));
593 DBG((dbg, DBG_DECIDE, "Decide for %+F\n", block));
595 workset_copy(env, env->ws, block_info->ws_start);
596 DBG((dbg, DBG_WSETS, "Start workset for %+F:\n", block));
597 workset_foreach(env->ws, irn, iter)
598 DBG((dbg, DBG_WSETS, " %+F (%u)\n", irn, workset_get_time(env->ws, iter)));
600 /* process the block from start to end */
601 DBG((dbg, DBG_WSETS, "Processing...\n"));
602 env->used = pset_new_ptr_default();
604 new_vals = new_workset(env, &env->ob);
605 sched_foreach(block, irn) {
607 assert(workset_get_length(env->ws) <= env->n_regs && "Too much values in workset!");
609 /* projs are handled with the tuple value.
610 * Phis are no real instr (see insert_starters())
611 * instr_nr does not increase */
612 if (is_Proj(irn) || is_Phi(irn)) {
613 DBG((dbg, DBG_DECIDE, " ...%+F skipped\n", irn));
616 DBG((dbg, DBG_DECIDE, " ...%+F\n", irn));
618 /* set instruction in the workset */
621 /* allocate all values _used_ by this instruction */
622 workset_clear(new_vals);
623 for(i = 0, arity = get_irn_arity(irn); i < arity; ++i) {
624 /* (note that reloaded_value is not interesting here) */
625 workset_insert(env, new_vals, get_irn_n(irn, i), 0);
627 displace(env, new_vals, 1);
629 /* allocate all values _defined_ by this instruction */
630 workset_clear(new_vals);
631 if (get_irn_mode(irn) == mode_T) { /* special handling for tuples and projs */
632 const ir_edge_t *edge;
634 foreach_out_edge(irn, edge) {
635 ir_node *proj = get_edge_src_irn(edge);
636 workset_insert(env, new_vals, proj, 0);
639 workset_insert(env, new_vals, irn, 0);
641 displace(env, new_vals, 0);
647 /* Remember end-workset for this block */
648 block_info->ws_end = workset_clone(env, &env->ob, env->ws);
649 block_info->processed = 1;
650 DBG((dbg, DBG_WSETS, "End workset for %+F:\n", block));
651 workset_foreach(block_info->ws_end, irn, iter)
652 DBG((dbg, DBG_WSETS, " %+F (%u)\n", irn, workset_get_time(block_info->ws_end, iter)));
656 * 'decide' is block-local and makes assumptions
657 * about the set of live-ins. Thus we must adapt the
658 * live-outs to the live-ins at each block-border.
660 static void fix_block_borders(ir_node *block, void *data)
662 ir_graph *irg = get_irn_irg(block);
663 ir_node *startblock = get_irg_start_block(irg);
664 belady_env_t *env = data;
665 workset_t *start_workset;
670 if(block == startblock)
673 DBG((dbg, DBG_FIX, "\n"));
674 DBG((dbg, DBG_FIX, "Fixing %+F\n", block));
676 start_workset = get_block_info(block)->ws_start;
678 /* process all pred blocks */
679 arity = get_irn_arity(block);
680 for (i = 0; i < arity; ++i) {
681 ir_node *pred = get_Block_cfgpred_block(block, i);
682 workset_t *workset_pred_end = get_block_info(pred)->ws_end;
685 DBG((dbg, DBG_FIX, " Pred %+F\n", pred));
687 /* spill all values not used anymore */
688 workset_foreach(workset_pred_end, node, iter) {
692 workset_foreach(start_workset, n2, iter2) {
697 /* note that we do not look at phi inputs, becuase the values
698 * will be either live-end and need no spill or
699 * they have other users in which must be somewhere else in the
703 if(!found && be_is_live_out(env->lv, pred, node)
704 && !workset_pred_end->vals[iter].reloaded_value) {
705 ir_node *insert_point
706 = be_get_end_of_block_insertion_point(pred);
707 DBG((dbg, DBG_SPILL, "Spill %+F before %+F\n", node,
709 be_add_spill(env->senv, node, insert_point);
713 /* reload missing values in predecessors */
714 workset_foreach(start_workset, node, iter) {
715 /* if node is a phi of the current block we reload
716 * the corresponding argument, else node itself */
717 if(is_Phi(node) && block == get_nodes_block(node)) {
718 node = get_irn_n(node, i);
720 /* we might have unknowns as argument for the phi */
721 if(!arch_irn_consider_in_reg_alloc(env->arch, env->cls, node))
725 /* check if node is in a register at end of pred */
726 if(workset_contains(workset_pred_end, node))
729 /* node is not in memory at the end of pred -> reload it */
730 DBG((dbg, DBG_FIX, " reload %+F\n", node));
731 DBG((dbg, DBG_SPILL, "Reload %+F before %+F,%d\n", node, block, i));
732 be_add_reload_on_edge(env->senv, node, block, i, env->cls, 1);
738 * Do spilling for a register class on a graph using the belady heuristic.
739 * In the transformed graph, the register pressure never exceeds the number
740 * of available registers.
742 * @param birg The backend graph
743 * @param cls The register class to spill
745 static void be_spill_belady(be_irg_t *birg, const arch_register_class_t *cls) {
746 be_spill_belady_spill_env(birg, cls, NULL);
749 void be_spill_belady_spill_env(be_irg_t *birg, const arch_register_class_t *cls, spill_env_t *spill_env) {
751 ir_graph *irg = be_get_birg_irg(birg);
754 n_regs = cls->n_regs - be_put_ignore_regs(birg, cls, NULL);
755 be_liveness_assure_sets(be_assure_liveness(birg));
757 /* construct control flow loop tree */
758 if(! (get_irg_loopinfo_state(irg) & loopinfo_cf_consistent)) {
759 construct_cf_backedges(irg);
764 /* init belady env */
765 obstack_init(&env.ob);
766 env.arch = birg->main_env->arch_env;
768 env.lv = be_get_birg_liveness(birg);
770 env.ws = new_workset(&env, &env.ob);
771 env.uses = be_begin_uses(irg, env.lv);
772 env.loop_ana = be_new_loop_pressure(birg);
773 if(spill_env == NULL) {
774 env.senv = be_new_spill_env(birg);
776 env.senv = spill_env;
779 /* Decide which phi nodes will be spilled and place copies for them into the graph */
780 irg_block_walk_graph(irg, compute_live_ins, NULL, &env);
781 /* Fix high register pressure with belady algorithm */
782 irg_block_walk_graph(irg, NULL, belady, &env);
783 /* belady was block-local, fix the global flow by adding reloads on the edges */
784 irg_block_walk_graph(irg, fix_block_borders, NULL, &env);
786 be_end_uses(env.uses);
787 be_free_loop_pressure(env.loop_ana);
788 obstack_free(&env.ob, NULL);
790 /* Insert spill/reload nodes into the graph and fix usages */
791 be_insert_spills_reloads(env.senv);
794 if(spill_env == NULL)
795 be_delete_spill_env(env.senv);
798 void be_init_spillbelady(void)
800 static be_spiller_t belady_spiller = {
804 be_register_spiller("belady", &belady_spiller);
805 FIRM_DBG_REGISTER(dbg, "firm.be.spill.belady");
808 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spillbelady);