adapted to interface changes
[libfirm] / ir / be / bespillbelady.c
1 /**
2  * Author:      Daniel Grund
3  * Date:                20.09.2005
4  * Copyright:   (c) Universitaet Karlsruhe
5  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
6  *
7  * NOTE: Comments my be (partially) wrong, since there was a major bug
8  *       (spilling of phis, prespill) whose fixing changed a lot.
9  */
10 #ifdef HAVE_CONFIG_H
11 #include "config.h"
12 #endif
13
14 #ifdef HAVE_ALLOCA_H
15 #include <alloca.h>
16 #endif
17
18 #ifdef HAVE_MALLOC_H
19 #include <malloc.h>
20 #endif
21
22 #include "obst.h"
23 #include "set.h"
24 #include "pset.h"
25 #include "irgraph.h"
26 #include "irnode.h"
27 #include "irmode.h"
28 #include "irgwalk.h"
29 #include "iredges_t.h"
30 #include "ircons_t.h"
31
32 #include "beutil.h"
33 #include "bearch.h"
34 #include "bespillbelady.h"
35 #include "beuses_t.h"
36 #include "besched_t.h"
37 #include "beirgmod.h"
38 #include "belive_t.h"
39 #include "benode_t.h"
40 #include "bechordal_t.h"
41
42 #define DBG_SPILL   1
43 #define DBG_WSETS   2
44 #define DBG_FIX     4
45 #define DBG_DECIDE  8
46 #define DBG_START  16
47 #define DBG_SLOTS  32
48 #define DBG_TRACE  64
49 #define DEBUG_LVL 0 //(DBG_START | DBG_DECIDE | DBG_WSETS | DBG_FIX | DBG_SPILL)
50 static firm_dbg_module_t *dbg = NULL;
51
52 #define MIN(a,b) (((a)<(b))?(a):(b))
53 #undef SINGLE_START_PROJS
54
55 typedef struct _workset_t workset_t;
56
57 typedef struct _belady_env_t {
58         struct obstack ob;
59         const arch_env_t *arch;
60         const arch_register_class_t *cls;
61         int n_regs;                     /** number of regs in this reg-class */
62
63         workset_t *ws;          /**< the main workset used while processing a block. ob-allocated */
64         be_uses_t *uses;        /**< env for the next-use magic */
65         ir_node *instr;         /**< current instruction */
66         unsigned instr_nr;      /**< current instruction number (relative to block start) */
67         pset *used;                     /**< holds the values used (so far) in the current BB */
68         pset *copies;           /**< holds all copies placed due to phi-spilling */
69
70         spill_env_t *senv;      /* see bespill.h */
71         pset *reloads;          /**< all reload nodes placed */
72 } belady_env_t;
73
74 struct _workset_t {
75         belady_env_t *bel;
76         int len;                        /**< current length */
77         loc_t vals[1];          /**< inlined array of the values/distances in this working set */
78 };
79
80 typedef struct _block_info_t {
81         workset_t *ws_start, *ws_end;
82 } block_info_t;
83
84 /**
85  * Alloc a new workset on obstack @p ob with maximum size @p max
86  */
87 static INLINE workset_t *new_workset(struct obstack *ob, belady_env_t *bel) {
88         workset_t *res;
89         size_t size = sizeof(*res) + (bel->n_regs-1)*sizeof(res->vals[0]);
90         res = obstack_alloc(ob, size);
91         memset(res, 0, size);
92         res->bel = bel;
93         return res;
94 }
95
96 /**
97  * Alloc a new instance on obstack and make it equal to @param ws
98  */
99 static INLINE workset_t *workset_clone(struct obstack *ob, workset_t *ws) {
100         workset_t *res;
101         size_t size = sizeof(*res) + (ws->bel->n_regs-1)*sizeof(res->vals[0]);
102         res = obstack_alloc(ob, size);
103         memcpy(res, ws, size);
104         return res;
105 }
106
107 /**
108  * Do NOT alloc anything. Make @param tgt equal to @param src.
109  * returns @param tgt for convinience
110  */
111 static INLINE workset_t *workset_copy(workset_t *tgt, workset_t *src) {
112         size_t size = sizeof(*src) + (src->bel->n_regs-1)*sizeof(src->vals[0]);
113         memcpy(tgt, src, size);
114         return tgt;
115 }
116
117 /**
118  * Overwrites the current content array of @param ws with the
119  * @param count locations given at memory @param locs.
120  * Set the length of @param ws to count.
121  */
122 #define workset_bulk_fill(ws, count, locs) memcpy(&(ws)->vals[0], locs, ((ws)->len=count)*sizeof(locs[0]));
123
124
125 /**
126  * Inserts the value @p val into the workset, iff it is not
127  * already contained. The workset must not be full.
128  */
129 static INLINE void workset_insert(workset_t *ws, ir_node *val) {
130         int i;
131         /* check for current regclass */
132         if (arch_get_irn_reg_class(ws->bel->arch, val, -1) != ws->bel->cls) {
133                 DBG((dbg, DBG_DECIDE, "Dropped %+F\n", val));
134                 return;
135         }
136
137         /* check if val is already contained */
138         for(i=0; i<ws->len; ++i)
139                 if (ws->vals[i].irn == val)
140                         return;
141
142         /* insert val */
143         assert(ws->len < ws->bel->n_regs && "Workset already full!");
144         ws->vals[ws->len++].irn = val;
145 }
146
147 /**
148  * Inserts all values in array @p vals of length @p cnt
149  * into the workset. There must be enough space for the
150  * entries.
151  */
152 static INLINE void workset_bulk_insert(workset_t *ws, int cnt, ir_node **vals) {
153         int i, o;
154
155         for(o=0; o<cnt; ++o) {
156                 ir_node *val = vals[o];
157                 DBG((dbg, DBG_TRACE, "Bulk insert %+F\n", val));
158                 /* check for current regclass */
159                 if (arch_get_irn_reg_class(ws->bel->arch, val, -1) != ws->bel->cls) {
160                         DBG((dbg, DBG_TRACE, "Wrong reg class\n"));
161                         goto no_insert;
162                 }
163
164                 /* check if val is already contained */
165                 for(i=0; i<ws->len; ++i)
166                         if (ws->vals[i].irn == val) {
167                                 DBG((dbg, DBG_TRACE, "Already contained\n"));
168                                 goto no_insert;
169                         }
170
171                 /* insert val */
172                 assert(ws->len < ws->bel->n_regs && "Workset does not have enough room!");
173                 ws->vals[ws->len++].irn = val;
174                 DBG((dbg, DBG_TRACE, "Inserted\n"));
175
176 no_insert:
177                 /*epsilon statement :)*/;
178         }
179 }
180
181 /**
182  * Removes all entries from this workset
183  */
184 #define workset_clear(ws) (ws)->len = 0;
185
186 /**
187  * Removes the value @p val from the workset if present.
188  */
189 static INLINE void workset_remove(workset_t *ws, ir_node *val) {
190         int i;
191         for(i=0; i<ws->len; ++i)
192                 if (ws->vals[i].irn == val) {
193                         ws->vals[i] = ws->vals[--ws->len];
194                         return;
195                 }
196 }
197
198 static INLINE int workset_contains(const workset_t *ws, const ir_node *val) {
199         int i;
200         for(i=0; i<ws->len; ++i)
201                 if (ws->vals[i].irn == val)
202                         return 1;
203         return 0;
204 }
205
206 /**
207  * Iterates over all values in the working set.
208  * @p ws The workset to iterate
209  * @p v  A variable to put the current value in
210  * @p i  An integer for internal use
211  */
212 #define workset_foreach(ws, v, i)       for(i=0; \
213                                                                                 v=(i < ws->len) ? ws->vals[i].irn : NULL, i < ws->len; \
214                                                                                 ++i)
215
216 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
217 #define workset_set_length(ws, length) (ws)->len = length
218 #define workset_get_length(ws) ((ws)->len)
219 #define workset_get_val(ws, i) ((ws)->vals[i].irn)
220 #define workset_sort(ws) qsort((ws)->vals, (ws)->len, sizeof((ws)->vals[0]), loc_compare);
221
222
223 static int is_mem_phi(const ir_node *irn, void *data) {
224         workset_t *sws;
225         ir_node *blk = get_nodes_block(irn);
226
227         DBG((dbg, DBG_SPILL, "Is %+F a mem-phi?\n", irn));
228         sws = ((block_info_t *) get_irn_link(blk))->ws_start;
229         DBG((dbg, DBG_SPILL, "  %d\n", !workset_contains(sws, irn)));
230         return !workset_contains(sws, irn);
231 }
232
233 /**
234  * @return The distance to the next use
235  *         Or 0 if irn is an ignore node
236  */
237 #define get_distance(bel, from, from_step, def, skip_from_uses) \
238                 ((arch_irn_is_ignore(bel->arch, def) ) ? 0 : be_get_next_use(bel->uses, from, from_step, def, skip_from_uses))
239
240
241 /**
242  * Collects all values live-in at block @p blk and all phi results in this block.
243  * Then it adds the best values (at most n_regs) to the blocks start_workset.
244  * The phis among the remaining values get spilled: Introduce psudo-copies of
245  *  their args to break interference and make it possible to spill them to the
246  *  same spill slot.
247  */
248 static void compute_block_start_info(ir_node *blk, void *env) {
249         belady_env_t *bel = env;
250         block_info_t *blk_info;
251         ir_node *irn, *first;
252         irn_live_t *li;
253         int i, count, ws_count;
254         loc_t loc, *starters;
255         ir_graph *irg = get_irn_irg(blk);
256         struct obstack ob;
257
258         obstack_init(&ob);
259
260         /* Get all values living at the block start */
261         DBG((dbg, DBG_START, "Living at start of %+F:\n", blk));
262         first = sched_first(blk);
263         count = 0;
264         sched_foreach(blk, irn)
265                 if (is_Phi(irn) && arch_get_irn_reg_class(bel->arch, irn, -1) == bel->cls) {
266                         loc.irn = irn;
267                         loc.time = get_distance(bel, first, 0, irn, 0);
268                         obstack_grow(&ob, &loc, sizeof(loc));
269                         DBG((dbg, DBG_START, "    %+F:\n", irn));
270                         count++;
271                 } else
272                         break;
273
274         live_foreach(blk, li)
275                 if (live_is_in(li) && arch_get_irn_reg_class(bel->arch, li->irn, -1) == bel->cls) {
276                         loc.irn = (ir_node *)li->irn;
277                         loc.time = get_distance(bel, first, 0, li->irn, 0);
278                         obstack_grow(&ob, &loc, sizeof(loc));
279                         DBG((dbg, DBG_START, "    %+F:\n", irn));
280                         count++;
281                 }
282         starters = obstack_finish(&ob);
283
284         /* Sort all values */
285         qsort(starters, count, sizeof(starters[0]), loc_compare);
286
287         /* Create the start workset for this block. Copy the best ones from starters */
288         blk_info = obstack_alloc(&bel->ob, sizeof(*blk_info));
289         set_irn_link(blk, blk_info);
290
291         ws_count = MIN(count, bel->n_regs);
292         blk_info->ws_start = new_workset(&bel->ob, bel);
293         workset_bulk_fill(blk_info->ws_start, ws_count, starters);
294
295         /* Spill the phis among the remaining values */
296         for (i=ws_count; i<count; ++i) {
297                 int o, max;
298
299                 irn = starters[i].irn;
300                 if (!is_Phi(irn) || get_nodes_block(irn) != blk)
301                         continue;
302
303                 DBG((dbg, DBG_START, "For %+F:\n", irn));
304
305                 for (max=get_irn_arity(irn), o=0; o<max; ++o) {
306                         ir_node *arg = get_irn_n(irn, o);
307                         ir_node *pred_block = get_Block_cfgpred_block(get_nodes_block(irn), o);
308                         ir_node *cpy = be_new_Copy(bel->cls, irg, pred_block, arg);
309                         pset_insert_ptr(bel->copies, cpy);
310                         DBG((dbg, DBG_START, "    place a %+F of %+F in %+F\n", cpy, arg, pred_block));
311                         sched_add_before(pred_block, cpy);
312                         set_irn_n(irn, o, cpy);
313                 }
314         }
315
316         obstack_free(&ob, NULL);
317 }
318
319 /**
320  * Performs the actions neccessary to grant the request that:
321  * - new_vals can be held in registers
322  * - as few as possible other values are disposed
323  * - the worst values get disposed
324  *
325  * @p is_usage indicates that the values in new_vals are used (not defined)
326  * In this case reloads must be performed
327  */
328 static void displace(belady_env_t *bel, workset_t *new_vals, int is_usage) {
329         ir_node *val;
330         int i, len, max_allowed, demand, iter;
331         workset_t *ws = bel->ws;
332         ir_node **to_insert = alloca(bel->n_regs * sizeof(*to_insert));
333
334         /*
335          * 1. Identify the number of needed slots and the values to reload
336          */
337         demand = 0;
338         workset_foreach(new_vals, val, iter) {
339                 /* mark value as used */
340                 if (is_usage)
341                         pset_insert_ptr(bel->used, val);
342
343                 if (!workset_contains(ws, val)) {
344                         DBG((dbg, DBG_DECIDE, "    insert %+F\n", val));
345                         to_insert[demand++] = val;
346                         if (is_usage)
347                                 be_add_reload(bel->senv, val, bel->instr);
348                 } else
349                         DBG((dbg, DBG_DECIDE, "    skip %+F\n", val));
350         }
351         DBG((dbg, DBG_DECIDE, "    demand = %d\n", demand));
352
353
354         /*
355          * 2. Make room for at least 'demand' slots
356          */
357         len = workset_get_length(ws);
358         max_allowed = bel->n_regs - demand;
359
360         /* Only make more free room if we do not have enough */
361         if (len > max_allowed) {
362                 /* get current next-use distance */
363                 for (i=0; i<ws->len; ++i)
364                         workset_set_time(ws, i, get_distance(bel, bel->instr, bel->instr_nr, workset_get_val(ws, i), !is_usage));
365
366                 /* sort entries by increasing nextuse-distance*/
367                 workset_sort(ws);
368
369                 /* Logic for not needed live-ins: If a value is disposed
370                    before its first usage, remove it from start workset */
371                 for (i=max_allowed; i<ws->len; ++i) {
372                         ir_node *irn = ws->vals[i].irn;
373                         if (!pset_find_ptr(bel->used, irn)) {
374                                 ir_node *curr_bb = get_nodes_block(bel->instr);
375                                 workset_t *ws_start = ((block_info_t *) get_irn_link(curr_bb))->ws_start;
376                                 workset_remove(ws_start, irn);
377
378                                 DBG((dbg, DBG_DECIDE, "    dispose %+F dumb\n", irn));
379                         } else
380                                 DBG((dbg, DBG_DECIDE, "    dispose %+F\n", irn));
381                 }
382
383                 /* kill the last 'demand' entries in the array */
384                 workset_set_length(ws, max_allowed);
385         }
386
387         /*
388          * 3. Insert the new values into the workset
389          */
390         workset_bulk_insert(bel->ws, demand, to_insert);
391 }
392
393 /**
394  * For the given block @p blk, decide for each values
395  * whether it is used from a register or is reloaded
396  * before the use.
397  */
398 static void belady(ir_node *blk, void *env) {
399         belady_env_t *bel = env;
400         workset_t *new_vals;
401         ir_node *irn;
402         int iter;
403
404 #ifdef SINGLE_START_PROJS
405         ir_node *start_blk = get_irg_start_block(get_irn_irg(blk));
406 #endif
407         block_info_t *blk_info = get_irn_link(blk);
408
409         DBG((dbg, DBG_DECIDE, "\n"));
410         DBG((dbg, DBG_DECIDE, "Decide for %+F\n", blk));
411
412         workset_copy(bel->ws, blk_info->ws_start);
413         DBG((dbg, DBG_WSETS, "Initial start workset for %+F:\n", blk));
414         workset_foreach(bel->ws, irn, iter)
415                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
416
417         /* process the block from start to end */
418         DBG((dbg, DBG_WSETS, "Processing...\n"));
419         bel->used = pset_new_ptr(32);
420         bel->instr_nr = 0;
421         new_vals = new_workset(&bel->ob, bel);
422         sched_foreach(blk, irn) {
423                 assert(workset_get_length(bel->ws) <= bel->n_regs && "Too much values in workset!");
424
425
426 #ifdef SINGLE_START_PROJS
427                 if (is_Phi(irn) ||
428                         (is_Proj(irn) && blk!=start_blk) ||
429                         (get_irn_mode(irn) == mode_T && blk==start_blk)) {
430                         DBG((dbg, DBG_DECIDE, "  ...%+F skipped\n", irn));
431                         continue;
432                 }
433 #else
434                 /* projs are handled with the tuple value.
435                  * Phis are no real instr (see insert_starters)
436                  * instr_nr does not increase */
437                 if (is_Proj(irn) || is_Phi(irn)) {
438                         DBG((dbg, DBG_DECIDE, "  ...%+F skipped\n", irn));
439                         continue;
440                 }
441 #endif
442                 DBG((dbg, DBG_DECIDE, "  ...%+F\n", irn));
443
444                 /* set instruction in the workset */
445                 bel->instr = irn;
446
447                 /* allocate all values _used_ by this instruction */
448                 workset_clear(new_vals);
449                 workset_bulk_insert(new_vals, get_irn_arity(irn)+1, get_irn_in(irn));
450                 displace(bel, new_vals, 1);
451
452                 /* allocate all values _defined_ by this instruction */
453                 workset_clear(new_vals);
454                 if (get_irn_mode(irn) == mode_T) { /* special handling for tuples and projs */
455                         ir_node *proj;
456                         for(proj=sched_next(irn); is_Proj(proj); proj=sched_next(proj))
457                                 workset_insert(new_vals, proj);
458                 } else {
459                         workset_insert(new_vals, irn);
460                 }
461                 displace(bel, new_vals, 0);
462
463                 bel->instr_nr++;
464         }
465         del_pset(bel->used);
466
467         /* Remember end-workset for this block */
468         blk_info->ws_end = workset_clone(&bel->ob, bel->ws);
469         DBG((dbg, DBG_WSETS, "Start workset for %+F:\n", blk));
470         workset_foreach(blk_info->ws_start, irn, iter)
471                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
472         DBG((dbg, DBG_WSETS, "End workset for %+F:\n", blk));
473         workset_foreach(blk_info->ws_end, irn, iter)
474                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
475 }
476
477 /**
478  * 'decide' is block-local and makes assumptions
479  * about the set of live-ins. Thus we must adapt the
480  * live-outs to the live-ins at each block-border.
481  */
482 static void fix_block_borders(ir_node *blk, void *env) {
483         workset_t *wsb;
484         belady_env_t *bel = env;
485         int i, max, iter, iter2;
486
487         DBG((dbg, DBG_FIX, "\n"));
488         DBG((dbg, DBG_FIX, "Fixing %+F\n", blk));
489
490         wsb = ((block_info_t *)get_irn_link(blk))->ws_start;
491
492         /* process all pred blocks */
493         for (i=0, max=get_irn_arity(blk); i<max; ++i) {
494                 ir_node *irnb, *irnp, *pred = get_Block_cfgpred_block(blk, i);
495                 workset_t *wsp = ((block_info_t *)get_irn_link(pred))->ws_end;
496
497                 DBG((dbg, DBG_FIX, "  Pred %+F\n", pred));
498
499                 workset_foreach(wsb, irnb, iter) {
500                         /* if irnb is a phi of the current block we reload
501                          * the corresponding argument, else irnb itself */
502                         if(is_Phi(irnb) && blk == get_nodes_block(irnb))
503                                 irnb = get_irn_n(irnb, i);
504
505                         /* Unknowns are available everywhere */
506                         if(get_irn_opcode(irnb) == iro_Unknown)
507                                 continue;
508
509                         /* check if irnb is in a register at end of pred */
510                         workset_foreach(wsp, irnp, iter2)
511                                 if (irnb == irnp)
512                                         goto next_value;
513
514                         /* irnb is in memory at the end of pred, so we have to reload it */
515                         DBG((dbg, DBG_FIX, "    reload %+F\n", irnb));
516                         be_add_reload_on_edge(bel->senv, irnb, blk, i);
517
518 next_value:
519                         /*epsilon statement :)*/;
520                 }
521         }
522 }
523
524 /**
525  * Removes all used reloads from bel->reloads.
526  * The remaining nodes in bel->reloads will be removed from the graph.
527  */
528 static void rescue_used_reloads(ir_node *irn, void *env) {
529         pset *rlds = (pset *)env;
530         if (pset_find_ptr(rlds, irn))
531                 pset_remove_ptr(rlds, irn);
532 }
533
534 /**
535  * Removes all copies introduced for phi-spills
536  */
537 static void remove_copies(belady_env_t *bel) {
538         ir_node *irn;
539
540         for (irn = pset_first(bel->copies); irn; irn = pset_next(bel->copies)) {
541                 ir_node *src, *spill;
542
543                 assert(be_is_Copy(irn));
544                 assert(get_irn_n_edges(irn) == 1 && "This is not a copy introduced in 'compute_block_start_info()'. Who created it?");
545
546                 spill = get_irn_edge(get_irn_irg(irn), irn, 0)->src;
547                 assert(be_is_Spill(spill) && "This is not a copy introduced in 'compute_block_start_info()'. Who created it?");
548
549                 src = get_irn_n(irn, 0);
550                 set_irn_n(spill, 0, src);
551         }
552 }
553
554 /**
555  * Finds all unused reloads and remove them from the schedule
556  * Also removes spills if they are not used anymore after removing reloads
557  */
558 static void remove_unused_reloads(ir_graph *irg, belady_env_t *bel) {
559         ir_node *irn;
560
561         irg_walk_graph(irg, rescue_used_reloads, NULL, bel->reloads);
562         for(irn = pset_first(bel->reloads); irn; irn = pset_next(bel->reloads)) {
563                 ir_node *spill;
564                 DBG((dbg, DBG_SPILL, "Removing %+F before %+F in %+F\n", irn, sched_next(irn), get_nodes_block(irn)));
565
566                 spill = get_irn_n(irn, 0);
567
568                 /* remove reload */
569                 set_irn_n(irn, 0, new_Bad());
570                 sched_remove(irn);
571
572                 /* if spill not used anymore, remove it too
573                  * test of regclass is necessary since spill may be a phi-M */
574                 if (get_irn_n_edges(spill) == 0 && bel->cls == arch_get_irn_reg_class(bel->arch, spill, -1)) {
575                         set_irn_n(spill, 0, new_Bad());
576                         sched_remove(spill);
577                 }
578         }
579 }
580
581 void be_spill_belady(const be_chordal_env_t *chordal_env) {
582         belady_env_t bel;
583
584         dbg = firm_dbg_register("ir.be.spillbelady");
585
586         /* init belady env */
587         obstack_init(&bel.ob);
588         bel.arch    = chordal_env->main_env->arch_env;
589         bel.cls     = chordal_env->cls;
590         bel.n_regs  = arch_register_class_n_regs(bel.cls);
591         bel.ws      = new_workset(&bel.ob, &bel);
592         bel.uses    = be_begin_uses(chordal_env->irg, chordal_env->main_env->arch_env, bel.cls);
593         bel.senv    = be_new_spill_env(dbg, chordal_env, is_mem_phi, NULL);
594         bel.reloads = pset_new_ptr_default();
595         bel.copies  = pset_new_ptr_default();
596
597         DBG((dbg, LEVEL_1, "running on register class: %s\n", bel.cls->name));
598
599         /* do the work */
600         irg_block_walk_graph(chordal_env->irg, compute_block_start_info, NULL, &bel);
601         irg_block_walk_graph(chordal_env->irg, belady, NULL, &bel);
602         irg_block_walk_graph(chordal_env->irg, fix_block_borders, NULL, &bel);
603         be_insert_spills_reloads(bel.senv, bel.reloads);
604         remove_unused_reloads(chordal_env->irg, &bel);
605         remove_copies(&bel);
606
607
608
609         /* clean up */
610         del_pset(bel.reloads);
611         be_delete_spill_env(bel.senv);
612         be_end_uses(bel.uses);
613         obstack_free(&bel.ob, NULL);
614 }