create register slots in attributes on irg obstack
[libfirm] / ir / be / bespill.c
1 /**
2  * Author:      Daniel Grund, Sebastian Hack
3  * Date:                29.09.2005
4  * Copyright:   (c) Universitaet Karlsruhe
5  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
6  */
7 #ifdef HAVE_CONFIG_H
8 #include "config.h"
9 #endif
10
11 #include <stdlib.h>
12
13 #include "pset.h"
14 #include "irnode_t.h"
15 #include "ircons_t.h"
16 #include "iredges_t.h"
17 #include "ident_t.h"
18 #include "type_t.h"
19 #include "entity_t.h"
20 #include "debug.h"
21 #include "irgwalk.h"
22 #include "array.h"
23
24 #include "belive_t.h"
25 #include "besched_t.h"
26 #include "bespill.h"
27 #include "benode_t.h"
28 #include "bechordal_t.h"
29
30 /* This enables re-computation of values. Current state: Unfinished and buggy. */
31 #undef BUGGY_REMAT
32
33 typedef struct _reloader_t reloader_t;
34 typedef struct _spill_info_t spill_info_t;
35
36 struct _reloader_t {
37         reloader_t *next;
38         ir_node *reloader;
39 };
40
41 struct _spill_info_t {
42         ir_node *spilled_node;
43         reloader_t *reloaders;
44 };
45
46 typedef struct _spill_ctx_t {
47         ir_node *spilled;  /**< The spilled node. */
48         ir_node *user;     /**< The node this spill is for. */
49         ir_node *spill;    /**< The spill itself. */
50 } spill_ctx_t;
51
52 struct _spill_env_t {
53         firm_dbg_module_t *dbg;
54         const arch_register_class_t *cls;
55         const be_chordal_env_t *chordal_env;
56         struct obstack obst;
57         set *spill_ctxs;
58         set *spills;                            /**< all spill_info_t's, which must be placed */
59         pset *mem_phis;                         /**< set of all special spilled phis. allocated and freed seperately */
60         decide_irn_t is_mem_phi;        /**< callback func to decide if a phi needs special spilling */
61         void *data;                                     /**< data passed to all callbacks */
62 };
63
64 static int cmp_spillctx(const void *a, const void *b, size_t n) {
65         const spill_ctx_t *p = a;
66         const spill_ctx_t *q = b;
67         return !(p->user == q->user && p->spilled == q->spilled);
68 }
69
70 static int cmp_spillinfo(const void *x, const void *y, size_t size) {
71         const spill_info_t *xx = x;
72         const spill_info_t *yy = y;
73         return ! (xx->spilled_node == yy->spilled_node);
74 }
75
76 spill_env_t *be_new_spill_env(firm_dbg_module_t *dbg,
77                                                           const be_chordal_env_t *chordal_env,
78                                                           decide_irn_t is_mem_phi, void *data) {
79
80         spill_env_t *env = xmalloc(sizeof(env[0]));
81         env->spill_ctxs  = new_set(cmp_spillctx, 1024);
82         env->spills      = new_set(cmp_spillinfo, 1024);
83         env->cls         = chordal_env->cls;
84         env->dbg         = dbg;
85         env->is_mem_phi  = is_mem_phi;
86         env->data        = data;
87         env->chordal_env = chordal_env;
88         obstack_init(&env->obst);
89         return env;
90 }
91
92 void be_delete_spill_env(spill_env_t *senv) {
93         del_set(senv->spill_ctxs);
94         del_set(senv->spills);
95         obstack_free(&senv->obst, NULL);
96         free(senv);
97 }
98
99 static spill_ctx_t *be_get_spill_ctx(set *sc, ir_node *to_spill, ir_node *ctx_irn) {
100         spill_ctx_t templ;
101
102         templ.spilled = to_spill;
103         templ.user    = ctx_irn;
104         templ.spill   = NULL;
105
106         return set_insert(sc, &templ, sizeof(templ), HASH_COMBINE(HASH_PTR(to_spill), HASH_PTR(ctx_irn)));
107 }
108
109 static ir_node *be_spill_irn(spill_env_t *senv, ir_node *irn, ir_node *ctx_irn) {
110         spill_ctx_t *ctx;
111         DBG((senv->dbg, LEVEL_1, "%+F in ctx %+F\n", irn, ctx_irn));
112
113         ctx = be_get_spill_ctx(senv->spill_ctxs, irn, ctx_irn);
114         if(!ctx->spill) {
115                 const be_main_env_t *env = senv->chordal_env->birg->main_env;
116                 ctx->spill = be_spill(env->arch_env, irn, ctx_irn);
117         }
118
119         return ctx->spill;
120 }
121
122 /**
123  * If the first usage of a phi result would be out of memory
124  * there is no sense in allocating a register for it.
125  * Thus we spill it and all its operands to the same spill slot.
126  * Therefore the phi/dataB becomes a phi/Memory
127  */
128 static ir_node *be_spill_phi(spill_env_t *senv, ir_node *phi, ir_node *ctx_irn) {
129         int i, n = get_irn_arity(phi);
130         ir_node **ins, *bl = get_nodes_block(phi);
131         ir_graph *irg = senv->chordal_env->irg;
132         spill_ctx_t *ctx;
133
134         assert(is_Phi(phi));
135         DBG((senv->dbg, LEVEL_1, "%+F in ctx %+F\n", phi, ctx_irn));
136
137         /* search an existing spill for this context */
138         ctx = be_get_spill_ctx(senv->spill_ctxs, phi, ctx_irn);
139
140         /* if not found spill the phi */
141         if(!ctx->spill) {
142                 /* build a new PhiM with dummy in-array */
143     NEW_ARR_A(ir_node *, ins, n);
144                 for(i=0; i<n; ++i)
145                         ins[i] = new_r_Unknown(irg, mode_M);
146                 ctx->spill = new_r_Phi(senv->chordal_env->irg, bl, n, ins, mode_M);
147
148                 /* re-wire the phiM */
149                 for(i=0; i<n; ++i) {
150                         ir_node *arg = get_irn_n(phi, i);
151                         ir_node *sub_res;
152
153                         if(is_Phi(arg) && pset_find_ptr(senv->mem_phis, arg))
154                                 sub_res = be_spill_phi(senv, arg, ctx_irn);
155                         else
156                                 sub_res = be_spill_irn(senv, arg, ctx_irn);
157
158                         set_irn_n(ctx->spill, i, sub_res);
159                 }
160         }
161         return ctx->spill;
162 }
163
164 static ir_node *be_spill_node(spill_env_t *senv, ir_node *to_spill) {
165         ir_node *res;
166         if (pset_find_ptr(senv->mem_phis, to_spill))
167                 res = be_spill_phi(senv, to_spill, to_spill);
168         else
169                 res = be_spill_irn(senv, to_spill, to_spill);
170
171         return res;
172 }
173
174 static void phi_walker(ir_node *irn, void *env) {
175         spill_env_t *senv = env;
176         const arch_env_t *arch = senv->chordal_env->birg->main_env->arch_env;
177
178         if (is_Phi(irn) && arch_irn_has_reg_class(arch, irn, 0, senv->cls)
179                         && senv->is_mem_phi(irn, senv->data)) {
180                 DBG((senv->dbg, LEVEL_1, "  %+F\n", irn));
181                 pset_insert_ptr(senv->mem_phis, irn);
182         }
183 }
184
185
186 #ifdef BUGGY_REMAT
187
188 static int check_remat_conditions(spill_env_t *senv, ir_node *spill, ir_node *spilled, ir_node *reloader) {
189         int pos, max;
190
191         /* check for 'normal' spill and general remat condition */
192         if (!be_is_Spill(spill) || !arch_irn_is(senv->chordal_env->birg->main_env->arch_env, spilled, rematerializable))
193                 return 0;
194
195         /* check availability of original arguments */
196         if (is_Block(reloader)) {
197
198                 /* we want to remat at the end of a block.
199                  * thus all arguments must be alive at the end of the block
200                  */
201                 for (pos=0, max=get_irn_arity(spilled); pos<max; ++pos) {
202                         ir_node *arg = get_irn_n(spilled, pos);
203                         if (!is_live_end(reloader, arg))
204                                 return 0;
205                 }
206
207         } else {
208
209                 /* we want to remat before the insn reloader
210                  * thus an arguments is alive if
211                  *   - it interferes with the reloaders result
212                  * or
213                  *   - or it is (last-) used by reloader itself
214                  */
215                 for (pos=0, max=get_irn_arity(spilled); pos<max; ++pos) {
216                         ir_node *arg = get_irn_n(spilled, pos);
217                         int i, m;
218
219                         if (values_interfere(reloader, arg))
220                                 goto is_alive;
221
222                         for (i=0, m=get_irn_arity(reloader); i<m; ++i) {
223                                 ir_node *rel_arg = get_irn_n(reloader, i);
224                                 if (rel_arg == arg)
225                                         goto is_alive;
226                         }
227
228                         /* arg is not alive before reloader */
229                         return 0;
230
231 is_alive:       ;
232
233                 }
234
235         }
236
237         return 1;
238 }
239
240 static ir_node *do_remat(spill_env_t *senv, ir_node *spilled, ir_node *reloader) {
241         ir_node *res;
242         ir_node *bl = (is_Block(reloader)) ? reloader : get_nodes_block(reloader);
243
244         /* recompute the value */
245         res = new_ir_node(get_irn_dbg_info(spilled), senv->chordal_env->irg, bl,
246                 get_irn_op(spilled),
247                 get_irn_mode(spilled),
248                 get_irn_arity(spilled),
249                 get_irn_in(spilled));
250
251         DBG((senv->dbg, LEVEL_1, "Insert remat %+F before reloader %+F\n", res, reloader));
252
253         /* insert in schedule */
254         if (is_Block(reloader)) {
255                 ir_node *insert = sched_skip(reloader, 0, sched_skip_cf_predicator, (void *) senv->chordal_env->birg->main_env->arch_env);
256                 sched_add_after(insert, res);
257         } else {
258                 sched_add_before(reloader, res);
259         }
260
261         return res;
262 }
263
264 #endif
265
266 void be_insert_spills_reloads(spill_env_t *senv, pset *reload_set) {
267         const arch_env_t *aenv = senv->chordal_env->birg->main_env->arch_env;
268         ir_graph *irg          = senv->chordal_env->irg;
269         ir_node *irn;
270         spill_info_t *si;
271
272         /* get all special spilled phis */
273         DBG((senv->dbg, LEVEL_1, "Mem-phis:\n"));
274         senv->mem_phis = pset_new_ptr_default();
275         irg_walk_graph(senv->chordal_env->irg, phi_walker, NULL, senv);
276
277         /* Add reloads for mem_phis */
278         /* BETTER: These reloads (1) should only be inserted, if they are really needed */
279         DBG((senv->dbg, LEVEL_1, "Reloads for mem-phis:\n"));
280         for(irn = pset_first(senv->mem_phis); irn; irn = pset_next(senv->mem_phis)) {
281                 const ir_edge_t *e;
282                 DBG((senv->dbg, LEVEL_1, " Mem-phi %+F\n", irn));
283                 foreach_out_edge(irn, e) {
284                         ir_node *user = e->src;
285                         if (is_Phi(user) && !pset_find_ptr(senv->mem_phis, user)) {
286                                         ir_node *use_bl = get_nodes_block(user);
287                                         DBG((senv->dbg, LEVEL_1, " non-mem-phi user %+F\n", user));
288                                         be_add_reload_on_edge(senv, irn, use_bl, e->pos); /* (1) */
289                         }
290                 }
291         }
292
293         /* process each spilled node */
294         DBG((senv->dbg, LEVEL_1, "Insert spills and reloads:\n"));
295         for(si = set_first(senv->spills); si; si = set_next(senv->spills)) {
296                 reloader_t *rld;
297                 ir_mode *mode = get_irn_mode(si->spilled_node);
298                 pset *values = pset_new_ptr(16);
299
300                 /* go through all reloads for this spill */
301                 for(rld = si->reloaders; rld; rld = rld->next) {
302                         ir_node *new_val;
303
304                         /* the spill for this reloader */
305                         ir_node *spill   = be_spill_node(senv, si->spilled_node);
306
307 #ifdef BUGGY_REMAT
308                         if (check_remat_conditions(senv, spill, si->spilled_node, rld->reloader))
309                                 new_val = do_remat(senv, si->spilled_node, rld->reloader);
310                         else
311 #endif
312                                 /* do a reload */
313                                 new_val = be_reload(aenv, senv->cls, rld->reloader, mode, spill);
314
315                         DBG((senv->dbg, LEVEL_1, " %+F of %+F before %+F\n", new_val, si->spilled_node, rld->reloader));
316                         pset_insert_ptr(values, new_val);
317                         if(reload_set)
318                                 pset_insert_ptr(reload_set, new_val);
319                 }
320
321                 /* introduce copies, rewire the uses */
322                 assert(pset_count(values) > 0 && "???");
323                 pset_insert_ptr(values, si->spilled_node);
324                 be_ssa_constr_set_ignore(senv->chordal_env->dom_front, values, senv->mem_phis);
325
326                 del_pset(values);
327         }
328
329         for(irn = pset_first(senv->mem_phis); irn; irn = pset_next(senv->mem_phis)) {
330                 int i, n;
331                 for(i = 0, n = get_irn_arity(irn); i < n; ++i)
332                         set_irn_n(irn, i, new_r_Bad(senv->chordal_env->irg));
333                 sched_remove(irn);
334         }
335
336         del_pset(senv->mem_phis);
337 }
338
339 void be_add_reload(spill_env_t *senv, ir_node *to_spill, ir_node *before) {
340         spill_info_t templ, *res;
341         reloader_t *rel;
342
343         templ.spilled_node = to_spill;
344         templ.reloaders    = NULL;
345         res = set_insert(senv->spills, &templ, sizeof(templ), HASH_PTR(to_spill));
346
347         rel           = obstack_alloc(&senv->obst, sizeof(rel[0]));
348         rel->reloader = before;
349         rel->next     = res->reloaders;
350         res->reloaders = rel;
351 }
352
353 void be_add_reload_on_edge(spill_env_t *senv, ir_node *to_spill, ir_node *bl, int pos) {
354         ir_node *insert_bl = get_irn_arity(bl) == 1 ? sched_first(bl) : get_Block_cfgpred_block(bl, pos);
355         be_add_reload(senv, to_spill, insert_bl);
356 }
357
358
359
360 /****************************************
361
362         SPILL SLOT MANAGEMENT AND OPTS
363
364 ****************************************/
365
366 typedef struct _spill_slot_t {
367         unsigned size;
368         unsigned align;
369         pset *members;
370         ir_mode *largest_mode;  /* the mode of all members with largest size */
371 } spill_slot_t;
372
373 typedef struct _ss_env_t {
374         firm_dbg_module_t *dbg;
375         struct obstack ob;
376         be_chordal_env_t *cenv;
377         pmap *slots;            /* maps spill_contexts to spill_slots */
378   pmap *types;    /* maps modes to types */
379 } ss_env_t;
380
381
382 static void compute_spill_slots_walker(ir_node *spill, void *env) {
383         ss_env_t *ssenv = env;
384         ir_node *ctx;
385         pmap_entry *entry;
386         spill_slot_t *ss;
387
388         if (!be_is_Spill(spill))
389                 return;
390
391         /* check, if this spill is for a context already known */
392         ctx = be_get_Spill_context(spill);
393         entry = pmap_find(ssenv->slots, ctx);
394
395         if (!entry) {
396                 /* this is a new spill context */
397                 ss = obstack_alloc(&ssenv->ob, sizeof(*ss));
398                 ss->members = pset_new_ptr(8);
399                 ss->largest_mode = get_irn_mode(get_irn_n(spill, be_pos_Spill_val));
400                 ss->size = get_mode_size_bytes(ss->largest_mode);
401                 ss->align = ss->size; /* TODO Assumed for now */
402                 pmap_insert(ssenv->slots, ctx, ss);
403         } else {
404                 ir_node *irn;
405                 /* values with the same spill_ctx must go into the same spill slot */
406                 ss = entry->value;
407                 assert(ss->size == (unsigned)get_mode_size_bytes(get_irn_mode(get_irn_n(spill, be_pos_Spill_val))) && "Different sizes for the same spill slot are not allowed yet.");
408                 for (irn = pset_first(ss->members); irn; irn = pset_next(ss->members)) {
409                         /* use values_interfere here, because it uses the dominance check,
410                            which does work for values in memory */
411                         assert(!values_interfere(spill, irn) && "Spills for the same spill slot must not interfere!");
412                 }
413         }
414
415         pset_insert_ptr(ss->members, spill);
416 }
417
418 static int ss_sorter(const void *v1, const void *v2) {
419         const spill_slot_t *ss1 = v1;
420         const spill_slot_t *ss2 = v2;
421         return ((int) ss2->size) - ((int) ss1->size);
422 }
423
424
425 /**
426  * This function should optimize the spill slots.
427  *  - Coalescing of multiple slots
428  *  - Ordering the slots
429  *
430  * Input slots are in @p ssenv->slots
431  * @p size The count of initial spill slots in @p ssenv->slots
432  *         This also is the size of the preallocated array @p ass
433  *
434  * @return An array of spill slots @p ass in specific order
435  **/
436 static void optimize_slots(ss_env_t *ssenv, int size, spill_slot_t **ass) {
437         int i, o, used_slots;
438         pmap_entry *entr;
439
440         i=0;
441         pmap_foreach(ssenv->slots, entr)
442                 ass[i++] = entr->value;
443
444         /* Sort the array to minimize fragmentation and cache footprint.
445            Large slots come first */
446         qsort(ass, size, sizeof(ass[0]), ss_sorter);
447
448         /* For each spill slot:
449                 - assign a new offset to this slot
450             - xor find another slot to coalesce with */
451         used_slots = 0;
452         for (i=0; i<size; ++i) { /* for each spill slot */
453                 ir_node *n1;
454                 int tgt_slot = -1;
455
456                 DBG((ssenv->dbg, LEVEL_1, "Spill slot %d members:\n", i));
457                 for(n1 = pset_first(ass[i]->members); n1; n1 = pset_next(ass[i]->members))
458                         DBG((ssenv->dbg, LEVEL_1, "  %+F\n", n1));
459
460
461                 for (o=0; o < used_slots && tgt_slot == -1; ++o) { /* for each offset-assigned spill slot */
462                         /* check inter-slot-pairs for interference */
463                         ir_node *n2;
464                         for(n1 = pset_first(ass[i]->members); n1; n1 = pset_next(ass[i]->members))
465                                 for(n2 = pset_first(ass[o]->members); n2; n2 = pset_next(ass[o]->members))
466                                         if(values_interfere(n1, n2)) {
467                                                 pset_break(ass[i]->members);
468                                                 pset_break(ass[o]->members);
469                                                 DBG((ssenv->dbg, LEVEL_1, "    Interf %+F -- %+F\n", n1, n2));
470                                                 goto interf_detected;
471                                         }
472
473                         /* if we are here, there is no interference between ass[i] and ass[o] */
474                         tgt_slot = o;
475
476 interf_detected: /*nothing*/ ;
477                 }
478
479                 /* now the members of ass[i] join the members of ass[tgt_slot] */
480
481                 /* do we need a new slot? */
482                 if (tgt_slot == -1) {
483                         tgt_slot = used_slots;
484                         used_slots++;
485
486                         /* init slot */
487                         if (tgt_slot != i) {
488                                 ass[tgt_slot]->size = ass[i]->size;
489                                 del_pset(ass[tgt_slot]->members);
490                                 ass[tgt_slot]->members = pset_new_ptr(8);
491                         }
492                 }
493
494                 /* copy the members to the target pset */
495                 /* NOTE: If src and tgt pset are the same, inserting while iterating is not allowed */
496                 if (tgt_slot != i)
497                         for(n1 = pset_first(ass[i]->members); n1; n1 = pset_next(ass[i]->members))
498                                         pset_insert_ptr(ass[tgt_slot]->members, n1);
499         }
500 }
501
502 #define ALIGN_SPILL_AREA 16
503 #define pset_foreach(pset, elm)  for(elm=pset_first(pset); elm; elm=pset_next(pset))
504
505 /**
506  * Returns a spill type for a mode. Keep them in a map to reduce
507  * the number of types.
508  */
509 static ir_type *get_spill_type(pmap *types, ir_mode *mode) {
510   pmap_entry *e = pmap_find(types, mode);
511   ir_type *res;
512
513   if (! e) {
514                 char buf[64];
515     snprintf(buf, sizeof(buf), "spill_slot_type_%s", get_mode_name(mode));
516     res = new_type_primitive(new_id_from_str(buf), mode);
517     pmap_insert(types, mode, res);
518   }
519   else
520     res = e->value;
521   return res;
522 }
523
524 static void assign_entities(ss_env_t *ssenv, int n, spill_slot_t **ss) {
525         int i, offset;
526         ir_type *frame = get_irg_frame_type(ssenv->cenv->irg);
527
528         /* aligning by increasing frame size */
529         offset = get_type_size_bits(frame) / 8;
530         offset = round_up2(offset, ALIGN_SPILL_AREA);
531         set_type_size_bytes(frame, -1);
532
533         /* create entities and assign offsets according to size and alignment*/
534         for (i=0; i<n; ++i) {
535                 char buf[64];
536                 ident *name;
537                 entity *spill_ent;
538                 ir_node *irn;
539
540                 /* build entity */
541                 snprintf(buf, sizeof(buf), "spill_slot_%d", i);
542                 name = new_id_from_str(buf);
543
544                 spill_ent = new_entity(frame, name, get_spill_type(ssenv->types, ss[i]->largest_mode));
545
546                 /* align */
547                 offset = round_up2(offset, ss[i]->align);
548                 /* set */
549                 set_entity_offset_bytes(spill_ent, offset);
550                 /* next possible offset */
551                 offset += ss[i]->size;
552
553                 pset_foreach(ss[i]->members, irn)
554                         be_set_Spill_entity(irn, spill_ent);
555         }
556
557         /* set final size of stack frame */
558         set_type_size_bytes(frame, offset);
559 }
560
561 void be_compute_spill_offsets(be_chordal_env_t *cenv) {
562         ss_env_t ssenv;
563         spill_slot_t **ss;
564         int ss_size;
565         pmap_entry *pme;
566
567         obstack_init(&ssenv.ob);
568         ssenv.cenv  = cenv;
569         ssenv.slots = pmap_create();
570         ssenv.types = pmap_create();
571         ssenv.dbg   = firm_dbg_register("ir.be.spillslots");
572
573         /* Get initial spill slots */
574         irg_walk_graph(cenv->irg, NULL, compute_spill_slots_walker, &ssenv);
575
576         /* Build an empty array for optimized spill slots */
577         ss_size = pmap_count(ssenv.slots);
578         ss = obstack_alloc(&ssenv.ob, ss_size * sizeof(*ss));
579         optimize_slots(&ssenv, ss_size, ss);
580
581         /* Integrate slots into the stack frame entity */
582         assign_entities(&ssenv, ss_size, ss);
583
584         /* Clean up */
585         pmap_foreach(ssenv.slots, pme)
586         del_pset(((spill_slot_t *)pme->value)->members);
587         pmap_destroy(ssenv.slots);
588         pmap_destroy(ssenv.types);
589         obstack_free(&ssenv.ob, NULL);
590
591         be_copy_entities_to_reloads(cenv->irg);
592 }