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