5bfe52dbf63d94389260762ccddc6dc063d01afc
[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;                     /**< holds the values used (so far) in the current BB */
66
67         spill_env_t *senv;      /**< see bespill.h */
68 } belady_env_t;
69
70 struct _workset_t {
71         belady_env_t *bel;
72         int len;                        /**< current length */
73         loc_t vals[0];          /**< inlined array of the values/distances in this working set */
74 };
75
76 void workset_print(const workset_t *w)
77 {
78         int i;
79
80         for(i = 0; i < w->len; ++i) {
81                 ir_printf("%+F %d\n", w->vals[i].irn, w->vals[i].time);
82         }
83 }
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)*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)*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)*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_irn_consider_in_reg_alloc(ws->bel->arch, ws->bel->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 < ws->bel->n_regs && "Workset already full!");
145         ws->vals[ws->len++].irn = val;
146 }
147
148 /**
149  * Removes all entries from this workset
150  */
151 #define workset_clear(ws) (ws)->len = 0;
152
153 /**
154  * Removes the value @p val from the workset if present.
155  */
156 static INLINE void workset_remove(workset_t *ws, ir_node *val) {
157         int i;
158         for(i=0; i<ws->len; ++i) {
159                 if (ws->vals[i].irn == val) {
160                         ws->vals[i] = ws->vals[--ws->len];
161                         return;
162                 }
163         }
164 }
165
166 static INLINE int workset_contains(const workset_t *ws, const ir_node *val) {
167         int i;
168         for(i=0; i<ws->len; ++i) {
169                 if (ws->vals[i].irn == val)
170                         return 1;
171         }
172
173         return 0;
174 }
175
176 /**
177  * Iterates over all values in the working set.
178  * @p ws The workset to iterate
179  * @p v  A variable to put the current value in
180  * @p i  An integer for internal use
181  */
182 #define workset_foreach(ws, v, i)       for(i=0; \
183                                                                                 v=(i < ws->len) ? ws->vals[i].irn : NULL, i < ws->len; \
184                                                                                 ++i)
185
186 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
187 #define workset_set_length(ws, length) (ws)->len = length
188 #define workset_get_length(ws) ((ws)->len)
189 #define workset_get_val(ws, i) ((ws)->vals[i].irn)
190 #define workset_sort(ws) qsort((ws)->vals, (ws)->len, sizeof((ws)->vals[0]), loc_compare);
191
192 typedef struct _block_info_t {
193         workset_t *ws_start, *ws_end;
194 } block_info_t;
195
196
197 static INLINE void *new_block_info(struct obstack *ob) {
198         block_info_t *res = obstack_alloc(ob, sizeof(*res));
199         res->ws_start = NULL;
200         res->ws_end = NULL;
201
202         return res;
203 }
204
205 #define get_block_info(blk)                     ((block_info_t *)get_irn_link(blk))
206 #define set_block_info(blk, info)       set_irn_link(blk, info)
207
208 /**
209  * @return The distance to the next use or 0 if irn has dont_spill flag set
210  */
211 static INLINE unsigned get_distance(belady_env_t *env, const ir_node *from, unsigned from_step, const ir_node *def, int skip_from_uses)
212 {
213         int flags = arch_irn_get_flags(env->arch, def);
214         unsigned dist = be_get_next_use(env->uses, from, from_step, def, skip_from_uses);
215
216         assert(! (flags & arch_irn_flags_ignore));
217         // we have to keep nonspillable nodes in the workingset
218         if(flags & arch_irn_flags_dont_spill)
219                 return 0;
220
221         return dist;
222 }
223
224 /**
225  * Performs the actions necessary to grant the request that:
226  * - new_vals can be held in registers
227  * - as few as possible other values are disposed
228  * - the worst values get disposed
229  *
230  * @p is_usage indicates that the values in new_vals are used (not defined)
231  * In this case reloads must be performed
232  */
233 static void displace(belady_env_t *env, workset_t *new_vals, int is_usage) {
234         ir_node *val;
235         int i, len, max_allowed, demand, iter;
236         workset_t *ws = env->ws;
237         ir_node **to_insert = alloca(env->n_regs * sizeof(*to_insert));
238
239         /*
240          * 1. Identify the number of needed slots and the values to reload
241          */
242         demand = 0;
243         workset_foreach(new_vals, val, iter) {
244                 /* mark value as used */
245                 if (is_usage)
246                         pset_insert_ptr(env->used, val);
247
248                 if (!workset_contains(ws, val)) {
249                         DBG((dbg, DBG_DECIDE, "    insert %+F\n", val));
250                         to_insert[demand++] = val;
251                         if (is_usage)
252                                 be_add_reload(env->senv, val, env->instr);
253                 } else {
254                         assert(is_usage || "Defined value already in workset?!?");
255                         DBG((dbg, DBG_DECIDE, "    skip %+F\n", val));
256                 }
257         }
258         DBG((dbg, DBG_DECIDE, "    demand = %d\n", demand));
259
260         /*
261          * 2. Make room for at least 'demand' slots
262          */
263         len = workset_get_length(ws);
264         max_allowed = env->n_regs - demand;
265
266         DBG((dbg, DBG_DECIDE, "    disposing %d values\n", ws->len - max_allowed));
267
268         /* Only make more free room if we do not have enough */
269         if (len > max_allowed) {
270                 /* get current next-use distance */
271                 for (i=0; i<ws->len; ++i)
272                         workset_set_time(ws, i, get_distance(env, env->instr, env->instr_nr, workset_get_val(ws, i), !is_usage));
273
274                 /* sort entries by increasing nextuse-distance*/
275                 workset_sort(ws);
276
277                 /* Logic for not needed live-ins: If a value is disposed
278                    before its first usage, remove it from start workset */
279                 for (i=max_allowed; i<ws->len; ++i) {
280                         ir_node *irn = ws->vals[i].irn;
281
282                         if (!pset_find_ptr(env->used, irn)) {
283                                 ir_node *curr_bb = get_nodes_block(env->instr);
284                                 workset_t *ws_start = get_block_info(curr_bb)->ws_start;
285                                 workset_remove(ws_start, irn);
286                                 if(is_Phi(irn))
287                                         be_spill_phi(env->senv, irn);
288
289                                 DBG((dbg, DBG_DECIDE, "    dispose %+F dumb\n", irn));
290                         } else {
291                                 DBG((dbg, DBG_DECIDE, "    dispose %+F\n", irn));
292                         }
293                 }
294
295                 /* kill the last 'demand' entries in the array */
296                 workset_set_length(ws, max_allowed);
297         }
298
299         /*
300          * 3. Insert the new values into the workset
301          */
302         for(i = 0; i < demand; ++i)
303                 workset_insert(env->ws, to_insert[i]);
304 }
305
306 static void belady(ir_node *blk, void *env);
307
308 /**
309  * Collects all values live-in at block @p blk and all phi results in this block.
310  * Then it adds the best values (at most n_regs) to the blocks start_workset.
311  * The phis among the remaining values get spilled: Introduce psudo-copies of
312  *  their args to break interference and make it possible to spill them to the
313  *  same spill slot.
314  */
315 static block_info_t *compute_block_start_info(ir_node *blk, void *data) {
316         belady_env_t *env = data;
317         ir_node *irn, *first;
318         irn_live_t *li;
319         int count, ws_count;
320         loc_t loc, *starters;
321         struct obstack ob;
322         block_info_t *res = get_block_info(blk);
323
324         /* Have we seen this block before? */
325         if (res)
326                 return res;
327
328         /* Create the block info for this block. */
329         res = new_block_info(&env->ob);
330         set_block_info(blk, res);
331
332         /* Get all values living at the block start sorted by next use*/
333         obstack_init(&ob);
334
335         DBG((dbg, DBG_START, "Living at start of %+F:\n", blk));
336         first = sched_first(blk);
337         count = 0;
338         sched_foreach(blk, 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                 obstack_grow(&ob, &loc, sizeof(loc));
347                 DBG((dbg, DBG_START, "    %+F:\n", irn));
348                 count++;
349         }
350
351         live_foreach(blk, li) {
352                 if (!live_is_in(li) || !arch_irn_consider_in_reg_alloc(env->arch, env->cls, li->irn))
353                         continue;
354
355                 loc.irn = (ir_node *)li->irn;
356                 loc.time = get_distance(env, first, 0, li->irn, 0);
357                 obstack_grow(&ob, &loc, sizeof(loc));
358                 DBG((dbg, DBG_START, "    %+F:\n", li->irn));
359                 count++;
360         }
361
362         starters = obstack_finish(&ob);
363         qsort(starters, count, sizeof(starters[0]), loc_compare);
364
365
366         /* If we have only one predecessor, we want the start_set of blk to be the end_set of pred */
367         if (get_Block_n_cfgpreds(blk) == 1 && blk != get_irg_start_block(get_irn_irg(blk))) {
368                 ir_node *pred_blk       = get_Block_cfgpred_block(blk, 0);
369                 block_info_t *pred_info = get_block_info(pred_blk);
370
371                 /* if pred block has not been processed yet, do it now */
372                 if (! pred_info) {
373                         belady(pred_blk, env);
374                         pred_info = get_block_info(pred_blk);
375                 }
376
377                 /* now we have an end_set of pred */
378                 assert(pred_info->ws_end && "The recursive call (above) is supposed to compute an end_set");
379                 res->ws_start = workset_clone(&env->ob, pred_info->ws_end);
380         } else {
381                 int i;
382
383                 /* Else we want the start_set to be the values used 'the closest' */
384                 /* Copy the best ones from starters to start workset */
385                 ws_count = MIN(count, env->n_regs);
386                 res->ws_start = new_workset(&env->ob, env);
387                 workset_bulk_fill(res->ws_start, ws_count, starters);
388
389                 /* The phis of this block which are not in the start set have to be spilled later.
390                  * Therefore we add temporary copies in the pred_blocks so the spills can spill
391                  * into the same spill slot.
392                  * After spilling these copies get deleted.
393                  */
394                 for (i = ws_count; i < count; ++i) {
395                         irn = starters[i].irn;
396                         if (!is_Phi(irn) || get_nodes_block(irn) != blk)
397                                 continue;
398
399                         be_spill_phi(env->senv, irn);
400                 }
401         }
402
403         obstack_free(&ob, NULL);
404         return res;
405 }
406
407
408 /**
409  * For the given block @p blk, decide for each values
410  * whether it is used from a register or is reloaded
411  * before the use.
412  */
413 static void belady(ir_node *blk, void *env) {
414         belady_env_t *bel = env;
415         workset_t *new_vals;
416         ir_node *irn;
417         int iter;
418         block_info_t *blk_info;
419
420         /* Don't do a block twice */
421         if (get_block_info(blk))
422                 return;
423
424         /* get the starting workset for this block */
425         blk_info = compute_block_start_info(blk, bel);
426
427         DBG((dbg, DBG_DECIDE, "\n"));
428         DBG((dbg, DBG_DECIDE, "Decide for %+F\n", blk));
429
430         workset_copy(bel->ws, blk_info->ws_start);
431         DBG((dbg, DBG_WSETS, "Start workset for %+F:\n", blk));
432         workset_foreach(bel->ws, irn, iter)
433                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
434
435         /* process the block from start to end */
436         DBG((dbg, DBG_WSETS, "Processing...\n"));
437         bel->used = pset_new_ptr(32);
438         bel->instr_nr = 0;
439         new_vals = new_workset(&bel->ob, bel);
440         sched_foreach(blk, irn) {
441                 int i, arity;
442                 assert(workset_get_length(bel->ws) <= bel->n_regs && "Too much values in workset!");
443
444                 /* projs are handled with the tuple value.
445                  * Phis are no real instr (see insert_starters())
446                  * instr_nr does not increase */
447                 if (is_Proj(irn) || is_Phi(irn)) {
448                         DBG((dbg, DBG_DECIDE, "  ...%+F skipped\n", irn));
449                         continue;
450                 }
451                 DBG((dbg, DBG_DECIDE, "  ...%+F\n", irn));
452
453                 /* set instruction in the workset */
454                 bel->instr = irn;
455
456                 /* allocate all values _used_ by this instruction */
457                 workset_clear(new_vals);
458                 for(i = 0, arity = get_irn_arity(irn); i < arity; ++i) {
459                         workset_insert(new_vals, get_irn_n(irn, i));
460                 }
461                 displace(bel, new_vals, 1);
462
463                 /* allocate all values _defined_ by this instruction */
464                 workset_clear(new_vals);
465                 if (get_irn_mode(irn) == mode_T) { /* special handling for tuples and projs */
466                         ir_node *proj;
467                         for(proj=sched_next(irn); is_Proj(proj); proj=sched_next(proj))
468                                 workset_insert(new_vals, proj);
469                 } else {
470                         workset_insert(new_vals, irn);
471                 }
472                 displace(bel, new_vals, 0);
473
474                 bel->instr_nr++;
475         }
476         del_pset(bel->used);
477
478         /* Remember end-workset for this block */
479         blk_info->ws_end = workset_clone(&bel->ob, bel->ws);
480         DBG((dbg, DBG_WSETS, "End workset for %+F:\n", blk));
481         workset_foreach(blk_info->ws_end, irn, iter)
482                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
483 }
484
485 /**
486  * 'decide' is block-local and makes assumptions
487  * about the set of live-ins. Thus we must adapt the
488  * live-outs to the live-ins at each block-border.
489  */
490 static void fix_block_borders(ir_node *blk, void *env) {
491         workset_t *wsb;
492         belady_env_t *bel = env;
493         int i, max, iter, iter2;
494
495         DBG((dbg, DBG_FIX, "\n"));
496         DBG((dbg, DBG_FIX, "Fixing %+F\n", blk));
497
498         wsb = get_block_info(blk)->ws_start;
499
500         /* process all pred blocks */
501         for (i=0, max=get_irn_arity(blk); i<max; ++i) {
502                 ir_node *irnb, *irnp, *pred = get_Block_cfgpred_block(blk, i);
503                 workset_t *wsp = get_block_info(pred)->ws_end;
504
505                 DBG((dbg, DBG_FIX, "  Pred %+F\n", pred));
506
507                 workset_foreach(wsb, irnb, iter) {
508                         /* if irnb is a phi of the current block we reload
509                          * the corresponding argument, else irnb itself */
510                         if(is_Phi(irnb) && blk == get_nodes_block(irnb))
511                                 irnb = get_irn_n(irnb, i);
512
513                         /* Unknowns are available everywhere */
514                         if(get_irn_opcode(irnb) == iro_Unknown)
515                                 continue;
516
517                         /* check if irnb is in a register at end of pred */
518                         workset_foreach(wsp, irnp, iter2) {
519                                 if (irnb == irnp)
520                                         goto next_value;
521                         }
522
523                         /* irnb is not in memory at the end of pred, so we have to reload it */
524                         DBG((dbg, DBG_FIX, "    reload %+F\n", irnb));
525                         be_add_reload_on_edge(bel->senv, irnb, blk, i);
526
527 next_value:
528                         /*epsilon statement :)*/;
529                 }
530         }
531 }
532
533 void be_spill_belady(const be_chordal_env_t *chordal_env) {
534         be_spill_belady_spill_env(chordal_env, NULL);
535 }
536
537 void be_spill_belady_spill_env(const be_chordal_env_t *chordal_env, spill_env_t *spill_env) {
538         belady_env_t bel;
539
540         FIRM_DBG_REGISTER(dbg, "firm.be.spill.belady");
541
542         /* init belady env */
543         obstack_init(&bel.ob);
544         bel.arch      = chordal_env->birg->main_env->arch_env;
545         bel.cls       = chordal_env->cls;
546         bel.n_regs    = arch_count_non_ignore_regs(bel.arch, bel.cls);
547         bel.ws        = new_workset(&bel.ob, &bel);
548         bel.uses      = be_begin_uses(chordal_env->irg, chordal_env->birg->main_env->arch_env, bel.cls);
549         if(spill_env == NULL) {
550                 bel.senv = be_new_spill_env(chordal_env);
551         } else {
552                 bel.senv = spill_env;
553         }
554         DEBUG_ONLY(be_set_spill_env_dbg_module(bel.senv, dbg);)
555
556         DBG((dbg, LEVEL_1, "running on register class: %s\n", bel.cls->name));
557
558         /* do the work */
559         be_clear_links(chordal_env->irg);
560         irg_block_walk_graph(chordal_env->irg, NULL, belady, &bel);
561         irg_block_walk_graph(chordal_env->irg, fix_block_borders, NULL, &bel);
562         be_insert_spills_reloads(bel.senv);
563
564         be_remove_dead_nodes_from_schedule(chordal_env->irg);
565
566         /* clean up */
567         if(spill_env == NULL)
568                 be_delete_spill_env(bel.senv);
569         be_end_uses(bel.uses);
570         obstack_free(&bel.ob, NULL);
571 }