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