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