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 version 2.
23 * @author Sebastian Hack, Matthias Braun, Daniel Grund
27 * The main differences to the original Belady are:
28 * - The workset is empty at the start of a block
29 * There is no attempt to fill it with variables which
30 * are not used in the block.
31 * - There is a global pass which tries to use the remaining
32 * capacity of the blocks to let global variables live through
43 #include "irnodeset.h"
45 #include "irprintf_t.h"
51 #include "iredges_t.h"
52 #include "irphase_t.h"
61 #include "bespillbelady.h"
62 #include "besched_t.h"
66 #include "bechordal_t.h"
67 #include "bespilloptions.h"
68 #include "beloopana.h"
72 #include <libcore/lc_opts.h>
73 #include <libcore/lc_opts_enum.h>
74 #include <libcore/lc_timing.h>
83 #define DBG_WORKSET 128
84 #define DBG_GLOBAL 256
86 #define ALREADY_SPILLED_FACTOR 2
89 #define LIVE_END (DEAD-1)
90 #define REMAT_DIST (DEAD-2)
92 static int already_spilled_factor = 2;
93 static int remat_live_range_ext = 1;
94 static int global_pass_enabled = 1;
96 static const lc_opt_table_entry_t options[] = {
97 LC_OPT_ENT_INT ("asf", "already spilled factor", &already_spilled_factor),
98 LC_OPT_ENT_BOOL ("remat", "rematerializable ops get infinite long live ranges", &remat_live_range_ext),
99 LC_OPT_ENT_BOOL ("global", "enable/disable the global pass", &global_pass_enabled),
103 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
106 * An association between a node and a point in time.
108 typedef struct _loc_t {
109 ir_node *irn; /**< A node. */
110 unsigned time; /**< A use time.
111 In the global pass this is used
112 as the version number and not as a time.
113 Only to save space...
117 typedef struct _workset_t {
118 int len; /**< current length */
119 loc_t vals[0]; /**< inlined array of the values/distances in this working set */
122 typedef struct _belady_env_t {
126 const arch_env_t *arch;
127 const arch_register_class_t *cls;
131 ir_node **blocks; /**< Array of all blocks. */
132 int n_blocks; /**< Number of blocks in the graph. */
133 int n_regs; /**< number of regs in this reg-class */
134 workset_t *ws; /**< the main workset used while processing a block. ob-allocated */
135 ir_node *instr; /**< current instruction */
136 int instr_nr; /**< current instruction number (relative to block start) */
138 spill_env_t *senv; /**< see bespill.h */
139 bitset_t *spilled; /**< bitset to keep all the irns which have already been spilled. */
143 static int loc_compare(const void *a, const void *b)
147 return (p->time > q->time) - (p->time < q->time);
150 static INLINE void workset_print(const workset_t *w)
154 for(i = 0; i < w->len; ++i) {
155 ir_fprintf(stderr, "%+F %d\n", w->vals[i].irn, w->vals[i].time);
160 * Alloc a new workset on obstack @p ob with maximum size @p max
162 static INLINE workset_t *new_workset(belady_env_t *env, struct obstack *ob) {
164 size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
165 res = obstack_alloc(ob, size);
166 memset(res, 0, size);
171 * Alloc a new instance on obstack and make it equal to @param ws
173 static INLINE workset_t *workset_clone(belady_env_t *env, struct obstack *ob, workset_t *ws) {
175 size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
176 res = obstack_alloc(ob, size);
177 memcpy(res, ws, size);
182 * Do NOT alloc anything. Make @param tgt equal to @param src.
183 * returns @param tgt for convenience
185 static INLINE workset_t *workset_copy(belady_env_t *env, workset_t *tgt, workset_t *src) {
186 size_t size = sizeof(*src) + (env->n_regs)*sizeof(src->vals[0]);
187 memcpy(tgt, src, size);
192 * Overwrites the current content array of @param ws with the
193 * @param count locations given at memory @param locs.
194 * Set the length of @param ws to count.
196 static INLINE void workset_bulk_fill(workset_t *workset, int count, const loc_t *locs) {
197 workset->len = count;
198 memcpy(&(workset->vals[0]), locs, count * sizeof(locs[0]));
202 * Inserts the value @p val into the workset, iff it is not
203 * already contained. The workset must not be full.
205 static INLINE void workset_insert(belady_env_t *env, workset_t *ws, ir_node *val) {
207 /* check for current regclass */
208 if (!arch_irn_consider_in_reg_alloc(env->arch, env->cls, val)) {
209 // DBG((dbg, DBG_WORKSET, "Skipped %+F\n", val));
213 /* check if val is already contained */
214 for(i=0; i<ws->len; ++i)
215 if (ws->vals[i].irn == val)
219 assert(ws->len < env->n_regs && "Workset already full!");
220 ws->vals[ws->len++].irn = val;
224 * Removes all entries from this workset
226 static INLINE void workset_clear(workset_t *ws) {
231 * Removes the value @p val from the workset if present.
233 static INLINE void workset_remove(workset_t *ws, ir_node *val) {
235 for(i=0; i<ws->len; ++i) {
236 if (ws->vals[i].irn == val) {
237 ws->vals[i] = ws->vals[--ws->len];
243 static INLINE int workset_get_index(const workset_t *ws, const ir_node *val) {
245 for(i=0; i<ws->len; ++i) {
246 if (ws->vals[i].irn == val)
254 * Iterates over all values in the working set.
255 * @p ws The workset to iterate
256 * @p v A variable to put the current value in
257 * @p i An integer for internal use
259 #define workset_foreach(ws, v, i) for(i=0; \
260 v=(i < ws->len) ? ws->vals[i].irn : NULL, i < ws->len; \
263 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
264 #define workset_get_time(ws, i) (ws)->vals[i].time
265 #define workset_set_length(ws, length) (ws)->len = length
266 #define workset_get_length(ws) ((ws)->len)
267 #define workset_get_val(ws, i) ((ws)->vals[i].irn)
268 #define workset_sort(ws) qsort((ws)->vals, (ws)->len, sizeof((ws)->vals[0]), loc_compare);
269 #define workset_contains(ws, n) (workset_get_index(ws, n) >= 0)
271 typedef struct _bring_in_t bring_in_t;
273 typedef struct _block_info_t {
278 workset_t *ws_end; /**< The end set after the local belady pass. */
279 double exec_freq; /**< The execution frequency of this block. */
281 double reload_cost; /**< Cost of a reload in this block. */
282 ir_node *first_non_in; /**< First node in block which is not a phi. */
283 ir_node *last_ins; /**< The instruction before which end of
284 block reloads will be inserted. */
286 int pressure; /**< The amount of registers which remain free
287 in this block. This capacity can be used to let
288 global variables, transported into other blocks,
289 live through this block. */
291 int front_pressure; /**< The pressure right before the first
292 real (non-phi) node. At the beginning
293 of the global pass, this is 0. */
294 struct list_head br_head; /**< List head for all bring_in variables. */
298 static INLINE void *new_block_info(belady_env_t *bel, int id)
300 ir_node *bl = bel->blocks[id];
301 block_info_t *res = obstack_alloc(&bel->ob, sizeof(*res));
302 memset(res, 0, sizeof(res[0]));
303 res->first_non_in = NULL;
304 res->last_ins = NULL;
308 res->exec_freq = get_block_execfreq(bel->ef, bl);
309 res->reload_cost = bel->arch->isa->reload_cost * res->exec_freq;
310 INIT_LIST_HEAD(&res->br_head);
311 set_irn_link(bl, res);
315 #define get_block_info(block) ((block_info_t *)get_irn_link(block))
316 #define set_block_info(block, info) set_irn_link(block, info)
318 static INLINE ir_node *block_info_get_last_ins(block_info_t *bi)
321 bi->last_ins = be_get_end_of_block_insertion_point(bi->bl);
326 typedef struct _next_use_t {
327 unsigned is_first_use : 1; /**< Indicate that this use is the first
328 in the block. Needed to identify
329 transport in values for the global
331 sched_timestep_t step; /**< The time step of the use. */
333 struct _next_use_t *next; /**< The next use int this block
337 static void *next_use_init(ir_phase *phase, ir_node *irn, void *old)
345 static void build_next_uses(block_info_t *bi)
349 sched_renumber(bi->bl);
351 phase_init(&bi->next_uses, "next uses", bi->bel->irg, PHASE_DEFAULT_GROWTH, next_use_init, NULL);
352 sched_foreach_reverse(bi->bl, irn) {
358 for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
359 ir_node *op = get_irn_n(irn, i);
360 next_use_t *curr = phase_get_irn_data(&bi->next_uses, op);
361 next_use_t *use = phase_alloc(&bi->next_uses, sizeof(use[0]));
363 use->is_first_use = 1;
364 use->step = sched_get_time_step(irn);
369 curr->is_first_use = 0;
370 assert(curr->step >= use->step);
373 phase_set_irn_data(&bi->next_uses, op, use);
378 #define get_current_use(bi, irn) phase_get_irn_data(&(bi)->next_uses, (irn))
380 static INLINE void advance_current_use(block_info_t *bi, const ir_node *irn)
382 next_use_t *use = get_current_use(bi, irn);
385 phase_set_irn_data(&bi->next_uses, irn, use->next);
388 static __attribute__((unused)) int block_freq_gt(const void *a, const void *b)
390 const ir_node * const *p = a;
391 const ir_node * const *q = b;
392 block_info_t *pi = get_block_info(*p);
393 block_info_t *qi = get_block_info(*q);
394 double diff = qi->exec_freq - pi->exec_freq;
395 return (diff > 0) - (diff < 0);
398 static int block_freq_dfs_gt(const void *a, const void *b)
400 const ir_node * const *p = a;
401 const ir_node * const *q = b;
402 block_info_t *pi = get_block_info(*p);
403 block_info_t *qi = get_block_info(*q);
406 if ((pi->exec_freq > 1.0 && qi->exec_freq > 1.0)
407 || (pi->exec_freq <= 1.0 && qi->exec_freq <= 1.0)) {
409 const dfs_t *dfs = pi->bel->dfs;
410 int pp = dfs_get_post_num(dfs, pi->bl);
411 int pq = dfs_get_post_num(dfs, qi->bl);
415 diff = qi->exec_freq - pi->exec_freq;
416 return (diff > 0) - (diff < 0);
421 | __ ) _ __(_)_ __ __ _ |_ _|_ __
422 | _ \| '__| | '_ \ / _` | | || '_ \
423 | |_) | | | | | | | (_| | | || | | |
424 |____/|_| |_|_| |_|\__, | |___|_| |_|
427 Data structures to represent bring in variables.
431 ir_node *irn; /**< The node to bring in. */
432 block_info_t *bi; /**< The block to which bring in should happen. */
433 int pressure_so_far; /**< The maximal pressure till the first use of irn in bl. */
434 ir_node *first_use; /**< The first user of irn in bl. */
435 sched_timestep_t use_step; /**< Schedule sttep of the first use. */
437 int is_remat : 1; /**< Is rematerializable. */
438 int sect_pressure; /**< Offset to maximum pressure in block. */
439 struct list_head list;
442 static INLINE bring_in_t *new_bring_in(block_info_t *bi, ir_node *irn, const next_use_t *use)
444 bring_in_t *br = obstack_alloc(&bi->bel->ob, sizeof(br[0]));
448 br->first_use = use->irn;
449 br->use_step = use->step;
450 br->is_remat = be_is_rematerializable(bi->bel->senv, irn, use->irn);
451 br->pressure_so_far = bi->pressure;
452 br->sect_pressure = bi->front_pressure;
454 INIT_LIST_HEAD(&br->list);
455 list_add_tail(&br->list, &bi->br_head);
459 static int bring_in_cmp(const void *a, const void *b)
461 const bring_in_t *p = *(const bring_in_t * const *) a;
462 const bring_in_t *q = *(const bring_in_t * const *) b;
465 /* if one of both is a remat node, it will be done after the other. */
466 if (p->is_remat != q->is_remat)
467 return p->is_remat - q->is_remat;
469 /* in the same block, the one further in the front has to be processed first!
470 * Otherwise the front_pressure 'trick' is not exact. */
472 return p->use_step - q->use_step;
474 fp = p->bi->exec_freq;
475 fq = q->bi->exec_freq;
477 /* if both have the same frequency, inspect the frequency of the definition */
479 double fdp = get_block_info(get_nodes_block(p->irn))->exec_freq;
480 double fdq = get_block_info(get_nodes_block(q->irn))->exec_freq;
482 /* if the defs of both have the same freq, we go for reverse dfs post order. */
484 const dfs_t *dfs = p->bi->bel->dfs;
485 int pp = dfs_get_post_num(dfs, p->bi->bl);
486 int pq = dfs_get_post_num(dfs, q->bi->bl);
490 return (fdq > fdp) - (fdq < fdp);
493 return (fq > fp) - (fq < fp);
496 static INLINE unsigned get_curr_distance(block_info_t *bi, const ir_node *irn, int is_usage)
498 belady_env_t *env = bi->bel;
499 sched_timestep_t curr_step = sched_get_time_step(env->instr);
500 next_use_t *use = get_current_use(bi, irn);
501 int flags = arch_irn_get_flags(env->arch, irn);
503 assert(!(flags & arch_irn_flags_ignore));
505 /* We have to keep nonspillable nodes in the workingset */
506 if(flags & arch_irn_flags_dont_spill)
509 if (!is_usage && use && use->step == curr_step)
513 unsigned res = use->step - curr_step;
515 assert(use->step >= curr_step);
518 if (remat_live_range_ext && be_is_rematerializable(env->senv, irn, use->irn))
520 else if (bitset_contains_irn(env->spilled, irn))
521 res *= already_spilled_factor;
527 return be_is_live_end(env->lv, bi->bl, irn) ? LIVE_END : DEAD;
530 static INLINE int is_local_phi(const ir_node *bl, const ir_node *irn)
532 return is_Phi(irn) && get_nodes_block(irn) == bl;
536 * Check, if the value is something that is transported into a block.
537 * That is, the value is defined elsewhere or defined by a Phi in the block.
538 * @param env The belady environment.
539 * @param bl The block in question.
540 * @param irn The node in question.
541 * @return 1, if node is something transported into @p bl, 0 if not.
542 * @note The function will only give correct answers in the case
543 * where @p irn is unsed in the block @p bl which is always
544 * the case in our usage scenario.
546 static INLINE int is_transport_in(const ir_node *bl, const ir_node *irn)
548 return get_nodes_block(irn) != bl || is_Phi(irn);
552 * Performs the actions necessary to grant the request that:
553 * - new_vals can be held in registers
554 * - as few as possible other values are disposed
555 * - the worst values get disposed
557 * @p is_usage indicates that the values in new_vals are used (not defined)
558 * In this case reloads must be performed
560 static void displace(block_info_t *bi, workset_t *new_vals, int is_usage) {
561 belady_env_t *env = bi->bel;
562 workset_t *ws = env->ws;
563 ir_node **to_insert = alloca(env->n_regs * sizeof(to_insert[0]));
565 int i, len, max_allowed, demand, iter;
569 1. Identify the number of needed slots and the values to reload
572 workset_foreach(new_vals, val, iter) {
573 /* mark value as used */
575 if (! workset_contains(ws, val)) {
576 DBG((dbg, DBG_DECIDE, "\t\tinsert %+F\n", val));
577 to_insert[demand++] = val;
579 next_use_t *use = get_current_use(bi, val);
582 * if we use a value which is transported in this block, i.e. a
583 * phi defined here or a live in, for the first time, we check
584 * if there is room for that guy to survive from the block's
585 * entrance to here or not.
588 assert(sched_get_time_step(env->instr) == (int) use->step);
589 if (is_transport_in(bi->bl, val) && use->is_first_use) {
590 bring_in_t *bri = new_bring_in(bi, val, use);
591 bri->first_use = env->instr;
593 /* reset the section pressure, since a new section starts. */
594 bi->front_pressure = 0;
596 DBG((dbg, DBG_DECIDE, "\t\tbring in node %+F, pressure %d:\n", val, bi->pressure));
597 DBG((dbg, DBG_DECIDE, "\t\tno reload. must be considered at block start\n"));
601 bitset_add_irn(env->spilled, val);
602 DBG((dbg, DBG_SPILL, "\t\tReload %+F before %+F\n", val, env->instr));
603 be_add_reload(env->senv, val, env->instr, env->cls, 1);
607 assert(is_usage || "Defined value already in workset?!?");
608 DBG((dbg, DBG_DECIDE, "\t\tskip %+F\n", val));
611 DBG((dbg, DBG_DECIDE, "\t\tdemand = %d\n", demand));
614 2. Make room for at least 'demand' slots
616 len = workset_get_length(ws);
617 max_allowed = env->n_regs - demand;
619 /* Only make more free room if we do not have enough */
620 if (len > max_allowed) {
621 DBG((dbg, DBG_DECIDE, "\t\tdisposing %d values\n", len - max_allowed));
623 /* get current next-use distance */
624 for (i = 0; i < ws->len; ++i) {
625 ir_node *val = workset_get_val(ws, i);
626 unsigned dist = get_curr_distance(bi, val, is_usage);
627 workset_set_time(ws, i, dist);
630 /* sort entries by increasing nextuse-distance*/
633 /* kill the last 'demand' entries in the array */
634 workset_set_length(ws, max_allowed);
638 3. Insert the new values into the workset
639 Also, we update the pressure in the block info.
640 That is important for the global pass to decide
641 how many values can live through the block.
643 for (i = 0; i < demand; ++i)
644 workset_insert(env, env->ws, to_insert[i]);
646 /* TODO: simplify this expression? */
647 bi->pressure = MAX(bi->pressure, workset_get_length(env->ws));
648 bi->front_pressure = MAX(bi->front_pressure, workset_get_length(env->ws));
652 * For the given block @p block, decide for each values
653 * whether it is used from a register or is reloaded
656 static void belady(belady_env_t *env, int id) {
657 block_info_t *block_info = new_block_info(env, id);
658 const ir_node *block = block_info->bl;
664 DBG((dbg, DBG_WSETS, "Belady on %+F\n", block_info->bl));
665 new_vals = new_workset(env, &env->ob);
666 workset_clear(env->ws);
668 /* build the next use information for this block. */
669 build_next_uses(block_info);
672 block_info->first_non_in = NULL;
674 /* process the block from start to end */
675 sched_foreach(block, irn) {
677 assert(workset_get_length(env->ws) <= env->n_regs && "Too much values in workset!");
679 /* projs are handled with the tuple value.
680 * Phis are no real instr (see insert_starters())
681 * instr_nr does not increase */
682 if (is_Proj(irn) || is_Phi(irn))
684 DBG((dbg, DBG_DECIDE, "\t%+F\n", irn));
686 if (!block_info->first_non_in)
687 block_info->first_non_in = irn;
689 /* set instruction in the workset */
692 /* allocate all values _used_ by this instruction */
693 workset_clear(new_vals);
694 for(i = 0, arity = get_irn_arity(irn); i < arity; ++i) {
695 workset_insert(env, new_vals, get_irn_n(irn, i));
697 DBG((dbg, DBG_DECIDE, "\t* uses\n"));
698 displace(block_info, new_vals, 1);
701 * set all used variables to the next use in their next_use_t list
702 * Also, kill all dead variables from the workset. They are only
703 * augmenting the pressure. Note, that a variable is dead
704 * if it has no further use in this block and is *not* live end
706 for(i = 0, arity = get_irn_arity(irn); i < arity; ++i) {
707 ir_node *op = get_irn_n(irn, i);
708 next_use_t *use = get_current_use(block_info, op);
711 if (!use->next && !be_is_live_end(env->lv, block, op))
712 workset_remove(env->ws, op);
714 advance_current_use(block_info, op);
717 /* allocate all values _defined_ by this instruction */
718 workset_clear(new_vals);
719 if (get_irn_mode(irn) == mode_T) { /* special handling for tuples and projs */
720 const ir_edge_t *edge;
722 foreach_out_edge(irn, edge) {
723 ir_node *proj = get_edge_src_irn(edge);
724 workset_insert(env, new_vals, proj);
727 workset_insert(env, new_vals, irn);
729 DBG((dbg, DBG_DECIDE, "\t* defs\n"));
730 displace(block_info, new_vals, 0);
735 phase_free(&block_info->next_uses);
737 /* Remember end-workset for this block */
738 block_info->ws_end = workset_clone(env, &env->ob, env->ws);
739 DBG((dbg, DBG_WSETS, "End workset for %+F:\n", block));
740 workset_foreach(block_info->ws_end, irn, iter)
741 DBG((dbg, DBG_WSETS, " %+F (%u)\n", irn, workset_get_time(block_info->ws_end, iter)));
742 DBG((dbg, DBG_WSETS, "Max pressure in block: %d\n", block_info->pressure));
744 /* now, initialize the front pressure to 0. */
745 block_info->front_pressure = 0;
750 |_ _| |__ ___ __ _| | ___ | |__ __ _| | | _ \ __ _ _ __| |_
751 | | | '_ \ / _ \ / _` | |/ _ \| '_ \ / _` | | | |_) / _` | '__| __|
752 | | | | | | __/ | (_| | | (_) | |_) | (_| | | | __/ (_| | | | |_
753 |_| |_| |_|\___| \__, |_|\___/|_.__/ \__,_|_| |_| \__,_|_| \__|
758 #define workset_set_version(ws, i, t) ((ws)->vals[(i)].time = (t))
759 #define workset_get_version(ws, i) ((ws)->vals[(i)].time)
761 #define ver_oldest (0)
762 #define ver_youngest ((unsigned) -1)
763 #define ver_make_newer(v) ((v) + 1)
764 #define ver_is_older(v, w) ((v) < (w))
765 #define ver_is_younger(v, w) ((v) > (w))
773 typedef struct _block_state_t {
774 struct _block_state_t *next;
775 struct _block_state_t *next_intern;
778 workset_t *end_state;
781 typedef struct _irn_action_t {
782 struct _irn_action_t *next;
788 typedef struct _global_end_state_t {
796 unsigned *bs_tops_vers;
797 block_state_t **bs_tops;
798 block_state_t *bs_top;
799 irn_action_t *ia_top;
800 } global_end_state_t;
804 block_state_t *bs_top;
805 irn_action_t *ia_top;
808 static INLINE block_state_t *get_block_state(global_end_state_t *ges, const block_info_t *bi)
811 assert(!ver_is_younger(ges->bs_tops_vers[id], ges->version));
812 return ver_is_older(ges->bs_tops_vers[id], ges->version) ? NULL : ges->bs_tops[bi->id];
815 static INLINE const workset_t *get_end_state(global_end_state_t *ges, block_info_t *bi)
817 block_state_t *bs = get_block_state(ges, bi);
818 return bs ? bs->end_state : bi->ws_end;
821 static block_state_t *new_block_state(global_end_state_t *ges, block_info_t *bi)
823 block_state_t *bs = get_block_state(ges, bi);
824 block_state_t *nw = obstack_alloc(&ges->obst, sizeof(nw[0]));
826 nw->next_intern = bs;
827 nw->next = ges->bs_top;
831 nw->pressure = bs->pressure;
832 nw->end_state = workset_clone(ges->env, &ges->obst, bs->end_state);
835 nw->pressure = bi->pressure;
836 nw->end_state = workset_clone(ges->env, &ges->obst, bi->ws_end);
840 ges->bs_tops[bi->id] = nw;
841 ges->bs_tops_vers[bi->id] = ges->version;
845 static irn_action_t *new_irn_action(global_end_state_t *ges, ir_node *irn, const ir_node *bl)
847 irn_action_t *ia = obstack_alloc(&ges->obst, sizeof(ia[0]));
851 ia->act = irn_act_none;
852 ia->next = ges->ia_top;
857 static INLINE rollback_info_t trans_begin(global_end_state_t *ges)
860 rb.obst_level = obstack_base(&ges->obst);
861 rb.bs_top = ges->bs_top;
862 rb.ia_top = ges->ia_top;
866 static INLINE void trans_rollback(global_end_state_t *ges, rollback_info_t *rb)
870 /* unwind all the stacks indiced with the block number */
871 for (bs = ges->bs_top; bs != rb->bs_top; bs = bs->next) {
872 unsigned id = bs->bi->id;
873 ges->bs_tops[id] = bs->next_intern;
876 ges->ia_top = rb->ia_top;
877 ges->bs_top = rb->bs_top;
878 obstack_free(&ges->obst, rb->obst_level);
882 static double can_bring_in(global_end_state_t *ges, ir_node *bl, ir_node *irn, double limit, int level);
884 static double can_make_available_at_end(global_end_state_t *ges, ir_node *bl, ir_node *irn, double limit, int level)
886 block_info_t *bi = get_block_info(bl);
887 const workset_t *end = get_end_state(ges, bi);
891 DBG((dbg, DBG_GLOBAL, "\t%2Dcan make avail %+F at end of %+F\n", level, irn, bl));
894 * to make the value available at end,
895 * we have several cases here.
897 * - we already visited that block.
898 * - If the value is in the final end set, return 0.
899 * somebody else already allocated it there.
900 * - If not and the final end set is already full,
901 * we cannot make the value available at the end
902 * of this block. return INFINITY.
903 * - Else (value not in final end set and there is room):
904 * 1) The value is in a register at the end of the local Belady pass.
905 * Allocate a slot in the final end set and return 0.
906 * 2) The value is not in the Belady end set:
907 * If the block's capacity is < k then check what it costs
908 * to transport the value from upper blocks to this block.
909 * Compare that against the reload cost in this block. If
910 * cheaper, do the other thing. If not, reload it here.
913 /* if the end set contains it already, it is in a reg and it costs nothing
914 * to load it to one. */
915 index = workset_get_index(end, irn);
917 unsigned ver = workset_get_version(end, index);
918 DBG((dbg, DBG_GLOBAL, "\t%2Dnode is in the end set and is %s fixed\n",
919 level, ver_is_older(ver, ges->version) ? "already" : "not yet"));
922 * if the version is older, the value is already fixed
923 * and cannot be removed from the end set.
925 * If not, we will create a new block state for that block since
926 * we modify it by giving the end state a new version.
928 if (ver_is_younger(ver, ges->version)) {
929 block_state_t *bs = new_block_state(ges, bi);
930 workset_set_version(bs->end_state, index, ges->version);
938 * Now we have two options:
939 * 1) Reload the value at the end of the block.
940 * Therefore, perhaps, we have to erase another one from the workset.
941 * This may only be done if it has not been fixed.
942 * Since fixed means that a previous pass has decided that that value
943 * *has* to stay in the end set.
944 * 2) we can try, if the capacity of the block allows it, to let
945 * the value live through the block and make it available at
948 * First, we test the local (reload in this block) alternative
949 * and compare against the other alternative.
950 * Of course, we chose the cheaper one.
954 int n_regs = bi->bel->n_regs;
955 int len = workset_get_length(end);
962 * look if there is room in the end array
963 * for the variable. Note that this does not
964 * mean that the var can live through the block.
965 * There is just room at the *end*
968 DBG((dbg, DBG_GLOBAL, "\t%2Dthe end set has %d free slots\n", level, n_regs - len));
971 for (i = 0; i < len; ++i) {
972 unsigned ver = workset_get_version(end, i);
973 if (ver_is_younger(ver, ges->version))
978 DBG((dbg, DBG_GLOBAL, "\t%2D%+F (slot %d) can be erased from the end set\n",
979 level, end->vals[i].irn, i));
985 * finally there is some room. we can at least reload the value.
986 * but we will try to let ot live through anyhow.
989 irn_action_t *vs = new_irn_action(ges, irn, bi->bl);
990 block_state_t *bs = new_block_state(ges, bi);
991 workset_t *end = bs->end_state;
992 ir_node *ins_before = block_info_get_last_ins(bi);
993 double reload_here = be_get_reload_costs(bi->bel->senv, irn, ins_before);
994 int pressure_ok = bs->pressure < n_regs;
996 if (reload_here < bi->reload_cost)
1000 * No matter what we do, the value will be in the end set
1001 * if the block from now on (of course only regarding the
1002 * current state). Enter it and set the new length
1005 end->vals[slot].irn = irn;
1006 workset_set_version(end, slot, ges->version);
1007 workset_set_length(end, MAX(workset_get_length(end), slot + 1));
1009 vs->act = irn_act_reload;
1012 DBG((dbg, DBG_GLOBAL, "\t%2Dthere is a free slot. capacity=%d, reload here=%f, pressure %s\n",
1013 level, n_regs - bs->pressure, reload_here, pressure_ok ? "ok" : "insufficient"));
1016 /* look if we can bring the value in. */
1017 if (pressure_ok && reload_here > 0.0) {
1018 rollback_info_t rb = trans_begin(ges);
1019 double new_limit = MIN(reload_here, limit);
1021 vs->act = irn_act_live_through;
1023 res = can_bring_in(ges, bl, irn, new_limit, level + 1);
1026 * if bring in is too expensive re-adjust the pressure
1027 * and roll back the state
1029 if (res >= reload_here) {
1031 vs->act = irn_act_reload;
1032 trans_rollback(ges, &rb);
1038 DBG((dbg, DBG_GLOBAL, "\t%2D%s\n", level,
1039 vs->act == irn_act_reload ? "reloading" : "bringing in"));
1044 DBG((dbg, DBG_GLOBAL, "\t%2D-> %f\n", level, res));
1048 static double can_bring_in(global_end_state_t *ges, ir_node *bl, ir_node *irn, double limit, int level)
1050 belady_env_t *env = ges->env;
1051 double glob_costs = HUGE_VAL;
1053 DBG((dbg, DBG_GLOBAL, "\t%2Dcan bring in (max %f) for %+F at block %+F\n", level, limit, irn, bl));
1055 if (is_transport_in(bl, irn)) {
1056 int i, n = get_irn_arity(bl);
1057 ir_node **nodes = alloca(get_irn_arity(bl) * sizeof(nodes[0]));
1058 rollback_info_t rb = trans_begin(ges);
1061 for (i = 0; i < n; ++i) {
1062 ir_node *pr = get_Block_cfgpred_block(bl, i);
1063 ir_node *op = is_local_phi(bl, irn) ? get_irn_n(irn, i) : irn;
1067 * there might by unknwons as operands of phis in that case
1068 * we set the costs to zero, since they won't get spilled.
1070 if (arch_irn_consider_in_reg_alloc(env->arch, env->cls, op))
1071 c = can_make_available_at_end(ges, pr, op, limit - glob_costs, level + 1);
1077 if (glob_costs >= limit) {
1078 glob_costs = HUGE_VAL;
1079 trans_rollback(ges, &rb);
1086 DBG((dbg, DBG_GLOBAL, "\t%2D-> %f\n", level, glob_costs));
1090 static void materialize_and_commit_end_state(global_end_state_t *ges)
1092 belady_env_t *env = ges->env;
1096 DBG((dbg, DBG_GLOBAL, "\tmaterializing\n"));
1099 * Perform all the variable actions.
1101 for (ia = ges->ia_top; ia != NULL; ia = ia->next) {
1103 case irn_act_live_through:
1104 if (is_local_phi(ia->bl, ia->irn)) {
1105 bitset_add_irn(ges->succ_phis, ia->irn);
1106 DBG((dbg, DBG_GLOBAL, "\t\tlive through phi kept alive: %+F\n", ia->irn));
1109 case irn_act_reload:
1110 be_add_reload_at_end(env->senv, ia->irn, ia->bl, env->cls, 1);
1111 DBG((dbg, DBG_GLOBAL, "\t\tadding reload of %+F at end of %+F\n", ia->irn, ia->bl));
1114 DBG((dbg, DBG_GLOBAL, "\t\t%+F is in the end set of %+F\n", ia->irn, ia->bl));
1119 * Commit the block end states
1121 for (bs = ges->bs_top; bs != NULL; bs = bs->next) {
1122 block_info_t *bi = bs->bi;
1124 if (!bitset_is_set(ges->committed, bi->id)) {
1125 DBG((dbg, DBG_GLOBAL, "\t\tcommiting workset of %+F with version %x\n", bi->bl, ges->version));
1126 // bes->bs->end_state->vals[idx].version = ges->version;
1127 workset_copy(env, bi->ws_end, bs->end_state);
1128 DBG((dbg, DBG_GLOBAL, "\t\told pressure: %d, new pressure: %d, end length: %d\n",
1129 bi->pressure, bs->pressure, workset_get_length(bs->end_state)));
1130 bi->pressure = bs->pressure;
1131 /* TODO: commit front pressure */
1132 bitset_set(ges->committed, bi->id);
1136 /* clear the committed bitset. the next call is expecting it. */
1137 bitset_clear_all(ges->committed);
1140 static ir_node *better_spilled_here(const bring_in_t *br)
1142 const block_info_t *bi = br->bi;
1143 double spill_ef = get_block_info(get_nodes_block(br->irn))->exec_freq;
1146 * If the bring in node is a phi in the bring in block,
1147 * we look at all definitions and sum up their execution frequencies,
1148 * since spills will be placed there.
1149 * (except for the case where an operand is also a phi which is spilled :-( )
1150 * If that cost is higher than spilling the phi in that block, we opt for
1151 * bringing the phi into the block and spill it there.
1153 if (is_local_phi(bi->bl, br->irn)) {
1154 ir_node *bl = bi->bl;
1158 for (i = get_Block_n_cfgpreds(bl) - 1; i >= 0; --i)
1159 spill_ef += get_block_info(get_Block_cfgpred_block(bl, i))->exec_freq;
1162 return bi->exec_freq < spill_ef ? sched_prev(bi->first_non_in) : NULL;
1165 static int get_max_pressure_so_far(const block_info_t *bi, const bring_in_t *br)
1167 const struct list_head *l;
1170 assert(br->bi == bi);
1171 for (l = &br->list; l != &bi->br_head; l = l->prev) {
1172 br = list_entry(l, bring_in_t, list);
1173 res = MAX(res, br->sect_pressure);
1176 /* finally consider the front pressure distance and add the reference line (the global block pressure) */
1177 return MAX(res, bi->front_pressure);
1180 #define block_last_bring_in(bi) list_entry((bi)->br_head.prev, bring_in_t, list)
1182 static int get_block_max_pressure(const block_info_t *bi)
1184 int max = get_max_pressure_so_far(bi, block_last_bring_in(bi));
1185 return MAX(bi->pressure, max);
1189 * Try to bring a variable into a block.
1190 * @param ges The state of all end sets.
1191 * @param block The block.
1192 * @param irn The variable.
1194 static void optimize_variable(global_end_state_t *ges, bring_in_t *br)
1196 block_info_t *bi = br->bi;
1197 ir_node *irn = br->irn;
1198 ir_node *bl = bi->bl;
1199 belady_env_t *env = ges->env;
1200 void *reset_level = obstack_base(&ges->obst);
1201 int k = env->n_regs;
1202 int pressure_upto_use = get_max_pressure_so_far(bi, br);
1203 int front_pressure = bi->front_pressure;
1204 ir_node *better_spill_loc = NULL;
1206 assert(front_pressure <= k);
1207 assert(pressure_upto_use <= k);
1209 DBG((dbg, DBG_GLOBAL, "fixing %+F at %+F (%f), front pr: %d, pr to use: %d, first use: %u\n",
1210 irn, bl, bi->exec_freq, front_pressure, pressure_upto_use, br->first_use));
1213 * if we cannot bring the value to the use, let's see ifit would be worthwhile
1214 * to bring the value to the beginning of the block to have a better spill
1217 * better _spilled_here will return a node where the value can be spilled after
1218 * or NULL if this block does not provide a better spill location.
1220 if (pressure_upto_use >= k && front_pressure < k)
1221 better_spill_loc = better_spilled_here(br);
1224 * If either we can bring the value to the use or we should try
1225 * to bring it here to do the spill here, let's try to bring it in.
1227 if (better_spill_loc || pressure_upto_use < k) {
1229 double bring_in_costs, local_costs;
1230 rollback_info_t trans;
1233 /* process all variables which shall be in a reg at
1234 * the beginning of the block in the order of the next use. */
1235 local_costs = be_get_reload_costs(env->senv, irn, br->first_use);
1237 /* reset the lists */
1241 /* if the variable will live into this block, we must adapt the pressure.
1242 * The new pressure is the MAX of:
1243 * 1) the total block pressure
1244 * 2) the pressure so far + the front pressure increase + 1
1246 * If the second is larger than the first,
1247 * we have to increment the total block pressure and hence
1248 * save the old pressure to restire it in case of failing to
1249 * bring the variable into the block in a register.
1251 trans = trans_begin(ges);
1252 bs = new_block_state(ges, bi);
1253 pressure_inc = MAX(bs->pressure, better_spill_loc ? front_pressure : pressure_upto_use + 1);
1254 bs->pressure = pressure_inc;
1257 assert(bi->pressure <= k);
1258 DBG((dbg, DBG_GLOBAL, "\ttrans in var %+F, version %x\n", irn, ges->version));
1259 bring_in_costs = can_bring_in(ges, bl, irn, local_costs, 1);
1260 DBG((dbg, DBG_GLOBAL, "\tbring in: %f, local: %f\n", bring_in_costs, local_costs));
1263 * Following cases can now occur:
1264 * 1) There is room and costs ok
1265 * 2) Cannot bring to use but can spill at begin and costs are ok
1266 * 3) neither of both worked.
1268 * following actions can be taken:
1270 * b) mark phi as succeded if node was phi
1271 * c) insert reload at use location
1272 * d) give a spill location hint
1274 * this is the case/action matrix
1282 /* the costs were acceptable... */
1283 if (bring_in_costs < local_costs) {
1287 * case 1 and first part of case 2:
1288 * commit all the changes done. this manifests the bring-in action.
1289 * if the transport-in was a phi (that is actually used in block)
1290 * mark it in the succ_phis set to *not* phi spill it.
1292 materialize_and_commit_end_state(ges);
1293 if (is_local_phi(bl, irn))
1294 bitset_add_irn(ges->succ_phis, irn);
1296 pressure_inc = bi->pressure - pressure_inc;
1297 assert(pressure_inc >= 0);
1299 DBG((dbg, DBG_GLOBAL, "\t-> bring it in\n"));
1301 /* second half of case 2 */
1302 if (pressure_upto_use >= k) {
1303 DBG((dbg, DBG_GLOBAL, "\t-> use blocked. local reload: %+F, try spill at: %+F\n",
1304 br->first_use, better_spill_loc));
1305 be_add_reload2(env->senv, irn, br->first_use, better_spill_loc, env->cls, 1);
1309 * go from the last bring in use to the first and add all the variabled
1310 * which additionally live through the block to their pressure.
1311 * at the point were the actually treated use is, we have to increase
1312 * the pressure by one more as the nrought in value starts to count.
1313 * Finally, adjust the front pressure as well.
1315 list_for_each_entry_reverse(bring_in_t, iter, &bi->br_head, list) {
1317 pressure_inc += pressure_upto_use < k;
1318 iter->sect_pressure += pressure_inc;
1320 bi->front_pressure += pressure_inc;
1323 /* case 3: nothing worked. insert normal reload and rollback. */
1325 DBG((dbg, DBG_GLOBAL, "\t-> bring in was too expensive. local reload: %+F\n", br->first_use));
1326 be_add_reload(env->senv, irn, br->first_use, env->cls, 1);
1327 trans_rollback(ges, &trans);
1331 /* there was no opportunity for optimization at all. reload and be sad ... */
1333 DBG((dbg, DBG_GLOBAL, "\t-> can\'t do anything but reload before %+F\n", br->first_use));
1334 be_add_reload(env->senv, irn, br->first_use, env->cls, 1);
1337 DBG((dbg, DBG_GLOBAL, "\n"));
1339 /* reset the obstack and create a new version. */
1340 obstack_free(&ges->obst, reset_level);
1341 ges->version = ver_make_newer(ges->version);
1344 static bring_in_t **determine_global_order(belady_env_t *env)
1350 for (i = env->n_blocks - 1; i >= 0; --i) {
1351 block_info_t *bi = get_block_info(env->blocks[i]);
1352 list_for_each_entry(bring_in_t, elm, &bi->br_head, list) {
1353 obstack_ptr_grow(&env->ob, elm);
1358 obstack_ptr_grow(&env->ob, NULL);
1359 res = obstack_finish(&env->ob);
1360 qsort(res, n, sizeof(res[0]), bring_in_cmp);
1364 static void global_assign(belady_env_t *env)
1366 global_end_state_t ges;
1371 * sort the blocks according to execution frequency.
1372 * That's not necessary for belady() but for the global pass later on.
1374 qsort(env->blocks, env->n_blocks, sizeof(env->blocks[0]), block_freq_dfs_gt);
1376 memset(&ges, 0, sizeof(ges));
1377 obstack_init(&ges.obst);
1379 ges.version = ver_make_newer(ver_oldest);
1380 ges.succ_phis = bitset_irg_obstack_alloc(&ges.obst, env->irg);
1381 ges.committed = bitset_obstack_alloc(&ges.obst, env->n_blocks);
1382 ges.bs_tops = obstack_alloc(&ges.obst, sizeof(ges.bs_tops[0]) * env->n_blocks);
1383 ges.bs_tops_vers = obstack_alloc(&ges.obst, sizeof(ges.bs_tops_vers[0]) * env->n_blocks);
1385 /* invalidate all state stack pointer versions */
1386 for (i = 0; i < env->n_blocks; ++i) {
1387 block_info_t *bi = get_block_info(env->blocks[i]);
1388 ges.bs_tops_vers[i] = ver_oldest;
1390 /* Set all block end sets entries to the youngest version */
1391 for (j = workset_get_length(bi->ws_end) - 1; j >= 0; --j)
1392 workset_set_version(bi->ws_end, j, ver_youngest);
1395 /* determine ordeer and optimize them */
1396 for (br = determine_global_order(env); *br; ++br)
1397 optimize_variable(&ges, *br);
1400 * Now we spill phis which cannot be kept since they were replaced
1401 * by reloads at the block entrances.
1403 for (i = 0; i < env->n_blocks; ++i) {
1404 ir_node *bl = env->blocks[i];
1407 sched_foreach(bl, irn) {
1411 if (arch_irn_consider_in_reg_alloc(env->arch, env->cls, irn)
1412 && !bitset_contains_irn(ges.succ_phis, irn))
1413 be_spill_phi(env->senv, irn);
1418 static void collect_blocks(ir_node *bl, void *data)
1420 belady_env_t *env = data;
1422 obstack_ptr_grow(&env->ob, bl);
1426 * Do spilling for a register class on a graph using the belady heuristic.
1427 * In the transformed graph, the register pressure never exceeds the number
1428 * of available registers.
1430 * @param birg The backend graph
1431 * @param cls The register class to spill
1433 void be_spill_belady(be_irg_t *birg, const arch_register_class_t *cls)
1435 ir_graph *irg = be_get_birg_irg(birg);
1439 /* some special classes contain only ignore regs, nothing to do then */
1440 n_regs = cls->n_regs - be_put_ignore_regs(birg, cls, NULL);
1444 be_clear_links(irg);
1446 /* init belady env */
1447 obstack_init(&env.ob);
1449 env.arch = be_get_birg_arch_env(birg);
1451 env.lv = be_get_birg_liveness(birg);
1452 env.dfs = env.lv->dfs;
1453 env.n_regs = n_regs;
1454 env.ws = new_workset(&env, &env.ob);
1455 env.senv = be_new_spill_env(birg);
1456 env.ef = be_get_birg_exec_freq(birg);
1457 env.spilled = bitset_irg_obstack_alloc(&env.ob, irg);
1460 irg_block_walk_graph(irg, NULL, collect_blocks, &env);
1461 obstack_ptr_grow(&env.ob, NULL);
1462 env.blocks = obstack_finish(&env.ob);
1464 /* renumbering in the blocks gives nicer debug output as number are smaller. */
1465 #ifdef DEBUG_libfirm
1466 for (i = 0; i < env.n_blocks; ++i)
1467 sched_renumber(env.blocks[i]);
1470 /* Fix high register pressure in blocks with belady algorithm */
1471 for (i = 0; i < env.n_blocks; ++i)
1474 global_assign(&env);
1476 /* Insert spill/reload nodes into the graph and fix usages */
1477 be_insert_spills_reloads(env.senv);
1480 be_delete_spill_env(env.senv);
1482 obstack_free(&env.ob, NULL);
1485 void be_init_spillbelady2(void)
1487 lc_opt_entry_t *be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
1488 lc_opt_entry_t *spill_grp = lc_opt_get_grp(be_grp, "spill");
1489 lc_opt_entry_t *bel2_grp = lc_opt_get_grp(spill_grp, "belady2");
1491 static be_spiller_t belady_spiller = {
1495 lc_opt_add_table(bel2_grp, options);
1496 be_register_spiller("belady2", &belady_spiller);
1497 FIRM_DBG_REGISTER(dbg, "firm.be.spill.belady2");
1500 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spillbelady2);