*** empty log message ***
[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
8 #include <alloca.h>
9 #include "obst.h"
10 #include "set.h"
11 #include "pset.h"
12 #include "irgraph.h"
13 #include "irnode.h"
14 #include "irmode.h"
15 #include "ircons.h"
16 #include "irgwalk.h"
17 #include "iredges_t.h"
18
19 #include "beutil.h"
20 #include "bearch.h"
21 #include "bespillbelady.h"
22 #include "beuses_t.h"
23 #include "besched_t.h"
24 #include "beirgmod.h"
25 #include "belive_t.h"
26 #include "benode_t.h"
27
28 #define MIN(a,b) (((a)<(b))?(a):(b))
29
30 #define DBG_DECIDE 1
31 #define DBG_WSETS 2
32 #define DBG_FIX 4
33 #define DBG_SPILL 8
34 #define DBG_START 16
35 #define DBG_TRACE 32
36 #define DEBUG_LVL (DBG_START | DBG_DECIDE | DBG_WSETS | DBG_FIX | DBG_SPILL)
37 static firm_dbg_module_t *dbg = NULL;
38
39 typedef struct _workset_t workset_t;
40
41 typedef struct _belady_env_t {
42         struct obstack ob;
43         const be_node_factory_t *factory;
44         const arch_env_t *arch;
45         const arch_register_class_t *cls;
46         int n_regs;                     /** number of regs in this reg-class */
47
48         workset_t *ws;          /**< the main workset used while processing a block. ob-allocated */
49         be_uses_t *uses;        /**< env for the next-use magic */
50         ir_node *instr;         /**< current instruction */
51         unsigned instr_nr;      /**< current instruction number (relative to block start) */
52         pset *used;                     /**< holds the values used (so far) in the current BB */
53
54         spill_env_t *senv;      /* see bespill.h */
55         pset *reloads;          /**< all reload nodes placed */
56 } belady_env_t;
57
58 struct _workset_t {
59         belady_env_t *bel;
60         int i;                          /**< used for iteration */
61         int len;                        /**< current length */
62         loc_t vals[1];          /**< inlined array of the values/distances in this working set */
63 };
64
65 typedef struct _block_info_t {
66         workset_t *ws_start, *ws_end;
67 } block_info_t;
68
69 /**
70  * Alloc a new workset on obstack @p ob with maximum size @p max
71  */
72 static INLINE workset_t *new_workset(struct obstack *ob, belady_env_t *bel) {
73         workset_t *res;
74         size_t size = sizeof(*res) + (bel->n_regs-1)*sizeof(res->vals[0]);
75         res = obstack_alloc(ob, size);
76         memset(res, 0, size);
77         res->bel = bel;
78         return res;
79 }
80
81 static INLINE workset_t *workset_clone(struct obstack *ob, workset_t *ws) {
82         workset_t *res;
83         size_t size = sizeof(*res) + (ws->bel->n_regs-1)*sizeof(res->vals[0]);
84         res = obstack_alloc(ob, size);
85         memcpy(res, ws, size);
86         return res;
87 }
88
89 /**
90  * Inserts the value @p val into the workset, iff it is not
91  * already contained. The workset must not be full.
92  */
93 static INLINE void workset_insert(workset_t *ws, ir_node *val) {
94         int i;
95         assert(ws->len < ws->bel->n_regs && "Workset already full!");
96         /* check for current regclass */
97         if (arch_get_irn_reg_class(ws->bel->arch, val, 0) != ws->bel->cls) {
98                 DBG((dbg, 0, "Dropped %+F\n", val));
99                 return;
100         }
101
102         /* check if val is already contained */
103         for(i=0; i<ws->len; ++i)
104                 if (ws->vals[i].irn == val)
105                         return;
106
107         /* insert val */
108         ws->vals[ws->len++].irn = val;
109 }
110
111 /**
112  * Inserts all values in array @p vals of length @p cnt
113  * into the workset. There must be enough space for the
114  * entries.
115  */
116 static INLINE void workset_bulk_insert(workset_t *ws, int cnt, ir_node **vals) {
117         int i, o;
118         assert(ws->len + cnt <= ws->bel->n_regs && "Workset does not have enough room!");
119
120         for(o=0; o<cnt; ++o) {
121                 ir_node *val = vals[o];
122                 DBG((dbg, DBG_TRACE, "Bulk insert %+F\n", val));
123                 /* check for current regclass */
124                 if (arch_get_irn_reg_class(ws->bel->arch, val, 0) != ws->bel->cls) {
125                         DBG((dbg, DBG_TRACE, "Wrong reg class\n"));
126                         goto no_insert;
127                 }
128
129                 /* check if val is already contained */
130                 for(i=0; i<ws->len; ++i)
131                         if (ws->vals[i].irn == val) {
132                                 DBG((dbg, DBG_TRACE, "Already contained\n"));
133                                 goto no_insert;
134                         }
135
136                 /* insert val */
137                 ws->vals[ws->len++].irn = val;
138                 DBG((dbg, DBG_TRACE, "Inserted\n"));
139
140 no_insert:
141                 /*epsilon statement :)*/;
142         }
143 }
144
145 /**
146  * Overwrites the current contents of @p ws with the
147  * locations given in @p locs
148  */
149 #define workset_bulk_fill(ws, count, locs) memcpy(&(ws)->vals[0], locs, ((ws)->len=count)*sizeof(locs[0]));
150
151 /**
152  * Removes all entries from this workset
153  */
154 #define workset_clear(ws) (ws)->len = 0;
155
156 /**
157  * Removes the value @p val from the workset if present.
158  */
159 static INLINE void workset_remove(workset_t *ws, ir_node *val) {
160         int i;
161         for(i=0; i<ws->len; ++i)
162                 if (ws->vals[i].irn == val) {
163                         ws->vals[i] = ws->vals[--ws->len];
164                         return;
165                 }
166 }
167
168 static INLINE int workset_contains(const workset_t *ws, const ir_node *val) {
169         int i;
170         for(i=0; i<ws->len; ++i)
171                 if (ws->vals[i].irn == val)
172                         return 1;
173         return 0;
174 }
175
176 #define workset_foreach(ws, v)  for(ws->i=0; \
177                                                                         v=(ws->i < ws->len) ? ws->vals[ws->i].irn : NULL, ws->i < ws->len; \
178                                                                         ws->i++)
179
180 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
181 #define workset_set_length(ws, length) (ws)->len = length
182 #define workset_get_length(ws) ((ws)->len)
183 #define workset_get_val(ws, i) ((ws)->vals[i].irn)
184 #define workset_sort(ws) qsort((ws)->vals, (ws)->len, sizeof((ws)->vals[0]), loc_compare);
185
186
187 /**
188  * Collects all values live-in at block @p blk and all phi results in this block.
189  * Then it adds the best values (at most n_regs) to the ws.
190  */
191 static void build_start_set(belady_env_t *bel, ir_node *blk) {
192         workset_t *ws = bel->ws;
193         ir_node *irn, *first;
194         irn_live_t *li;
195         int count;
196         loc_t loc, *starters;
197         struct obstack ob;
198
199         obstack_init(&ob);
200
201         /* get all values */
202         first = sched_first(blk);
203         count = 0;
204         sched_foreach(blk, irn)
205                 if (is_Phi(irn) && arch_get_irn_reg_class(bel->arch, irn, 0) == bel->cls) {
206                         loc.irn = irn;
207                         loc.time = be_get_next_use(bel->uses, first, 0, irn, 0);
208                         DBG((dbg, DBG_START, "  %+F next-use %d\n", loc.irn, loc.time));
209                         obstack_grow(&ob, &loc, sizeof(loc));
210                         count++;
211                 } else
212                         break;
213
214         live_foreach(blk, li)
215                 if (live_is_in(li) && arch_get_irn_reg_class(bel->arch, li->irn, 0) == bel->cls) {
216                         loc.irn = (ir_node *)li->irn;
217                         loc.time = be_get_next_use(bel->uses, first, 0, li->irn, 0);
218                         DBG((dbg, DBG_START, "  %+F next-use %d\n", loc.irn, loc.time));
219                         obstack_grow(&ob, &loc, sizeof(loc));
220                         count++;
221                 }
222         starters = obstack_finish(&ob);
223
224         /* sort all values */
225         qsort(starters, count, sizeof(starters[0]), loc_compare);
226
227         /* copy the best ones to the ws */
228         count = MIN(count, ws->bel->n_regs);
229         workset_bulk_fill(ws, count, starters);
230
231         obstack_free(&ob, NULL);
232 }
233
234 /**
235  * Performs the actions neccessary to grant the request that:
236  * - new_vals can be held in registers
237  * - as few as possible other values are disposed
238  * - the worst values get disposed
239  *
240  * @p is_usage indicates that the values in new_vals are used (not defined)
241  * In this case reloads must be performed
242  */
243 static void displace(belady_env_t *bel, workset_t *new_vals, int is_usage) {
244         ir_node *val;
245         int i, len, max_allowed, demand;
246         workset_t *ws = bel->ws;
247         ir_node **to_insert = alloca(bel->n_regs * sizeof(*to_insert));
248
249         /*
250          * 1. Identify the number of needed slots and the values to reload
251          */
252         demand = 0;
253         workset_foreach(new_vals, val) {
254                 /* mark value as used */
255                 if (is_usage)
256                         pset_insert_ptr(bel->used, val);
257
258                 if (!workset_contains(ws, val)) {
259                         DBG((dbg, DBG_DECIDE, "    insert %+F\n", val));
260                         to_insert[demand++] = val;
261                         if (is_usage)
262                                 be_add_reload(bel->senv, val, bel->instr);
263                 } else
264                         DBG((dbg, DBG_DECIDE, "    skip %+F\n", val));
265         }
266         DBG((dbg, DBG_DECIDE, "    demand = %d\n", demand));
267
268
269         /*
270          * 2. Make room for at least 'demand' slots
271          */
272         len = workset_get_length(ws);
273         max_allowed = bel->n_regs - demand;
274
275         /* Only make more free room if we do not have enough */
276         if (len > max_allowed) {
277                 /* get current next-use distance */
278                 for (i=0; i<ws->len; ++i)
279                         workset_set_time(ws, i, be_get_next_use(bel->uses, bel->instr, bel->instr_nr, workset_get_val(ws, i), is_usage));
280
281                 /* sort entries by increasing nextuse-distance*/
282                 workset_sort(ws);
283
284                 /* Logic for not needed live-ins: If a value is disposed
285                    before its first usage, remove it from start workset */
286                 for (i=max_allowed; i<ws->len; ++i) {
287                         ir_node *irn = ws->vals[i].irn;
288                         if (!pset_find_ptr(bel->used, irn)) {
289                                 ir_node *curr_bb = get_nodes_block(bel->instr);
290                                 workset_t *ws_start = ((block_info_t *) get_irn_link(curr_bb))->ws_start;
291                                 workset_remove(ws_start, irn);
292
293                                 DBG((dbg, DBG_DECIDE, "    dispose %+F dumb\n", irn));
294                         } else
295                                 DBG((dbg, DBG_DECIDE, "    dispose %+F\n", irn));
296                 }
297
298                 /* kill the last 'demand' entries in the array */
299                 workset_set_length(ws, max_allowed);
300         }
301
302         /*
303          * 3. Insert the new values into the workset
304          */
305         workset_bulk_insert(bel->ws, demand, to_insert);
306 }
307
308 /**
309  * For the given block @p blk, decide for each values
310  * whether it is used from a register or is reloaded
311  * before the use.
312  */
313 static void decide(ir_node *blk, void *env) {
314         belady_env_t *bel = env;
315         workset_t *new_vals;
316         ir_node *irn;
317         block_info_t *blk_info = obstack_alloc(&bel->ob, sizeof(*blk_info));
318         set_irn_link(blk, blk_info);
319
320         DBG((dbg, DBG_DECIDE, "\n"));
321         DBG((dbg, DBG_DECIDE, "Decide for %+F\n", blk));
322
323         /* build starting-workset for this block */
324         build_start_set(bel, blk);
325         blk_info->ws_start = workset_clone(&bel->ob, bel->ws);
326         DBG((dbg, DBG_WSETS, "Initial start workset for %+F:\n", blk));
327         workset_foreach(blk_info->ws_start, irn)
328                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
329
330         /* process the block from start to end */
331         DBG((dbg, DBG_WSETS, "Processing...\n"));
332         bel->used = pset_new_ptr(32);
333         bel->instr_nr = 0;
334         new_vals = new_workset(&bel->ob, bel);
335         sched_foreach(blk, irn) {
336                 ir_node *iii;
337                 DBG((dbg, DBG_WSETS, "Current workset for %+F:\n", blk));
338                 workset_foreach(bel->ws, iii)
339                         DBG((dbg, DBG_WSETS, "  %+F\n", iii));
340                 assert(workset_get_length(bel->ws) <= bel->n_regs && "Too much values in workset!");
341
342                 DBG((dbg, DBG_DECIDE, "  ...%+F\n", irn));
343
344                 /* projs are handled with the tuple value.
345                  * Phis are no real instr (see insert_starters)
346                  * instr_nr does not increase */
347                 if (is_Proj(irn) || is_Phi(irn))
348                         continue;
349
350                 /* set instruction in the workset */
351                 bel->instr = irn;
352
353                 /* allocate all values _used_ by this instruction */
354                 workset_clear(new_vals);
355                 workset_bulk_insert(new_vals, get_irn_arity(irn)+1, get_irn_in(irn));
356                 displace(bel, new_vals, 1);
357
358                 /* allocate all values _defined_ by this instruction */
359                 workset_clear(new_vals);
360                 if (get_irn_mode(irn) == mode_T) { /* special handling for tuples and projs */
361                         ir_node *proj;
362                         for(proj=sched_next(irn); is_Proj(proj); proj=sched_next(proj))
363                                 workset_insert(new_vals, proj);
364                 } else {
365                         workset_insert(new_vals, irn);
366                 }
367                 displace(bel, new_vals, 0);
368
369                 bel->instr_nr++;
370         }
371         del_pset(bel->used);
372
373         /* Remember end-workset for this block */
374         blk_info->ws_end = workset_clone(&bel->ob, bel->ws);
375         DBG((dbg, DBG_WSETS, "Start workset for %+F:\n", blk));
376         workset_foreach(blk_info->ws_start, irn)
377                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
378         DBG((dbg, DBG_WSETS, "End workset for %+F:\n", blk));
379         workset_foreach(blk_info->ws_end, irn)
380                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
381 }
382
383 /**
384  * 'decide' is block-local and makes assumtions
385  * about the set of live-ins. Thus we must adapt the
386  * live-outs to the live-ins at each block-border.
387  */
388 static void fix_block_borders(ir_node *blk, void *env) {
389         belady_env_t *bel = env;
390         int i, max;
391
392         DBG((dbg, DBG_FIX, "\n"));
393         DBG((dbg, DBG_FIX, "Fixing %+F\n", blk));
394
395         workset_t *wsb = ((block_info_t *)get_irn_link(blk))->ws_start;
396
397         /* process all pred blocks */
398         for (i=0, max=get_irn_arity(blk); i<max; ++i) {
399                 ir_node *irnb, *irnp, *pred = get_Block_cfgpred_block(blk, i);
400                 workset_t *wsp = ((block_info_t *)get_irn_link(pred))->ws_end;
401
402                 DBG((dbg, DBG_FIX, "  Pred %+F\n", pred));
403
404                 workset_foreach(wsb, irnb) {
405                         /* if irnb is a phi of the current block we reload
406                          * the corresponding argument, else irnb itself */
407                         if(is_Phi(irnb) && blk == get_nodes_block(irnb))
408                                 irnb = get_irn_n(irnb, i);
409
410                         /* check if irnb is in a register at end of pred */
411                         workset_foreach(wsp, irnp)
412                                 if (irnb == irnp)
413                                         goto next_value;
414
415                         /* irnb is in memory at the end of pred, so we have to reload it */
416                         be_add_reload_on_edge(bel->senv, irnb, blk, i);
417
418 next_value:
419                         /*epsilon statement :)*/;
420                 }
421         }
422 }
423
424 /**
425  * Removes all used reloads from bel->reloads.
426  * The remaining nodes in bel->reloads will be removed from the graph.
427  */
428 static void rescue_used_reloads(ir_node *irn, void *env) {
429         pset *rlds = ((belady_env_t *)env)->reloads;
430         if (pset_find_ptr(rlds, irn)) {
431                 DBG((dbg, DBG_SPILL, "Removing %+F in %+F\n", irn, get_nodes_block(irn)));
432                 pset_remove_ptr(rlds, irn);
433         }
434 }
435
436 static int is_mem_phi(const ir_node *irn, void *data) {
437         ir_node *blk = get_nodes_block(irn);
438         workset_t *sws = ((block_info_t *)get_irn_link(blk))->ws_start;
439         return !workset_contains(sws, irn);
440 }
441
442 void be_spill_belady(const be_main_session_env_t *session, const arch_register_class_t *cls) {
443         ir_node *irn;
444
445         dbg = firm_dbg_register("ir.be.spillbelady");
446         firm_dbg_set_mask(dbg, DEBUG_LVL);
447
448         /* init belady env */
449         belady_env_t *bel = alloca(sizeof(*bel));
450         obstack_init(&bel->ob);
451         bel->factory = session->main_env->node_factory;
452         bel->arch = session->main_env->arch_env;
453         bel->cls = cls;
454         bel->n_regs = arch_register_class_n_regs(cls);
455         bel->ws = new_workset(&bel->ob, bel);
456         bel->uses = be_begin_uses(session->irg, session->main_env->arch_env, cls);
457         bel->senv = be_new_spill_env(dbg, session, cls);
458         bel->reloads = pset_new_ptr_default();
459
460         /* do the work */
461         irg_block_walk_graph(session->irg, decide, NULL, bel);
462         irg_block_walk_graph(session->irg, fix_block_borders, NULL, bel);
463         be_insert_spills_reloads(bel->senv, bel->reloads, is_mem_phi, NULL);
464
465         /* find all unused reloads and remove them from the schedule */
466         irg_walk_graph(session->irg, rescue_used_reloads, NULL, bel);
467         for(irn = pset_first(bel->reloads); irn; irn = pset_next(bel->reloads))
468                 sched_remove(irn);
469
470         /* clean up */
471         del_pset(bel->reloads);
472         be_delete_spill_env(bel->senv);
473         be_end_uses(bel->uses);
474         obstack_free(&bel->ob, NULL);
475 }