rematerialized values are like reloads
[libfirm] / ir / be / bespillbelady.c
1 /*
2  * Copyright (C) 1995-2007 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       Beladys spillalgorithm.
23  * @author      Daniel Grund, Matthias Braun
24  * @date        20.09.2005
25  * @version     $Id$
26  */
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include "obst.h"
32 #include "set.h"
33 #include "pset.h"
34 #include "irprintf_t.h"
35 #include "irgraph.h"
36 #include "irnode.h"
37 #include "irmode.h"
38 #include "irgwalk.h"
39 #include "irloop.h"
40 #include "iredges_t.h"
41 #include "ircons_t.h"
42 #include "irprintf.h"
43 #include "xmalloc.h"
44
45 #include "beutil.h"
46 #include "bearch_t.h"
47 #include "bespillbelady.h"
48 #include "beuses.h"
49 #include "besched_t.h"
50 #include "beirgmod.h"
51 #include "belive_t.h"
52 #include "benode_t.h"
53 #include "bechordal_t.h"
54 #include "bespilloptions.h"
55 #include "beloopana.h"
56 #include "beirg_t.h"
57 #include "bemodule.h"
58
59 #define DBG_SPILL   1
60 #define DBG_WSETS   2
61 #define DBG_FIX     4
62 #define DBG_DECIDE  8
63 #define DBG_START  16
64 #define DBG_SLOTS  32
65 #define DBG_TRACE  64
66 #define DBG_WORKSET 128
67 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
68
69 /**
70  * An association between a node and a point in time.
71  */
72 typedef struct _loc_t {
73   ir_node *irn;        /**< A node. */
74   unsigned time;       /**< A use time (see beuses.h). */
75 } loc_t;
76
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 */
80 } workset_t;
81
82 typedef struct _belady_env_t {
83         struct obstack ob;
84         const arch_env_t *arch;
85         const arch_register_class_t *cls;
86         be_lv_t *lv;
87         be_loopana_t *loop_ana;
88         int n_regs;                     /** number of regs in this reg-class */
89
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) */
94         pset *used;
95
96         spill_env_t *senv;      /**< see bespill.h */
97 } belady_env_t;
98
99 static int loc_compare(const void *a, const void *b)
100 {
101         const loc_t *p = a;
102         const loc_t *q = b;
103         return p->time - q->time;
104 }
105
106 static INLINE void workset_print(const workset_t *w)
107 {
108         int i;
109
110         for(i = 0; i < w->len; ++i) {
111                 ir_fprintf(stderr, "%+F %d\n", w->vals[i].irn, w->vals[i].time);
112         }
113 }
114
115 /**
116  * Alloc a new workset on obstack @p ob with maximum size @p max
117  */
118 static INLINE workset_t *new_workset(belady_env_t *env, struct obstack *ob) {
119         workset_t *res;
120         size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
121         res = obstack_alloc(ob, size);
122         memset(res, 0, size);
123         return res;
124 }
125
126 /**
127  * Alloc a new instance on obstack and make it equal to @param ws
128  */
129 static INLINE workset_t *workset_clone(belady_env_t *env, struct obstack *ob, workset_t *ws) {
130         workset_t *res;
131         size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
132         res = obstack_alloc(ob, size);
133         memcpy(res, ws, size);
134         return res;
135 }
136
137 /**
138  * Do NOT alloc anything. Make @param tgt equal to @param src.
139  * returns @param tgt for convenience
140  */
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);
144         return tgt;
145 }
146
147 /**
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.
151  */
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]));
155 }
156
157 /**
158  * Inserts the value @p val into the workset, iff it is not
159  * already contained. The workset must not be full.
160  */
161 static INLINE void workset_insert(belady_env_t *env, workset_t *ws, ir_node *val) {
162         int i;
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));
166                 return;
167         }
168
169         /* check if val is already contained */
170         for(i=0; i<ws->len; ++i)
171                 if (ws->vals[i].irn == val)
172                         return;
173
174         /* insert val */
175         assert(ws->len < env->n_regs && "Workset already full!");
176         ws->vals[ws->len++].irn = val;
177 }
178
179 /**
180  * Removes all entries from this workset
181  */
182 static INLINE void workset_clear(workset_t *ws) {
183         ws->len = 0;
184 }
185
186 /**
187  * Removes the value @p val from the workset if present.
188  */
189 static INLINE void workset_remove(workset_t *ws, ir_node *val) {
190         int i;
191         for(i=0; i<ws->len; ++i) {
192                 if (ws->vals[i].irn == val) {
193                         ws->vals[i] = ws->vals[--ws->len];
194                         return;
195                 }
196         }
197 }
198
199 static INLINE int workset_contains(const workset_t *ws, const ir_node *val) {
200         int i;
201         for(i=0; i<ws->len; ++i) {
202                 if (ws->vals[i].irn == val)
203                         return 1;
204         }
205
206         return 0;
207 }
208
209 /**
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
214  */
215 #define workset_foreach(ws, v, i)       for(i=0; \
216                                                                                 v=(i < ws->len) ? ws->vals[i].irn : NULL, i < ws->len; \
217                                                                                 ++i)
218
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);
225
226 typedef struct _block_info_t {
227         workset_t *ws_start, *ws_end;
228         int processed;
229 } block_info_t;
230
231
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;
235         res->ws_end = NULL;
236         res->processed = 0;
237
238         return res;
239 }
240
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)
243
244 /**
245  * @return The distance to the next use or 0 if irn has dont_spill flag set
246  */
247 static INLINE unsigned get_distance(belady_env_t *env, ir_node *from, unsigned from_step, const ir_node *def, int skip_from_uses)
248 {
249         be_next_use_t use;
250         int flags = arch_irn_get_flags(env->arch, def);
251
252         assert(! (flags & arch_irn_flags_ignore));
253
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;
257
258         /* We have to keep nonspillable nodes in the workingset */
259         if(flags & arch_irn_flags_dont_spill)
260                 return 0;
261
262         return use.time;
263 }
264
265 /**
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
270  *
271  * @p is_usage indicates that the values in new_vals are used (not defined)
272  * In this case reloads must be performed
273  */
274 static void displace(belady_env_t *env, workset_t *new_vals, int is_usage) {
275         ir_node *val;
276         int     i, len, max_allowed, demand, iter;
277
278         workset_t *ws         = env->ws;
279         ir_node   **to_insert = alloca(env->n_regs * sizeof(*to_insert));
280
281         /*
282                 1. Identify the number of needed slots and the values to reload
283         */
284         demand = 0;
285         workset_foreach(new_vals, val, iter) {
286                 /* mark value as used */
287                 if (is_usage)
288                         pset_insert_ptr(env->used, val);
289
290                 if (! workset_contains(ws, val)) {
291                         DBG((dbg, DBG_DECIDE, "    insert %+F\n", val));
292                         to_insert[demand++] = val;
293                         if (is_usage) {
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);
296                         }
297                 }
298                 else {
299                         assert(is_usage || "Defined value already in workset?!?");
300                         DBG((dbg, DBG_DECIDE, "    skip %+F\n", val));
301                 }
302         }
303         DBG((dbg, DBG_DECIDE, "    demand = %d\n", demand));
304
305         /*
306                 2. Make room for at least 'demand' slots
307         */
308         len         = workset_get_length(ws);
309         max_allowed = env->n_regs - demand;
310
311         DBG((dbg, DBG_DECIDE, "    disposing %d values\n", ws->len - max_allowed));
312
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);
319                 }
320
321                 /* sort entries by increasing nextuse-distance*/
322                 workset_sort(ws);
323
324                 /*
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
328                 */
329                 for (i = max_allowed; i < ws->len; ++i) {
330                         ir_node *irn = ws->vals[i].irn;
331
332                         DBG((dbg, DBG_DECIDE, "    disposing %+F (%u)\n", irn,
333                              workset_get_time(ws, i)));
334
335                         if(!USES_IS_INFINITE(ws->vals[i].time)) {
336                                 be_add_spill(env->senv, irn, env->instr);
337                         }
338
339             if (is_Phi(irn))
340                 continue;
341
342                         if (! pset_find_ptr(env->used, irn)) {
343                                 ir_node   *curr_bb  = get_nodes_block(env->instr);
344                                 workset_t *ws_start = get_block_info(curr_bb)->ws_start;
345                                 workset_remove(ws_start, irn);
346
347                                 DBG((dbg, DBG_DECIDE, "    (and removing %+F from start workset)\n", irn));
348                         }
349                 }
350
351                 /* kill the last 'demand' entries in the array */
352                 workset_set_length(ws, max_allowed);
353         }
354
355         /*
356                 3. Insert the new values into the workset
357         */
358         for (i = 0; i < demand; ++i)
359                 workset_insert(env, env->ws, to_insert[i]);
360 }
361
362 static void belady(ir_node *block, void *env);
363
364 /** Decides whether a specific node should be in the start workset or not
365  *
366  * @param env      belady environment
367  * @param first
368  * @param node     the node to test
369  * @param block    the block of the node
370  * @param loop     the loop of the node
371  */
372 static loc_t to_take_or_not_to_take(belady_env_t *env, ir_node* first,
373                                             ir_node *node, ir_node *block,
374                                                                         ir_loop *loop)
375 {
376         be_next_use_t next_use;
377         loc_t loc;
378         loc.time = USES_INFINITY;
379         loc.irn = node;
380         (void) block;
381
382         if (!arch_irn_consider_in_reg_alloc(env->arch, env->cls, node)) {
383                 loc.time = USES_INFINITY;
384                 return loc;
385         }
386
387         /* We have to keep nonspillable nodes in the workingset */
388         if(arch_irn_get_flags(env->arch, node) & arch_irn_flags_dont_spill) {
389                 loc.time = 0;
390                 DBG((dbg, DBG_START, "    %+F taken (dontspill node)\n", node, loc.time));
391                 return loc;
392         }
393
394         next_use = be_get_next_use(env->uses, first, 0, node, 0);
395         if(USES_IS_INFINITE(next_use.time)) {
396                 // the nodes marked as live in shouldn't be dead, so it must be a phi
397                 assert(is_Phi(node));
398                 loc.time = USES_INFINITY;
399                 DBG((dbg, DBG_START, "    %+F not taken (dead)\n", node));
400                 if(is_Phi(node)) {
401                         be_spill_phi(env->senv, node);
402                 }
403                 return loc;
404         }
405
406         loc.time = next_use.time;
407
408         if(next_use.outermost_loop >= get_loop_depth(loop)) {
409                 DBG((dbg, DBG_START, "    %+F taken (%u, loop %d)\n", node, loc.time, next_use.outermost_loop));
410         } else {
411                 loc.time = USES_PENDING;
412                 DBG((dbg, DBG_START, "    %+F delayed (outerloopdepth %d < loopdetph %d)\n", node, next_use.outermost_loop, get_loop_depth(loop)));
413         }
414         return loc;
415 }
416
417 /*
418  * Computes set of live-ins for each block with multiple predecessors
419  * and notifies spill algorithm which phis need to be spilled
420  */
421 static void compute_live_ins(ir_node *block, void *data) {
422         belady_env_t  *env  = data;
423         ir_loop       *loop = get_irn_loop(block);
424         const be_lv_t *lv   = env->lv;
425         block_info_t  *block_info;
426         ir_node       *first, *irn;
427         loc_t         loc, *starters, *delayed;
428         int           i, len, ws_count;
429         int               free_slots, free_pressure_slots;
430         unsigned      pressure;
431
432         if (get_Block_n_cfgpreds(block) == 1 && get_irg_start_block(get_irn_irg(block)) != block)
433                 return;
434
435         block_info = new_block_info(&env->ob);
436         set_block_info(block, block_info);
437
438         /* Collect all values living at start of block */
439         starters = NEW_ARR_F(loc_t, 0);
440         delayed  = NEW_ARR_F(loc_t, 0);
441
442         DBG((dbg, DBG_START, "Living at start of %+F:\n", block));
443         first = sched_first(block);
444
445         /* check all Phis first */
446         sched_foreach(block, irn) {
447                 if (! is_Phi(irn))
448                         break;
449
450                 loc = to_take_or_not_to_take(env, first, irn, block, loop);
451
452                 if (! USES_IS_INFINITE(loc.time)) {
453                         if (USES_IS_PENDING(loc.time))
454                                 ARR_APP1(loc_t, delayed, loc);
455                         else
456                                 ARR_APP1(loc_t, starters, loc);
457                 }
458         }
459
460         /* check all Live-Ins */
461         be_lv_foreach(lv, block, be_lv_state_in, i) {
462                 ir_node *node = be_lv_get_irn(lv, block, i);
463
464                 loc = to_take_or_not_to_take(env, first, node, block, loop);
465
466                 if (! USES_IS_INFINITE(loc.time)) {
467                         if (USES_IS_PENDING(loc.time))
468                                 ARR_APP1(loc_t, delayed, loc);
469                         else
470                                 ARR_APP1(loc_t, starters, loc);
471                 }
472         }
473
474         pressure            = be_get_loop_pressure(env->loop_ana, env->cls, loop);
475         assert(ARR_LEN(delayed) <= (signed)pressure);
476         free_slots          = env->n_regs - ARR_LEN(starters);
477         free_pressure_slots = env->n_regs - (pressure - ARR_LEN(delayed));
478         free_slots          = MIN(free_slots, free_pressure_slots);
479         /* append nodes delayed due to loop structure until start set is full */
480         for (i = 0; i < ARR_LEN(delayed) && i < free_slots; ++i) {
481                 DBG((dbg, DBG_START, "    delayed %+F taken\n", delayed[i].irn));
482                 ARR_APP1(loc_t, starters, delayed[i]);
483                 delayed[i].irn = NULL;
484         }
485
486         /* spill all delayed phis which didn't make it into start workset */
487         for ( ; i < ARR_LEN(delayed); ++i) {
488                 ir_node *irn = delayed[i].irn;
489                 if (irn && is_Phi(irn) && get_nodes_block(irn) == block) {
490                         DBG((dbg, DBG_START, "    spilling delayed phi %+F\n", irn));
491                         be_spill_phi(env->senv, irn);
492                 }
493         }
494         DEL_ARR_F(delayed);
495
496         /* Sort start values by first use */
497         qsort(starters, ARR_LEN(starters), sizeof(starters[0]), loc_compare);
498
499         /* Copy the best ones from starters to start workset */
500         ws_count             = MIN(ARR_LEN(starters), env->n_regs);
501         block_info->ws_start = new_workset(env, &env->ob);
502         workset_bulk_fill(block_info->ws_start, ws_count, starters);
503
504         /* The phis of this block which are not in the start set have to be spilled later. */
505         len = ARR_LEN(starters);
506         for (i = ws_count; i < len; ++i) {
507                 irn = starters[i].irn;
508                 if (! is_Phi(irn) || get_nodes_block(irn) != block)
509                         continue;
510
511                 be_spill_phi(env->senv, irn);
512         }
513
514         DEL_ARR_F(starters);
515 }
516
517 /**
518  * Collects all values live-in at block @p block and all phi results in this block.
519  * Then it adds the best values (at most n_regs) to the blocks start_workset.
520  * The phis among the remaining values get spilled: Introduce psudo-copies of
521  *  their args to break interference and make it possible to spill them to the
522  *  same spill slot.
523  */
524 static block_info_t *compute_block_start_info(belady_env_t *env, ir_node *block) {
525         ir_node *pred_block;
526         block_info_t *res, *pred_info;
527
528         /* Have we seen this block before? */
529         res = get_block_info(block);
530         if (res)
531                 return res;
532
533         /* Create the block info for this block. */
534         res = new_block_info(&env->ob);
535         set_block_info(block, res);
536
537         /* Use endset of predecessor block as startset */
538         assert(get_Block_n_cfgpreds(block) == 1 && block != get_irg_start_block(get_irn_irg(block)));
539         pred_block = get_Block_cfgpred_block(block, 0);
540         pred_info = get_block_info(pred_block);
541
542         /* if pred block has not been processed yet, do it now */
543         if (pred_info == NULL || pred_info->processed == 0) {
544                 belady(pred_block, env);
545                 pred_info = get_block_info(pred_block);
546         }
547
548         /* now we have an end_set of pred */
549         assert(pred_info->ws_end && "The recursive call (above) is supposed to compute an end_set");
550         res->ws_start = workset_clone(env, &env->ob, pred_info->ws_end);
551
552         return res;
553 }
554
555
556 /**
557  * For the given block @p block, decide for each values
558  * whether it is used from a register or is reloaded
559  * before the use.
560  */
561 static void belady(ir_node *block, void *data) {
562         belady_env_t *env = data;
563         workset_t *new_vals;
564         ir_node *irn;
565         int iter;
566         block_info_t *block_info;
567
568         /* make sure we have blockinfo (with startset) */
569         block_info = get_block_info(block);
570         if (block_info == NULL)
571                 block_info = compute_block_start_info(env, block);
572
573         /* Don't do a block twice */
574         if(block_info->processed)
575                 return;
576
577         /* get the starting workset for this block */
578         DBG((dbg, DBG_DECIDE, "\n"));
579         DBG((dbg, DBG_DECIDE, "Decide for %+F\n", block));
580
581         workset_copy(env, env->ws, block_info->ws_start);
582         DBG((dbg, DBG_WSETS, "Start workset for %+F:\n", block));
583         workset_foreach(env->ws, irn, iter)
584                 DBG((dbg, DBG_WSETS, "  %+F (%u)\n", irn, workset_get_time(env->ws, iter)));
585
586         /* process the block from start to end */
587         DBG((dbg, DBG_WSETS, "Processing...\n"));
588         env->used = pset_new_ptr_default();
589         env->instr_nr = 0;
590         new_vals = new_workset(env, &env->ob);
591         sched_foreach(block, irn) {
592                 int i, arity;
593                 assert(workset_get_length(env->ws) <= env->n_regs && "Too much values in workset!");
594
595                 /* projs are handled with the tuple value.
596                  * Phis are no real instr (see insert_starters())
597                  * instr_nr does not increase */
598                 if (is_Proj(irn) || is_Phi(irn)) {
599                         DBG((dbg, DBG_DECIDE, "  ...%+F skipped\n", irn));
600                         continue;
601                 }
602                 DBG((dbg, DBG_DECIDE, "  ...%+F\n", irn));
603
604                 /* set instruction in the workset */
605                 env->instr = irn;
606
607                 /* allocate all values _used_ by this instruction */
608                 workset_clear(new_vals);
609                 for(i = 0, arity = get_irn_arity(irn); i < arity; ++i) {
610                         workset_insert(env, new_vals, get_irn_n(irn, i));
611                 }
612                 displace(env, new_vals, 1);
613
614                 /* allocate all values _defined_ by this instruction */
615                 workset_clear(new_vals);
616                 if (get_irn_mode(irn) == mode_T) { /* special handling for tuples and projs */
617                         const ir_edge_t *edge;
618
619                         foreach_out_edge(irn, edge) {
620                                 ir_node *proj = get_edge_src_irn(edge);
621                                 workset_insert(env, new_vals, proj);
622                         }
623                 } else {
624                         workset_insert(env, new_vals, irn);
625                 }
626                 displace(env, new_vals, 0);
627
628                 env->instr_nr++;
629         }
630         del_pset(env->used);
631
632         /* Remember end-workset for this block */
633         block_info->ws_end = workset_clone(env, &env->ob, env->ws);
634         block_info->processed = 1;
635         DBG((dbg, DBG_WSETS, "End workset for %+F:\n", block));
636         workset_foreach(block_info->ws_end, irn, iter)
637                 DBG((dbg, DBG_WSETS, "  %+F (%u)\n", irn, workset_get_time(block_info->ws_end, iter)));
638 }
639
640 /**
641  * 'decide' is block-local and makes assumptions
642  * about the set of live-ins. Thus we must adapt the
643  * live-outs to the live-ins at each block-border.
644  */
645 static void fix_block_borders(ir_node *block, void *data)
646 {
647         ir_graph     *irg        = get_irn_irg(block);
648         ir_node      *startblock = get_irg_start_block(irg);
649         belady_env_t *env        = data;
650         workset_t    *start_workset;
651         int           arity;
652         int           i;
653         int           iter;
654
655         if(block == startblock)
656                 return;
657
658         DBG((dbg, DBG_FIX, "\n"));
659         DBG((dbg, DBG_FIX, "Fixing %+F\n", block));
660
661         start_workset = get_block_info(block)->ws_start;
662
663         /* process all pred blocks */
664         arity = get_irn_arity(block);
665         for (i = 0; i < arity; ++i) {
666                 ir_node   *pred             = get_Block_cfgpred_block(block, i);
667                 workset_t *workset_pred_end = get_block_info(pred)->ws_end;
668                 ir_node   *node;
669
670                 DBG((dbg, DBG_FIX, "  Pred %+F\n", pred));
671
672                 /* spill all values not used anymore */
673                 workset_foreach(workset_pred_end, node, iter) {
674                         ir_node *n2;
675                         int      iter2;
676                         int      found = 0;
677                         workset_foreach(start_workset, n2, iter2) {
678                                 if(n2 == node) {
679                                         found = 1;
680                                         break;
681                                 }
682                                 /* note that we do not look at phi inputs, becuase the values
683                                  * will be either live-end and need no spill or
684                                  * they have other users in which must be somewhere else in the
685                                  * workset */
686                         }
687
688                         if(!found && be_is_live_out(env->lv, pred, node)) {
689                                 ir_node *insert_point
690                                         = be_get_end_of_block_insertion_point(pred);
691                                 DBG((dbg, DBG_SPILL, "Spill %+F before %+F\n", node,
692                                      insert_point));
693                                 be_add_spill(env->senv, node, insert_point);
694                         }
695                 }
696
697                 /* reload missing values in predecessors */
698                 workset_foreach(start_workset, node, iter) {
699                         /* if node is a phi of the current block we reload
700                          * the corresponding argument, else node itself */
701                         if(is_Phi(node) && block == get_nodes_block(node)) {
702                                 node = get_irn_n(node, i);
703
704                                 /* we might have unknowns as argument for the phi */
705                                 if(!arch_irn_consider_in_reg_alloc(env->arch, env->cls, node))
706                                         continue;
707                         }
708
709                         /* check if node is in a register at end of pred */
710                         if(workset_contains(workset_pred_end, node))
711                                 continue;
712
713                         /* node is not in memory at the end of pred -> reload it */
714                         DBG((dbg, DBG_FIX, "    reload %+F\n", node));
715                         DBG((dbg, DBG_SPILL, "Reload %+F before %+F,%d\n", node, block, i));
716                         be_add_reload_on_edge(env->senv, node, block, i, env->cls, 1);
717                 }
718         }
719 }
720
721 /**
722  * Do spilling for a register class on a graph using the belady heuristic.
723  * In the transformed graph, the register pressure never exceeds the number
724  * of available registers.
725  *
726  * @param birg  The backend graph
727  * @param cls   The register class to spill
728  */
729 static void be_spill_belady(be_irg_t *birg, const arch_register_class_t *cls) {
730         be_spill_belady_spill_env(birg, cls, NULL);
731 }
732
733 void be_spill_belady_spill_env(be_irg_t *birg, const arch_register_class_t *cls, spill_env_t *spill_env) {
734         belady_env_t env;
735         ir_graph *irg = be_get_birg_irg(birg);
736         int n_regs;
737
738         n_regs = cls->n_regs - be_put_ignore_regs(birg, cls, NULL);
739         be_liveness_assure_sets(be_assure_liveness(birg));
740
741         /* construct control flow loop tree */
742         if(! (get_irg_loopinfo_state(irg) & loopinfo_cf_consistent)) {
743                 construct_cf_backedges(irg);
744         }
745
746         be_clear_links(irg);
747
748         /* init belady env */
749         obstack_init(&env.ob);
750         env.arch      = birg->main_env->arch_env;
751         env.cls       = cls;
752         env.lv        = be_get_birg_liveness(birg);
753         env.n_regs    = n_regs;
754         env.ws        = new_workset(&env, &env.ob);
755         env.uses      = be_begin_uses(irg, env.lv);
756         env.loop_ana  = be_new_loop_pressure(birg);
757         if(spill_env == NULL) {
758                 env.senv = be_new_spill_env(birg);
759         } else {
760                 env.senv = spill_env;
761         }
762
763         /* Decide which phi nodes will be spilled and place copies for them into the graph */
764         irg_block_walk_graph(irg, compute_live_ins, NULL, &env);
765         /* Fix high register pressure with belady algorithm */
766         irg_block_walk_graph(irg, NULL, belady, &env);
767         /* belady was block-local, fix the global flow by adding reloads on the edges */
768         irg_block_walk_graph(irg, fix_block_borders, NULL, &env);
769
770         be_end_uses(env.uses);
771         be_free_loop_pressure(env.loop_ana);
772         obstack_free(&env.ob, NULL);
773
774         /* Insert spill/reload nodes into the graph and fix usages */
775         be_insert_spills_reloads(env.senv);
776
777         /* clean up */
778         if(spill_env == NULL)
779                 be_delete_spill_env(env.senv);
780 }
781
782 void be_init_spillbelady(void)
783 {
784         static be_spiller_t belady_spiller = {
785                 be_spill_belady
786         };
787
788         be_register_spiller("belady", &belady_spiller);
789         FIRM_DBG_REGISTER(dbg, "firm.be.spill.belady");
790 }
791
792 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spillbelady);