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