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