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