d2da6f099ae21f779d779d2049ca5306da1d4cab
[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 #ifdef HAVE_CONFIG_H
9 #include "config.h"
10 #endif
11
12 #ifdef HAVE_ALLOCA_H
13 #include <alloca.h>
14 #endif
15
16 #ifdef HAVE_MALLOC_H
17 #include <malloc.h>
18 #endif
19
20 #include "obst.h"
21 #include "set.h"
22 #include "pset.h"
23 #include "irprintf_t.h"
24 #include "irgraph.h"
25 #include "irnode.h"
26 #include "irmode.h"
27 #include "irgwalk.h"
28 #include "iredges_t.h"
29 #include "ircons_t.h"
30 #include "irprintf.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 DBG_WORKSET 128
50 #define DEBUG_LVL 0 //(DBG_START | DBG_DECIDE | DBG_WSETS | DBG_FIX | DBG_SPILL)
51 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
52
53 typedef struct _workset_t workset_t;
54
55 typedef struct _belady_env_t {
56         struct obstack ob;
57         const arch_env_t *arch;
58         const arch_register_class_t *cls;
59         int n_regs;                     /** number of regs in this reg-class */
60
61         workset_t *ws;          /**< the main workset used while processing a block. ob-allocated */
62         be_uses_t *uses;        /**< env for the next-use magic */
63         ir_node *instr;         /**< current instruction */
64         unsigned instr_nr;      /**< current instruction number (relative to block start) */
65         pset *used;
66
67         spill_env_t *senv;      /**< see bespill.h */
68 } belady_env_t;
69
70 struct _workset_t {
71         int len;                        /**< current length */
72         loc_t vals[0];          /**< inlined array of the values/distances in this working set */
73 };
74
75 void workset_print(const workset_t *w)
76 {
77         int i;
78
79         for(i = 0; i < w->len; ++i) {
80                 ir_printf("%+F %d\n", w->vals[i].irn, w->vals[i].time);
81         }
82 }
83
84 /**
85  * Alloc a new workset on obstack @p ob with maximum size @p max
86  */
87 static INLINE workset_t *new_workset(belady_env_t *env, struct obstack *ob) {
88         workset_t *res;
89         size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
90         res = obstack_alloc(ob, size);
91         memset(res, 0, size);
92         return res;
93 }
94
95 /**
96  * Alloc a new instance on obstack and make it equal to @param ws
97  */
98 static INLINE workset_t *workset_clone(belady_env_t *env, struct obstack *ob, workset_t *ws) {
99         workset_t *res;
100         size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
101         res = obstack_alloc(ob, size);
102         memcpy(res, ws, size);
103         return res;
104 }
105
106 /**
107  * Do NOT alloc anything. Make @param tgt equal to @param src.
108  * returns @param tgt for convinience
109  */
110 static INLINE workset_t *workset_copy(belady_env_t *env, workset_t *tgt, workset_t *src) {
111         size_t size = sizeof(*src) + (env->n_regs)*sizeof(src->vals[0]);
112         memcpy(tgt, src, size);
113         return tgt;
114 }
115
116 /**
117  * Overwrites the current content array of @param ws with the
118  * @param count locations given at memory @param locs.
119  * Set the length of @param ws to count.
120  */
121 static INLINE void workset_bulk_fill(workset_t *workset, int count, const loc_t *locs) {
122         workset->len = count;
123         memcpy(&(workset->vals[0]), locs, 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(belady_env_t *env, workset_t *ws, ir_node *val) {
131         int i;
132         /* check for current regclass */
133         if (!arch_irn_consider_in_reg_alloc(env->arch, env->cls, val)) {
134                 DBG((dbg, DBG_WORKSET, "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 < env->n_regs && "Workset already full!");
145         ws->vals[ws->len++].irn = val;
146 }
147
148 /**
149  * Removes all entries from this workset
150  */
151 static INLINE void workset_clear(workset_t *ws) {
152         ws->len = 0;
153 }
154
155 /**
156  * Removes the value @p val from the workset if present.
157  */
158 static INLINE void workset_remove(workset_t *ws, ir_node *val) {
159         int i;
160         for(i=0; i<ws->len; ++i) {
161                 if (ws->vals[i].irn == val) {
162                         ws->vals[i] = ws->vals[--ws->len];
163                         return;
164                 }
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         }
174
175         return 0;
176 }
177
178 /**
179  * Iterates over all values in the working set.
180  * @p ws The workset to iterate
181  * @p v  A variable to put the current value in
182  * @p i  An integer for internal use
183  */
184 #define workset_foreach(ws, v, i)       for(i=0; \
185                                                                                 v=(i < ws->len) ? ws->vals[i].irn : NULL, i < ws->len; \
186                                                                                 ++i)
187
188 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
189 #define workset_set_length(ws, length) (ws)->len = length
190 #define workset_get_length(ws) ((ws)->len)
191 #define workset_get_val(ws, i) ((ws)->vals[i].irn)
192 #define workset_sort(ws) qsort((ws)->vals, (ws)->len, sizeof((ws)->vals[0]), loc_compare);
193
194 typedef struct _block_info_t {
195         workset_t *ws_start, *ws_end;
196         int processed;
197 } block_info_t;
198
199
200 static INLINE void *new_block_info(struct obstack *ob) {
201         block_info_t *res = obstack_alloc(ob, sizeof(*res));
202         res->ws_start = NULL;
203         res->ws_end = NULL;
204         res->processed = 0;
205
206         return res;
207 }
208
209 #define get_block_info(blk)                     ((block_info_t *)get_irn_link(blk))
210 #define set_block_info(blk, info)       set_irn_link(blk, info)
211
212 /**
213  * @return The distance to the next use or 0 if irn has dont_spill flag set
214  */
215 static INLINE unsigned get_distance(belady_env_t *env, const ir_node *from, unsigned from_step, const ir_node *def, int skip_from_uses)
216 {
217         int flags = arch_irn_get_flags(env->arch, def);
218         unsigned dist = be_get_next_use(env->uses, from, from_step, def, skip_from_uses);
219
220         assert(! (flags & arch_irn_flags_ignore));
221         // we have to keep nonspillable nodes in the workingset
222         if(flags & arch_irn_flags_dont_spill)
223                 return 0;
224
225         return dist;
226 }
227
228 /**
229  * Performs the actions necessary to grant the request that:
230  * - new_vals can be held in registers
231  * - as few as possible other values are disposed
232  * - the worst values get disposed
233  *
234  * @p is_usage indicates that the values in new_vals are used (not defined)
235  * In this case reloads must be performed
236  */
237 static void displace(belady_env_t *env, workset_t *new_vals, int is_usage) {
238         ir_node *val;
239         int i, len, max_allowed, demand, iter;
240         workset_t *ws = env->ws;
241         ir_node **to_insert = alloca(env->n_regs * sizeof(*to_insert));
242
243         /*
244          * 1. Identify the number of needed slots and the values to reload
245          */
246         demand = 0;
247         workset_foreach(new_vals, val, iter) {
248                 /* mark value as used */
249                 if (is_usage)
250                         pset_insert_ptr(env->used, val);
251
252                 if (!workset_contains(ws, val)) {
253                         DBG((dbg, DBG_DECIDE, "    insert %+F\n", val));
254                         to_insert[demand++] = val;
255                         if (is_usage)
256                                 be_add_reload(env->senv, val, env->instr);
257                 } else {
258                         assert(is_usage || "Defined value already in workset?!?");
259                         DBG((dbg, DBG_DECIDE, "    skip %+F\n", val));
260                 }
261         }
262         DBG((dbg, DBG_DECIDE, "    demand = %d\n", demand));
263
264         /*
265          * 2. Make room for at least 'demand' slots
266          */
267         len = workset_get_length(ws);
268         max_allowed = env->n_regs - demand;
269
270         DBG((dbg, DBG_DECIDE, "    disposing %d values\n", ws->len - max_allowed));
271
272         /* Only make more free room if we do not have enough */
273         if (len > max_allowed) {
274                 /* get current next-use distance */
275                 for (i=0; i<ws->len; ++i)
276                         workset_set_time(ws, i, get_distance(env, env->instr, env->instr_nr, workset_get_val(ws, i), !is_usage));
277
278                 /* sort entries by increasing nextuse-distance*/
279                 workset_sort(ws);
280
281                 /* Logic for not needed live-ins: If a value is disposed
282                  * before its first usage, remove it from start workset
283                  * We don't do this for phis though
284                  */
285                 for (i=max_allowed; i<ws->len; ++i) {
286                         ir_node *irn = ws->vals[i].irn;
287
288                         if(is_Phi(irn))
289                             continue;
290
291                         if (!pset_find_ptr(env->used, irn)) {
292                                 ir_node *curr_bb = get_nodes_block(env->instr);
293                                 workset_t *ws_start = get_block_info(curr_bb)->ws_start;
294                                 workset_remove(ws_start, irn);
295
296                                 DBG((dbg, DBG_DECIDE, "    dispose %+F dumb\n", irn));
297                         } else {
298                                 DBG((dbg, DBG_DECIDE, "    dispose %+F\n", irn));
299                         }
300                 }
301
302                 /* kill the last 'demand' entries in the array */
303                 workset_set_length(ws, max_allowed);
304         }
305
306         /*
307          * 3. Insert the new values into the workset
308          */
309         for(i = 0; i < demand; ++i)
310                 workset_insert(env, env->ws, to_insert[i]);
311 }
312
313 static void belady(ir_node *blk, void *env);
314
315 /*
316  * Computes set of live-ins for each block with multiple predecessors and
317  * places copies in the predecessors when phis get spilled
318  */
319 static void place_copy_walker(ir_node *block, void *data) {
320         belady_env_t *env = data;
321         block_info_t *block_info;
322         irn_live_t *li;
323         ir_node *first, *irn;
324         loc_t loc, *starters;
325         int i, len, ws_count;
326
327         if(get_Block_n_cfgpreds(block) == 1 && get_irg_start_block(get_irn_irg(block)) != block)
328                 return;
329
330         block_info = new_block_info(&env->ob);
331         set_block_info(block, block_info);
332
333         /* Collect all values living at start of block */
334         starters = NEW_ARR_F(loc_t, 0);
335
336         DBG((dbg, DBG_START, "Living at start of %+F:\n", block));
337         first = sched_first(block);
338         sched_foreach(block, irn) {
339                 if(!is_Phi(irn))
340                         break;
341                 if(!arch_irn_consider_in_reg_alloc(env->arch, env->cls, irn))
342                         continue;
343
344                 loc.irn = irn;
345                 loc.time = get_distance(env, first, 0, irn, 0);
346                 ARR_APP1(loc_t, starters, loc);
347                 DBG((dbg, DBG_START, "    %+F:\n", irn));
348         }
349
350         live_foreach(block, li) {
351                 if (!live_is_in(li) || !arch_irn_consider_in_reg_alloc(env->arch, env->cls, li->irn))
352                         continue;
353
354                 loc.irn = (ir_node *)li->irn;
355                 loc.time = get_distance(env, first, 0, li->irn, 0);
356                 ARR_APP1(loc_t, starters, loc);
357                 DBG((dbg, DBG_START, "    %+F:\n", li->irn));
358         }
359
360         // Sort start values by first use
361         qsort(starters, ARR_LEN(starters), sizeof(starters[0]), loc_compare);
362
363         /* Copy the best ones from starters to start workset */
364         ws_count = MIN(ARR_LEN(starters), env->n_regs);
365         block_info->ws_start = new_workset(env, &env->ob);
366         workset_bulk_fill(block_info->ws_start, ws_count, starters);
367
368         /* The phis of this block which are not in the start set have to be spilled later. */
369         for (i = ws_count, len = ARR_LEN(starters); i < len; ++i) {
370                 irn = starters[i].irn;
371                 if (!is_Phi(irn) || get_nodes_block(irn) != block)
372                         continue;
373
374                 be_spill_phi(env->senv, irn);
375         }
376
377         DEL_ARR_F(starters);
378 }
379
380 /**
381  * Collects all values live-in at block @p blk and all phi results in this block.
382  * Then it adds the best values (at most n_regs) to the blocks start_workset.
383  * The phis among the remaining values get spilled: Introduce psudo-copies of
384  *  their args to break interference and make it possible to spill them to the
385  *  same spill slot.
386  */
387 static block_info_t *compute_block_start_info(belady_env_t *env, ir_node *block) {
388         ir_node *pred_block;
389         block_info_t *res, *pred_info;
390
391         /* Have we seen this block before? */
392         res = get_block_info(block);
393         if (res)
394                 return res;
395
396         /* Create the block info for this block. */
397         res = new_block_info(&env->ob);
398         set_block_info(block, res);
399
400         /* Use endset of predecessor block as startset */
401         assert(get_Block_n_cfgpreds(block) == 1 && block != get_irg_start_block(get_irn_irg(block)));
402         pred_block = get_Block_cfgpred_block(block, 0);
403         pred_info = get_block_info(pred_block);
404
405         /* if pred block has not been processed yet, do it now */
406         if (pred_info == NULL || pred_info->processed == 0) {
407                 belady(pred_block, env);
408                 pred_info = get_block_info(pred_block);
409         }
410
411         /* now we have an end_set of pred */
412         assert(pred_info->ws_end && "The recursive call (above) is supposed to compute an end_set");
413         res->ws_start = workset_clone(env, &env->ob, pred_info->ws_end);
414
415         return res;
416 }
417
418
419 /**
420  * For the given block @p blk, decide for each values
421  * whether it is used from a register or is reloaded
422  * before the use.
423  */
424 static void belady(ir_node *block, void *data) {
425         belady_env_t *env = data;
426         workset_t *new_vals;
427         ir_node *irn;
428         int iter;
429         block_info_t *block_info;
430
431         /* make sure we have blockinfo (with startset) */
432         block_info = get_block_info(block);
433         if (block_info == NULL)
434                 block_info = compute_block_start_info(env, block);
435
436         /* Don't do a block twice */
437         if(block_info->processed)
438                 return;
439
440         /* get the starting workset for this block */
441         DBG((dbg, DBG_DECIDE, "\n"));
442         DBG((dbg, DBG_DECIDE, "Decide for %+F\n", block));
443
444         workset_copy(env, env->ws, block_info->ws_start);
445         DBG((dbg, DBG_WSETS, "Start workset for %+F:\n", block));
446         workset_foreach(env->ws, irn, iter)
447                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
448
449         /* process the block from start to end */
450         DBG((dbg, DBG_WSETS, "Processing...\n"));
451         env->used = pset_new_ptr_default();
452         env->instr_nr = 0;
453         new_vals = new_workset(env, &env->ob);
454         sched_foreach(block, irn) {
455                 int i, arity;
456                 assert(workset_get_length(env->ws) <= env->n_regs && "Too much values in workset!");
457
458                 /* projs are handled with the tuple value.
459                  * Phis are no real instr (see insert_starters())
460                  * instr_nr does not increase */
461                 if (is_Proj(irn) || is_Phi(irn)) {
462                         DBG((dbg, DBG_DECIDE, "  ...%+F skipped\n", irn));
463                         continue;
464                 }
465                 DBG((dbg, DBG_DECIDE, "  ...%+F\n", irn));
466
467                 /* set instruction in the workset */
468                 env->instr = irn;
469
470                 /* allocate all values _used_ by this instruction */
471                 workset_clear(new_vals);
472                 for(i = 0, arity = get_irn_arity(irn); i < arity; ++i) {
473                         workset_insert(env, new_vals, get_irn_n(irn, i));
474                 }
475                 displace(env, new_vals, 1);
476
477                 /* allocate all values _defined_ by this instruction */
478                 workset_clear(new_vals);
479                 if (get_irn_mode(irn) == mode_T) { /* special handling for tuples and projs */
480                         ir_node *proj;
481                         for(proj=sched_next(irn); is_Proj(proj); proj=sched_next(proj))
482                                 workset_insert(env, new_vals, proj);
483                 } else {
484                         workset_insert(env, new_vals, irn);
485                 }
486                 displace(env, new_vals, 0);
487
488                 env->instr_nr++;
489         }
490         del_pset(env->used);
491
492         /* Remember end-workset for this block */
493         block_info->ws_end = workset_clone(env, &env->ob, env->ws);
494         block_info->processed = 1;
495         DBG((dbg, DBG_WSETS, "End workset for %+F:\n", block));
496         workset_foreach(block_info->ws_end, irn, iter)
497                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
498 }
499
500 /**
501  * 'decide' is block-local and makes assumptions
502  * about the set of live-ins. Thus we must adapt the
503  * live-outs to the live-ins at each block-border.
504  */
505 static void fix_block_borders(ir_node *blk, void *env) {
506         workset_t *wsb;
507         belady_env_t *bel = env;
508         int i, max, iter, iter2;
509
510         DBG((dbg, DBG_FIX, "\n"));
511         DBG((dbg, DBG_FIX, "Fixing %+F\n", blk));
512
513         wsb = get_block_info(blk)->ws_start;
514
515         /* process all pred blocks */
516         for (i=0, max=get_irn_arity(blk); i<max; ++i) {
517                 ir_node *irnb, *irnp, *pred = get_Block_cfgpred_block(blk, i);
518                 workset_t *wsp = get_block_info(pred)->ws_end;
519
520                 DBG((dbg, DBG_FIX, "  Pred %+F\n", pred));
521
522                 workset_foreach(wsb, irnb, iter) {
523                         /* if irnb is a phi of the current block we reload
524                          * the corresponding argument, else irnb itself */
525                         if(is_Phi(irnb) && blk == get_nodes_block(irnb))
526                                 irnb = get_irn_n(irnb, i);
527
528                         /* Unknowns are available everywhere */
529                         if(get_irn_opcode(irnb) == iro_Unknown)
530                                 continue;
531
532                         /* check if irnb is in a register at end of pred */
533                         workset_foreach(wsp, irnp, iter2) {
534                                 if (irnb == irnp)
535                                         goto next_value;
536                         }
537
538                         /* irnb is not in memory at the end of pred, so we have to reload it */
539                         DBG((dbg, DBG_FIX, "    reload %+F\n", irnb));
540                         be_add_reload_on_edge(bel->senv, irnb, blk, i);
541
542 next_value:
543                         /*epsilon statement :)*/;
544                 }
545         }
546 }
547
548 void be_spill_belady(const be_chordal_env_t *chordal_env) {
549         be_spill_belady_spill_env(chordal_env, NULL);
550 }
551
552 void be_spill_belady_spill_env(const be_chordal_env_t *chordal_env, spill_env_t *spill_env) {
553         belady_env_t env;
554
555         FIRM_DBG_REGISTER(dbg, "firm.be.spill.belady");
556
557         /* init belady env */
558         obstack_init(&env.ob);
559         env.arch      = chordal_env->birg->main_env->arch_env;
560         env.cls       = chordal_env->cls;
561         env.n_regs    = arch_count_non_ignore_regs(env.arch, env.cls);
562         env.ws        = new_workset(&env, &env.ob);
563         env.uses      = be_begin_uses(chordal_env->irg, chordal_env->birg->main_env->arch_env, env.cls);
564         if(spill_env == NULL) {
565                 env.senv = be_new_spill_env(chordal_env);
566         } else {
567                 env.senv = spill_env;
568         }
569         DEBUG_ONLY(be_set_spill_env_dbg_module(env.senv, dbg);)
570
571         DBG((dbg, LEVEL_1, "running on register class: %s\n", env.cls->name));
572
573         /* do the work */
574         be_clear_links(chordal_env->irg);
575         irg_block_walk_graph(chordal_env->irg, place_copy_walker, NULL, &env);
576         irg_block_walk_graph(chordal_env->irg, NULL, belady, &env);
577         irg_block_walk_graph(chordal_env->irg, fix_block_borders, NULL, &env);
578         be_insert_spills_reloads(env.senv);
579
580         be_remove_dead_nodes_from_schedule(chordal_env->irg);
581
582         /* clean up */
583         if(spill_env == NULL)
584                 be_delete_spill_env(env.senv);
585         be_end_uses(env.uses);
586         obstack_free(&env.ob, NULL);
587 }