more libc mapper functions added
[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         int      reloaded_value; /**< the value is a reloaded value */
76 } loc_t;
77
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 */
81 } workset_t;
82
83 typedef struct _belady_env_t {
84         struct obstack ob;
85         const arch_env_t *arch;
86         const arch_register_class_t *cls;
87         be_lv_t *lv;
88         be_loopana_t *loop_ana;
89         int n_regs;                     /** number of regs in this reg-class */
90
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) */
95         pset *used;
96
97         spill_env_t *senv;      /**< see bespill.h */
98 } belady_env_t;
99
100 static int loc_compare(const void *a, const void *b)
101 {
102         const loc_t *p = a;
103         const loc_t *q = b;
104         return p->time - q->time;
105 }
106
107 /* debug helper */
108 static void workset_print(const workset_t *w)
109 {
110         int i;
111
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);
114         }
115         /* avoid unused warning */
116         (void) workset_print;
117 }
118
119 /**
120  * Alloc a new workset on obstack @p ob with maximum size @p max
121  */
122 static INLINE workset_t *new_workset(belady_env_t *env, struct obstack *ob) {
123         workset_t *res;
124         size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
125         res = obstack_alloc(ob, size);
126         memset(res, 0, size);
127         return res;
128 }
129
130 /**
131  * Alloc a new instance on obstack and make it equal to @param ws
132  */
133 static INLINE workset_t *workset_clone(belady_env_t *env, struct obstack *ob, workset_t *ws) {
134         workset_t *res;
135         size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
136         res = obstack_alloc(ob, size);
137         memcpy(res, ws, size);
138         return res;
139 }
140
141 /**
142  * Do NOT alloc anything. Make @param tgt equal to @param src.
143  * returns @param tgt for convenience
144  */
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);
148         return tgt;
149 }
150
151 /**
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.
155  */
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]));
159 }
160
161 /**
162  * Inserts the value @p val into the workset, iff it is not
163  * already contained. The workset must not be full.
164  */
165 static INLINE void workset_insert(belady_env_t *env, workset_t *ws,
166                                   ir_node *val, int reloaded_value)
167 {
168         int i;
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));
172                 return;
173         }
174
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;
180                         return;
181                 }
182         }
183
184         /* insert val */
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;
188         ws->vals[ws->len].time           = 6666;
189         ws->len++;
190 }
191
192 /**
193  * Removes all entries from this workset
194  */
195 static INLINE void workset_clear(workset_t *ws) {
196         ws->len = 0;
197 }
198
199 /**
200  * Removes the value @p val from the workset if present.
201  */
202 static INLINE void workset_remove(workset_t *ws, ir_node *val) {
203         int i;
204         for(i=0; i<ws->len; ++i) {
205                 if (ws->vals[i].irn == val) {
206                         ws->vals[i] = ws->vals[--ws->len];
207                         return;
208                 }
209         }
210 }
211
212 static INLINE int workset_contains(const workset_t *ws, const ir_node *val) {
213         int i;
214         for(i=0; i<ws->len; ++i) {
215                 if (ws->vals[i].irn == val)
216                         return 1;
217         }
218
219         return 0;
220 }
221
222 /**
223  * Iterates over all values in the working set.
224  * @p ws The workset to iterate
225  * @p v  A variable to put the current value in
226  * @p i  An integer for internal use
227  */
228 #define workset_foreach(ws, v, i)       for(i=0; \
229                                                                                 v=(i < ws->len) ? ws->vals[i].irn : NULL, i < ws->len; \
230                                                                                 ++i)
231
232 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
233 #define workset_get_time(ws, i) (ws)->vals[i].time
234 #define workset_set_length(ws, length) (ws)->len = length
235 #define workset_get_length(ws) ((ws)->len)
236 #define workset_get_val(ws, i) ((ws)->vals[i].irn)
237 #define workset_sort(ws) qsort((ws)->vals, (ws)->len, sizeof((ws)->vals[0]), loc_compare);
238
239 typedef struct _block_info_t {
240         workset_t *ws_start, *ws_end;
241         int processed;
242 } block_info_t;
243
244
245 static INLINE void *new_block_info(struct obstack *ob) {
246         block_info_t *res = obstack_alloc(ob, sizeof(*res));
247         res->ws_start = NULL;
248         res->ws_end = NULL;
249         res->processed = 0;
250
251         return res;
252 }
253
254 #define get_block_info(block)        ((block_info_t *)get_irn_link(block))
255 #define set_block_info(block, info)  set_irn_link(block, info)
256
257 /**
258  * @return The distance to the next use or 0 if irn has dont_spill flag set
259  */
260 static INLINE unsigned get_distance(belady_env_t *env, ir_node *from, unsigned from_step, const ir_node *def, int skip_from_uses)
261 {
262         be_next_use_t use;
263         int           flags = arch_irn_get_flags(env->arch, def);
264         unsigned      time;
265
266         assert(! (flags & arch_irn_flags_ignore));
267
268         use = be_get_next_use(env->uses, from, from_step, def, skip_from_uses);
269         if(USES_IS_INFINITE(use.time))
270                 return USES_INFINITY;
271
272         /* We have to keep nonspillable nodes in the workingset */
273         if(flags & arch_irn_flags_dont_spill)
274                 return 0;
275
276         time  = use.time;
277         time += be_get_reload_costs_no_weight(env->senv, def, use.before) * 10;
278
279         return use.time;
280 }
281
282 /**
283  * Performs the actions necessary to grant the request that:
284  * - new_vals can be held in registers
285  * - as few as possible other values are disposed
286  * - the worst values get disposed
287  *
288  * @p is_usage indicates that the values in new_vals are used (not defined)
289  * In this case reloads must be performed
290  */
291 static void displace(belady_env_t *env, workset_t *new_vals, int is_usage) {
292         ir_node *val;
293         int     i, len, max_allowed, demand, iter;
294
295         workset_t *ws         = env->ws;
296         ir_node   **to_insert = alloca(env->n_regs * sizeof(*to_insert));
297
298         /*
299                 1. Identify the number of needed slots and the values to reload
300         */
301         demand = 0;
302         workset_foreach(new_vals, val, iter) {
303                 /* mark value as used */
304                 if (is_usage)
305                         pset_insert_ptr(env->used, val);
306
307                 if (! workset_contains(ws, val)) {
308                         DBG((dbg, DBG_DECIDE, "    insert %+F\n", val));
309
310                         to_insert[demand++] = val;
311                         if (is_usage) {
312                                 DBG((dbg, DBG_SPILL, "Reload %+F before %+F\n", val, env->instr));
313                                 be_add_reload(env->senv, val, env->instr, env->cls, 1);
314                         }
315                 } else {
316                         DBG((dbg, DBG_DECIDE, "    %+F already in workset\n", val));
317                         assert(is_usage);
318                 }
319         }
320
321         /*
322                 2. Make room for at least 'demand' slots
323         */
324         len         = workset_get_length(ws);
325         max_allowed = env->n_regs - demand;
326
327         /* Only make more free room if we do not have enough */
328         if (len > max_allowed) {
329                 DBG((dbg, DBG_DECIDE, "    disposing %d values\n", ws->len - max_allowed));
330
331                 /* get current next-use distance */
332                 for (i = 0; i < ws->len; ++i) {
333                         unsigned dist = get_distance(env, env->instr, env->instr_nr, workset_get_val(ws, i), !is_usage);
334                         workset_set_time(ws, i, dist);
335                 }
336
337                 /* sort entries by increasing nextuse-distance*/
338                 workset_sort(ws);
339
340                 /*
341                         Logic for not needed live-ins: If a value is disposed
342                         before its first usage, remove it from start workset
343                         We don't do this for phis though
344                 */
345                 for (i = max_allowed; i < ws->len; ++i) {
346                         ir_node *irn = ws->vals[i].irn;
347
348                         DBG((dbg, DBG_DECIDE, "    disposing node %+F (%u)\n", irn,
349                              workset_get_time(ws, i)));
350
351                         if(!USES_IS_INFINITE(ws->vals[i].time)
352                                         && !ws->vals[i].reloaded_value) {
353                                 //be_add_spill(env->senv, irn, env->instr);
354                         }
355
356             if (is_Phi(irn))
357                 continue;
358
359                         if (! pset_find_ptr(env->used, irn)) {
360                                 ir_node   *curr_bb  = get_nodes_block(env->instr);
361                                 workset_t *ws_start = get_block_info(curr_bb)->ws_start;
362                                 workset_remove(ws_start, irn);
363
364                                 DBG((dbg, DBG_DECIDE, "    (and removing %+F from start workset)\n", irn));
365                         }
366                 }
367
368                 /* kill the last 'demand' entries in the array */
369                 workset_set_length(ws, max_allowed);
370         }
371
372         /*
373                 3. Insert the new values into the workset
374         */
375         for (i = 0; i < demand; ++i) {
376                 workset_insert(env, env->ws, to_insert[i], 1);
377         }
378 }
379
380 static void belady(ir_node *block, void *env);
381
382 /**
383  * Decides whether a specific node should be in the start workset or not
384  *
385  * @param env      belady environment
386  * @param first
387  * @param node     the node to test
388  * @param block    the block of the node
389  * @param loop     the loop of the node
390  */
391 static loc_t to_take_or_not_to_take(belady_env_t *env, ir_node* first,
392                                             ir_node *node, ir_node *block,
393                                                                         ir_loop *loop)
394 {
395         be_next_use_t next_use;
396         loc_t loc;
397         loc.time = USES_INFINITY;
398         loc.irn  = node;
399         loc.reloaded_value = 0;
400         (void) block;
401
402         if (!arch_irn_consider_in_reg_alloc(env->arch, env->cls, node)) {
403                 loc.time = USES_INFINITY;
404                 return loc;
405         }
406
407         /* We have to keep nonspillable nodes in the workingset */
408         if(arch_irn_get_flags(env->arch, node) & arch_irn_flags_dont_spill) {
409                 loc.time = 0;
410                 DBG((dbg, DBG_START, "    %+F taken (dontspill node)\n", node, loc.time));
411                 return loc;
412         }
413
414         next_use = be_get_next_use(env->uses, first, 0, node, 0);
415         if(USES_IS_INFINITE(next_use.time)) {
416                 // the nodes marked as live in shouldn't be dead, so it must be a phi
417                 assert(is_Phi(node));
418                 loc.time = USES_INFINITY;
419                 DBG((dbg, DBG_START, "    %+F not taken (dead)\n", node));
420                 if(is_Phi(node)) {
421                         be_spill_phi(env->senv, node);
422                 }
423                 return loc;
424         }
425
426         loc.time = next_use.time;
427
428         if(next_use.outermost_loop >= get_loop_depth(loop)) {
429                 DBG((dbg, DBG_START, "    %+F taken (%u, loop %d)\n", node, loc.time, next_use.outermost_loop));
430         } else {
431                 loc.time = USES_PENDING;
432                 DBG((dbg, DBG_START, "    %+F delayed (outerloopdepth %d < loopdetph %d)\n", node, next_use.outermost_loop, get_loop_depth(loop)));
433         }
434         return loc;
435 }
436
437 /*
438  * Computes set of live-ins for each block with multiple predecessors
439  * and notifies spill algorithm which phis need to be spilled
440  */
441 static void compute_live_ins(ir_node *block, void *data) {
442         belady_env_t  *env  = data;
443         ir_loop       *loop = get_irn_loop(block);
444         const be_lv_t *lv   = env->lv;
445         block_info_t  *block_info;
446         ir_node       *first, *irn;
447         loc_t         loc, *starters, *delayed;
448         int           i, len, ws_count;
449         int               free_slots, free_pressure_slots;
450         unsigned      pressure;
451
452         if (get_Block_n_cfgpreds(block) == 1 && get_irg_start_block(get_irn_irg(block)) != block)
453                 return;
454
455         block_info = new_block_info(&env->ob);
456         set_block_info(block, block_info);
457
458         /* Collect all values living at start of block */
459         starters = NEW_ARR_F(loc_t, 0);
460         delayed  = NEW_ARR_F(loc_t, 0);
461
462         DBG((dbg, DBG_START, "Living at start of %+F:\n", block));
463         first = sched_first(block);
464
465         /* check all Phis first */
466         sched_foreach(block, irn) {
467                 if (! is_Phi(irn))
468                         break;
469
470                 loc = to_take_or_not_to_take(env, first, irn, block, loop);
471                 /* the phis can't be reloaded here (they just get defined) */
472                 loc.reloaded_value = 0;
473
474                 if (! USES_IS_INFINITE(loc.time)) {
475                         if (USES_IS_PENDING(loc.time))
476                                 ARR_APP1(loc_t, delayed, loc);
477                         else
478                                 ARR_APP1(loc_t, starters, loc);
479                 }
480         }
481
482         /* check all Live-Ins */
483         be_lv_foreach(lv, block, be_lv_state_in, i) {
484                 ir_node *node = be_lv_get_irn(lv, block, i);
485
486                 loc = to_take_or_not_to_take(env, first, node, block, loop);
487
488                 if (! USES_IS_INFINITE(loc.time)) {
489                         if (USES_IS_PENDING(loc.time))
490                                 ARR_APP1(loc_t, delayed, loc);
491                         else
492                                 ARR_APP1(loc_t, starters, loc);
493                 }
494         }
495
496         pressure            = be_get_loop_pressure(env->loop_ana, env->cls, loop);
497         assert(ARR_LEN(delayed) <= (signed)pressure);
498         free_slots          = env->n_regs - ARR_LEN(starters);
499         free_pressure_slots = env->n_regs - (pressure - ARR_LEN(delayed));
500         free_slots          = MIN(free_slots, free_pressure_slots);
501         /* append nodes delayed due to loop structure until start set is full */
502         for (i = 0; i < ARR_LEN(delayed) && i < free_slots; ++i) {
503                 DBG((dbg, DBG_START, "    delayed %+F taken\n", delayed[i].irn));
504                 ARR_APP1(loc_t, starters, delayed[i]);
505                 delayed[i].irn = NULL;
506         }
507
508         /* spill all delayed phis which didn't make it into start workset */
509         for ( ; i < ARR_LEN(delayed); ++i) {
510                 ir_node *irn = delayed[i].irn;
511                 if (irn && is_Phi(irn) && get_nodes_block(irn) == block) {
512                         DBG((dbg, DBG_START, "    spilling delayed phi %+F\n", irn));
513                         be_spill_phi(env->senv, irn);
514                 }
515         }
516         DEL_ARR_F(delayed);
517
518         /* Sort start values by first use */
519         qsort(starters, ARR_LEN(starters), sizeof(starters[0]), loc_compare);
520
521         /* Copy the best ones from starters to start workset */
522         ws_count             = MIN(ARR_LEN(starters), env->n_regs);
523         block_info->ws_start = new_workset(env, &env->ob);
524         workset_bulk_fill(block_info->ws_start, ws_count, starters);
525
526         /* The phis of this block which are not in the start set have to be spilled later. */
527         len = ARR_LEN(starters);
528         for (i = ws_count; i < len; ++i) {
529                 irn = starters[i].irn;
530                 if (! is_Phi(irn) || get_nodes_block(irn) != block)
531                         continue;
532
533                 be_spill_phi(env->senv, irn);
534         }
535
536         DEL_ARR_F(starters);
537 }
538
539 /**
540  * Collects all values live-in at block @p block and all phi results in this block.
541  * Then it adds the best values (at most n_regs) to the blocks start_workset.
542  * The phis among the remaining values get spilled: Introduce psudo-copies of
543  *  their args to break interference and make it possible to spill them to the
544  *  same spill slot.
545  */
546 static block_info_t *compute_block_start_info(belady_env_t *env, ir_node *block) {
547         ir_node *pred_block;
548         block_info_t *res, *pred_info;
549
550         /* Have we seen this block before? */
551         res = get_block_info(block);
552         if (res)
553                 return res;
554
555         /* Create the block info for this block. */
556         res = new_block_info(&env->ob);
557         set_block_info(block, res);
558
559         /* Use endset of predecessor block as startset */
560         assert(get_Block_n_cfgpreds(block) == 1 && block != get_irg_start_block(get_irn_irg(block)));
561         pred_block = get_Block_cfgpred_block(block, 0);
562         pred_info = get_block_info(pred_block);
563
564         /* if pred block has not been processed yet, do it now */
565         if (pred_info == NULL || pred_info->processed == 0) {
566                 belady(pred_block, env);
567                 pred_info = get_block_info(pred_block);
568         }
569
570         /* now we have an end_set of pred */
571         assert(pred_info->ws_end && "The recursive call (above) is supposed to compute an end_set");
572         res->ws_start = workset_clone(env, &env->ob, pred_info->ws_end);
573
574         return res;
575 }
576
577
578 /**
579  * For the given block @p block, decide for each values
580  * whether it is used from a register or is reloaded
581  * before the use.
582  */
583 static void belady(ir_node *block, void *data) {
584         belady_env_t *env = data;
585         workset_t *new_vals;
586         ir_node *irn;
587         int iter;
588         block_info_t *block_info;
589
590         /* make sure we have blockinfo (with startset) */
591         block_info = get_block_info(block);
592         if (block_info == NULL)
593                 block_info = compute_block_start_info(env, block);
594
595         /* Don't do a block twice */
596         if(block_info->processed)
597                 return;
598
599         /* get the starting workset for this block */
600         DBG((dbg, DBG_DECIDE, "\n"));
601         DBG((dbg, DBG_DECIDE, "Decide for %+F\n", block));
602
603         workset_copy(env, env->ws, block_info->ws_start);
604         DBG((dbg, DBG_WSETS, "Start workset for %+F:\n", block));
605         workset_foreach(env->ws, irn, iter)
606                 DBG((dbg, DBG_WSETS, "  %+F (%u)\n", irn, workset_get_time(env->ws, iter)));
607
608         /* process the block from start to end */
609         DBG((dbg, DBG_WSETS, "Processing...\n"));
610         env->used = pset_new_ptr_default();
611         env->instr_nr = 0;
612         new_vals = new_workset(env, &env->ob);
613         sched_foreach(block, irn) {
614                 int i, arity;
615                 assert(workset_get_length(env->ws) <= env->n_regs && "Too much values in workset!");
616
617                 /* projs are handled with the tuple value.
618                  * Phis are no real instr (see insert_starters())
619                  * instr_nr does not increase */
620                 if (is_Proj(irn) || is_Phi(irn)) {
621                         DBG((dbg, DBG_DECIDE, "  ...%+F skipped\n", irn));
622                         continue;
623                 }
624                 DBG((dbg, DBG_DECIDE, "  ...%+F\n", irn));
625
626                 /* set instruction in the workset */
627                 env->instr = irn;
628
629                 /* allocate all values _used_ by this instruction */
630                 workset_clear(new_vals);
631                 for(i = 0, arity = get_irn_arity(irn); i < arity; ++i) {
632                         /* (note that reloaded_value is not interesting here) */
633                         workset_insert(env, new_vals, get_irn_n(irn, i), 0);
634                 }
635                 displace(env, new_vals, 1);
636
637                 /* allocate all values _defined_ by this instruction */
638                 workset_clear(new_vals);
639                 if (get_irn_mode(irn) == mode_T) { /* special handling for tuples and projs */
640                         const ir_edge_t *edge;
641
642                         foreach_out_edge(irn, edge) {
643                                 ir_node *proj = get_edge_src_irn(edge);
644                                 workset_insert(env, new_vals, proj, 0);
645                         }
646                 } else {
647                         workset_insert(env, new_vals, irn, 0);
648                 }
649                 displace(env, new_vals, 0);
650
651                 env->instr_nr++;
652         }
653         del_pset(env->used);
654
655         /* Remember end-workset for this block */
656         block_info->ws_end = workset_clone(env, &env->ob, env->ws);
657         block_info->processed = 1;
658         DBG((dbg, DBG_WSETS, "End workset for %+F:\n", block));
659         workset_foreach(block_info->ws_end, irn, iter)
660                 DBG((dbg, DBG_WSETS, "  %+F (%u)\n", irn, workset_get_time(block_info->ws_end, iter)));
661 }
662
663 /**
664  * 'decide' is block-local and makes assumptions
665  * about the set of live-ins. Thus we must adapt the
666  * live-outs to the live-ins at each block-border.
667  */
668 static void fix_block_borders(ir_node *block, void *data)
669 {
670         ir_graph     *irg        = get_irn_irg(block);
671         ir_node      *startblock = get_irg_start_block(irg);
672         belady_env_t *env        = data;
673         workset_t    *start_workset;
674         int           arity;
675         int           i;
676         int           iter;
677
678         if(block == startblock)
679                 return;
680
681         DBG((dbg, DBG_FIX, "\n"));
682         DBG((dbg, DBG_FIX, "Fixing %+F\n", block));
683
684         start_workset = get_block_info(block)->ws_start;
685
686         /* process all pred blocks */
687         arity = get_irn_arity(block);
688         for (i = 0; i < arity; ++i) {
689                 ir_node   *pred             = get_Block_cfgpred_block(block, i);
690                 workset_t *workset_pred_end = get_block_info(pred)->ws_end;
691                 ir_node   *node;
692
693                 DBG((dbg, DBG_FIX, "  Pred %+F\n", pred));
694
695                 /* spill all values not used anymore */
696                 workset_foreach(workset_pred_end, node, iter) {
697                         ir_node *n2;
698                         int      iter2;
699                         int      found = 0;
700                         workset_foreach(start_workset, n2, iter2) {
701                                 if(n2 == node) {
702                                         found = 1;
703                                         break;
704                                 }
705                                 /* note that we do not look at phi inputs, becuase the values
706                                  * will be either live-end and need no spill or
707                                  * they have other users in which must be somewhere else in the
708                                  * workset */
709                         }
710
711 #if 0
712                         if(!found && be_is_live_out(env->lv, pred, node)
713                                         && !workset_pred_end->vals[iter].reloaded_value) {
714                                 ir_node *insert_point
715                                         = be_get_end_of_block_insertion_point(pred);
716                                 DBG((dbg, DBG_SPILL, "Spill %+F before %+F\n", node,
717                                      insert_point));
718                                 be_add_spill(env->senv, node, insert_point);
719                         }
720 #endif
721                 }
722
723                 /* reload missing values in predecessors */
724                 workset_foreach(start_workset, node, iter) {
725                         /* if node is a phi of the current block we reload
726                          * the corresponding argument, else node itself */
727                         if(is_Phi(node) && block == get_nodes_block(node)) {
728                                 node = get_irn_n(node, i);
729
730                                 /* we might have unknowns as argument for the phi */
731                                 if(!arch_irn_consider_in_reg_alloc(env->arch, env->cls, node))
732                                         continue;
733                         }
734
735                         /* check if node is in a register at end of pred */
736                         if(workset_contains(workset_pred_end, node))
737                                 continue;
738
739                         /* node is not in memory at the end of pred -> reload it */
740                         DBG((dbg, DBG_FIX, "    reload %+F\n", node));
741                         DBG((dbg, DBG_SPILL, "Reload %+F before %+F,%d\n", node, block, i));
742                         be_add_reload_on_edge(env->senv, node, block, i, env->cls, 1);
743                 }
744         }
745 }
746
747 /**
748  * Do spilling for a register class on a graph using the belady heuristic.
749  * In the transformed graph, the register pressure never exceeds the number
750  * of available registers.
751  *
752  * @param birg  The backend graph
753  * @param cls   The register class to spill
754  */
755 static void be_spill_belady(be_irg_t *birg, const arch_register_class_t *cls) {
756         be_spill_belady_spill_env(birg, cls, NULL);
757 }
758
759 void be_spill_belady_spill_env(be_irg_t *birg, const arch_register_class_t *cls, spill_env_t *spill_env) {
760         belady_env_t env;
761         ir_graph *irg = be_get_birg_irg(birg);
762         int n_regs;
763
764         n_regs = cls->n_regs - be_put_ignore_regs(birg, cls, NULL);
765         be_liveness_assure_sets(be_assure_liveness(birg));
766
767         /* construct control flow loop tree */
768         if(! (get_irg_loopinfo_state(irg) & loopinfo_cf_consistent)) {
769                 construct_cf_backedges(irg);
770         }
771
772         be_clear_links(irg);
773
774         /* init belady env */
775         obstack_init(&env.ob);
776         env.arch      = birg->main_env->arch_env;
777         env.cls       = cls;
778         env.lv        = be_get_birg_liveness(birg);
779         env.n_regs    = n_regs;
780         env.ws        = new_workset(&env, &env.ob);
781         env.uses      = be_begin_uses(irg, env.lv);
782         env.loop_ana  = be_new_loop_pressure(birg);
783         if(spill_env == NULL) {
784                 env.senv = be_new_spill_env(birg);
785         } else {
786                 env.senv = spill_env;
787         }
788
789         /* Decide which phi nodes will be spilled and place copies for them into the graph */
790         irg_block_walk_graph(irg, compute_live_ins, NULL, &env);
791         /* Fix high register pressure with belady algorithm */
792         irg_block_walk_graph(irg, NULL, belady, &env);
793         /* belady was block-local, fix the global flow by adding reloads on the edges */
794         irg_block_walk_graph(irg, fix_block_borders, NULL, &env);
795
796         be_end_uses(env.uses);
797         be_free_loop_pressure(env.loop_ana);
798         obstack_free(&env.ob, NULL);
799
800         /* Insert spill/reload nodes into the graph and fix usages */
801         be_insert_spills_reloads(env.senv);
802
803         /* clean up */
804         if(spill_env == NULL)
805                 be_delete_spill_env(env.senv);
806 }
807
808 void be_init_spillbelady(void)
809 {
810         static be_spiller_t belady_spiller = {
811                 be_spill_belady
812         };
813
814         be_register_spiller("belady", &belady_spiller);
815         FIRM_DBG_REGISTER(dbg, "firm.be.spill.belady");
816 }
817
818 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spillbelady);