78ff1482b3a57669823d58e27f5b907c0182b3f4
[libfirm] / ir / be / bespill.c
1 /*
2  * Copyright (C) 1995-2008 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 #include "error.h"
49
50 #include "bearch_t.h"
51 #include "belive_t.h"
52 #include "besched_t.h"
53 #include "bespill.h"
54 #include "belive_t.h"
55 #include "benode_t.h"
56 #include "bechordal_t.h"
57 #include "bejavacoal.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 #include "be_t.h"
65
66 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
67
68 #define REMAT_COST_INFINITE  1000
69
70 typedef struct reloader_t reloader_t;
71 struct reloader_t {
72         reloader_t *next;
73         ir_node    *can_spill_after;
74         ir_node    *reloader;
75         ir_node    *rematted_node;
76         int         remat_cost_delta; /** costs needed for rematerialization,
77                                            compared to placing a reload */
78 };
79
80 typedef struct spill_t spill_t;
81 struct spill_t {
82         spill_t *next;
83         ir_node *before;   /**< spill has to be placed before this node (or earlier) */
84         ir_node *spill;
85 };
86
87 typedef struct spill_info_t spill_info_t;
88 struct spill_info_t {
89         ir_node    *to_spill;  /**< the value that should get spilled */
90         reloader_t *reloaders; /**< list of places where the value should get
91                                     reloaded */
92         spill_t    *spills;    /**< list of latest places where spill must be
93                                     placed */
94         double      spill_costs; /**< costs needed for spilling the value */
95         const arch_register_class_t *reload_cls; /** the register class in which the
96                                                      reload should be placed */
97 };
98
99 struct spill_env_t {
100         const arch_env_t *arch_env;
101         ir_graph         *irg;
102         struct obstack    obst;
103         be_irg_t         *birg;
104         int               spill_cost;     /**< the cost of a single spill node */
105         int               reload_cost;    /**< the cost of a reload node */
106         set              *spills;         /**< all spill_info_t's, which must be
107                                                placed */
108         ir_nodeset_t      mem_phis;       /**< set of all spilled phis. */
109         ir_exec_freq     *exec_freq;
110         unsigned          new_nodes_idx;  /**< all old nodes idx is smaller than
111                                                this */
112
113 #ifdef FIRM_STATISTICS
114         unsigned          spill_count;
115         unsigned          reload_count;
116         unsigned          remat_count;
117         unsigned          spilled_phi_count;
118 #endif
119 };
120
121 /**
122  * Compare two spill infos.
123  */
124 static int cmp_spillinfo(const void *x, const void *y, size_t size)
125 {
126         const spill_info_t *xx = x;
127         const spill_info_t *yy = y;
128         (void) size;
129
130         return xx->to_spill != yy->to_spill;
131 }
132
133 /**
134  * Returns spill info for a specific value (the value that is to be spilled)
135  */
136 static spill_info_t *get_spillinfo(const spill_env_t *env, ir_node *value)
137 {
138         spill_info_t info, *res;
139         int hash = hash_irn(value);
140
141         info.to_spill = value;
142         res = set_find(env->spills, &info, sizeof(info), hash);
143
144         if (res == NULL) {
145                 info.reloaders   = NULL;
146                 info.spills      = NULL;
147                 info.spill_costs = -1;
148                 info.reload_cls  = NULL;
149                 res = set_insert(env->spills, &info, sizeof(info), hash);
150         }
151
152         return res;
153 }
154
155 spill_env_t *be_new_spill_env(be_irg_t *birg)
156 {
157         const arch_env_t *arch_env = birg->main_env->arch_env;
158
159         spill_env_t *env        = xmalloc(sizeof(env[0]));
160         env->spills                     = new_set(cmp_spillinfo, 1024);
161         env->irg            = be_get_birg_irg(birg);
162         env->birg           = birg;
163         env->arch_env       = arch_env;
164         ir_nodeset_init(&env->mem_phis);
165         env->spill_cost     = arch_env->spill_cost;
166         env->reload_cost    = arch_env->reload_cost;
167         env->exec_freq      = be_get_birg_exec_freq(birg);
168         obstack_init(&env->obst);
169
170 #ifdef FIRM_STATISTICS
171         env->spill_count       = 0;
172         env->reload_count      = 0;
173         env->remat_count       = 0;
174         env->spilled_phi_count = 0;
175 #endif
176
177         return env;
178 }
179
180 void be_delete_spill_env(spill_env_t *env)
181 {
182         del_set(env->spills);
183         ir_nodeset_destroy(&env->mem_phis);
184         obstack_free(&env->obst, NULL);
185         free(env);
186 }
187
188 /*
189  *  ____  _                  ____      _                 _
190  * |  _ \| | __ _  ___ ___  |  _ \ ___| | ___   __ _  __| |___
191  * | |_) | |/ _` |/ __/ _ \ | |_) / _ \ |/ _ \ / _` |/ _` / __|
192  * |  __/| | (_| | (_|  __/ |  _ <  __/ | (_) | (_| | (_| \__ \
193  * |_|   |_|\__,_|\___\___| |_| \_\___|_|\___/ \__,_|\__,_|___/
194  *
195  */
196
197 void be_add_spill(spill_env_t *env, ir_node *to_spill, ir_node *before)
198 {
199 #if 1
200         spill_info_t *spill_info = get_spillinfo(env, to_spill);
201         spill_t      *spill;
202         spill_t      *s;
203         spill_t      *last;
204
205         assert(! arch_irn_is(env->arch_env, to_spill, dont_spill));
206         DB((dbg, LEVEL_1, "Add spill of %+F before %+F\n", to_spill, before));
207
208         /* Just for safety make sure that we do not insert the spill in front of a phi */
209         for (; is_Phi(before); before = sched_next(before));
210
211         /* spills that are dominated by others are not needed */
212         last = NULL;
213         s    = spill_info->spills;
214         for( ; s != NULL; s = s->next) {
215                 /* no need to add this spill if it is dominated by another */
216                 if(value_dominates(s->before, before)) {
217                         DB((dbg, LEVEL_1, "...dominated by %+F, not added\n", s->before));
218                         return;
219                 }
220                 /* remove spills that we dominate */
221                 if(value_dominates(before, s->before)) {
222                         DB((dbg, LEVEL_1, "...remove old spill at %+F\n", s->before));
223                         if(last != NULL) {
224                                 last->next         = s->next;
225                         } else {
226                                 spill_info->spills = s->next;
227                         }
228                 } else {
229                         last = s;
230                 }
231         }
232
233         spill         = obstack_alloc(&env->obst, sizeof(spill[0]));
234         spill->before = before;
235         spill->next   = spill_info->spills;
236         spill->spill  = NULL;
237
238         spill_info->spills = spill;
239 #endif
240 }
241
242 void be_add_remat(spill_env_t *env, ir_node *to_spill, ir_node *before,
243                   ir_node *rematted_node)
244 {
245         spill_info_t *spill_info;
246         reloader_t *reloader;
247
248         spill_info = get_spillinfo(env, to_spill);
249
250         /* add the remat information */
251         reloader                   = obstack_alloc(&env->obst, sizeof(reloader[0]));
252         reloader->next             = spill_info->reloaders;
253         reloader->reloader         = before;
254         reloader->rematted_node    = rematted_node;
255         reloader->remat_cost_delta = 0; /* We will never have a cost win over a
256                                            reload since we're not even allowed to
257                                            create a reload */
258
259         spill_info->reloaders  = reloader;
260
261         DBG((dbg, LEVEL_1, "creating spillinfo for %+F, will be rematerialized before %+F\n",
262                 to_spill, before));
263 }
264
265 void be_add_reload2(spill_env_t *env, ir_node *to_spill, ir_node *before,
266                 ir_node *can_spill_after, const arch_register_class_t *reload_cls,
267                 int allow_remat)
268 {
269         spill_info_t *info;
270         reloader_t *rel;
271
272         assert(! arch_irn_is(env->arch_env, to_spill, dont_spill));
273
274         info = get_spillinfo(env, to_spill);
275
276         if (is_Phi(to_spill)) {
277                 int i, arity;
278
279                 /* create spillinfos for the phi arguments */
280                 for (i = 0, arity = get_irn_arity(to_spill); i < arity; ++i) {
281                         ir_node *arg = get_irn_n(to_spill, i);
282                         get_spillinfo(env, arg);
283                 }
284         }
285
286         assert(!is_Proj(before) && !be_is_Keep(before));
287
288         /* put reload into list */
289         rel                   = obstack_alloc(&env->obst, sizeof(rel[0]));
290         rel->next             = info->reloaders;
291         rel->reloader         = before;
292         rel->rematted_node    = NULL;
293         rel->can_spill_after  = can_spill_after;
294         rel->remat_cost_delta = allow_remat ? 0 : REMAT_COST_INFINITE;
295
296         info->reloaders  = rel;
297         assert(info->reload_cls == NULL || info->reload_cls == reload_cls);
298         info->reload_cls = reload_cls;
299
300         DBG((dbg, LEVEL_1, "creating spillinfo for %+F, will be reloaded before %+F, may%s be rematerialized\n",
301                 to_spill, before, allow_remat ? "" : " not"));
302 }
303
304 void be_add_reload(spill_env_t *senv, ir_node *to_spill, ir_node *before,
305                    const arch_register_class_t *reload_cls, int allow_remat)
306 {
307         be_add_reload2(senv, to_spill, before, to_spill, reload_cls, allow_remat);
308
309 }
310
311 ir_node *be_get_end_of_block_insertion_point(const ir_node *block)
312 {
313         ir_node *last = sched_last(block);
314
315         /* we might have keeps behind the jump... */
316         while (be_is_Keep(last)) {
317                 last = sched_prev(last);
318                 assert(!sched_is_end(last));
319         }
320
321         assert(is_cfop(last));
322
323         /* add the reload before the (cond-)jump */
324         return last;
325 }
326
327 static ir_node *skip_keeps_phis(ir_node *node)
328 {
329         node = sched_next(node);
330         while(is_Phi(node) || be_is_Keep(node)) {
331                 node = sched_next(node);
332         }
333         return node;
334 }
335
336 /**
337  * Returns the point at which you can insert a node that should be executed
338  * before block @p block when coming from pred @p pos.
339  */
340 static ir_node *get_block_insertion_point(ir_node *block, int pos)
341 {
342         ir_node *predblock;
343
344         /* simply add the reload to the beginning of the block if we only have 1
345          * predecessor. We don't need to check for phis as there can't be any in a
346          * block with only 1 pred. */
347         if(get_Block_n_cfgpreds(block) == 1) {
348                 assert(!is_Phi(sched_first(block)));
349                 return sched_first(block);
350         }
351
352         /* We have to reload the value in pred-block */
353         predblock = get_Block_cfgpred_block(block, pos);
354         return be_get_end_of_block_insertion_point(predblock);
355 }
356
357 void be_add_reload_at_end(spill_env_t *env, ir_node *to_spill,
358                           const ir_node *block,
359                           const arch_register_class_t *reload_cls,
360                           int allow_remat)
361 {
362         ir_node *before = be_get_end_of_block_insertion_point(block);
363         be_add_reload(env, to_spill, before, reload_cls, allow_remat);
364 }
365
366 void be_add_reload_on_edge(spill_env_t *env, ir_node *to_spill, ir_node *block,
367                            int pos,     const arch_register_class_t *reload_cls,
368                            int allow_remat)
369 {
370         ir_node *before = get_block_insertion_point(block, pos);
371         be_add_reload(env, to_spill, before, reload_cls, allow_remat);
372 }
373
374 void be_spill_phi(spill_env_t *env, ir_node *node)
375 {
376         ir_node *block;
377         spill_info_t* spill;
378         int i, arity;
379
380         assert(is_Phi(node));
381
382         ir_nodeset_insert(&env->mem_phis, node);
383
384         /* create spills for the phi arguments */
385         block = get_nodes_block(node);
386         spill = get_spillinfo(env, node);
387         for(i = 0, arity = get_irn_arity(node); i < arity; ++i) {
388                 ir_node *arg        = get_irn_n(node, i);
389                 ir_node *insert;
390                 //get_spillinfo(env, arg);
391
392                 /* some backends have virtual noreg/unknown nodes that are not scheduled
393                  * and simply always available. */
394                 if(!sched_is_scheduled(arg)) {
395                         ir_node *pred_block = get_Block_cfgpred_block(block, i);
396                         insert = be_get_end_of_block_insertion_point(pred_block);
397                 } else {
398                         insert = skip_keeps_phis(arg);
399                 }
400
401                 be_add_spill(env, arg, insert);
402         }
403 }
404
405 /*
406  *   ____                _         ____        _ _ _
407  *  / ___|_ __ ___  __ _| |_ ___  / ___| _ __ (_) | |___
408  * | |   | '__/ _ \/ _` | __/ _ \ \___ \| '_ \| | | / __|
409  * | |___| | |  __/ (_| | ||  __/  ___) | |_) | | | \__ \
410  *  \____|_|  \___|\__,_|\__\___| |____/| .__/|_|_|_|___/
411  *                                      |_|
412  */
413
414 static void determine_spill_costs(spill_env_t *env, spill_info_t *spillinfo);
415
416 /**
417  * Creates a spill.
418  *
419  * @param senv      the spill environment
420  * @param irn       the node that should be spilled
421  * @param ctx_irn   an user of the spilled node
422  *
423  * @return a be_Spill node
424  */
425 static void spill_irn(spill_env_t *env, spill_info_t *spillinfo)
426 {
427         ir_node *to_spill = spillinfo->to_spill;
428         spill_t *spill;
429
430         /* determine_spill_costs must have been run before */
431         assert(spillinfo->spill_costs >= 0);
432
433         /* some backends have virtual noreg/unknown nodes that are not scheduled
434          * and simply always available. */
435         if(!sched_is_scheduled(to_spill)) {
436                 /* override spillinfos or create a new one */
437                 spillinfo->spills->spill = new_NoMem();
438                 DB((dbg, LEVEL_1, "don't spill %+F use NoMem\n", to_spill));
439                 return;
440         }
441
442         DBG((dbg, LEVEL_1, "spilling %+F ... \n", to_spill));
443         spill = spillinfo->spills;
444         for( ; spill != NULL; spill = spill->next) {
445                 ir_node *block  = get_block(spill->before);
446                 ir_node *before = spill->before;
447
448                 /* place all spills before the reloads (as we can't guarantee the
449                  * same order as the be_add_spill and be_add_reload calls.
450                  * Also make sure that we do not run into Phis when going up. */
451                 while(get_irn_idx(sched_prev(before)) > env->new_nodes_idx && !is_Phi(sched_prev(before))) {
452                         before = sched_prev(before);
453                 }
454
455                 spill->spill    = be_spill(env->arch_env, block, to_spill);
456                 sched_add_before(before, spill->spill);
457                 DB((dbg, LEVEL_1, "\t%+F before %+F\n", spill->spill, before));
458 #ifdef FIRM_STATISTICS
459                 env->spill_count++;
460 #endif
461         }
462         DBG((dbg, LEVEL_1, "\n"));
463 }
464
465 static void spill_node(spill_env_t *env, spill_info_t *spillinfo);
466
467 /**
468  * If the first usage of a Phi result would be out of memory
469  * there is no sense in allocating a register for it.
470  * Thus we spill it and all its operands to the same spill slot.
471  * Therefore the phi/dataB becomes a phi/Memory
472  *
473  * @param senv      the spill environment
474  * @param phi       the Phi node that should be spilled
475  * @param ctx_irn   an user of the spilled node
476  */
477 static void spill_phi(spill_env_t *env, spill_info_t *spillinfo)
478 {
479         ir_graph *irg   = env->irg;
480         ir_node  *phi   = spillinfo->to_spill;
481         ir_node  *block = get_nodes_block(phi);
482         ir_node  *unknown;
483         ir_node **ins;
484         spill_t  *spill;
485         int       i;
486         int       arity;
487
488         assert(is_Phi(phi));
489         assert(!get_opt_cse());
490         DBG((dbg, LEVEL_1, "spilling Phi %+F:\n", phi));
491
492         /* build a new PhiM */
493         arity   = get_irn_arity(phi);
494         ins     = alloca(sizeof(ir_node*) * arity);
495         unknown = new_r_Unknown(irg, mode_M);
496         for(i = 0; i < arity; ++i) {
497                 ins[i] = unknown;
498         }
499
500         /* override or replace spills list... */
501         spill         = obstack_alloc(&env->obst, sizeof(spill[0]));
502         spill->before = skip_keeps_phis(phi);
503         spill->spill  = new_r_Phi(irg, block, arity, ins, mode_M);
504         spill->next   = NULL;
505
506         spillinfo->spills = spill;
507 #ifdef FIRM_STATISTICS
508         env->spilled_phi_count++;
509 #endif
510
511         for(i = 0; i < arity; ++i) {
512                 ir_node      *arg      = get_irn_n(phi, i);
513                 spill_info_t *arg_info = get_spillinfo(env, arg);
514
515                 determine_spill_costs(env, arg_info);
516                 spill_node(env, arg_info);
517
518                 set_irn_n(spill->spill, i, arg_info->spills->spill);
519         }
520         DBG((dbg, LEVEL_1, "... done spilling Phi %+F, created PhiM %+F\n", phi,
521              spill->spill));
522 }
523
524 /**
525  * Spill a node.
526  *
527  * @param senv      the spill environment
528  * @param to_spill  the node that should be spilled
529  */
530 static void spill_node(spill_env_t *env, spill_info_t *spillinfo)
531 {
532         ir_node *to_spill;
533
534         /* node is already spilled */
535         if(spillinfo->spills != NULL && spillinfo->spills->spill != NULL)
536                 return;
537
538         to_spill = spillinfo->to_spill;
539
540         if (is_Phi(to_spill) && ir_nodeset_contains(&env->mem_phis, to_spill)) {
541                 spill_phi(env, spillinfo);
542         } else {
543                 spill_irn(env, spillinfo);
544         }
545 }
546
547 /*
548  *
549  *  ____                      _            _       _ _
550  * |  _ \ ___ _ __ ___   __ _| |_ ___ _ __(_) __ _| (_)_______
551  * | |_) / _ \ '_ ` _ \ / _` | __/ _ \ '__| |/ _` | | |_  / _ \
552  * |  _ <  __/ | | | | | (_| | ||  __/ |  | | (_| | | |/ /  __/
553  * |_| \_\___|_| |_| |_|\__,_|\__\___|_|  |_|\__,_|_|_/___\___|
554  *
555  */
556
557 /**
558  * Tests whether value @p arg is available before node @p reloader
559  * @returns 1 if value is available, 0 otherwise
560  */
561 static int is_value_available(spill_env_t *env, const ir_node *arg,
562                               const ir_node *reloader)
563 {
564         if(is_Unknown(arg) || arg == new_NoMem())
565                 return 1;
566
567         if(be_is_Spill(arg))
568                 return 1;
569
570         if(arg == get_irg_frame(env->irg))
571                 return 1;
572
573         /* hack for now (happens when command should be inserted at end of block) */
574         if(is_Block(reloader)) {
575                 return 0;
576         }
577
578         /*
579          * Ignore registers are always available
580          */
581         if(arch_irn_is(env->arch_env, arg, ignore)) {
582                 return 1;
583         }
584
585         /* the following test does not work while spilling,
586          * because the liveness info is not adapted yet to the effects of the
587          * additional spills/reloads.
588          */
589 #if 0
590         /* we want to remat before the insn reloader
591          * thus an arguments is alive if
592          *   - it interferes with the reloaders result
593          *   - or it is (last-) used by reloader itself
594          */
595         if (values_interfere(env->birg->lv, reloader, arg)) {
596                 return 1;
597         }
598
599         arity = get_irn_arity(reloader);
600         for (i = 0; i < arity; ++i) {
601                 ir_node *rel_arg = get_irn_n(reloader, i);
602                 if (rel_arg == arg)
603                         return 1;
604         }
605 #endif
606
607         return 0;
608 }
609
610 /**
611  * Checks whether the node can principally be rematerialized
612  */
613 static int is_remat_node(spill_env_t *env, const ir_node *node)
614 {
615         const arch_env_t *arch_env = env->arch_env;
616
617         assert(!be_is_Spill(node));
618
619         if(arch_irn_is(arch_env, node, rematerializable))
620                 return 1;
621
622         return 0;
623 }
624
625 /**
626  * Check if a node is rematerializable. This tests for the following conditions:
627  *
628  * - The node itself is rematerializable
629  * - All arguments of the node are available or also rematerialisable
630  * - The costs for the rematerialisation operation is less or equal a limit
631  *
632  * Returns the costs needed for rematerialisation or something
633  * >= REMAT_COST_INFINITE if remat is not possible.
634  */
635 static int check_remat_conditions_costs(spill_env_t *env,
636                 const ir_node *spilled, const ir_node *reloader, int parentcosts)
637 {
638         int i, arity;
639         int argremats;
640         int costs = 0;
641
642         if(!is_remat_node(env, spilled))
643                 return REMAT_COST_INFINITE;
644
645         if(be_is_Reload(spilled)) {
646                 costs += 2;
647         } else {
648                 costs += arch_get_op_estimated_cost(env->arch_env, spilled);
649         }
650         if(parentcosts + costs >= env->reload_cost + env->spill_cost) {
651                 return REMAT_COST_INFINITE;
652         }
653         if(arch_irn_is(env->arch_env, spilled, modify_flags)) {
654                 return REMAT_COST_INFINITE;
655         }
656
657         argremats = 0;
658         for(i = 0, arity = get_irn_arity(spilled); i < arity; ++i) {
659                 ir_node *arg = get_irn_n(spilled, i);
660
661                 if(is_value_available(env, arg, reloader))
662                         continue;
663
664                 /* we have to rematerialize the argument as well */
665                 if(argremats >= 1) {
666                         /* we only support rematerializing 1 argument at the moment,
667                          * so that we don't have to care about register pressure
668                          */
669                         return REMAT_COST_INFINITE;
670                 }
671                 argremats++;
672
673                 costs += check_remat_conditions_costs(env, arg, reloader,
674                                                       parentcosts + costs);
675                 if(parentcosts + costs >= env->reload_cost + env->spill_cost)
676                         return REMAT_COST_INFINITE;
677         }
678
679         return costs;
680 }
681
682 /**
683  * Re-materialize a node.
684  *
685  * @param senv      the spill environment
686  * @param spilled   the node that was spilled
687  * @param reloader  a irn that requires a reload
688  */
689 static ir_node *do_remat(spill_env_t *env, ir_node *spilled, ir_node *reloader)
690 {
691         int i, arity;
692         ir_node *res;
693         ir_node *bl;
694         ir_node **ins;
695
696         if(is_Block(reloader)) {
697                 bl = reloader;
698         } else {
699                 bl = get_nodes_block(reloader);
700         }
701
702         ins = alloca(get_irn_arity(spilled) * sizeof(ins[0]));
703         for(i = 0, arity = get_irn_arity(spilled); i < arity; ++i) {
704                 ir_node *arg = get_irn_n(spilled, i);
705
706                 if(is_value_available(env, arg, reloader)) {
707                         ins[i] = arg;
708                 } else {
709                         ins[i] = do_remat(env, arg, reloader);
710 #ifdef FIRM_STATISTICS
711                         /* don't count the recursive call as remat */
712                         env->remat_count--;
713 #endif
714                 }
715         }
716
717         /* create a copy of the node */
718         res = new_ir_node(get_irn_dbg_info(spilled), env->irg, bl,
719                           get_irn_op(spilled), get_irn_mode(spilled),
720                           get_irn_arity(spilled), ins);
721         copy_node_attr(spilled, res);
722         new_backedge_info(res);
723
724         DBG((dbg, LEVEL_1, "Insert remat %+F of %+F before reloader %+F\n", res, spilled, reloader));
725
726         if (! is_Proj(res)) {
727                 /* insert in schedule */
728                 sched_reset(res);
729                 sched_add_before(reloader, res);
730 #ifdef FIRM_STATISTICS
731                 env->remat_count++;
732 #endif
733         }
734
735         return res;
736 }
737
738 double be_get_spill_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         (void) to_spill;
743
744         return env->spill_cost * freq;
745 }
746
747 unsigned be_get_reload_costs_no_weight(spill_env_t *env, const ir_node *to_spill,
748                                        const ir_node *before)
749 {
750         if(be_do_remats) {
751                 /* is the node rematerializable? */
752                 unsigned costs = check_remat_conditions_costs(env, to_spill, before, 0);
753                 if(costs < (unsigned) env->reload_cost)
754                         return costs;
755         }
756
757         return env->reload_cost;
758 }
759
760 double be_get_reload_costs(spill_env_t *env, ir_node *to_spill, ir_node *before)
761 {
762         ir_node      *block = get_nodes_block(before);
763         double        freq  = get_block_execfreq(env->exec_freq, block);
764
765         if(be_do_remats) {
766                 /* is the node rematerializable? */
767                 int costs = check_remat_conditions_costs(env, to_spill, before, 0);
768                 if(costs < env->reload_cost)
769                         return costs * freq;
770         }
771
772         return env->reload_cost * freq;
773 }
774
775 int be_is_rematerializable(spill_env_t *env, const ir_node *to_remat,
776                            const ir_node *before)
777 {
778         return check_remat_conditions_costs(env, to_remat, before, 0) < REMAT_COST_INFINITE;
779 }
780
781 double be_get_reload_costs_on_edge(spill_env_t *env, ir_node *to_spill,
782                                    ir_node *block, int pos)
783 {
784         ir_node *before = get_block_insertion_point(block, pos);
785         return be_get_reload_costs(env, to_spill, before);
786 }
787
788 /*
789  *  ___                     _     ____      _                 _
790  * |_ _|_ __  ___  ___ _ __| |_  |  _ \ ___| | ___   __ _  __| |___
791  *  | || '_ \/ __|/ _ \ '__| __| | |_) / _ \ |/ _ \ / _` |/ _` / __|
792  *  | || | | \__ \  __/ |  | |_  |  _ <  __/ | (_) | (_| | (_| \__ \
793  * |___|_| |_|___/\___|_|   \__| |_| \_\___|_|\___/ \__,_|\__,_|___/
794  *
795  */
796
797 /**
798  * analyzes how to best spill a node and determine costs for that
799  */
800 static void determine_spill_costs(spill_env_t *env, spill_info_t *spillinfo)
801 {
802         ir_node *to_spill = spillinfo->to_spill;
803         ir_node *spill_block;
804         spill_t *spill;
805         double   spill_execfreq;
806
807         /* already calculated? */
808         if(spillinfo->spill_costs >= 0)
809                 return;
810
811         assert(! arch_irn_is(env->arch_env, to_spill, dont_spill));
812         assert(!be_is_Reload(to_spill));
813
814         /* some backends have virtual noreg/unknown nodes that are not scheduled
815          * and simply always available.
816          * TODO: this is kinda hairy, the NoMem is correct for an Unknown as Phi
817          * predecessor (of a PhiM) but this test might match other things too...
818          */
819         if(!sched_is_scheduled(to_spill)) {
820                 /* override spillinfos or create a new one */
821                 spill_t *spill = obstack_alloc(&env->obst, sizeof(spill[0]));
822                 spill->before  = NULL;
823                 spill->next    = NULL;
824                 spill->spill   = new_NoMem();
825
826                 spillinfo->spills      = spill;
827                 spillinfo->spill_costs = 0;
828
829                 DB((dbg, LEVEL_1, "don't spill %+F use NoMem\n", to_spill));
830                 return;
831         }
832
833         spill_block    = get_nodes_block(to_spill);
834         spill_execfreq = get_block_execfreq(env->exec_freq, spill_block);
835
836         if (is_Phi(to_spill) && ir_nodeset_contains(&env->mem_phis, to_spill)) {
837                 /* TODO calculate correct costs...
838                  * (though we can't remat this node anyway so no big problem) */
839                 spillinfo->spill_costs = env->spill_cost * spill_execfreq;
840                 return;
841         }
842
843         if(spillinfo->spills != NULL) {
844                 spill_t *s;
845                 double   spills_execfreq;
846
847                 /* calculate sum of executaion frequencies of individual spills */
848                 spills_execfreq = 0;
849                 s               = spillinfo->spills;
850                 for( ; s != NULL; s = s->next) {
851                         ir_node *spill_block = s->before;
852                         double   freq;
853
854                         if(!is_Block(spill_block)) {
855                                 spill_block = get_nodes_block(spill_block);
856                         }
857                         freq = get_block_execfreq(env->exec_freq, spill_block);
858
859                         spills_execfreq += freq;
860                 }
861
862                 DB((dbg, LEVEL_1, "%+F: latespillcosts %f after def: %f\n", to_spill,
863                     spills_execfreq * env->spill_cost,
864                     spill_execfreq * env->spill_cost));
865
866                 /* multi-/latespill is advantageous -> return*/
867                 if(spills_execfreq < spill_execfreq) {
868                         DB((dbg, LEVEL_1, "use latespills for %+F\n", to_spill));
869                         spillinfo->spill_costs = spills_execfreq * env->spill_cost;
870                         return;
871                 }
872         }
873
874         /* override spillinfos or create a new one */
875         spill         = obstack_alloc(&env->obst, sizeof(spill[0]));
876         spill->before = skip_keeps_phis(to_spill);
877         spill->next   = NULL;
878         spill->spill  = NULL;
879
880         spillinfo->spills      = spill;
881         spillinfo->spill_costs = spill_execfreq * env->spill_cost;
882         DB((dbg, LEVEL_1, "spill %+F after definition\n", to_spill));
883 }
884
885 void make_spill_locations_dominate_irn(spill_env_t *env, ir_node *irn)
886 {
887         const spill_info_t *si = get_spillinfo(env, irn);
888         ir_node *start_block   = get_irg_start_block(get_irn_irg(irn));
889         int n_blocks           = get_Block_dom_max_subtree_pre_num(start_block);
890         bitset_t *reloads      = bitset_alloca(n_blocks);
891         reloader_t *r;
892         spill_t *s;
893
894         if (si == NULL)
895                 return;
896
897         /* Fill the bitset with the dominance pre-order numbers
898          * of the blocks the reloads are located in. */
899         for (r = si->reloaders; r != NULL; r = r->next) {
900                 ir_node *bl = get_nodes_block(r->reloader);
901                 bitset_set(reloads, get_Block_dom_tree_pre_num(bl));
902         }
903
904         /* Now, cancel out all the blocks that are dominated by each spill.
905          * If the bitset is not empty after that, we have reloads that are
906          * not dominated by any spill. */
907         for (s = si->spills; s != NULL; s = s->next) {
908                 ir_node *bl = get_nodes_block(s->before);
909                 int start   = get_Block_dom_tree_pre_num(bl);
910                 int end     = get_Block_dom_max_subtree_pre_num(bl);
911
912                 bitset_clear_range(reloads, start, end);
913         }
914
915         if (!bitset_is_empty(reloads))
916                 be_add_spill(env, si->to_spill, sched_next(si->to_spill));
917 }
918
919 void be_insert_spills_reloads(spill_env_t *env)
920 {
921         ir_graph              *irg       = env->irg;
922         const arch_env_t      *arch_env  = env->arch_env;
923         const ir_exec_freq    *exec_freq = env->exec_freq;
924         spill_info_t          *si;
925         ir_nodeset_iterator_t  iter;
926         ir_node               *node;
927
928         BE_TIMER_PUSH(t_ra_spill_apply);
929
930         env->new_nodes_idx = get_irg_last_idx(irg);
931
932         /* create all phi-ms first, this is needed so, that phis, hanging on
933            spilled phis work correctly */
934         foreach_ir_nodeset(&env->mem_phis, node, iter) {
935                 spill_info_t *info = get_spillinfo(env, node);
936                 spill_node(env, info);
937         }
938
939         /* process each spilled node */
940         for (si = set_first(env->spills); si; si = set_next(env->spills)) {
941                 reloader_t *rld;
942                 ir_node  *to_spill        = si->to_spill;
943                 ir_mode  *mode            = get_irn_mode(to_spill);
944                 ir_node **copies          = NEW_ARR_F(ir_node*, 0);
945                 double    all_remat_costs = 0; /** costs when we would remat all nodes */
946                 int       force_remat     = 0;
947
948                 DBG((dbg, LEVEL_1, "\nhandling all reloaders of %+F:\n", to_spill));
949
950                 determine_spill_costs(env, si);
951
952                 /* determine possibility of rematerialisations */
953                 if(be_do_remats) {
954                         /* calculate cost savings for each indivial value when it would
955                            be rematted instead of reloaded */
956                         for (rld = si->reloaders; rld != NULL; rld = rld->next) {
957                                 double   freq;
958                                 int      remat_cost;
959                                 int      remat_cost_delta;
960                                 ir_node *block;
961                                 ir_node *reloader = rld->reloader;
962
963                                 if(rld->rematted_node != NULL) {
964                                         DBG((dbg, LEVEL_2, "\tforced remat %+F before %+F\n",
965                                              rld->rematted_node, reloader));
966                                         continue;
967                                 }
968                                 if(rld->remat_cost_delta >= REMAT_COST_INFINITE) {
969                                         DBG((dbg, LEVEL_2, "\treload before %+F is forbidden\n",
970                                              reloader));
971                                         all_remat_costs = REMAT_COST_INFINITE;
972                                         continue;
973                                 }
974
975                                 remat_cost  = check_remat_conditions_costs(env, to_spill,
976                                                                            reloader, 0);
977                                 if(remat_cost >= REMAT_COST_INFINITE) {
978                                         DBG((dbg, LEVEL_2, "\tremat before %+F not possible\n",
979                                              reloader));
980                                         rld->remat_cost_delta = REMAT_COST_INFINITE;
981                                         all_remat_costs       = REMAT_COST_INFINITE;
982                                         continue;
983                                 }
984
985                                 remat_cost_delta      = remat_cost - env->reload_cost;
986                                 rld->remat_cost_delta = remat_cost_delta;
987                                 block                 = is_Block(reloader) ? reloader : get_nodes_block(reloader);
988                                 freq                  = get_block_execfreq(exec_freq, block);
989                                 all_remat_costs      += remat_cost_delta * freq;
990                                 DBG((dbg, LEVEL_2, "\tremat costs delta before %+F: "
991                                      "%d (rel %f)\n", reloader, remat_cost_delta,
992                                      remat_cost_delta * freq));
993                         }
994                         if(all_remat_costs < REMAT_COST_INFINITE) {
995                                 /* we don't need the costs for the spill if we can remat
996                                    all reloaders */
997                                 all_remat_costs -= si->spill_costs;
998
999                                 DBG((dbg, LEVEL_2, "\tspill costs %d (rel %f)\n",
1000                                      env->spill_cost, si->spill_costs));
1001                         }
1002
1003                         if(all_remat_costs < 0) {
1004                                 DBG((dbg, LEVEL_1, "\nforcing remats of all reloaders (%f)\n",
1005                                      all_remat_costs));
1006                                 force_remat = 1;
1007                         }
1008                 }
1009
1010                 /* go through all reloads for this spill */
1011                 for (rld = si->reloaders; rld != NULL; rld = rld->next) {
1012                         ir_node *copy; /* a reload is a "copy" of the original value */
1013
1014                         if (rld->rematted_node != NULL) {
1015                                 copy = rld->rematted_node;
1016                                 sched_add_before(rld->reloader, copy);
1017                         } else if (be_do_remats &&
1018                                         (force_remat || rld->remat_cost_delta < 0)) {
1019                                 copy = do_remat(env, to_spill, rld->reloader);
1020                         } else {
1021                                 /* make sure we have a spill */
1022                                 spill_node(env, si);
1023
1024                                 /* create a reload, use the first spill for now SSA
1025                                  * reconstruction for memory comes below */
1026                                 assert(si->spills != NULL);
1027                                 copy = be_reload(arch_env, si->reload_cls, rld->reloader, mode,
1028                                                  si->spills->spill);
1029 #ifdef FIRM_STATISTICS
1030                                 env->reload_count++;
1031 #endif
1032                         }
1033
1034                         DBG((dbg, LEVEL_1, " %+F of %+F before %+F\n",
1035                              copy, to_spill, rld->reloader));
1036                         ARR_APP1(ir_node*, copies, copy);
1037                 }
1038
1039                 /* if we had any reloads or remats, then we need to reconstruct the
1040                  * SSA form for the spilled value */
1041                 if (ARR_LEN(copies) > 0) {
1042                         be_ssa_construction_env_t senv;
1043                         /* be_lv_t *lv = be_get_birg_liveness(env->birg); */
1044
1045                         be_ssa_construction_init(&senv, env->birg);
1046                         be_ssa_construction_add_copy(&senv, to_spill);
1047                         be_ssa_construction_add_copies(&senv, copies, ARR_LEN(copies));
1048                         be_ssa_construction_fix_users(&senv, to_spill);
1049
1050 #if 0
1051                         /* no need to enable this as long as we invalidate liveness
1052                            after this function... */
1053                         be_ssa_construction_update_liveness_phis(&senv);
1054                         be_liveness_update(to_spill);
1055                         len = ARR_LEN(copies);
1056                         for(i = 0; i < len; ++i) {
1057                                 be_liveness_update(lv, copies[i]);
1058                         }
1059 #endif
1060                         be_ssa_construction_destroy(&senv);
1061                 }
1062                 /* need to reconstruct SSA form if we had multiple spills */
1063                 if (si->spills != NULL && si->spills->next != NULL) {
1064                         spill_t *spill;
1065                         int      spill_count = 0;
1066
1067                         be_ssa_construction_env_t senv;
1068
1069                         be_ssa_construction_init(&senv, env->birg);
1070                         spill = si->spills;
1071                         for( ; spill != NULL; spill = spill->next) {
1072                                 /* maybe we rematerialized the value and need no spill */
1073                                 if(spill->spill == NULL)
1074                                         continue;
1075                                 be_ssa_construction_add_copy(&senv, spill->spill);
1076                                 spill_count++;
1077                         }
1078                         if(spill_count > 1) {
1079                                 /* all reloads are attached to the first spill, fix them now */
1080                                 be_ssa_construction_fix_users(&senv, si->spills->spill);
1081                         }
1082
1083                         be_ssa_construction_destroy(&senv);
1084                 }
1085
1086                 DEL_ARR_F(copies);
1087                 si->reloaders = NULL;
1088         }
1089
1090         stat_ev_dbl("spill_spills", env->spill_count);
1091         stat_ev_dbl("spill_reloads", env->reload_count);
1092         stat_ev_dbl("spill_remats", env->remat_count);
1093         stat_ev_dbl("spill_spilled_phis", env->spilled_phi_count);
1094
1095         /* Matze: In theory be_ssa_construction should take care of the liveness...
1096          * try to disable this again in the future */
1097         be_liveness_invalidate(env->birg->lv);
1098
1099         be_remove_dead_nodes_from_schedule(env->birg);
1100
1101         BE_TIMER_POP(t_ra_spill_apply);
1102 }
1103
1104 void be_init_spill(void)
1105 {
1106         FIRM_DBG_REGISTER(dbg, "firm.be.spill");
1107 }
1108
1109 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spill);