add a bunch of commandline options for easier benchmarking of different belady optimi...
[libfirm] / ir / be / bespillbelady.c
1 /*
2  * Copyright (C) 1995-2008 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 <stdbool.h>
32
33 #include "obst.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 "irnodeset.h"
44 #include "xmalloc.h"
45 #include "pdeq.h"
46
47 #include "beutil.h"
48 #include "bearch_t.h"
49 #include "beuses.h"
50 #include "besched_t.h"
51 #include "beirgmod.h"
52 #include "belive_t.h"
53 #include "benode_t.h"
54 #include "bechordal_t.h"
55 #include "bespilloptions.h"
56 #include "beloopana.h"
57 #include "beirg_t.h"
58 #include "bespill.h"
59 #include "bemodule.h"
60
61 #define DBG_SPILL     1
62 #define DBG_WSETS     2
63 #define DBG_FIX       4
64 #define DBG_DECIDE    8
65 #define DBG_START    16
66 #define DBG_SLOTS    32
67 #define DBG_TRACE    64
68 #define DBG_WORKSET 128
69 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
70
71 #define TIME_UNDEFINED 6666
72
73 //#define LOOK_AT_LOOPDEPTH
74
75 /**
76  * An association between a node and a point in time.
77  */
78 typedef struct loc_t {
79         ir_node          *node;
80         unsigned          time;     /**< A use time (see beuses.h). */
81         bool              spilled;  /**< the value was already spilled on this path */
82 } loc_t;
83
84 typedef struct _workset_t {
85         int   len;          /**< current length */
86         loc_t vals[0];      /**< inlined array of the values/distances in this working set */
87 } workset_t;
88
89 static struct obstack               obst;
90 static const arch_env_t            *arch_env;
91 static const arch_register_class_t *cls;
92 static const be_lv_t               *lv;
93 static be_loopana_t                *loop_ana;
94 static int                          n_regs;
95 static workset_t                   *ws;     /**< the main workset used while
96                                                      processing a block. */
97 static be_uses_t                   *uses;   /**< env for the next-use magic */
98 static ir_node                     *instr;  /**< current instruction */
99 static unsigned                     instr_nr; /**< current instruction number
100                                                        (relative to block start) */
101 static ir_nodeset_t                 used;
102 static spill_env_t                 *senv;   /**< see bespill.h */
103 static pdeq                        *worklist;
104
105 static bool                         move_spills      = true;
106 static bool                         respectloopdepth = true;
107 static bool                         improve_known_preds = true;
108 /* factor to weight the different costs of reloading/rematerializing a node
109    (see bespill.h be_get_reload_costs_no_weight) */
110 static int                          remat_bonus      = 10;
111
112 static const lc_opt_table_entry_t options[] = {
113         LC_OPT_ENT_BOOL   ("movespills", "try to move spills out of loops", &move_spills),
114         LC_OPT_ENT_BOOL   ("respectloopdepth", "exprimental (outermost loop cutting)", &respectloopdepth),
115         LC_OPT_ENT_BOOL   ("improveknownpreds", "experimental (known preds cutting)", &improve_known_preds),
116         LC_OPT_ENT_INT    ("rematbonus", "give bonus to rematerialisable nodes", &remat_bonus),
117         LC_OPT_LAST
118 };
119
120 static int loc_compare(const void *a, const void *b)
121 {
122         const loc_t *p = a;
123         const loc_t *q = b;
124         return p->time - q->time;
125 }
126
127 void workset_print(const workset_t *w)
128 {
129         int i;
130
131         for(i = 0; i < w->len; ++i) {
132                 ir_fprintf(stderr, "%+F %d\n", w->vals[i].node, w->vals[i].time);
133         }
134 }
135
136 /**
137  * Alloc a new workset on obstack @p ob with maximum size @p max
138  */
139 static workset_t *new_workset(void)
140 {
141         workset_t *res;
142         size_t     size = sizeof(*res) + n_regs * sizeof(res->vals[0]);
143
144         res  = obstack_alloc(&obst, size);
145         memset(res, 0, size);
146         return res;
147 }
148
149 /**
150  * Alloc a new instance on obstack and make it equal to @param workset
151  */
152 static workset_t *workset_clone(workset_t *workset)
153 {
154         workset_t *res;
155         size_t size = sizeof(*res) + n_regs * sizeof(res->vals[0]);
156         res = obstack_alloc(&obst, size);
157         memcpy(res, workset, size);
158         return res;
159 }
160
161 /**
162  * Copy workset @param src to @param tgt
163  */
164 static void workset_copy(workset_t *dest, const workset_t *src)
165 {
166         size_t size = sizeof(*src) + n_regs * sizeof(src->vals[0]);
167         memcpy(dest, src, size);
168 }
169
170 /**
171  * Overwrites the current content array of @param ws with the
172  * @param count locations given at memory @param locs.
173  * Set the length of @param ws to count.
174  */
175 static void workset_bulk_fill(workset_t *workset, int count, const loc_t *locs)
176 {
177         workset->len = count;
178         memcpy(&(workset->vals[0]), locs, count * sizeof(locs[0]));
179 }
180
181 /**
182  * Inserts the value @p val into the workset, iff it is not
183  * already contained. The workset must not be full.
184  */
185 static void workset_insert(workset_t *workset, ir_node *val, bool spilled)
186 {
187         loc_t *loc;
188         int    i;
189         /* check for current regclass */
190         assert(arch_irn_consider_in_reg_alloc(arch_env, cls, val));
191
192         /* check if val is already contained */
193         for (i = 0; i < workset->len; ++i) {
194                 loc = &workset->vals[i];
195                 if (loc->node == val) {
196                         if (spilled) {
197                                 loc->spilled = true;
198                         }
199                         return;
200                 }
201         }
202
203         /* insert val */
204         assert(workset->len < n_regs && "Workset already full!");
205         loc           = &workset->vals[workset->len];
206         loc->node     = val;
207         loc->spilled  = spilled;
208         loc->time     = TIME_UNDEFINED;
209         workset->len++;
210 }
211
212 /**
213  * Removes all entries from this workset
214  */
215 static void workset_clear(workset_t *workset)
216 {
217         workset->len = 0;
218 }
219
220 /**
221  * Removes the value @p val from the workset if present.
222  */
223 static INLINE void workset_remove(workset_t *workset, ir_node *val)
224 {
225         int i;
226         for(i = 0; i < workset->len; ++i) {
227                 if (workset->vals[i].node == val) {
228                         workset->vals[i] = workset->vals[--workset->len];
229                         return;
230                 }
231         }
232 }
233
234 static INLINE const loc_t *workset_contains(const workset_t *ws,
235                                             const ir_node *val)
236 {
237         int i;
238
239         for (i = 0; i < ws->len; ++i) {
240                 if (ws->vals[i].node == val)
241                         return &ws->vals[i];
242         }
243
244         return NULL;
245 }
246
247 /**
248  * Iterates over all values in the working set.
249  * @p ws The workset to iterate
250  * @p v  A variable to put the current value in
251  * @p i  An integer for internal use
252  */
253 #define workset_foreach(ws, v, i)       for(i=0; \
254                                                                                 v=(i < ws->len) ? ws->vals[i].node : NULL, i < ws->len; \
255                                                                                 ++i)
256
257 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
258 #define workset_get_time(ws, i) (ws)->vals[i].time
259 #define workset_set_length(ws, length) (ws)->len = length
260 #define workset_get_length(ws) ((ws)->len)
261 #define workset_get_val(ws, i) ((ws)->vals[i].node)
262 #define workset_sort(ws) qsort((ws)->vals, (ws)->len, sizeof((ws)->vals[0]), loc_compare);
263
264 typedef struct _block_info_t
265 {
266         workset_t *start_workset;
267         workset_t *end_workset;
268 } block_info_t;
269
270
271 static void *new_block_info(void)
272 {
273         block_info_t *res = obstack_alloc(&obst, sizeof(res[0]));
274         memset(res, 0, sizeof(res[0]));
275
276         return res;
277 }
278
279 #define get_block_info(block)        ((block_info_t *)get_irn_link(block))
280 #define set_block_info(block, info)  set_irn_link(block, info)
281
282 /**
283  * @return The distance to the next use or 0 if irn has dont_spill flag set
284  */
285 static INLINE unsigned get_distance(ir_node *from, unsigned from_step,
286                                     const ir_node *def, int skip_from_uses)
287 {
288         be_next_use_t use;
289         int           flags = arch_irn_get_flags(arch_env, def);
290         unsigned      costs;
291         unsigned      time;
292
293         assert(! (flags & arch_irn_flags_ignore));
294
295         use = be_get_next_use(uses, from, from_step, def, skip_from_uses);
296         if (USES_IS_INFINITE(use.time))
297                 return USES_INFINITY;
298
299         /* We have to keep nonspillable nodes in the workingset */
300         if (flags & arch_irn_flags_dont_spill)
301                 return 0;
302
303         /* give some bonus to rematerialisable nodes */
304         if (remat_bonus > 0) {
305                 costs = be_get_reload_costs_no_weight(senv, def, use.before);
306                 assert(costs * remat_bonus < 1000);
307                 time  = use.time + 1000 - (costs * remat_bonus);
308         }
309
310         return time;
311 }
312
313 /**
314  * Performs the actions necessary to grant the request that:
315  * - new_vals can be held in registers
316  * - as few as possible other values are disposed
317  * - the worst values get disposed
318  *
319  * @p is_usage indicates that the values in new_vals are used (not defined)
320  * In this case reloads must be performed
321  */
322 static void displace(workset_t *new_vals, int is_usage)
323 {
324         ir_node **to_insert = alloca(n_regs * sizeof(to_insert[0]));
325         bool     *spilled   = alloca(n_regs * sizeof(spilled[0]));
326         ir_node  *val;
327         int       i;
328         int       len;
329         int       spills_needed;
330         int       demand;
331         int       iter;
332
333         /* 1. Identify the number of needed slots and the values to reload */
334         demand = 0;
335         workset_foreach(new_vals, val, iter) {
336                 bool reloaded = false;
337
338                 /* mark value as used */
339                 if (is_usage)
340                         ir_nodeset_insert(&used, val);
341
342                 if (! workset_contains(ws, val)) {
343                         DB((dbg, DBG_DECIDE, "    insert %+F\n", val));
344                         if (is_usage) {
345                                 DB((dbg, DBG_SPILL, "Reload %+F before %+F\n", val, instr));
346                                 be_add_reload(senv, val, instr, cls, 1);
347                                 reloaded = true;
348                         }
349                 } else {
350                         DB((dbg, DBG_DECIDE, "    %+F already in workset\n", val));
351                         assert(is_usage);
352                         /* remove the value from the current workset so it is not accidently
353                          * spilled */
354                         workset_remove(ws, val);
355                 }
356                 spilled[demand]   = reloaded;
357                 to_insert[demand] = val;
358                 ++demand;
359         }
360
361         /* 2. Make room for at least 'demand' slots */
362         len           = workset_get_length(ws);
363         spills_needed = len + demand - n_regs;
364         assert(spills_needed <= len);
365
366         /* Only make more free room if we do not have enough */
367         if (spills_needed > 0) {
368                 ir_node   *curr_bb  = NULL;
369                 workset_t *ws_start = NULL;
370
371                 if (move_spills) {
372                         curr_bb  = get_nodes_block(instr);
373                         ws_start = get_block_info(curr_bb)->start_workset;
374                 }
375
376                 DB((dbg, DBG_DECIDE, "    disposing %d values\n", spills_needed));
377
378                 /* calculate current next-use distance for live values */
379                 for (i = 0; i < len; ++i) {
380                         ir_node  *val  = workset_get_val(ws, i);
381                         unsigned  dist = get_distance(instr, instr_nr, val, !is_usage);
382                         workset_set_time(ws, i, dist);
383                 }
384
385                 /* sort entries by increasing nextuse-distance*/
386                 workset_sort(ws);
387
388                 for (i = len - spills_needed; i < len; ++i) {
389                         ir_node *val = ws->vals[i].node;
390
391                         DB((dbg, DBG_DECIDE, "    disposing node %+F (%u)\n", val,
392                              workset_get_time(ws, i)));
393
394                         if (move_spills) {
395                                 if (!USES_IS_INFINITE(ws->vals[i].time)
396                                                 && !ws->vals[i].spilled) {
397                                         ir_node *after_pos = sched_prev(instr);
398                                         DB((dbg, DBG_DECIDE, "Spill %+F after node %+F\n", val,
399                                                 after_pos));
400                                         be_add_spill(senv, val, after_pos);
401                                 }
402                         } else {
403                                 /* Logic for not needed live-ins: If a value is disposed
404                                  * before its first use, remove it from start workset
405                                  * We don't do this for phis though     */
406                                 if (!is_Phi(val) && ! ir_nodeset_contains(&used, val)) {
407                                         workset_remove(ws_start, val);
408                                         DB((dbg, DBG_DECIDE, "    (and removing %+F from start workset)\n", val));
409                                 }
410                         }
411                 }
412
413                 /* kill the last 'demand' entries in the array */
414                 workset_set_length(ws, len - spills_needed);
415         }
416
417         /* 3. Insert the new values into the workset */
418         for (i = 0; i < demand; ++i) {
419                 ir_node *val = to_insert[i];
420
421                 workset_insert(ws, val, spilled[i]);
422         }
423 }
424
425 enum {
426         AVAILABLE_EVERYWHERE,
427         AVAILABLE_NOWHERE,
428         AVAILABLE_PARTLY,
429         AVAILABLE_UNKNOWN
430 };
431
432 static unsigned available_in_all_preds(workset_t* const* pred_worksets,
433                                        size_t n_pred_worksets,
434                                        const ir_node *value, bool is_local_phi)
435 {
436         size_t i;
437         bool   avail_everywhere = true;
438         bool   avail_nowhere    = true;
439
440         assert(n_pred_worksets > 0);
441
442         /* value available in all preds? */
443         for (i = 0; i < n_pred_worksets; ++i) {
444                 bool             found     = false;
445                 const workset_t *p_workset = pred_worksets[i];
446                 int              p_len     = workset_get_length(p_workset);
447                 int              p_i;
448                 const ir_node   *l_value;
449
450                 if (is_local_phi) {
451                         assert(is_Phi(value));
452                         l_value = get_irn_n(value, i);
453                 } else {
454                         l_value = value;
455                 }
456
457                 for (p_i = 0; p_i < p_len; ++p_i) {
458                         const loc_t *p_l = &p_workset->vals[p_i];
459                         if (p_l->node != l_value)
460                                 continue;
461
462                         found = true;
463                         break;
464                 }
465
466                 if (found) {
467                         avail_nowhere = false;
468                 } else {
469                         avail_everywhere = false;
470                 }
471         }
472
473         if (avail_everywhere) {
474                 assert(!avail_nowhere);
475                 return AVAILABLE_EVERYWHERE;
476         } else if (avail_nowhere) {
477                 return AVAILABLE_NOWHERE;
478         } else {
479                 return AVAILABLE_PARTLY;
480         }
481 }
482
483 /** Decides whether a specific node should be in the start workset or not
484  *
485  * @param env      belady environment
486  * @param first
487  * @param node     the node to test
488  * @param loop     the loop of the node
489  */
490 static loc_t to_take_or_not_to_take(ir_node* first, ir_node *node,
491                                     ir_loop *loop, unsigned available)
492 {
493         be_next_use_t next_use;
494         loc_t         loc;
495
496         loc.time    = USES_INFINITY;
497         loc.node    = node;
498         loc.spilled = false;
499
500         if (!arch_irn_consider_in_reg_alloc(arch_env, cls, node)) {
501                 loc.time = USES_INFINITY;
502                 return loc;
503         }
504
505         /* We have to keep nonspillable nodes in the workingset */
506         if (arch_irn_get_flags(arch_env, node) & arch_irn_flags_dont_spill) {
507                 loc.time = 0;
508                 DB((dbg, DBG_START, "    %+F taken (dontspill node)\n", node, loc.time));
509                 return loc;
510         }
511
512         next_use = be_get_next_use(uses, first, 0, node, 0);
513         if (USES_IS_INFINITE(next_use.time)) {
514                 // the nodes marked as live in shouldn't be dead, so it must be a phi
515                 assert(is_Phi(node));
516                 loc.time = USES_INFINITY;
517                 DB((dbg, DBG_START, "    %+F not taken (dead)\n", node));
518                 return loc;
519         }
520
521         loc.time = next_use.time;
522
523         if (improve_known_preds) {
524                 if (available == AVAILABLE_EVERYWHERE) {
525                         DB((dbg, DBG_START, "    %+F taken (%u, live in all preds)\n",
526                             node, loc.time));
527                         return loc;
528                 } else if(available == AVAILABLE_NOWHERE) {
529                         DB((dbg, DBG_START, "    %+F not taken (%u, live in no pred)\n",
530                             node, loc.time));
531                         loc.time = USES_INFINITY;
532                         return loc;
533                 }
534         }
535
536         if (!respectloopdepth || next_use.outermost_loop >= get_loop_depth(loop)) {
537                 DB((dbg, DBG_START, "    %+F taken (%u, loop %d)\n", node, loc.time,
538                     next_use.outermost_loop));
539         } else {
540                 loc.time = USES_PENDING;
541                 DB((dbg, DBG_START, "    %+F delayed (outerdepth %d < loopdepth %d)\n",
542                     node, next_use.outermost_loop, get_loop_depth(loop)));
543         }
544
545         return loc;
546 }
547
548 /**
549  * Computes the start-workset for a block with multiple predecessors. We assume
550  * that at least 1 of the predeccesors is a back-edge which means we're at the
551  * beginning of a loop. We try to reload as much values as possible now so they
552  * don't get reloaded inside the loop.
553  */
554 static void decide_start_workset(const ir_node *block)
555 {
556         ir_loop    *loop = get_irn_loop(block);
557         ir_node    *first;
558         ir_node    *node;
559         loc_t       loc;
560         loc_t      *starters;
561         loc_t      *delayed;
562         int         i, len, ws_count;
563         int             free_slots, free_pressure_slots;
564         unsigned    pressure;
565         int         arity;
566         workset_t **pred_worksets;
567         bool        all_preds_known;
568
569         /* check predecessors */
570         arity           = get_irn_arity(block);
571         pred_worksets   = alloca(sizeof(pred_worksets[0]) * arity);
572         all_preds_known = true;
573         for(i = 0; i < arity; ++i) {
574                 ir_node      *pred_block = get_Block_cfgpred_block(block, i);
575                 block_info_t *pred_info  = get_block_info(pred_block);
576
577                 if (pred_info == NULL) {
578                         pred_worksets[i] = NULL;
579                         all_preds_known  = false;
580                 } else {
581                         pred_worksets[i] = pred_info->end_workset;
582                 }
583         }
584
585         /* Collect all values living at start of block */
586         starters = NEW_ARR_F(loc_t, 0);
587         delayed  = NEW_ARR_F(loc_t, 0);
588
589         DB((dbg, DBG_START, "Living at start of %+F:\n", block));
590         first = sched_first(block);
591
592         /* check all Phis first */
593         sched_foreach(block, node) {
594                 unsigned available;
595
596                 if (! is_Phi(node))
597                         break;
598                 if (!arch_irn_consider_in_reg_alloc(arch_env, cls, node))
599                         continue;
600
601                 if (all_preds_known) {
602                         available = available_in_all_preds(pred_worksets, arity, node, true);
603                 } else {
604                         available = AVAILABLE_UNKNOWN;
605                 }
606
607                 loc = to_take_or_not_to_take(first, node, loop, available);
608
609                 if (! USES_IS_INFINITE(loc.time)) {
610                         if (USES_IS_PENDING(loc.time))
611                                 ARR_APP1(loc_t, delayed, loc);
612                         else
613                                 ARR_APP1(loc_t, starters, loc);
614                 } else {
615                         be_spill_phi(senv, node);
616                 }
617         }
618
619         /* check all Live-Ins */
620         be_lv_foreach(lv, block, be_lv_state_in, i) {
621                 ir_node *node = be_lv_get_irn(lv, block, i);
622                 unsigned available;
623
624                 if (all_preds_known) {
625                         available = available_in_all_preds(pred_worksets, arity, node, false);
626                 } else {
627                         available = AVAILABLE_UNKNOWN;
628                 }
629
630                 loc = to_take_or_not_to_take(first, node, loop, available);
631
632                 if (! USES_IS_INFINITE(loc.time)) {
633                         if (USES_IS_PENDING(loc.time))
634                                 ARR_APP1(loc_t, delayed, loc);
635                         else
636                                 ARR_APP1(loc_t, starters, loc);
637                 }
638         }
639
640         pressure            = be_get_loop_pressure(loop_ana, cls, loop);
641         assert(ARR_LEN(delayed) <= (signed)pressure);
642         free_slots          = n_regs - ARR_LEN(starters);
643         free_pressure_slots = n_regs - (pressure - ARR_LEN(delayed));
644         free_slots          = MIN(free_slots, free_pressure_slots);
645
646         /* so far we only put nodes into the starters list that are used inside
647          * the loop. If register pressure in the loop is low then we can take some
648          * values and let them live through the loop */
649         DB((dbg, DBG_START, "Loop pressure %d, taking %d delayed vals\n",
650             pressure, free_slots));
651         if (free_slots > 0) {
652                 qsort(delayed, ARR_LEN(delayed), sizeof(delayed[0]), loc_compare);
653
654                 for (i = 0; i < ARR_LEN(delayed) && free_slots > 0; ++i) {
655                         int    p, arity;
656                         loc_t *loc = & delayed[i];
657
658                         /* don't use values which are dead in a known predecessors
659                          * to not induce unnecessary reloads */
660                         arity = get_irn_arity(block);
661                         for (p = 0; p < arity; ++p) {
662                                 ir_node      *pred_block = get_Block_cfgpred_block(block, p);
663                                 block_info_t *pred_info  = get_block_info(pred_block);
664
665                                 if (pred_info == NULL)
666                                         continue;
667
668                                 if (!workset_contains(pred_info->end_workset, loc->node)) {
669                                         DB((dbg, DBG_START,
670                                             "    delayed %+F not live at pred %+F\n", loc->node,
671                                             pred_block));
672                                         goto skip_delayed;
673                                 }
674                         }
675
676                         DB((dbg, DBG_START, "    delayed %+F taken\n", loc->node));
677                         ARR_APP1(loc_t, starters, *loc);
678                         loc->node = NULL;
679                         --free_slots;
680                 skip_delayed:
681                         ;
682                 }
683         }
684
685         /* spill phis (the actual phis not just their values) that are in this block
686          * but not in the start workset */
687         for (i = ARR_LEN(delayed) - 1; i >= 0; --i) {
688                 ir_node *node = delayed[i].node;
689                 if (node == NULL || !is_Phi(node) || get_nodes_block(node) != block)
690                         continue;
691
692                 DB((dbg, DBG_START, "    spilling delayed phi %+F\n", node));
693                 be_spill_phi(senv, node);
694         }
695         DEL_ARR_F(delayed);
696
697         /* Sort start values by first use */
698         qsort(starters, ARR_LEN(starters), sizeof(starters[0]), loc_compare);
699
700         /* Copy the best ones from starters to start workset */
701         ws_count = MIN(ARR_LEN(starters), n_regs);
702         workset_clear(ws);
703         workset_bulk_fill(ws, ws_count, starters);
704
705         /* spill phis (the actual phis not just their values) that are in this block
706          * but not in the start workset */
707         len = ARR_LEN(starters);
708         for (i = ws_count; i < len; ++i) {
709                 ir_node *node = starters[i].node;
710                 if (! is_Phi(node) || get_nodes_block(node) != block)
711                         continue;
712
713                 DB((dbg, DBG_START, "    spilling phi %+F\n", node));
714                 be_spill_phi(senv, node);
715         }
716
717         DEL_ARR_F(starters);
718
719         /* determine spill status of the values: If there's 1 pred block (which
720          * is no backedge) where the value is spilled then we must set it to
721          * spilled here. */
722         for(i = 0; i < ws_count; ++i) {
723                 loc_t   *loc     = &ws->vals[i];
724                 ir_node *value   = loc->node;
725                 bool     spilled;
726                 int      n;
727
728                 /* phis from this block aren't spilled */
729                 if (get_nodes_block(value) == block) {
730                         assert(is_Phi(value));
731                         loc->spilled = false;
732                         continue;
733                 }
734
735                 /* determine if value was spilled on any predecessor */
736                 spilled = false;
737                 for(n = 0; n < arity; ++n) {
738                         workset_t *pred_workset = pred_worksets[n];
739                         int        p_len;
740                         int        p;
741
742                         if (pred_workset == NULL)
743                                 continue;
744
745                         p_len = workset_get_length(pred_workset);
746                         for(p = 0; p < p_len; ++p) {
747                                 loc_t *l = &pred_workset->vals[p];
748
749                                 if (l->node != value)
750                                         continue;
751
752                                 if (l->spilled) {
753                                         spilled = true;
754                                 }
755                                 break;
756                         }
757                 }
758
759                 loc->spilled = spilled;
760         }
761 }
762
763 /**
764  * For the given block @p block, decide for each values
765  * whether it is used from a register or is reloaded
766  * before the use.
767  */
768 static void belady(ir_node *block)
769 {
770         workset_t       *new_vals;
771         ir_node         *irn;
772         int              iter;
773         block_info_t    *block_info;
774         int              i, arity;
775         int              has_backedges = 0;
776         //int              first         = 0;
777         const ir_edge_t *edge;
778
779         /* no need to process a block twice */
780         if (get_block_info(block) != NULL) {
781                 return;
782         }
783
784         /* check if all predecessor blocks are processed yet (though for backedges
785          * we have to make an exception as we can't process them first) */
786         arity = get_Block_n_cfgpreds(block);
787         for(i = 0; i < arity; ++i) {
788                 ir_node      *pred_block = get_Block_cfgpred_block(block, i);
789                 block_info_t *pred_info  = get_block_info(pred_block);
790
791                 if (pred_info == NULL) {
792                         /* process predecessor first (it will be in the queue already) */
793                         if (!is_backedge(block, i)) {
794                                 return;
795                         }
796                         has_backedges = 1;
797                 }
798         }
799         (void) has_backedges;
800         if (arity == 0) {
801                 workset_clear(ws);
802         } else if (arity == 1) {
803                 ir_node      *pred_block = get_Block_cfgpred_block(block, 0);
804                 block_info_t *pred_info  = get_block_info(pred_block);
805
806                 assert(pred_info != NULL);
807                 workset_copy(ws, pred_info->end_workset);
808         } else {
809                 /* we need 2 heuristics here, for the case when all predecessor blocks
810                  * are known and when some are backedges (and therefore can't be known
811                  * yet) */
812                 decide_start_workset(block);
813         }
814
815         DB((dbg, DBG_DECIDE, "\n"));
816         DB((dbg, DBG_DECIDE, "Decide for %+F\n", block));
817
818         block_info = new_block_info();
819         set_block_info(block, block_info);
820
821         DB((dbg, DBG_WSETS, "Start workset for %+F:\n", block));
822         workset_foreach(ws, irn, iter) {
823                 DB((dbg, DBG_WSETS, "  %+F (%u)\n", irn,
824                      workset_get_time(ws, iter)));
825         }
826
827         block_info->start_workset = workset_clone(ws);
828
829         /* process the block from start to end */
830         DB((dbg, DBG_WSETS, "Processing...\n"));
831         ir_nodeset_init(&used);
832         instr_nr = 0;
833         /* TODO: this leaks (into the obstack)... */
834         new_vals = new_workset();
835
836         sched_foreach(block, irn) {
837                 int i, arity;
838                 assert(workset_get_length(ws) <= n_regs);
839
840                 /* Phis are no real instr (see insert_starters()) */
841                 if (is_Phi(irn)) {
842                         continue;
843                 }
844                 DB((dbg, DBG_DECIDE, "  ...%+F\n", irn));
845
846                 /* set instruction in the workset */
847                 instr = irn;
848
849                 /* allocate all values _used_ by this instruction */
850                 workset_clear(new_vals);
851                 for(i = 0, arity = get_irn_arity(irn); i < arity; ++i) {
852                         ir_node *in = get_irn_n(irn, i);
853                         if (!arch_irn_consider_in_reg_alloc(arch_env, cls, in))
854                                 continue;
855
856                         /* (note that "spilled" is irrelevant here) */
857                         workset_insert(new_vals, in, false);
858                 }
859                 displace(new_vals, 1);
860
861                 /* allocate all values _defined_ by this instruction */
862                 workset_clear(new_vals);
863                 if (get_irn_mode(irn) == mode_T) {
864                         const ir_edge_t *edge;
865
866                         foreach_out_edge(irn, edge) {
867                                 ir_node *proj = get_edge_src_irn(edge);
868                                 if (!arch_irn_consider_in_reg_alloc(arch_env, cls, proj))
869                                         continue;
870                                 workset_insert(new_vals, proj, false);
871                         }
872                 } else {
873                         if (!arch_irn_consider_in_reg_alloc(arch_env, cls, irn))
874                                 continue;
875                         workset_insert(new_vals, irn, false);
876                 }
877                 displace(new_vals, 0);
878
879                 instr_nr++;
880         }
881         ir_nodeset_destroy(&used);
882
883         /* Remember end-workset for this block */
884         block_info->end_workset = workset_clone(ws);
885         DB((dbg, DBG_WSETS, "End workset for %+F:\n", block));
886         workset_foreach(ws, irn, iter)
887                 DB((dbg, DBG_WSETS, "  %+F (%u)\n", irn,
888                      workset_get_time(ws, iter)));
889
890         /* add successor blocks into worklist */
891         foreach_block_succ(block, edge) {
892                 ir_node *succ = get_edge_src_irn(edge);
893                 pdeq_putr(worklist, succ);
894         }
895 }
896
897 /**
898  * 'decide' is block-local and makes assumptions
899  * about the set of live-ins. Thus we must adapt the
900  * live-outs to the live-ins at each block-border.
901  */
902 static void fix_block_borders(ir_node *block, void *data)
903 {
904         workset_t    *start_workset;
905         int           arity;
906         int           i;
907         int           iter;
908         (void) data;
909
910         DB((dbg, DBG_FIX, "\n"));
911         DB((dbg, DBG_FIX, "Fixing %+F\n", block));
912
913         start_workset = get_block_info(block)->start_workset;
914
915         /* process all pred blocks */
916         arity = get_irn_arity(block);
917         for (i = 0; i < arity; ++i) {
918                 ir_node   *pred = get_Block_cfgpred_block(block, i);
919                 workset_t *pred_end_workset = get_block_info(pred)->end_workset;
920                 ir_node   *node;
921
922                 DB((dbg, DBG_FIX, "  Pred %+F\n", pred));
923
924                 /* spill all values not used anymore */
925                 workset_foreach(pred_end_workset, node, iter) {
926                         ir_node *n2;
927                         int      iter2;
928                         bool     found = false;
929                         workset_foreach(start_workset, n2, iter2) {
930                                 if (n2 == node) {
931                                         found = true;
932                                         break;
933                                 }
934                                 /* note that we do not look at phi inputs, becuase the values
935                                  * will be either live-end and need no spill or
936                                  * they have other users in which must be somewhere else in the
937                                  * workset */
938                         }
939
940                         if (found)
941                                 continue;
942
943                         if (move_spills && be_is_live_in(lv, block, node)
944                                         && !pred_end_workset->vals[iter].spilled) {
945                                 ir_node *insert_point;
946                                 if (arity > 1) {
947                                         insert_point = be_get_end_of_block_insertion_point(pred);
948                                         insert_point = sched_prev(insert_point);
949                                 } else {
950                                         insert_point = block;
951                                 }
952                                 DB((dbg, DBG_SPILL, "Spill %+F after %+F\n", node,
953                                      insert_point));
954                                 be_add_spill(senv, node, insert_point);
955                         }
956                 }
957
958                 /* reload missing values in predecessors, add missing spills */
959                 workset_foreach(start_workset, node, iter) {
960                         const loc_t *l    = &start_workset->vals[iter];
961                         const loc_t *pred_loc;
962
963                         /* if node is a phi of the current block we reload
964                          * the corresponding argument, else node itself */
965                         if (is_Phi(node) && get_nodes_block(node) == block) {
966                                 node = get_irn_n(node, i);
967                                 assert(!l->spilled);
968
969                                 /* we might have unknowns as argument for the phi */
970                                 if (!arch_irn_consider_in_reg_alloc(arch_env, cls, node))
971                                         continue;
972                         }
973
974                         /* check if node is in a register at end of pred */
975                         pred_loc = workset_contains(pred_end_workset, node);
976                         if (pred_loc != NULL) {
977                                 /* we might have to spill value on this path */
978                                 if (move_spills && !pred_loc->spilled && l->spilled) {
979                                         ir_node *insert_point
980                                                 = be_get_end_of_block_insertion_point(pred);
981                                         insert_point = sched_prev(insert_point);
982                                         DB((dbg, DBG_SPILL, "Spill %+F after %+F\n", node,
983                                             insert_point));
984                                         be_add_spill(senv, node, insert_point);
985                                 }
986                         } else {
987                                 /* node is not in register at the end of pred -> reload it */
988                                 DB((dbg, DBG_FIX, "    reload %+F\n", node));
989                                 DB((dbg, DBG_SPILL, "Reload %+F before %+F,%d\n", node, block, i));
990                                 be_add_reload_on_edge(senv, node, block, i, cls, 1);
991                         }
992                 }
993         }
994 }
995
996 static void be_spill_belady(be_irg_t *birg, const arch_register_class_t *rcls)
997 {
998         ir_graph *irg = be_get_birg_irg(birg);
999
1000         be_liveness_assure_sets(be_assure_liveness(birg));
1001
1002         /* construct control flow loop tree */
1003         if (! (get_irg_loopinfo_state(irg) & loopinfo_cf_consistent)) {
1004                 construct_cf_backedges(irg);
1005         }
1006
1007         be_clear_links(irg);
1008
1009         /* init belady env */
1010         obstack_init(&obst);
1011         arch_env = birg->main_env->arch_env;
1012         cls      = rcls;
1013         lv       = be_get_birg_liveness(birg);
1014         n_regs   = cls->n_regs - be_put_ignore_regs(birg, cls, NULL);
1015         ws       = new_workset();
1016         uses     = be_begin_uses(irg, lv);
1017         loop_ana = be_new_loop_pressure(birg);
1018         senv     = be_new_spill_env(birg);
1019         worklist = new_pdeq();
1020
1021         pdeq_putr(worklist, get_irg_start_block(irg));
1022
1023         while(!pdeq_empty(worklist)) {
1024                 ir_node *block = pdeq_getl(worklist);
1025                 belady(block);
1026         }
1027         /* end block might not be reachable in endless loops */
1028         belady(get_irg_end_block(irg));
1029
1030         del_pdeq(worklist);
1031
1032         /* belady was block-local, fix the global flow by adding reloads on the
1033          * edges */
1034         irg_block_walk_graph(irg, fix_block_borders, NULL, NULL);
1035
1036         /* Insert spill/reload nodes into the graph and fix usages */
1037         be_insert_spills_reloads(senv);
1038
1039         /* clean up */
1040         be_delete_spill_env(senv);
1041         be_end_uses(uses);
1042         be_free_loop_pressure(loop_ana);
1043         obstack_free(&obst, NULL);
1044 }
1045
1046 void be_init_spillbelady(void)
1047 {
1048         lc_opt_entry_t *be_grp       = lc_opt_get_grp(firm_opt_get_root(), "be");
1049         lc_opt_entry_t *belady_group = lc_opt_get_grp(be_grp, "belady");
1050         lc_opt_add_table(belady_group, options);
1051
1052         static be_spiller_t belady_spiller = {
1053                 be_spill_belady
1054         };
1055
1056         be_register_spiller("belady", &belady_spiller);
1057         FIRM_DBG_REGISTER(dbg, "firm.be.spill.belady");
1058 }
1059
1060 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spillbelady);