no environment anymore for emitters
[libfirm] / ir / be / bespill.c
1 /*
2  * Copyright (C) 1995-2007 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       implementation of the spill/reload placement abstraction layer
23  * @author      Daniel Grund, Sebastian Hack, Matthias Braun
24  * @date                29.09.2005
25  * @version     $Id$
26  */
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include <stdlib.h>
32
33 #include "pset.h"
34 #include "irnode_t.h"
35 #include "ircons_t.h"
36 #include "iredges_t.h"
37 #include "irbackedge_t.h"
38 #include "irprintf.h"
39 #include "ident_t.h"
40 #include "type_t.h"
41 #include "entity_t.h"
42 #include "debug.h"
43 #include "irgwalk.h"
44 #include "array.h"
45 #include "pdeq.h"
46 #include "execfreq.h"
47 #include "irnodeset.h"
48
49 #include "bearch_t.h"
50 #include "belive_t.h"
51 #include "besched_t.h"
52 #include "bespill.h"
53 #include "belive_t.h"
54 #include "benode_t.h"
55 #include "bechordal_t.h"
56 #include "bejavacoal.h"
57 #include "benodesets.h"
58 #include "bespilloptions.h"
59 #include "bestatevent.h"
60 #include "bessaconstr.h"
61 #include "beirg_t.h"
62 #include "beintlive_t.h"
63 #include "bemodule.h"
64
65 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
66
67 #define REMAT_COST_INFINITE  1000
68
69 typedef struct reloader_t reloader_t;
70 struct reloader_t {
71         reloader_t *next;
72         ir_node    *can_spill_after;
73         ir_node    *reloader;
74         ir_node    *rematted_node;
75         int         remat_cost_delta; /** costs needed for rematerialization,
76                                            compared to placing a reload */
77 };
78
79 typedef struct spill_info_t spill_info_t;
80 struct spill_info_t {
81         ir_node    *to_spill;  /**< the value that should get spilled */
82         reloader_t *reloaders; /**< list of places where the value should get
83                                     reloaded */
84         ir_node    *spill;     /**< the spill node, or a PhiM node */
85         ir_node    *old_spill; /**< if we had the value of a phi spilled before but
86                                     not the phi itself then this field contains the
87                                     spill for the phi value */
88         const arch_register_class_t *reload_cls; /** the register class in which the
89                                                      reload should be placed */
90 };
91
92 struct spill_env_t {
93         const arch_env_t *arch_env;
94         ir_graph         *irg;
95         struct obstack    obst;
96         be_irg_t         *birg;
97         int               spill_cost;     /**< the cost of a single spill node */
98         int               reload_cost;    /**< the cost of a reload node */
99         set              *spills;         /**< all spill_info_t's, which must be
100                                                placed */
101         ir_nodeset_t      mem_phis;       /**< set of all spilled phis. */
102         ir_exec_freq     *exec_freq;
103
104 #ifdef FIRM_STATISTICS
105         unsigned          spill_count;
106         unsigned          reload_count;
107         unsigned          remat_count;
108         unsigned          spilled_phi_count;
109 #endif
110 };
111
112 /**
113  * Compare two spill infos.
114  */
115 static
116 int cmp_spillinfo(const void *x, const void *y, size_t size)
117 {
118         const spill_info_t *xx = x;
119         const spill_info_t *yy = y;
120         (void) size;
121
122         return xx->to_spill != yy->to_spill;
123 }
124
125 /**
126  * Returns spill info for a specific value (the value that is to be spilled)
127  */
128 static
129 spill_info_t *get_spillinfo(const spill_env_t *env, ir_node *value)
130 {
131         spill_info_t info, *res;
132         int hash = nodeset_hash(value);
133
134         info.to_spill = value;
135         res = set_find(env->spills, &info, sizeof(info), hash);
136
137         if (res == NULL) {
138                 info.reloaders = NULL;
139                 info.spill = NULL;
140                 info.old_spill = NULL;
141                 info.reload_cls = NULL;
142                 res = set_insert(env->spills, &info, sizeof(info), hash);
143         }
144
145         return res;
146 }
147
148 spill_env_t *be_new_spill_env(be_irg_t *birg)
149 {
150         const arch_env_t *arch_env = birg->main_env->arch_env;
151
152         spill_env_t *env        = xmalloc(sizeof(env[0]));
153         env->spills                     = new_set(cmp_spillinfo, 1024);
154         env->irg            = be_get_birg_irg(birg);
155         env->birg           = birg;
156         env->arch_env       = arch_env;
157         ir_nodeset_init(&env->mem_phis);
158         env->spill_cost     = arch_env->isa->spill_cost;
159         env->reload_cost    = arch_env->isa->reload_cost;
160         env->exec_freq      = be_get_birg_exec_freq(birg);
161         obstack_init(&env->obst);
162
163 #ifdef FIRM_STATISTICS
164         env->spill_count       = 0;
165         env->reload_count      = 0;
166         env->remat_count       = 0;
167         env->spilled_phi_count = 0;
168 #endif
169
170         return env;
171 }
172
173 void be_delete_spill_env(spill_env_t *env)
174 {
175         del_set(env->spills);
176         ir_nodeset_destroy(&env->mem_phis);
177         obstack_free(&env->obst, NULL);
178         free(env);
179 }
180
181 /*
182  *  ____  _                  ____      _                 _
183  * |  _ \| | __ _  ___ ___  |  _ \ ___| | ___   __ _  __| |___
184  * | |_) | |/ _` |/ __/ _ \ | |_) / _ \ |/ _ \ / _` |/ _` / __|
185  * |  __/| | (_| | (_|  __/ |  _ <  __/ | (_) | (_| | (_| \__ \
186  * |_|   |_|\__,_|\___\___| |_| \_\___|_|\___/ \__,_|\__,_|___/
187  *
188  */
189
190 void be_add_remat(spill_env_t *env, ir_node *to_spill, ir_node *before,
191                   ir_node *rematted_node)
192 {
193         spill_info_t *spill_info;
194         reloader_t *reloader;
195
196         spill_info = get_spillinfo(env, to_spill);
197
198         /* add the remat information */
199         reloader                = obstack_alloc(&env->obst, sizeof(reloader[0]));
200         reloader->next          = spill_info->reloaders;
201         reloader->reloader      = before;
202         reloader->rematted_node = rematted_node;
203         reloader->remat_cost_delta = 0; /* We will never have a cost win over a
204                                            reload since we're not even allowed to
205                                            create a reload */
206
207         spill_info->reloaders  = reloader;
208
209         DBG((dbg, LEVEL_1, "creating spillinfo for %+F, will be rematerialized before %+F\n",
210                 to_spill, before));
211 }
212
213 void be_add_reload2(spill_env_t *env, ir_node *to_spill, ir_node *before, ir_node *can_spill_after,
214                    const arch_register_class_t *reload_cls, int allow_remat)
215 {
216         spill_info_t *info;
217         reloader_t *rel;
218
219         info = get_spillinfo(env, to_spill);
220
221         if (is_Phi(to_spill)) {
222                 int i, arity;
223
224                 /* create spillinfos for the phi arguments */
225                 for (i = 0, arity = get_irn_arity(to_spill); i < arity; ++i) {
226                         ir_node *arg = get_irn_n(to_spill, i);
227                         get_spillinfo(env, arg);
228                 }
229
230 #if 1
231                 /* hackery... sometimes the morgan algo spilled the value of a phi,
232                  * the belady algo decides later to spill the whole phi, then sees the
233                  * spill node and adds a reload for that spill node, problem is the
234                  * reload gets attach to that same spill (and is totally unnecessary)
235                  */
236                 if (info->old_spill != NULL &&
237                         (before == info->old_spill || value_dominates(before, info->old_spill)))
238                 {
239                         printf("spilledphi hack was needed...\n");
240                         before = sched_next(info->old_spill);
241                 }
242 #endif
243         }
244
245         assert(!is_Proj(before) && !be_is_Keep(before));
246
247         /* put reload into list */
248         rel                   = obstack_alloc(&env->obst, sizeof(rel[0]));
249         rel->next             = info->reloaders;
250         rel->reloader         = before;
251         rel->rematted_node    = NULL;
252         rel->can_spill_after  = can_spill_after;
253         rel->remat_cost_delta = allow_remat ? 0 : REMAT_COST_INFINITE;
254
255         info->reloaders  = rel;
256         assert(info->reload_cls == NULL || info->reload_cls == reload_cls);
257         info->reload_cls = reload_cls;
258
259         DBG((dbg, LEVEL_1, "creating spillinfo for %+F, will be reloaded before %+F, may%s be rematerialized\n",
260                 to_spill, before, allow_remat ? "" : " not"));
261 }
262
263 void be_add_reload(spill_env_t *senv, ir_node *to_spill, ir_node *before,
264                    const arch_register_class_t *reload_cls, int allow_remat)
265 {
266         be_add_reload2(senv, to_spill, before, to_spill, reload_cls, allow_remat);
267
268 }
269
270 ir_node *be_get_end_of_block_insertion_point(const ir_node *block)
271 {
272         ir_node *last = sched_last(block);
273
274         /* we might have projs and keepanys behind the jump... */
275         while(is_Proj(last) || be_is_Keep(last)) {
276                 last = sched_prev(last);
277                 assert(!sched_is_end(last));
278         }
279
280         if(!is_cfop(last)) {
281                 last = sched_next(last);
282                 /* last node must be a cfop, only exception is the start block */
283                 assert(last     == get_irg_start_block(get_irn_irg(block)));
284         }
285
286         /* add the reload before the (cond-)jump */
287         return last;
288 }
289
290 /**
291  * Returns the point at which you can insert a node that should be executed
292  * before block @p block when coming from pred @p pos.
293  */
294 static
295 ir_node *get_block_insertion_point(ir_node *block, int pos)
296 {
297         ir_node *predblock;
298
299         /* simply add the reload to the beginning of the block if we only have 1
300          * predecessor. We don't need to check for phis as there can't be any in a
301          * block with only 1 pred. */
302         if(get_Block_n_cfgpreds(block) == 1) {
303                 assert(!is_Phi(sched_first(block)));
304                 return sched_first(block);
305         }
306
307         /* We have to reload the value in pred-block */
308         predblock = get_Block_cfgpred_block(block, pos);
309         return be_get_end_of_block_insertion_point(predblock);
310 }
311
312 void be_add_reload_at_end(spill_env_t *env, ir_node *to_spill, const ir_node *block,
313                           const arch_register_class_t *reload_cls,
314                           int allow_remat)
315 {
316         ir_node *before = be_get_end_of_block_insertion_point(block);
317         be_add_reload(env, to_spill, before, reload_cls, allow_remat);
318 }
319
320 void be_add_reload_on_edge(spill_env_t *env, ir_node *to_spill, ir_node *block,
321                            int pos,     const arch_register_class_t *reload_cls,
322                            int allow_remat)
323 {
324         ir_node *before = get_block_insertion_point(block, pos);
325         be_add_reload(env, to_spill, before, reload_cls, allow_remat);
326 }
327
328 void be_spill_phi(spill_env_t *env, ir_node *node)
329 {
330         spill_info_t* spill;
331         int i, arity;
332
333         assert(is_Phi(node));
334
335         ir_nodeset_insert(&env->mem_phis, node);
336
337         /* create spillinfos for the phi arguments */
338         spill = get_spillinfo(env, node);
339         for(i = 0, arity = get_irn_arity(node); i < arity; ++i) {
340                 ir_node *arg = get_irn_n(node, i);
341                 get_spillinfo(env, arg);
342         }
343
344         /* if we had a spill for the phi value before, then remove this spill from
345          * schedule, as we will remove it in the insert spill/reload phase
346          */
347         if(spill->spill != NULL && !is_Phi(spill->spill)) {
348                 assert(spill->old_spill == NULL);
349                 spill->old_spill = spill->spill;
350                 spill->spill = NULL;
351         }
352 }
353
354 /*
355  *   ____                _         ____        _ _ _
356  *  / ___|_ __ ___  __ _| |_ ___  / ___| _ __ (_) | |___
357  * | |   | '__/ _ \/ _` | __/ _ \ \___ \| '_ \| | | / __|
358  * | |___| | |  __/ (_| | ||  __/  ___) | |_) | | | \__ \
359  *  \____|_|  \___|\__,_|\__\___| |____/| .__/|_|_|_|___/
360  *                                      |_|
361  */
362
363 /**
364  * Schedules a node after an instruction. That is the place after all projs and
365  * phis that are scheduled after the instruction. This function also skips phi
366  * nodes at the beginning of a block
367  */
368 static
369 void sched_add_after_insn(ir_node *sched_after, ir_node *node)
370 {
371         ir_node *next = sched_next(sched_after);
372         while(is_Proj(next) || is_Phi(next) || be_is_Keep(next)) {
373                 next = sched_next(next);
374         }
375         assert(next != NULL);
376
377         if(sched_is_end(next)) {
378                 sched_add_after(sched_last(get_nodes_block(sched_after)), node);
379         } else {
380                 sched_add_before(next, node);
381         }
382 }
383
384 /**
385  * Creates a spill.
386  *
387  * @param senv      the spill environment
388  * @param irn       the node that should be spilled
389  * @param ctx_irn   an user of the spilled node
390  *
391  * @return a be_Spill node
392  */
393 static
394 void spill_irn(spill_env_t *env, spill_info_t *spillinfo)
395 {
396         optimization_state_t  opt;
397         ir_node              *to_spill = spillinfo->to_spill;
398
399         DBG((dbg, LEVEL_1, "spilling %+F ... ", to_spill));
400
401         /* Trying to spill an already spilled value, no need for a new spill
402          * node then, we can simply connect to the same one for this reload
403          *
404          * Normally reloads get simply rematerialized instead of spilled again; this
405          * can happen annyway when the reload is the pred of a phi to spill)
406          */
407         if (be_is_Reload(to_spill)) {
408                 spillinfo->spill = get_irn_n(to_spill, be_pos_Reload_mem);
409                 DB((dbg, LEVEL_1, "skip reload, using existing spill %+F\n", spillinfo->spill));
410                 return;
411         }
412
413         assert(!(arch_irn_is(env->arch_env, to_spill, dont_spill)
414                                 && "Attempt to spill a node marked 'dont_spill'"));
415
416         /* some backends have virtual noreg/unknown nodes that are not scheduled */
417         if(!sched_is_scheduled(to_spill)) {
418                 spillinfo->spill = new_NoMem();
419                 return;
420         }
421
422
423         /*
424          * We switch on optimizations here to get CSE. This is needed as the STA
425          * backends has some extra spill phases and we want to make use of those
426          * spills instead of creating new ones.
427          */
428         save_optimization_state(&opt);
429         set_optimize(1);
430         spillinfo->spill = be_spill(env->arch_env, to_spill);
431         restore_optimization_state(&opt);
432         if (! sched_is_scheduled(spillinfo->spill)) {
433                 DB((dbg, LEVEL_1, "add spill %+F after %+F\n", spillinfo->spill, to_spill));
434 #ifdef FIRM_STATISTICS
435                 env->spill_count++;
436 #endif
437                 sched_add_after_insn(to_spill, spillinfo->spill);
438         } else {
439                 DB((dbg, LEVEL_1, "re-using spill %+F after %+F\n", spillinfo->spill, to_spill));
440         }
441 }
442
443 static
444 void spill_node(spill_env_t *env, spill_info_t *spillinfo);
445
446 /**
447  * If the first usage of a Phi result would be out of memory
448  * there is no sense in allocating a register for it.
449  * Thus we spill it and all its operands to the same spill slot.
450  * Therefore the phi/dataB becomes a phi/Memory
451  *
452  * @param senv      the spill environment
453  * @param phi       the Phi node that should be spilled
454  * @param ctx_irn   an user of the spilled node
455  */
456 static
457 void spill_phi(spill_env_t *env, spill_info_t *spillinfo)
458 {
459         ir_node *phi = spillinfo->to_spill;
460         int i;
461         int arity = get_irn_arity(phi);
462         ir_node     *block    = get_nodes_block(phi);
463         ir_node     **ins;
464
465         assert(is_Phi(phi));
466
467         DBG((dbg, LEVEL_1, "spilling Phi %+F:\n", phi));
468         /* build a new PhiM */
469         ins = alloca(sizeof(ir_node*) * arity);
470         for(i = 0; i < arity; ++i) {
471                 ins[i] = get_irg_bad(env->irg);
472         }
473         spillinfo->spill = new_r_Phi(env->irg, block, arity, ins, mode_M);
474 #ifdef FIRM_STATISTICS
475         env->spilled_phi_count++;
476 #endif
477
478         for(i = 0; i < arity; ++i) {
479                 ir_node *arg = get_irn_n(phi, i);
480                 spill_info_t *arg_info = get_spillinfo(env, arg);
481
482                 spill_node(env, arg_info);
483
484                 set_irn_n(spillinfo->spill, i, arg_info->spill);
485         }
486         DBG((dbg, LEVEL_1, "... done spilling Phi %+F, created PhiM %+F\n", phi, spillinfo->spill));
487
488         /* rewire reloads from old_spill to phi */
489         if (spillinfo->old_spill != NULL) {
490                 const ir_edge_t *edge, *next;
491                 ir_node *old_spill = spillinfo->old_spill;
492
493                 DBG((dbg, LEVEL_1, "old spill found, rewiring reloads:\n"));
494
495                 foreach_out_edge_safe(old_spill, edge, next) {
496                         ir_node *reload = get_edge_src_irn(edge);
497                         int     pos     = get_edge_src_pos(edge);
498
499                         DBG((dbg, LEVEL_1, "\tset input %d of %+F to %+F\n", pos, reload, spillinfo->spill));
500
501                         assert(be_is_Reload(reload) || is_Phi(reload));
502                         set_irn_n(reload, pos, spillinfo->spill);
503                 }
504                 DBG((dbg, LEVEL_1, "\tset input of %+F to BAD\n", old_spill));
505                 set_irn_n(old_spill, be_pos_Spill_val, new_Bad());
506                 /* sched_remove(old_spill); */
507                 spillinfo->old_spill = NULL;
508         }
509 }
510
511 /**
512  * Spill a node.
513  *
514  * @param senv      the spill environment
515  * @param to_spill  the node that should be spilled
516  */
517 static
518 void spill_node(spill_env_t *env, spill_info_t *spillinfo)
519 {
520         ir_node *to_spill;
521
522         /* the node should be tagged for spilling already... */
523         if(spillinfo->spill != NULL)
524                 return;
525
526         to_spill = spillinfo->to_spill;
527
528         if (is_Phi(to_spill) && ir_nodeset_contains(&env->mem_phis, to_spill)) {
529                 spill_phi(env, spillinfo);
530         } else {
531                 spill_irn(env, spillinfo);
532         }
533 }
534
535 /*
536  *
537  *  ____                      _            _       _ _
538  * |  _ \ ___ _ __ ___   __ _| |_ ___ _ __(_) __ _| (_)_______
539  * | |_) / _ \ '_ ` _ \ / _` | __/ _ \ '__| |/ _` | | |_  / _ \
540  * |  _ <  __/ | | | | | (_| | ||  __/ |  | | (_| | | |/ /  __/
541  * |_| \_\___|_| |_| |_|\__,_|\__\___|_|  |_|\__,_|_|_/___\___|
542  *
543  */
544
545 /**
546  * Tests whether value @p arg is available before node @p reloader
547  * @returns 1 if value is available, 0 otherwise
548  */
549 static
550 int is_value_available(spill_env_t *env, const ir_node *arg, const ir_node *reloader)
551 {
552         if(is_Unknown(arg) || arg == new_NoMem())
553                 return 1;
554
555         if(be_is_Spill(arg))
556                 return 1;
557
558         if(arg == get_irg_frame(env->irg))
559                 return 1;
560
561         /* hack for now (happens when command should be inserted at end of block) */
562         if(is_Block(reloader)) {
563                 return 0;
564         }
565
566         /*
567          * Ignore registers are always available
568          */
569         if(arch_irn_is(env->arch_env, arg, ignore)) {
570                 return 1;
571         }
572
573         /* the following test does not work while spilling,
574          * because the liveness info is not adapted yet to the effects of the
575          * additional spills/reloads.
576          */
577 #if 0
578         /* we want to remat before the insn reloader
579          * thus an arguments is alive if
580          *   - it interferes with the reloaders result
581          *   - or it is (last-) used by reloader itself
582          */
583         if (values_interfere(env->birg->lv, reloader, arg)) {
584                 return 1;
585         }
586
587         arity = get_irn_arity(reloader);
588         for (i = 0; i < arity; ++i) {
589                 ir_node *rel_arg = get_irn_n(reloader, i);
590                 if (rel_arg == arg)
591                         return 1;
592         }
593 #endif
594
595         return 0;
596 }
597
598 /**
599  * Checks whether the node can principally be rematerialized
600  */
601 static
602 int is_remat_node(spill_env_t *env, const ir_node *node)
603 {
604         const arch_env_t *arch_env = env->arch_env;
605
606         assert(!be_is_Spill(node));
607
608         if(arch_irn_is(arch_env, node, rematerializable))
609                 return 1;
610
611         return 0;
612 }
613
614 /**
615  * Check if a node is rematerializable. This tests for the following conditions:
616  *
617  * - The node itself is rematerializable
618  * - All arguments of the node are available or also rematerialisable
619  * - The costs for the rematerialisation operation is less or equal a limit
620  *
621  * Returns the costs needed for rematerialisation or something
622  * >= REMAT_COST_INFINITE if remat is not possible.
623  */
624 static
625 int check_remat_conditions_costs(spill_env_t *env, const ir_node *spilled,
626                                  const ir_node *reloader, int parentcosts)
627 {
628         int i, arity;
629         int argremats;
630         int costs = 0;
631
632         if(!is_remat_node(env, spilled))
633                 return REMAT_COST_INFINITE;
634
635         if(be_is_Reload(spilled)) {
636                 costs += 2;
637         } else {
638                 costs += arch_get_op_estimated_cost(env->arch_env, spilled);
639         }
640         if(parentcosts + costs >= env->reload_cost + env->spill_cost) {
641                 return REMAT_COST_INFINITE;
642         }
643         if(arch_irn_is(env->arch_env, spilled, modify_flags)) {
644                 return REMAT_COST_INFINITE;
645         }
646
647         argremats = 0;
648         for(i = 0, arity = get_irn_arity(spilled); i < arity; ++i) {
649                 ir_node *arg = get_irn_n(spilled, i);
650
651                 if(is_value_available(env, arg, reloader))
652                         continue;
653
654                 /* we have to rematerialize the argument as well */
655                 if(argremats >= 1) {
656                         /* we only support rematerializing 1 argument at the moment,
657                          * so that we don't have to care about register pressure
658                          */
659                         return REMAT_COST_INFINITE;
660                 }
661                 argremats++;
662
663                 costs += check_remat_conditions_costs(env, arg, reloader, parentcosts + costs);
664                 if(parentcosts + costs >= env->reload_cost + env->spill_cost)
665                         return REMAT_COST_INFINITE;
666         }
667
668         return costs;
669 }
670
671 /**
672  * Re-materialize a node.
673  *
674  * @param senv      the spill environment
675  * @param spilled   the node that was spilled
676  * @param reloader  a irn that requires a reload
677  */
678 static
679 ir_node *do_remat(spill_env_t *env, ir_node *spilled, ir_node *reloader)
680 {
681         int i, arity;
682         ir_node *res;
683         ir_node *bl;
684         ir_node **ins;
685
686         if(is_Block(reloader)) {
687                 bl = reloader;
688         } else {
689                 bl = get_nodes_block(reloader);
690         }
691
692         ins = alloca(get_irn_arity(spilled) * sizeof(ins[0]));
693         for(i = 0, arity = get_irn_arity(spilled); i < arity; ++i) {
694                 ir_node *arg = get_irn_n(spilled, i);
695
696                 if(is_value_available(env, arg, reloader)) {
697                         ins[i] = arg;
698                 } else {
699                         ins[i] = do_remat(env, arg, reloader);
700 #ifdef FIRM_STATISTICS
701                         /* don't count the recursive call as remat */
702                         env->remat_count--;
703 #endif
704                 }
705         }
706
707         /* create a copy of the node */
708         res = new_ir_node(get_irn_dbg_info(spilled), env->irg, bl,
709                           get_irn_op(spilled), get_irn_mode(spilled),
710                           get_irn_arity(spilled), ins);
711         copy_node_attr(spilled, res);
712         new_backedge_info(res);
713
714         DBG((dbg, LEVEL_1, "Insert remat %+F of %+F before reloader %+F\n", res, spilled, reloader));
715
716         if (! is_Proj(res)) {
717                 /* insert in schedule */
718                 sched_reset(res);
719                 sched_add_before(reloader, res);
720 #ifdef FIRM_STATISTICS
721                 env->remat_count++;
722 #endif
723         }
724
725         return res;
726 }
727
728 double be_get_spill_costs(spill_env_t *env, ir_node *to_spill, ir_node *after)
729 {
730         ir_node *block = get_nodes_block(after);
731         double   freq  = get_block_execfreq(env->exec_freq, block);
732         (void) to_spill;
733
734         return env->spill_cost * freq;
735 }
736
737 double be_get_reload_costs(spill_env_t *env, ir_node *to_spill, ir_node *before)
738 {
739         ir_node      *block = get_nodes_block(before);
740         double        freq  = get_block_execfreq(env->exec_freq, block);
741
742         if(be_do_remats) {
743                 /* is the node rematerializable? */
744                 int costs = check_remat_conditions_costs(env, to_spill, before, 0);
745                 if(costs < env->reload_cost)
746                         return costs * freq;
747         }
748
749         return env->reload_cost * freq;
750 }
751
752 int be_is_rematerializable(spill_env_t *env, const ir_node *to_remat, const ir_node *before)
753 {
754         return check_remat_conditions_costs(env, to_remat, before, 0) < REMAT_COST_INFINITE;
755 }
756
757 double be_get_reload_costs_on_edge(spill_env_t *env, ir_node *to_spill,
758                                 ir_node *block, int pos)
759 {
760         ir_node *before = get_block_insertion_point(block, pos);
761         return be_get_reload_costs(env, to_spill, before);
762 }
763
764 /*
765  *  ___                     _     ____      _                 _
766  * |_ _|_ __  ___  ___ _ __| |_  |  _ \ ___| | ___   __ _  __| |___
767  *  | || '_ \/ __|/ _ \ '__| __| | |_) / _ \ |/ _ \ / _` |/ _` / __|
768  *  | || | | \__ \  __/ |  | |_  |  _ <  __/ | (_) | (_| | (_| \__ \
769  * |___|_| |_|___/\___|_|   \__| |_| \_\___|_|\___/ \__,_|\__,_|___/
770  *
771  */
772
773 void be_insert_spills_reloads(spill_env_t *env)
774 {
775         const arch_env_t      *arch_env  = env->arch_env;
776         const ir_exec_freq    *exec_freq = env->exec_freq;
777         spill_info_t          *si;
778         ir_nodeset_iterator_t  iter;
779         ir_node               *node;
780
781         /* create all phi-ms first, this is needed so, that phis, hanging on
782            spilled phis work correctly */
783         foreach_ir_nodeset(&env->mem_phis, node, iter) {
784                 spill_info_t *info = get_spillinfo(env, node);
785                 spill_node(env, info);
786         }
787
788         /* process each spilled node */
789         for (si = set_first(env->spills); si; si = set_next(env->spills)) {
790                 reloader_t *rld;
791                 ir_node  *to_spill        = si->to_spill;
792                 ir_mode  *mode            = get_irn_mode(to_spill);
793                 ir_node **copies          = NEW_ARR_F(ir_node*, 0);
794                 double    all_remat_costs = 0; /** costs when we would remat all nodes */
795                 int       force_remat     = 0;
796
797                 DBG((dbg, LEVEL_1, "\nhandling all reloaders of %+F:\n", to_spill));
798
799                 /* determine possibility of rematerialisations */
800                 if(be_do_remats) {
801                         for (rld = si->reloaders; rld != NULL; rld = rld->next) {
802                                 double   freq;
803                                 int      remat_cost;
804                                 int      remat_cost_delta;
805                                 ir_node *block;
806                                 ir_node *reloader = rld->reloader;
807
808                                 if(rld->rematted_node != NULL) {
809                                         DBG((dbg, LEVEL_2, "\tforced remat %+F before %+F\n",
810                                              rld->rematted_node, reloader));
811                                         continue;
812                                 }
813                                 if(rld->remat_cost_delta >= REMAT_COST_INFINITE) {
814                                         DBG((dbg, LEVEL_2, "\treload before %+F is forbidden\n",
815                                              reloader));
816                                         all_remat_costs = REMAT_COST_INFINITE;
817                                         continue;
818                                 }
819
820                                 remat_cost  = check_remat_conditions_costs(env, to_spill,
821                                                                            reloader, 0);
822                                 if(remat_cost >= REMAT_COST_INFINITE) {
823                                         DBG((dbg, LEVEL_2, "\tremat before %+F not possible\n",
824                                              reloader));
825                                         rld->remat_cost_delta = REMAT_COST_INFINITE;
826                                         all_remat_costs       = REMAT_COST_INFINITE;
827                                         continue;
828                                 }
829
830                                 remat_cost_delta      = remat_cost - env->reload_cost;
831                                 rld->remat_cost_delta = remat_cost_delta;
832                                 block                 = is_Block(reloader) ? reloader : get_nodes_block(reloader);
833                                 freq                  = get_block_execfreq(exec_freq, block);
834                                 all_remat_costs      += remat_cost_delta * freq;
835                                 DBG((dbg, LEVEL_2, "\tremat costs delta before %+F: "
836                                      "%d (rel %f)\n", reloader, remat_cost_delta,
837                                      remat_cost_delta * freq));
838                         }
839                         if(all_remat_costs < REMAT_COST_INFINITE) {
840                                 ir_node *block = get_nodes_block(to_spill);
841                                 double   freq  = get_block_execfreq(exec_freq, block);
842                                 /* we don't need the costs for the spill if we can remat
843                                    all reloaders */
844                                 all_remat_costs -= env->spill_cost * freq;
845
846                                 DBG((dbg, LEVEL_2, "\tspill costs %d (rel %f)\n",
847                                      env->spill_cost, env->spill_cost * freq));
848                         }
849
850                         if(all_remat_costs < 0) {
851                                 DBG((dbg, LEVEL_1, "\nforcing remats of all reloaders (%f)\n",
852                                      all_remat_costs));
853                                 force_remat = 1;
854                         }
855                 }
856
857                 /* go through all reloads for this spill */
858                 for (rld = si->reloaders; rld != NULL; rld = rld->next) {
859                         ir_node *copy; /* a reload is a "copy" of the original value */
860
861                         if (rld->rematted_node != NULL) {
862                                 copy = rld->rematted_node;
863                                 sched_add_before(rld->reloader, copy);
864                         } else if (be_do_remats &&
865                                         (force_remat || rld->remat_cost_delta < 0)) {
866                                 copy = do_remat(env, to_spill, rld->reloader);
867                         } else {
868                                 /* make sure we have a spill */
869                                 if (si->spill == NULL) {
870                                         spill_node(env, si);
871                                 }
872
873                                 /* create a reload */
874                                 copy = be_reload(arch_env, si->reload_cls, rld->reloader, mode,
875                                                  si->spill);
876 #ifdef FIRM_STATISTICS
877                                 env->reload_count++;
878 #endif
879                         }
880
881                         DBG((dbg, LEVEL_1, " %+F of %+F before %+F\n",
882                              copy, to_spill, rld->reloader));
883                         ARR_APP1(ir_node*, copies, copy);
884                 }
885
886                 /* if we had any reloads or remats, then we need to reconstruct the
887                  * SSA form for the spilled value */
888                 if (ARR_LEN(copies) > 0) {
889                         be_ssa_construction_env_t senv;
890                         /* be_lv_t *lv = be_get_birg_liveness(env->birg); */
891
892                         be_ssa_construction_init(&senv, env->birg);
893                         be_ssa_construction_add_copy(&senv, to_spill);
894                         be_ssa_construction_add_copies(&senv, copies, ARR_LEN(copies));
895                         be_ssa_construction_fix_users(&senv, to_spill);
896
897 #if 0
898                         /* no need to enable this as long as we invalidate liveness
899                            after this function... */
900                         be_ssa_construction_update_liveness_phis(&senv);
901                         be_liveness_update(to_spill);
902                         len = ARR_LEN(copies);
903                         for(i = 0; i < len; ++i) {
904                                 be_liveness_update(lv, copies[i]);
905                         }
906 #endif
907                         be_ssa_construction_destroy(&senv);
908                 }
909
910                 DEL_ARR_F(copies);
911                 si->reloaders = NULL;
912         }
913
914         stat_ev_dbl("spill_spills", env->spill_count);
915         stat_ev_dbl("spill_reloads", env->reload_count);
916         stat_ev_dbl("spill_remats", env->remat_count);
917         stat_ev_dbl("spill_spilled_phis", env->spilled_phi_count);
918
919         /* Matze: In theory be_ssa_construction should take care of the liveness...
920          * try to disable this again in the future */
921         be_liveness_invalidate(env->birg->lv);
922
923         be_remove_dead_nodes_from_schedule(env->birg);
924 }
925
926 void be_init_spill(void)
927 {
928         FIRM_DBG_REGISTER(dbg, "firm.be.spill");
929 }
930
931 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spill);