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