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