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