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