values may die at every use
[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 #include "pdeq.h"
24
25 #include "belive_t.h"
26 #include "besched_t.h"
27 #include "bespill.h"
28 #include "benode_t.h"
29 #include "bechordal_t.h"
30
31 #define REMAT
32 /* This enables re-computation of values. Current state: Unfinished and buggy. */
33 #undef BUGGY_REMAT
34
35 typedef struct _reloader_t reloader_t;
36 typedef struct _spill_info_t spill_info_t;
37
38 struct _reloader_t {
39         reloader_t *next;
40         ir_node *reloader;
41 };
42
43 struct _spill_info_t {
44         ir_node *spilled_node;
45         reloader_t *reloaders;
46 };
47
48 typedef struct _spill_ctx_t {
49         ir_node *spilled;  /**< The spilled node. */
50         ir_node *user;     /**< The node this spill is for. */
51         ir_node *spill;    /**< The spill itself. */
52 } spill_ctx_t;
53
54 struct _spill_env_t {
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 separately */
61         ir_node **copies;                       /**< set of copies placed because of phi spills */
62         DEBUG_ONLY(firm_dbg_module_t *dbg;)
63 };
64
65 /* associated Phi -> Spill*/
66 typedef struct _phi_spill_assoc_t {
67         ir_node *phi;
68         ir_node *spill;
69 } phi_spill_assoc_t;
70
71 /**
72  * Compare two Phi->Spill associations.
73  */
74 static int cmp_phi_spill_assoc(const void *a, const void *b, size_t n) {
75         const phi_spill_assoc_t *p1 = a;
76         const phi_spill_assoc_t *p2 = b;
77         return p1->phi != p2->phi;
78 }
79
80 /**
81  * compare two spill contexts.
82  */
83 static int cmp_spillctx(const void *a, const void *b, size_t n) {
84         const spill_ctx_t *p = a;
85         const spill_ctx_t *q = b;
86         return p->user != q->user || p->spilled != q->spilled;
87 }
88
89 /**
90  * Compare two spill infos.
91  */
92 static int cmp_spillinfo(const void *x, const void *y, size_t size) {
93         const spill_info_t *xx = x;
94         const spill_info_t *yy = y;
95         return xx->spilled_node != yy->spilled_node;
96 }
97
98 DEBUG_ONLY(
99 /* Sets the debug module of a spill environment. */
100 void be_set_spill_env_dbg_module(spill_env_t *env, firm_dbg_module_t *dbg) {
101         env->dbg = dbg;
102 }
103 )
104
105 /* Creates a new spill environment. */
106 spill_env_t *be_new_spill_env(const be_chordal_env_t *chordal_env) {
107         spill_env_t *env        = xmalloc(sizeof(env[0]));
108         env->spill_ctxs         = new_set(cmp_spillctx, 1024);
109         env->spills                     = new_set(cmp_spillinfo, 1024);
110         env->cls                        = chordal_env->cls;
111         env->chordal_env        = chordal_env;
112         env->mem_phis           = pset_new_ptr_default();
113         env->copies                     = NEW_ARR_F(ir_node*, 0);
114         obstack_init(&env->obst);
115         return env;
116 }
117
118 /* Deletes a spill environment. */
119 void be_delete_spill_env(spill_env_t *env) {
120         del_set(env->spill_ctxs);
121         del_set(env->spills);
122         del_pset(env->mem_phis);
123         DEL_ARR_F(env->copies);
124         obstack_free(&env->obst, NULL);
125         free(env);
126 }
127
128 /**
129  * Returns a spill context. If the context did not exists, create one.
130  *
131  * @param sc        the set containing all spill contexts
132  * @param to_spill  the node that should be spilled
133  * @param ctx_irn   an user of the spilled node
134  *
135  * @return a spill context.
136  */
137 static spill_ctx_t *be_get_spill_ctx(set *sc, ir_node *to_spill, ir_node *ctx_irn) {
138         spill_ctx_t templ;
139
140         templ.spilled = to_spill;
141         templ.user    = ctx_irn;
142         templ.spill   = NULL;
143
144         return set_insert(sc, &templ, sizeof(templ), HASH_COMBINE(HASH_PTR(to_spill), HASH_PTR(ctx_irn)));
145 }
146
147 /**
148  * Schedules a node after an instruction. (That is the place after all projs and phis
149  * that are scheduled after the instruction)
150  */
151 static void sched_add_after_insn(ir_node *sched_after, ir_node *node) {
152         ir_node *next = sched_next(sched_after);
153         while(!sched_is_end(next)) {
154                 if(!is_Proj(next) && !is_Phi(next))
155                         break;
156                 next = sched_next(next);
157         }
158
159         if(sched_is_end(next)) {
160                 next = sched_last(get_nodes_block(sched_after));
161                 sched_add_after(next, node);
162         } else {
163                 sched_add_before(next, node);
164         }
165 }
166
167 /**
168  * Creates a spill.
169  *
170  * @param senv      the spill environment
171  * @param irn       the node that should be spilled
172  * @param ctx_irn   an user of the spilled node
173  *
174  * @return a be_Spill node
175  */
176 static ir_node *be_spill_irn(spill_env_t *senv, ir_node *irn, ir_node *ctx_irn) {
177         spill_ctx_t *ctx;
178         const be_main_env_t *env = senv->chordal_env->birg->main_env;
179         DBG((senv->dbg, LEVEL_1, "%+F in ctx %+F\n", irn, ctx_irn));
180
181         // Has the value already been spilled?
182         ctx = be_get_spill_ctx(senv->spill_ctxs, irn, ctx_irn);
183         if(ctx->spill)
184                 return ctx->spill;
185
186         /* Trying to spill an already spilled value, no need for a new spill
187          * node then, we can simply connect to the same one for this reload
188          */
189         if(be_is_Reload(irn)) {
190                 return get_irn_n(irn, be_pos_Reload_mem);
191         }
192
193         ctx->spill = be_spill(env->arch_env, irn, ctx_irn);
194         sched_add_after_insn(irn, ctx->spill);
195
196         return ctx->spill;
197 }
198
199 /**
200  * Removes all copies introduced for phi-spills
201  */
202 static void remove_copies(spill_env_t *env) {
203         int i;
204
205         for(i = 0; i < ARR_LEN(env->copies); ++i) {
206                 ir_node *node = env->copies[i];
207                 ir_node *src;
208                 const ir_edge_t *edge, *ne;
209
210                 assert(be_is_Copy(node));
211
212                 src = be_get_Copy_op(node);
213                 foreach_out_edge_safe(node, edge, ne) {
214                         ir_node *user = get_edge_src_irn(edge);
215                         int user_pos  = get_edge_src_pos(edge);
216
217                         set_irn_n(user, user_pos, src);
218                 }
219         }
220
221         ARR_SETLEN(ir_node*, env->copies, 0);
222 }
223
224 static INLINE ir_node *skip_projs(ir_node *node) {
225         while(is_Proj(node)) {
226                 node = sched_next(node);
227                 assert(!sched_is_end(node));
228         }
229
230         return node;
231 }
232
233 /**
234  * Searchs the schedule backwards until we reach the first use or def of a
235  * value or a phi.
236  * Returns the node before this node (so that you can do sched_add_before)
237  */
238 static ir_node *find_last_use_def(spill_env_t *env, ir_node *block, ir_node *value) {
239         ir_node *node, *last;
240
241         last = NULL;
242         sched_foreach_reverse(block, node) {
243                 int i, arity;
244
245                 if(is_Phi(node)) {
246                         return last;
247                 }
248                 if(value == node) {
249                         return skip_projs(last);
250                 }
251                 for(i = 0, arity = get_irn_arity(node); i < arity; ++i) {
252                         ir_node *arg = get_irn_n(node, i);
253                         if(arg == value) {
254                                 return skip_projs(node);
255                         }
256                 }
257                 last = node;
258         }
259
260         // simply return first node if no def or use found
261         return sched_first(block);
262 }
263
264 /**
265  * If the first usage of a Phi result would be out of memory
266  * there is no sense in allocating a register for it.
267  * Thus we spill it and all its operands to the same spill slot.
268  * Therefore the phi/dataB becomes a phi/Memory
269  *
270  * @param senv      the spill environment
271  * @param phi       the Phi node that should be spilled
272  * @param ctx_irn   an user of the spilled node
273  *
274  * @return a be_Spill node
275  */
276 static ir_node *spill_phi(spill_env_t *senv, ir_node *phi, ir_node *ctx_irn, set *already_visited_phis, bitset_t *bs) {
277         int         i;
278         int arity = get_irn_arity(phi);
279         ir_graph    *irg      = senv->chordal_env->irg;
280         ir_node     *bl       = get_nodes_block(phi);
281         ir_node     **ins, *phi_spill;
282         phi_spill_assoc_t key;
283         spill_ctx_t *ctx;
284
285         assert(is_Phi(phi));
286         DBG((senv->dbg, LEVEL_1, "%+F in ctx %+F\n", phi, ctx_irn));
287
288         /* build a new PhiM */
289         NEW_ARR_A(ir_node *, ins, arity);
290         for (i = 0; i < arity; ++i) {
291                 ins[i] = new_r_Bad(irg);
292         }
293         phi_spill = new_r_Phi(senv->chordal_env->irg, bl, arity, ins, mode_M);
294         key.phi   = phi;
295         key.spill = phi_spill;
296         set_insert(already_visited_phis, &key, sizeof(key), HASH_PTR(phi));
297         bitset_set(bs, get_irn_idx(phi));
298
299         /* search an existing spill for this context */
300         ctx = be_get_spill_ctx(senv->spill_ctxs, phi, ctx_irn);
301
302         /* if not found spill the phi */
303         if (! ctx->spill) {
304                 /* collect all arguments of the phi */
305                 for (i = 0; i < arity; ++i) {
306                         ir_node *arg = get_irn_n(phi, i);
307                         ir_node *sub_res;
308                         phi_spill_assoc_t *entry;
309
310                         if(is_Phi(arg) && pset_find_ptr(senv->mem_phis, arg)) {
311                                 // looping edge?
312                                 if(arg == phi) {
313                                         sub_res = phi_spill;
314                                 } else if (! bitset_is_set(bs, get_irn_idx(arg))) {
315                                         sub_res = spill_phi(senv, arg, ctx_irn, already_visited_phis, bs);
316                                 } else {
317                                         /* we already visited the argument phi: get it's spill */
318                                         key.phi   = arg;
319                                         key.spill = NULL;
320                                         entry     = set_find(already_visited_phis, &key, sizeof(key), HASH_PTR(arg));
321                                         assert(entry && "argument phi already visited, but no spill found?!?");
322                                         sub_res   = entry->spill;
323                                         assert(sub_res && "spill missing?!?");
324                                 }
325                         } else {
326                                 sub_res = be_spill_irn(senv, arg, ctx_irn);
327                         }
328
329                         set_irn_n(phi_spill, i, sub_res);
330                 }
331
332                 ctx->spill = phi_spill;
333         }
334         return ctx->spill;
335 }
336
337 /**
338  * Spill a node.
339  *
340  * @param senv      the spill environment
341  * @param to_spill  the node that should be spilled
342  *
343  * @return a be_Spill node
344  */
345 static ir_node *be_spill_node(spill_env_t *senv, ir_node *to_spill) {
346         ir_graph *irg = get_irn_irg(to_spill);
347         ir_node  *res;
348
349         if (pset_find_ptr(senv->mem_phis, to_spill)) {
350                 set *already_visited_phis = new_set(cmp_phi_spill_assoc, 10);
351                 bitset_t *bs = bitset_alloca(get_irg_last_idx(irg));
352                 res = spill_phi(senv, to_spill, to_spill, already_visited_phis, bs);
353                 del_set(already_visited_phis);
354         } else {
355                 res = be_spill_irn(senv, to_spill, to_spill);
356         }
357
358         return res;
359 }
360
361 #ifdef REMAT
362
363 #ifdef BUGGY_REMAT
364
365 /**
366  * Check if a spilled node could be rematerialized.
367  *
368  * @param senv      the spill environment
369  * @param spill     the Spill node
370  * @param spilled   the node that was spilled
371  * @param reloader  a irn that requires a reload
372  */
373 static int check_remat_conditions(spill_env_t *senv, ir_node *spill, ir_node *spilled, ir_node *reloader) {
374         int pos, max;
375
376         /* check for 'normal' spill and general remat condition */
377         if (!be_is_Spill(spill) || !arch_irn_is(senv->chordal_env->birg->main_env->arch_env, spilled, rematerializable))
378                 return 0;
379
380         /* check availability of original arguments */
381         if (is_Block(reloader)) {
382
383                 /* we want to remat at the end of a block.
384                  * thus all arguments must be alive at the end of the block
385                  */
386                 for (pos=0, max=get_irn_arity(spilled); pos<max; ++pos) {
387                         ir_node *arg = get_irn_n(spilled, pos);
388                         if (!is_live_end(reloader, arg))
389                                 return 0;
390                 }
391
392         } else {
393
394                 /* we want to remat before the insn reloader
395                  * thus an arguments is alive if
396                  *   - it interferes with the reloaders result
397                  * or
398                  *   - or it is (last-) used by reloader itself
399                  */
400                 for (pos=0, max=get_irn_arity(spilled); pos<max; ++pos) {
401                         ir_node *arg = get_irn_n(spilled, pos);
402                         int i, m;
403
404                         if (values_interfere(reloader, arg))
405                                 goto is_alive;
406
407                         for (i=0, m=get_irn_arity(reloader); i<m; ++i) {
408                                 ir_node *rel_arg = get_irn_n(reloader, i);
409                                 if (rel_arg == arg)
410                                         goto is_alive;
411                         }
412
413                         /* arg is not alive before reloader */
414                         return 0;
415
416 is_alive:       ;
417
418                 }
419
420         }
421
422         return 1;
423 }
424
425 #else /* BUGGY_REMAT */
426
427 /**
428  * A very simple rematerialization checker.
429  *
430  * @param senv      the spill environment
431  * @param spill     the Spill node
432  * @param spilled   the node that was spilled
433  * @param reloader  a irn that requires a reload
434  */
435 static int check_remat_conditions(spill_env_t *senv, ir_node *spill, ir_node *spilled, ir_node *reloader) {
436         const arch_env_t *aenv = senv->chordal_env->birg->main_env->arch_env;
437
438         return get_irn_arity(spilled) == 0 &&
439                    be_is_Spill(spill) &&
440                    arch_irn_is(aenv, spilled, rematerializable);
441 }
442
443 #endif /* BUGGY_REMAT */
444
445 #endif /* REMAT */
446
447 /**
448  * Re-materialize a node.
449  *
450  * @param senv      the spill environment
451  * @param spilled   the node that was spilled
452  * @param reloader  a irn that requires a reload
453  */
454 static ir_node *do_remat(spill_env_t *senv, ir_node *spilled, ir_node *reloader) {
455         ir_node *res;
456         ir_node *bl = (is_Block(reloader)) ? reloader : get_nodes_block(reloader);
457
458         /* recompute the value */
459         res = new_ir_node(get_irn_dbg_info(spilled), senv->chordal_env->irg, bl,
460                 get_irn_op(spilled),
461                 get_irn_mode(spilled),
462                 get_irn_arity(spilled),
463                 get_irn_in(spilled) + 1);
464         copy_node_attr(spilled, res);
465
466         DBG((senv->dbg, LEVEL_1, "Insert remat %+F before reloader %+F\n", res, reloader));
467
468         /* insert in schedule */
469         if (is_Block(reloader)) {
470                 ir_node *insert = sched_skip(reloader, 0, sched_skip_cf_predicator, (void *) senv->chordal_env->birg->main_env->arch_env);
471                 sched_add_after(insert, res);
472         } else {
473                 sched_add_before(reloader, res);
474         }
475
476         return res;
477 }
478
479 void be_spill_phi(spill_env_t *env, ir_node *node) {
480         int i, arity;
481
482         assert(is_Phi(node));
483
484         pset_insert_ptr(env->mem_phis, node);
485
486         /* We have to place copy nodes in the predecessor blocks to temporarily
487          * produce new values that get separate spill slots
488          */
489         for(i = 0, arity = get_irn_arity(node); i < arity; ++i) {
490                 ir_node *pred_block, *arg, *copy, *insert_point;
491
492                 /* Don't do anything for looping edges (there's no need
493                  * and placing copies here breaks stuff as it suddenly
494                  * generates new living values through the whole loop)
495                  */
496                 arg = get_irn_n(node, i);
497                 if(arg == node)
498                         continue;
499
500                 pred_block = get_Block_cfgpred_block(get_nodes_block(node), i);
501                 copy = be_new_Copy(env->cls, get_irn_irg(arg), pred_block, arg);
502
503                 ARR_APP1(ir_node*, env->copies, copy);
504                 insert_point = find_last_use_def(env, pred_block, arg);
505                 sched_add_before(insert_point, copy);
506
507                 set_irn_n(node, i, copy);
508         }
509 }
510
511 void be_insert_spills_reloads(spill_env_t *env) {
512         const arch_env_t *arch_env = env->chordal_env->birg->main_env->arch_env;
513         ir_node *node;
514         spill_info_t *si;
515
516         DBG((env->dbg, LEVEL_1, "Reloads for mem-phis:\n"));
517         foreach_pset(env->mem_phis, node) {
518                 const ir_edge_t *e;
519
520                 assert(is_Phi(node));
521
522                 /* Add reloads for mem_phis */
523                 /* BETTER: These reloads (1) should only be inserted, if they are really needed */
524                 DBG((env->dbg, LEVEL_1, " Mem-phi %+F\n", node));
525                 foreach_out_edge(node, e) {
526                         ir_node *user = e->src;
527                         if (is_Phi(user) && !pset_find_ptr(env->mem_phis, user)) {
528                                 ir_node *use_bl = get_nodes_block(user);
529                                 DBG((env->dbg, LEVEL_1, " non-mem-phi user %+F\n", user));
530                                 be_add_reload_on_edge(env, node, use_bl, e->pos); /* (1) */
531                         }
532                 }
533         }
534
535         /* process each spilled node */
536         DBG((env->dbg, LEVEL_1, "Insert spills and reloads:\n"));
537         for(si = set_first(env->spills); si; si = set_next(env->spills)) {
538                 reloader_t *rld;
539                 ir_mode *mode = get_irn_mode(si->spilled_node);
540                 pset *values = pset_new_ptr(16);
541
542                 /* go through all reloads for this spill */
543                 for(rld = si->reloaders; rld; rld = rld->next) {
544                         ir_node *new_val;
545
546                         /* the spill for this reloader */
547                         ir_node *spill   = be_spill_node(env, si->spilled_node);
548
549 #ifdef REMAT
550                         if (check_remat_conditions(env, spill, si->spilled_node, rld->reloader)) {
551                                 new_val = do_remat(env, si->spilled_node, rld->reloader);
552                         } else
553 #endif
554                                 /* do a reload */
555                                 new_val = be_reload(arch_env, env->cls, rld->reloader, mode, spill);
556
557                         DBG((env->dbg, LEVEL_1, " %+F of %+F before %+F\n", new_val, si->spilled_node, rld->reloader));
558                         pset_insert_ptr(values, new_val);
559                 }
560
561                 /* introduce copies, rewire the uses */
562                 assert(pset_count(values) > 0 && "???");
563                 pset_insert_ptr(values, si->spilled_node);
564                 be_ssa_constr_set_ignore(env->chordal_env->dom_front, values, env->mem_phis);
565
566                 del_pset(values);
567         }
568
569         remove_copies(env);
570
571         // reloads are placed now, but we might reuse the spill environment for further spilling decisions
572         del_set(env->spills);
573         env->spills = new_set(cmp_spillinfo, 1024);
574 }
575
576 void be_add_reload(spill_env_t *env, ir_node *to_spill, ir_node *before) {
577         spill_info_t templ, *res;
578         reloader_t *rel;
579
580         assert(sched_is_scheduled(before));
581         assert(arch_irn_consider_in_reg_alloc(env->chordal_env->birg->main_env->arch_env, env->cls, to_spill));
582
583         templ.spilled_node = to_spill;
584         templ.reloaders    = NULL;
585         res = set_insert(env->spills, &templ, sizeof(templ), HASH_PTR(to_spill));
586
587         rel           = obstack_alloc(&env->obst, sizeof(rel[0]));
588         rel->reloader = before;
589         rel->next     = res->reloaders;
590         res->reloaders = rel;
591 }
592
593 void be_add_reload_on_edge(spill_env_t *env, ir_node *to_spill, ir_node *block, int pos) {
594         ir_node *predblock, *last;
595
596         /* simply add the reload to the beginning of the block if we only have 1 predecessor
597          * (we don't need to check for phis as there can't be any in a block with only 1 pred)
598          */
599         if(get_Block_n_cfgpreds(block) == 1) {
600                 assert(!is_Phi(sched_first(block)));
601                 be_add_reload(env, to_spill, sched_first(block));
602                 return;
603         }
604
605         /* We have to reload the value in pred-block */
606         predblock = get_Block_cfgpred_block(block, pos);
607         last = sched_last(predblock);
608
609         /* we might have projs and keepanys behind the jump... */
610         while(is_Proj(last) || be_is_Keep(last)) {
611                 last = sched_prev(last);
612                 assert(!sched_is_end(last));
613         }
614         assert(is_cfop(last));
615
616         // add the reload before the (cond-)jump
617         be_add_reload(env, to_spill, last);
618 }
619
620 /****************************************
621
622         SPILL SLOT MANAGEMENT AND OPTS
623
624 ****************************************/
625
626 typedef struct _spill_slot_t {
627         unsigned size;
628         unsigned align;
629         pset *members;
630         ir_mode *largest_mode;  /* the mode of all members with largest size */
631 } spill_slot_t;
632
633 typedef struct _ss_env_t {
634         struct obstack ob;
635         be_chordal_env_t *cenv;
636         pmap *slots;            /* maps spill_contexts to spill_slots */
637         pmap *types;    /* maps modes to types */
638         DEBUG_ONLY(firm_dbg_module_t *dbg;)
639 } ss_env_t;
640
641
642 /**
643  * Walker: compute the spill slots
644  */
645 static void compute_spill_slots_walker(ir_node *spill, void *env) {
646         ss_env_t *ssenv = env;
647         ir_node *ctx;
648         pmap_entry *entry;
649         spill_slot_t *ss;
650
651         if (!be_is_Spill(spill))
652                 return;
653
654         /* check, if this spill is for a context already known */
655         ctx = be_get_Spill_context(spill);
656         entry = pmap_find(ssenv->slots, ctx);
657
658         if (!entry) {
659                 struct _arch_env_t *arch_env     = ssenv->cenv->birg->main_env->arch_env;
660                 const arch_register_class_t *cls = arch_get_irn_reg_class(arch_env, spill, be_pos_Spill_val);
661                 ir_mode *largest_mode            = arch_register_class_mode(cls);
662
663                 /* this is a new spill context */
664                 ss = obstack_alloc(&ssenv->ob, sizeof(*ss));
665                 ss->members      = pset_new_ptr(8);
666                 ss->largest_mode = largest_mode;
667                 ss->size         = get_mode_size_bytes(ss->largest_mode);
668                 ss->align        = arch_isa_get_reg_class_alignment(arch_env->isa, cls);
669                 pmap_insert(ssenv->slots, ctx, ss);
670         } else {
671                 /* values with the same spill_ctx must go into the same spill slot */
672                 ss = entry->value;
673
674 #ifndef NDEBUG
675                 /* ugly mega assert :-) */
676                 {
677                         ir_node *irn;
678                         struct _arch_env_t *arch_env     = ssenv->cenv->birg->main_env->arch_env;
679                         const arch_register_class_t *cls = arch_get_irn_reg_class(arch_env, spill, be_pos_Spill_val);
680                         int size = get_mode_size_bytes(arch_register_class_mode(cls));
681                         assert((int) ss->size == size && "Different sizes for the same spill slot are not allowed.");
682                         for (irn = pset_first(ss->members); irn; irn = pset_next(ss->members)) {
683                                 /* use values_interfere here, because it uses the dominance check,
684                                          which does work for values in memory */
685                                 assert(!values_interfere(spill, irn) && "Spills for the same spill slot must not interfere!");
686                         }
687                 }
688 #endif /* NDEBUG */
689         }
690
691         pset_insert_ptr(ss->members, spill);
692 }
693
694 /**
695  * qsort compare function, sort spill slots by size.
696  */
697 static int ss_sorter(const void *v1, const void *v2) {
698         const spill_slot_t **ss1 = (const spill_slot_t **)v1;
699         const spill_slot_t **ss2 = (const spill_slot_t **)v2;
700         return ((int) (*ss2)->size) - ((int) (*ss1)->size);
701 }
702
703
704 /**
705  * This function should optimize the spill slots.
706  *  - Coalescing of multiple slots
707  *  - Ordering the slots
708  *
709  * Input slots are in @p ssenv->slots
710  * @p size The count of initial spill slots in @p ssenv->slots
711  *         This also is the size of the preallocated array @p ass
712  *
713  * @return An array of spill slots @p ass in specific order
714  **/
715 static void optimize_slots(ss_env_t *ssenv, int size, spill_slot_t *ass[]) {
716         int i, o, used_slots;
717         pmap_entry *entr;
718
719         i=0;
720         pmap_foreach(ssenv->slots, entr)
721                 ass[i++] = entr->value;
722
723         /* Sort the array to minimize fragmentation and cache footprint.
724            Large slots come first */
725         qsort(ass, size, sizeof(ass[0]), ss_sorter);
726
727         /* For each spill slot:
728                 - assign a new offset to this slot
729             - xor find another slot to coalesce with */
730         used_slots = 0;
731         for (i=0; i<size; ++i) { /* for each spill slot */
732                 ir_node *n1;
733                 int tgt_slot = -1;
734
735                 DBG((ssenv->dbg, LEVEL_1, "Spill slot %d members:\n", i));
736                 for(n1 = pset_first(ass[i]->members); n1; n1 = pset_next(ass[i]->members))
737                         DBG((ssenv->dbg, LEVEL_1, "  %+F\n", n1));
738
739
740                 for (o=0; o < used_slots && tgt_slot == -1; ++o) { /* for each offset-assigned spill slot */
741                         /* check inter-slot-pairs for interference */
742                         ir_node *n2;
743                         for(n1 = pset_first(ass[i]->members); n1; n1 = pset_next(ass[i]->members))
744                                 for(n2 = pset_first(ass[o]->members); n2; n2 = pset_next(ass[o]->members))
745                                         if(values_interfere(n1, n2)) {
746                                                 pset_break(ass[i]->members);
747                                                 pset_break(ass[o]->members);
748                                                 DBG((ssenv->dbg, LEVEL_1, "    Interf %+F -- %+F\n", n1, n2));
749                                                 goto interf_detected;
750                                         }
751
752                         /* if we are here, there is no interference between ass[i] and ass[o] */
753                         tgt_slot = o;
754
755 interf_detected: /*nothing*/ ;
756                 }
757
758                 /* now the members of ass[i] join the members of ass[tgt_slot] */
759
760                 /* do we need a new slot? */
761                 if (tgt_slot == -1) {
762                         tgt_slot = used_slots;
763                         used_slots++;
764
765                         /* init slot */
766                         if (tgt_slot != i) {
767                                 ass[tgt_slot]->size = ass[i]->size;
768                                 del_pset(ass[tgt_slot]->members);
769                                 ass[tgt_slot]->members = pset_new_ptr(8);
770                         }
771                 }
772
773                 /* copy the members to the target pset */
774                 /* NOTE: If src and tgt pset are the same, inserting while iterating is not allowed */
775                 if (tgt_slot != i)
776                         for(n1 = pset_first(ass[i]->members); n1; n1 = pset_next(ass[i]->members))
777                                         pset_insert_ptr(ass[tgt_slot]->members, n1);
778         }
779 }
780
781 #define ALIGN_SPILL_AREA 16
782 #define pset_foreach(pset, elm)  for(elm=pset_first(pset); elm; elm=pset_next(pset))
783
784 /**
785  * Returns a spill type for a mode. Keep them in a map to reduce
786  * the number of types.
787  *
788  * @param types  a map containing all created types
789  * @param ss     the spill slot
790  *
791  * Note that type types should are identical for every mode.
792  * This rule might break if two different register classes return the same
793  * mode but different alignments.
794  */
795 static ir_type *get_spill_type(pmap *types, spill_slot_t *ss) {
796         pmap_entry *e = pmap_find(types, ss->largest_mode);
797         ir_type *res;
798
799         if (! e) {
800                 char buf[64];
801                 snprintf(buf, sizeof(buf), "spill_slot_type_%s", get_mode_name(ss->largest_mode));
802                 buf[sizeof(buf) - 1] = '\0';
803                 res = new_type_primitive(new_id_from_str(buf), ss->largest_mode);
804                 set_type_alignment_bytes(res, ss->align);
805                 pmap_insert(types, ss->largest_mode, res);
806         } else {
807                 res = e->value;
808                 assert(get_type_alignment_bytes(res) == (int)ss->align);
809         }
810
811         return res;
812 }
813
814 /**
815  * Create spill slot entities on the frame type.
816  *
817  * @param ssenv   the spill environment
818  * @param n       number of spill slots
819  * @param ss      array of spill slots
820  */
821 static void assign_entities(ss_env_t *ssenv, int n_slots, spill_slot_t *ss[]) {
822         int i, offset, frame_align;
823         ir_type *frame;
824
825         /* do not align the frame if no spill slots are needed */
826         if (n_slots <= 0)
827                 return;
828
829         frame = get_irg_frame_type(ssenv->cenv->irg);
830
831         /* aligning by increasing frame size */
832         offset = get_type_size_bytes(frame);
833         offset = round_up2(offset, ALIGN_SPILL_AREA);
834
835         /* create entities and assign offsets according to size and alignment*/
836         for (i = 0; i < n_slots; ++i) {
837                 char buf[64];
838                 ident *name;
839                 entity *spill_ent;
840                 ir_node *irn;
841
842                 /* build entity */
843                 snprintf(buf, sizeof(buf), "spill_slot_%d", i);
844                 buf[sizeof(buf) - 1] = '\0';
845                 name = new_id_from_str(buf);
846
847                 spill_ent = new_entity(frame, name, get_spill_type(ssenv->types, ss[i]));
848
849                 /* align */
850                 offset = round_up2(offset, ss[i]->align);
851                 /* set */
852                 set_entity_offset_bytes(spill_ent, offset);
853                 /* next possible offset */
854                 offset += round_up2(ss[i]->size, ss[i]->align);
855
856                 pset_foreach(ss[i]->members, irn)
857                         be_set_Spill_entity(irn, spill_ent);
858         }
859
860
861         /* set final size of stack frame */
862         frame_align = get_type_alignment_bytes(frame);
863         set_type_size_bytes(frame, round_up2(offset, frame_align));
864 }
865
866 void be_compute_spill_offsets(be_chordal_env_t *cenv) {
867         ss_env_t ssenv;
868         spill_slot_t **ss;
869         int ss_size;
870         pmap_entry *pme;
871
872         obstack_init(&ssenv.ob);
873         ssenv.cenv  = cenv;
874         ssenv.slots = pmap_create();
875         ssenv.types = pmap_create();
876         FIRM_DBG_REGISTER(ssenv.dbg, "ir.be.spillslots");
877
878         /* Get initial spill slots */
879         irg_walk_graph(cenv->irg, NULL, compute_spill_slots_walker, &ssenv);
880
881         /* Build an empty array for optimized spill slots */
882         ss_size = pmap_count(ssenv.slots);
883         ss = obstack_alloc(&ssenv.ob, ss_size * sizeof(*ss));
884         optimize_slots(&ssenv, ss_size, ss);
885
886         /* Integrate slots into the stack frame entity */
887         assign_entities(&ssenv, ss_size, ss);
888
889         /* Clean up */
890         pmap_foreach(ssenv.slots, pme)
891         del_pset(((spill_slot_t *)pme->value)->members);
892         pmap_destroy(ssenv.slots);
893         pmap_destroy(ssenv.types);
894         obstack_free(&ssenv.ob, NULL);
895
896         be_copy_entities_to_reloads(cenv->irg);
897 }