really disable CSE in backend, and add an assert about that in bespill.c
[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         assert(!get_opt_cse());
474         spillinfo->spill = new_r_Phi(env->irg, block, arity, ins, mode_M);
475 #ifdef FIRM_STATISTICS
476         env->spilled_phi_count++;
477 #endif
478
479         for(i = 0; i < arity; ++i) {
480                 ir_node *arg = get_irn_n(phi, i);
481                 spill_info_t *arg_info = get_spillinfo(env, arg);
482
483                 spill_node(env, arg_info);
484
485                 set_irn_n(spillinfo->spill, i, arg_info->spill);
486         }
487         DBG((dbg, LEVEL_1, "... done spilling Phi %+F, created PhiM %+F\n", phi, spillinfo->spill));
488
489         /* rewire reloads from old_spill to phi */
490         if (spillinfo->old_spill != NULL) {
491                 const ir_edge_t *edge, *next;
492                 ir_node *old_spill = spillinfo->old_spill;
493
494                 DBG((dbg, LEVEL_1, "old spill found, rewiring reloads:\n"));
495
496                 foreach_out_edge_safe(old_spill, edge, next) {
497                         ir_node *reload = get_edge_src_irn(edge);
498                         int     pos     = get_edge_src_pos(edge);
499
500                         DBG((dbg, LEVEL_1, "\tset input %d of %+F to %+F\n", pos, reload, spillinfo->spill));
501
502                         assert(be_is_Reload(reload) || is_Phi(reload));
503                         set_irn_n(reload, pos, spillinfo->spill);
504                 }
505                 DBG((dbg, LEVEL_1, "\tset input of %+F to BAD\n", old_spill));
506                 set_irn_n(old_spill, be_pos_Spill_val, new_Bad());
507                 /* sched_remove(old_spill); */
508                 spillinfo->old_spill = NULL;
509         }
510 }
511
512 /**
513  * Spill a node.
514  *
515  * @param senv      the spill environment
516  * @param to_spill  the node that should be spilled
517  */
518 static
519 void spill_node(spill_env_t *env, spill_info_t *spillinfo)
520 {
521         ir_node *to_spill;
522
523         /* the node should be tagged for spilling already... */
524         if(spillinfo->spill != NULL)
525                 return;
526
527         to_spill = spillinfo->to_spill;
528
529         if (is_Phi(to_spill) && ir_nodeset_contains(&env->mem_phis, to_spill)) {
530                 spill_phi(env, spillinfo);
531         } else {
532                 spill_irn(env, spillinfo);
533         }
534 }
535
536 /*
537  *
538  *  ____                      _            _       _ _
539  * |  _ \ ___ _ __ ___   __ _| |_ ___ _ __(_) __ _| (_)_______
540  * | |_) / _ \ '_ ` _ \ / _` | __/ _ \ '__| |/ _` | | |_  / _ \
541  * |  _ <  __/ | | | | | (_| | ||  __/ |  | | (_| | | |/ /  __/
542  * |_| \_\___|_| |_| |_|\__,_|\__\___|_|  |_|\__,_|_|_/___\___|
543  *
544  */
545
546 /**
547  * Tests whether value @p arg is available before node @p reloader
548  * @returns 1 if value is available, 0 otherwise
549  */
550 static
551 int is_value_available(spill_env_t *env, const ir_node *arg, const ir_node *reloader)
552 {
553         if(is_Unknown(arg) || arg == new_NoMem())
554                 return 1;
555
556         if(be_is_Spill(arg))
557                 return 1;
558
559         if(arg == get_irg_frame(env->irg))
560                 return 1;
561
562         /* hack for now (happens when command should be inserted at end of block) */
563         if(is_Block(reloader)) {
564                 return 0;
565         }
566
567         /*
568          * Ignore registers are always available
569          */
570         if(arch_irn_is(env->arch_env, arg, ignore)) {
571                 return 1;
572         }
573
574         /* the following test does not work while spilling,
575          * because the liveness info is not adapted yet to the effects of the
576          * additional spills/reloads.
577          */
578 #if 0
579         /* we want to remat before the insn reloader
580          * thus an arguments is alive if
581          *   - it interferes with the reloaders result
582          *   - or it is (last-) used by reloader itself
583          */
584         if (values_interfere(env->birg->lv, reloader, arg)) {
585                 return 1;
586         }
587
588         arity = get_irn_arity(reloader);
589         for (i = 0; i < arity; ++i) {
590                 ir_node *rel_arg = get_irn_n(reloader, i);
591                 if (rel_arg == arg)
592                         return 1;
593         }
594 #endif
595
596         return 0;
597 }
598
599 /**
600  * Checks whether the node can principally be rematerialized
601  */
602 static
603 int is_remat_node(spill_env_t *env, const ir_node *node)
604 {
605         const arch_env_t *arch_env = env->arch_env;
606
607         assert(!be_is_Spill(node));
608
609         if(arch_irn_is(arch_env, node, rematerializable))
610                 return 1;
611
612         return 0;
613 }
614
615 /**
616  * Check if a node is rematerializable. This tests for the following conditions:
617  *
618  * - The node itself is rematerializable
619  * - All arguments of the node are available or also rematerialisable
620  * - The costs for the rematerialisation operation is less or equal a limit
621  *
622  * Returns the costs needed for rematerialisation or something
623  * >= REMAT_COST_INFINITE if remat is not possible.
624  */
625 static
626 int check_remat_conditions_costs(spill_env_t *env, const ir_node *spilled,
627                                  const ir_node *reloader, int parentcosts)
628 {
629         int i, arity;
630         int argremats;
631         int costs = 0;
632
633         if(!is_remat_node(env, spilled))
634                 return REMAT_COST_INFINITE;
635
636         if(be_is_Reload(spilled)) {
637                 costs += 2;
638         } else {
639                 costs += arch_get_op_estimated_cost(env->arch_env, spilled);
640         }
641         if(parentcosts + costs >= env->reload_cost + env->spill_cost) {
642                 return REMAT_COST_INFINITE;
643         }
644         if(arch_irn_is(env->arch_env, spilled, modify_flags)) {
645                 return REMAT_COST_INFINITE;
646         }
647
648         argremats = 0;
649         for(i = 0, arity = get_irn_arity(spilled); i < arity; ++i) {
650                 ir_node *arg = get_irn_n(spilled, i);
651
652                 if(is_value_available(env, arg, reloader))
653                         continue;
654
655                 /* we have to rematerialize the argument as well */
656                 if(argremats >= 1) {
657                         /* we only support rematerializing 1 argument at the moment,
658                          * so that we don't have to care about register pressure
659                          */
660                         return REMAT_COST_INFINITE;
661                 }
662                 argremats++;
663
664                 costs += check_remat_conditions_costs(env, arg, reloader, parentcosts + costs);
665                 if(parentcosts + costs >= env->reload_cost + env->spill_cost)
666                         return REMAT_COST_INFINITE;
667         }
668
669         return costs;
670 }
671
672 /**
673  * Re-materialize a node.
674  *
675  * @param senv      the spill environment
676  * @param spilled   the node that was spilled
677  * @param reloader  a irn that requires a reload
678  */
679 static
680 ir_node *do_remat(spill_env_t *env, ir_node *spilled, ir_node *reloader)
681 {
682         int i, arity;
683         ir_node *res;
684         ir_node *bl;
685         ir_node **ins;
686
687         if(is_Block(reloader)) {
688                 bl = reloader;
689         } else {
690                 bl = get_nodes_block(reloader);
691         }
692
693         ins = alloca(get_irn_arity(spilled) * sizeof(ins[0]));
694         for(i = 0, arity = get_irn_arity(spilled); i < arity; ++i) {
695                 ir_node *arg = get_irn_n(spilled, i);
696
697                 if(is_value_available(env, arg, reloader)) {
698                         ins[i] = arg;
699                 } else {
700                         ins[i] = do_remat(env, arg, reloader);
701 #ifdef FIRM_STATISTICS
702                         /* don't count the recursive call as remat */
703                         env->remat_count--;
704 #endif
705                 }
706         }
707
708         /* create a copy of the node */
709         res = new_ir_node(get_irn_dbg_info(spilled), env->irg, bl,
710                           get_irn_op(spilled), get_irn_mode(spilled),
711                           get_irn_arity(spilled), ins);
712         copy_node_attr(spilled, res);
713         new_backedge_info(res);
714
715         DBG((dbg, LEVEL_1, "Insert remat %+F of %+F before reloader %+F\n", res, spilled, reloader));
716
717         if (! is_Proj(res)) {
718                 /* insert in schedule */
719                 sched_reset(res);
720                 sched_add_before(reloader, res);
721 #ifdef FIRM_STATISTICS
722                 env->remat_count++;
723 #endif
724         }
725
726         return res;
727 }
728
729 double be_get_spill_costs(spill_env_t *env, ir_node *to_spill, ir_node *after)
730 {
731         ir_node *block = get_nodes_block(after);
732         double   freq  = get_block_execfreq(env->exec_freq, block);
733         (void) to_spill;
734
735         return env->spill_cost * freq;
736 }
737
738 double be_get_reload_costs(spill_env_t *env, ir_node *to_spill, ir_node *before)
739 {
740         ir_node      *block = get_nodes_block(before);
741         double        freq  = get_block_execfreq(env->exec_freq, block);
742
743         if(be_do_remats) {
744                 /* is the node rematerializable? */
745                 int costs = check_remat_conditions_costs(env, to_spill, before, 0);
746                 if(costs < env->reload_cost)
747                         return costs * freq;
748         }
749
750         return env->reload_cost * freq;
751 }
752
753 int be_is_rematerializable(spill_env_t *env, const ir_node *to_remat, const ir_node *before)
754 {
755         return check_remat_conditions_costs(env, to_remat, before, 0) < REMAT_COST_INFINITE;
756 }
757
758 double be_get_reload_costs_on_edge(spill_env_t *env, ir_node *to_spill,
759                                 ir_node *block, int pos)
760 {
761         ir_node *before = get_block_insertion_point(block, pos);
762         return be_get_reload_costs(env, to_spill, before);
763 }
764
765 /*
766  *  ___                     _     ____      _                 _
767  * |_ _|_ __  ___  ___ _ __| |_  |  _ \ ___| | ___   __ _  __| |___
768  *  | || '_ \/ __|/ _ \ '__| __| | |_) / _ \ |/ _ \ / _` |/ _` / __|
769  *  | || | | \__ \  __/ |  | |_  |  _ <  __/ | (_) | (_| | (_| \__ \
770  * |___|_| |_|___/\___|_|   \__| |_| \_\___|_|\___/ \__,_|\__,_|___/
771  *
772  */
773
774 void be_insert_spills_reloads(spill_env_t *env)
775 {
776         const arch_env_t      *arch_env  = env->arch_env;
777         const ir_exec_freq    *exec_freq = env->exec_freq;
778         spill_info_t          *si;
779         ir_nodeset_iterator_t  iter;
780         ir_node               *node;
781
782         /* create all phi-ms first, this is needed so, that phis, hanging on
783            spilled phis work correctly */
784         foreach_ir_nodeset(&env->mem_phis, node, iter) {
785                 spill_info_t *info = get_spillinfo(env, node);
786                 spill_node(env, info);
787         }
788
789         /* process each spilled node */
790         for (si = set_first(env->spills); si; si = set_next(env->spills)) {
791                 reloader_t *rld;
792                 ir_node  *to_spill        = si->to_spill;
793                 ir_mode  *mode            = get_irn_mode(to_spill);
794                 ir_node **copies          = NEW_ARR_F(ir_node*, 0);
795                 double    all_remat_costs = 0; /** costs when we would remat all nodes */
796                 int       force_remat     = 0;
797
798                 DBG((dbg, LEVEL_1, "\nhandling all reloaders of %+F:\n", to_spill));
799
800                 /* determine possibility of rematerialisations */
801                 if(be_do_remats) {
802                         for (rld = si->reloaders; rld != NULL; rld = rld->next) {
803                                 double   freq;
804                                 int      remat_cost;
805                                 int      remat_cost_delta;
806                                 ir_node *block;
807                                 ir_node *reloader = rld->reloader;
808
809                                 if(rld->rematted_node != NULL) {
810                                         DBG((dbg, LEVEL_2, "\tforced remat %+F before %+F\n",
811                                              rld->rematted_node, reloader));
812                                         continue;
813                                 }
814                                 if(rld->remat_cost_delta >= REMAT_COST_INFINITE) {
815                                         DBG((dbg, LEVEL_2, "\treload before %+F is forbidden\n",
816                                              reloader));
817                                         all_remat_costs = REMAT_COST_INFINITE;
818                                         continue;
819                                 }
820
821                                 remat_cost  = check_remat_conditions_costs(env, to_spill,
822                                                                            reloader, 0);
823                                 if(remat_cost >= REMAT_COST_INFINITE) {
824                                         DBG((dbg, LEVEL_2, "\tremat before %+F not possible\n",
825                                              reloader));
826                                         rld->remat_cost_delta = REMAT_COST_INFINITE;
827                                         all_remat_costs       = REMAT_COST_INFINITE;
828                                         continue;
829                                 }
830
831                                 remat_cost_delta      = remat_cost - env->reload_cost;
832                                 rld->remat_cost_delta = remat_cost_delta;
833                                 block                 = is_Block(reloader) ? reloader : get_nodes_block(reloader);
834                                 freq                  = get_block_execfreq(exec_freq, block);
835                                 all_remat_costs      += remat_cost_delta * freq;
836                                 DBG((dbg, LEVEL_2, "\tremat costs delta before %+F: "
837                                      "%d (rel %f)\n", reloader, remat_cost_delta,
838                                      remat_cost_delta * freq));
839                         }
840                         if(all_remat_costs < REMAT_COST_INFINITE) {
841                                 ir_node *block = get_nodes_block(to_spill);
842                                 double   freq  = get_block_execfreq(exec_freq, block);
843                                 /* we don't need the costs for the spill if we can remat
844                                    all reloaders */
845                                 all_remat_costs -= env->spill_cost * freq;
846
847                                 DBG((dbg, LEVEL_2, "\tspill costs %d (rel %f)\n",
848                                      env->spill_cost, env->spill_cost * freq));
849                         }
850
851                         if(all_remat_costs < 0) {
852                                 DBG((dbg, LEVEL_1, "\nforcing remats of all reloaders (%f)\n",
853                                      all_remat_costs));
854                                 force_remat = 1;
855                         }
856                 }
857
858                 /* go through all reloads for this spill */
859                 for (rld = si->reloaders; rld != NULL; rld = rld->next) {
860                         ir_node *copy; /* a reload is a "copy" of the original value */
861
862                         if (rld->rematted_node != NULL) {
863                                 copy = rld->rematted_node;
864                                 sched_add_before(rld->reloader, copy);
865                         } else if (be_do_remats &&
866                                         (force_remat || rld->remat_cost_delta < 0)) {
867                                 copy = do_remat(env, to_spill, rld->reloader);
868                         } else {
869                                 /* make sure we have a spill */
870                                 if (si->spill == NULL) {
871                                         spill_node(env, si);
872                                 }
873
874                                 /* create a reload */
875                                 copy = be_reload(arch_env, si->reload_cls, rld->reloader, mode,
876                                                  si->spill);
877 #ifdef FIRM_STATISTICS
878                                 env->reload_count++;
879 #endif
880                         }
881
882                         DBG((dbg, LEVEL_1, " %+F of %+F before %+F\n",
883                              copy, to_spill, rld->reloader));
884                         ARR_APP1(ir_node*, copies, copy);
885                 }
886
887                 /* if we had any reloads or remats, then we need to reconstruct the
888                  * SSA form for the spilled value */
889                 if (ARR_LEN(copies) > 0) {
890                         be_ssa_construction_env_t senv;
891                         /* be_lv_t *lv = be_get_birg_liveness(env->birg); */
892
893                         be_ssa_construction_init(&senv, env->birg);
894                         be_ssa_construction_add_copy(&senv, to_spill);
895                         be_ssa_construction_add_copies(&senv, copies, ARR_LEN(copies));
896                         be_ssa_construction_fix_users(&senv, to_spill);
897
898 #if 0
899                         /* no need to enable this as long as we invalidate liveness
900                            after this function... */
901                         be_ssa_construction_update_liveness_phis(&senv);
902                         be_liveness_update(to_spill);
903                         len = ARR_LEN(copies);
904                         for(i = 0; i < len; ++i) {
905                                 be_liveness_update(lv, copies[i]);
906                         }
907 #endif
908                         be_ssa_construction_destroy(&senv);
909                 }
910
911                 DEL_ARR_F(copies);
912                 si->reloaders = NULL;
913         }
914
915         stat_ev_dbl("spill_spills", env->spill_count);
916         stat_ev_dbl("spill_reloads", env->reload_count);
917         stat_ev_dbl("spill_remats", env->remat_count);
918         stat_ev_dbl("spill_spilled_phis", env->spilled_phi_count);
919
920         /* Matze: In theory be_ssa_construction should take care of the liveness...
921          * try to disable this again in the future */
922         be_liveness_invalidate(env->birg->lv);
923
924         be_remove_dead_nodes_from_schedule(env->birg);
925 }
926
927 void be_init_spill(void)
928 {
929         FIRM_DBG_REGISTER(dbg, "firm.be.spill");
930 }
931
932 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spill);