change spiller and related interface to use ir_graph* instead of be_irg_t*
[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 "beintlive_t.h"
61 #include "bemodule.h"
62 #include "be_t.h"
63
64 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
65
66 #define REMAT_COST_INFINITE  1000
67
68 typedef struct reloader_t reloader_t;
69 struct reloader_t {
70         reloader_t *next;
71         ir_node    *can_spill_after;
72         ir_node    *reloader;
73         ir_node    *rematted_node;
74         int         remat_cost_delta; /** costs needed for rematerialization,
75                                            compared to placing a reload */
76 };
77
78 typedef struct spill_t spill_t;
79 struct spill_t {
80         spill_t *next;
81         ir_node *after;  /**< spill has to be placed after this node (or earlier) */
82         ir_node *spill;
83 };
84
85 typedef struct spill_info_t spill_info_t;
86 struct spill_info_t {
87         ir_node    *to_spill;  /**< the value that should get spilled */
88         reloader_t *reloaders; /**< list of places where the value should get
89                                     reloaded */
90         spill_t    *spills;    /**< list of latest places where spill must be
91                                     placed */
92         double      spill_costs; /**< costs needed for spilling the value */
93         const arch_register_class_t *reload_cls; /** the register class in which the
94                                                      reload should be placed */
95 };
96
97 struct spill_env_t {
98         const arch_env_t *arch_env;
99         ir_graph         *irg;
100         struct obstack    obst;
101         int               spill_cost;     /**< the cost of a single spill node */
102         int               reload_cost;    /**< the cost of a reload node */
103         set              *spills;         /**< all spill_info_t's, which must be
104                                                placed */
105         ir_nodeset_t      mem_phis;       /**< set of all spilled phis. */
106         ir_exec_freq     *exec_freq;
107
108 #ifdef FIRM_STATISTICS
109         unsigned          spill_count;
110         unsigned          reload_count;
111         unsigned          remat_count;
112         unsigned          spilled_phi_count;
113 #endif
114 };
115
116 /**
117  * Compare two spill infos.
118  */
119 static int cmp_spillinfo(const void *x, const void *y, size_t size)
120 {
121         const spill_info_t *xx = x;
122         const spill_info_t *yy = y;
123         (void) size;
124
125         return xx->to_spill != yy->to_spill;
126 }
127
128 /**
129  * Returns spill info for a specific value (the value that is to be spilled)
130  */
131 static spill_info_t *get_spillinfo(const spill_env_t *env, ir_node *value)
132 {
133         spill_info_t info, *res;
134         int hash = hash_irn(value);
135
136         info.to_spill = value;
137         res = set_find(env->spills, &info, sizeof(info), hash);
138
139         if (res == NULL) {
140                 info.reloaders   = NULL;
141                 info.spills      = NULL;
142                 info.spill_costs = -1;
143                 info.reload_cls  = NULL;
144                 res = set_insert(env->spills, &info, sizeof(info), hash);
145         }
146
147         return res;
148 }
149
150 spill_env_t *be_new_spill_env(ir_graph *irg)
151 {
152         const arch_env_t *arch_env = be_get_irg_arch_env(irg);
153
154         spill_env_t *env = XMALLOC(spill_env_t);
155         env->spills                     = new_set(cmp_spillinfo, 1024);
156         env->irg            = irg;
157         env->arch_env       = arch_env;
158         ir_nodeset_init(&env->mem_phis);
159         env->spill_cost     = arch_env->spill_cost;
160         env->reload_cost    = arch_env->reload_cost;
161         env->exec_freq      = be_get_irg_exec_freq(irg);
162         obstack_init(&env->obst);
163
164 #ifdef FIRM_STATISTICS
165         env->spill_count       = 0;
166         env->reload_count      = 0;
167         env->remat_count       = 0;
168         env->spilled_phi_count = 0;
169 #endif
170
171         return env;
172 }
173
174 void be_delete_spill_env(spill_env_t *env)
175 {
176         del_set(env->spills);
177         ir_nodeset_destroy(&env->mem_phis);
178         obstack_free(&env->obst, NULL);
179         free(env);
180 }
181
182 /*
183  *  ____  _                  ____      _                 _
184  * |  _ \| | __ _  ___ ___  |  _ \ ___| | ___   __ _  __| |___
185  * | |_) | |/ _` |/ __/ _ \ | |_) / _ \ |/ _ \ / _` |/ _` / __|
186  * |  __/| | (_| | (_|  __/ |  _ <  __/ | (_) | (_| | (_| \__ \
187  * |_|   |_|\__,_|\___\___| |_| \_\___|_|\___/ \__,_|\__,_|___/
188  *
189  */
190
191 void be_add_spill(spill_env_t *env, ir_node *to_spill, ir_node *after)
192 {
193         spill_info_t  *spill_info = get_spillinfo(env, to_spill);
194         const ir_node *insn       = skip_Proj_const(to_spill);
195         spill_t       *spill;
196         spill_t       *s;
197         spill_t       *last;
198
199         assert(!arch_irn_is(insn, 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         const ir_node *insn = skip_Proj_const(to_spill);
265
266         assert(!arch_irn_is(insn, dont_spill));
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                   = OALLOC(&env->obst, reloader_t);
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         while (true) {
324                 ir_node *next = sched_next(node);
325                 if (!is_Phi(next) && !be_is_Keep(next) && !be_is_CopyKeep(next))
326                         break;
327                 node = next;
328         }
329         return node;
330 }
331
332 /**
333  * Returns the point at which you can insert a node that should be executed
334  * before block @p block when coming from pred @p pos.
335  */
336 static ir_node *get_block_insertion_point(ir_node *block, int pos)
337 {
338         ir_node *predblock;
339
340         /* simply add the reload to the beginning of the block if we only have 1
341          * predecessor. We don't need to check for phis as there can't be any in a
342          * block with only 1 pred. */
343         if (get_Block_n_cfgpreds(block) == 1) {
344                 assert(!is_Phi(sched_first(block)));
345                 return sched_first(block);
346         }
347
348         /* We have to reload the value in pred-block */
349         predblock = get_Block_cfgpred_block(block, pos);
350         return be_get_end_of_block_insertion_point(predblock);
351 }
352
353 void be_add_reload_at_end(spill_env_t *env, ir_node *to_spill,
354                           const ir_node *block,
355                           const arch_register_class_t *reload_cls,
356                           int allow_remat)
357 {
358         ir_node *before = be_get_end_of_block_insertion_point(block);
359         be_add_reload(env, to_spill, before, reload_cls, allow_remat);
360 }
361
362 void be_add_reload_on_edge(spill_env_t *env, ir_node *to_spill, ir_node *block,
363                            int pos,     const arch_register_class_t *reload_cls,
364                            int allow_remat)
365 {
366         ir_node *before = get_block_insertion_point(block, pos);
367         be_add_reload(env, to_spill, before, reload_cls, allow_remat);
368 }
369
370 void be_spill_phi(spill_env_t *env, ir_node *node)
371 {
372         ir_node *block;
373         int i, arity;
374
375         assert(is_Phi(node));
376
377         ir_nodeset_insert(&env->mem_phis, node);
378
379         /* create spills for the phi arguments */
380         block = get_nodes_block(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
385                 /* some backends have virtual noreg/unknown nodes that are not scheduled
386                  * and simply always available. */
387                 if (!sched_is_scheduled(arg)) {
388                         ir_node *pred_block = get_Block_cfgpred_block(block, i);
389                         insert = be_get_end_of_block_insertion_point(pred_block);
390                         insert = sched_prev(insert);
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         const ir_node *insn     = skip_Proj_const(to_spill);
423         spill_t *spill;
424
425         /* determine_spill_costs must have been run before */
426         assert(spillinfo->spill_costs >= 0);
427
428         /* some backends have virtual noreg/unknown nodes that are not scheduled
429          * and simply always available. */
430         if (!sched_is_scheduled(insn)) {
431                 /* override spillinfos or create a new one */
432                 spillinfo->spills->spill = new_NoMem();
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  = new_r_Phi(block, arity, ins, mode_M);
494         spill->next   = NULL;
495
496         spillinfo->spills = spill;
497 #ifdef FIRM_STATISTICS
498         env->spilled_phi_count++;
499 #endif
500
501         for (i = 0; i < arity; ++i) {
502                 ir_node      *arg      = get_irn_n(phi, i);
503                 spill_info_t *arg_info = get_spillinfo(env, arg);
504
505                 determine_spill_costs(env, arg_info);
506                 spill_node(env, arg_info);
507
508                 set_irn_n(spill->spill, i, arg_info->spills->spill);
509         }
510         DBG((dbg, LEVEL_1, "... done spilling Phi %+F, created PhiM %+F\n", phi,
511              spill->spill));
512 }
513
514 /**
515  * Spill a node.
516  *
517  * @param senv      the spill environment
518  * @param to_spill  the node that should be spilled
519  */
520 static void spill_node(spill_env_t *env, spill_info_t *spillinfo)
521 {
522         ir_node *to_spill;
523
524         /* node is already spilled */
525         if (spillinfo->spills != NULL && spillinfo->spills->spill != NULL)
526                 return;
527
528         to_spill = spillinfo->to_spill;
529
530         if (is_Phi(to_spill) && ir_nodeset_contains(&env->mem_phis, to_spill)) {
531                 spill_phi(env, spillinfo);
532         } else {
533                 spill_irn(env, spillinfo);
534         }
535 }
536
537 /*
538  *
539  *  ____                      _            _       _ _
540  * |  _ \ ___ _ __ ___   __ _| |_ ___ _ __(_) __ _| (_)_______
541  * | |_) / _ \ '_ ` _ \ / _` | __/ _ \ '__| |/ _` | | |_  / _ \
542  * |  _ <  __/ | | | | | (_| | ||  __/ |  | | (_| | | |/ /  __/
543  * |_| \_\___|_| |_| |_|\__,_|\__\___|_|  |_|\__,_|_|_/___\___|
544  *
545  */
546
547 /**
548  * Tests whether value @p arg is available before node @p reloader
549  * @returns 1 if value is available, 0 otherwise
550  */
551 static int is_value_available(spill_env_t *env, const ir_node *arg,
552                               const ir_node *reloader)
553 {
554         if (is_Unknown(arg) || arg == new_NoMem())
555                 return 1;
556
557         if (be_is_Spill(skip_Proj_const(arg)))
558                 return 1;
559
560         if (arg == get_irg_frame(env->irg))
561                 return 1;
562
563         (void)reloader;
564
565         if (get_irn_mode(arg) == mode_T)
566                 return 0;
567
568         /*
569          * Ignore registers are always available
570          */
571         if (arch_irn_is_ignore(arg))
572                 return 1;
573
574         return 0;
575 }
576
577 /**
578  * Check if a node is rematerializable. This tests for the following conditions:
579  *
580  * - The node itself is rematerializable
581  * - All arguments of the node are available or also rematerialisable
582  * - The costs for the rematerialisation operation is less or equal a limit
583  *
584  * Returns the costs needed for rematerialisation or something
585  * >= REMAT_COST_INFINITE if remat is not possible.
586  */
587 static int check_remat_conditions_costs(spill_env_t *env,
588                 const ir_node *spilled, const ir_node *reloader, int parentcosts)
589 {
590         int i, arity;
591         int argremats;
592         int costs = 0;
593         const ir_node *insn = skip_Proj_const(spilled);
594
595         assert(!be_is_Spill(insn));
596         if (!arch_irn_is(insn, rematerializable))
597                 return REMAT_COST_INFINITE;
598
599         if (be_is_Reload(insn)) {
600                 costs += 2;
601         } else {
602                 costs += arch_get_op_estimated_cost(insn);
603         }
604         if (parentcosts + costs >= env->reload_cost + env->spill_cost) {
605                 return REMAT_COST_INFINITE;
606         }
607         /* never rematerialize a node which modifies the flags.
608          * (would be better to test wether the flags are actually live at point
609          * reloader...)
610          */
611         if (arch_irn_is(insn, modify_flags)) {
612                 return REMAT_COST_INFINITE;
613         }
614
615         argremats = 0;
616         for (i = 0, arity = get_irn_arity(insn); i < arity; ++i) {
617                 ir_node *arg = get_irn_n(insn, i);
618
619                 if (is_value_available(env, arg, reloader))
620                         continue;
621
622                 /* we have to rematerialize the argument as well */
623                 ++argremats;
624                 if (argremats > 1) {
625                         /* we only support rematerializing 1 argument at the moment,
626                          * as multiple arguments could increase register pressure */
627                         return REMAT_COST_INFINITE;
628                 }
629
630                 costs += check_remat_conditions_costs(env, arg, reloader,
631                                                       parentcosts + costs);
632                 if (parentcosts + costs >= env->reload_cost + env->spill_cost)
633                         return REMAT_COST_INFINITE;
634         }
635
636         return costs;
637 }
638
639 /**
640  * Re-materialize a node.
641  *
642  * @param senv      the spill environment
643  * @param spilled   the node that was spilled
644  * @param reloader  a irn that requires a reload
645  */
646 static ir_node *do_remat(spill_env_t *env, ir_node *spilled, ir_node *reloader)
647 {
648         int i, arity;
649         ir_node *res;
650         ir_node *bl;
651         ir_node **ins;
652
653         if (is_Block(reloader)) {
654                 bl = reloader;
655         } else {
656                 bl = get_nodes_block(reloader);
657         }
658
659         ins = ALLOCAN(ir_node*, get_irn_arity(spilled));
660         for (i = 0, arity = get_irn_arity(spilled); i < arity; ++i) {
661                 ir_node *arg = get_irn_n(spilled, i);
662
663                 if (is_value_available(env, arg, reloader)) {
664                         ins[i] = arg;
665                 } else {
666                         ins[i] = do_remat(env, arg, reloader);
667 #ifdef FIRM_STATISTICS
668                         /* don't count the recursive call as remat */
669                         env->remat_count--;
670 #endif
671                 }
672         }
673
674         /* create a copy of the node */
675         res = new_ir_node(get_irn_dbg_info(spilled), env->irg, bl,
676                           get_irn_op(spilled), get_irn_mode(spilled),
677                           get_irn_arity(spilled), ins);
678         copy_node_attr(env->irg, spilled, res);
679         arch_env_mark_remat(env->arch_env, res);
680
681         DBG((dbg, LEVEL_1, "Insert remat %+F of %+F before reloader %+F\n", res, spilled, reloader));
682
683         if (! is_Proj(res)) {
684                 /* insert in schedule */
685                 sched_reset(res);
686                 sched_add_before(reloader, res);
687 #ifdef FIRM_STATISTICS
688                 env->remat_count++;
689 #endif
690         }
691
692         return res;
693 }
694
695 double be_get_spill_costs(spill_env_t *env, ir_node *to_spill, ir_node *before)
696 {
697         ir_node *block = get_nodes_block(before);
698         double   freq  = get_block_execfreq(env->exec_freq, block);
699         (void) to_spill;
700
701         return env->spill_cost * freq;
702 }
703
704 unsigned be_get_reload_costs_no_weight(spill_env_t *env, const ir_node *to_spill,
705                                        const ir_node *before)
706 {
707         if (be_do_remats) {
708                 /* is the node rematerializable? */
709                 unsigned costs = check_remat_conditions_costs(env, to_spill, before, 0);
710                 if (costs < (unsigned) env->reload_cost)
711                         return costs;
712         }
713
714         return env->reload_cost;
715 }
716
717 double be_get_reload_costs(spill_env_t *env, ir_node *to_spill, ir_node *before)
718 {
719         ir_node      *block = get_nodes_block(before);
720         double        freq  = get_block_execfreq(env->exec_freq, block);
721
722         if (be_do_remats) {
723                 /* is the node rematerializable? */
724                 int costs = check_remat_conditions_costs(env, to_spill, before, 0);
725                 if (costs < env->reload_cost)
726                         return costs * freq;
727         }
728
729         return env->reload_cost * freq;
730 }
731
732 int be_is_rematerializable(spill_env_t *env, const ir_node *to_remat,
733                            const ir_node *before)
734 {
735         return check_remat_conditions_costs(env, to_remat, before, 0) < REMAT_COST_INFINITE;
736 }
737
738 double be_get_reload_costs_on_edge(spill_env_t *env, ir_node *to_spill,
739                                    ir_node *block, int pos)
740 {
741         ir_node *before = get_block_insertion_point(block, pos);
742         return be_get_reload_costs(env, to_spill, before);
743 }
744
745 /*
746  *  ___                     _     ____      _                 _
747  * |_ _|_ __  ___  ___ _ __| |_  |  _ \ ___| | ___   __ _  __| |___
748  *  | || '_ \/ __|/ _ \ '__| __| | |_) / _ \ |/ _ \ / _` |/ _` / __|
749  *  | || | | \__ \  __/ |  | |_  |  _ <  __/ | (_) | (_| | (_| \__ \
750  * |___|_| |_|___/\___|_|   \__| |_| \_\___|_|\___/ \__,_|\__,_|___/
751  *
752  */
753
754 /**
755  * analyzes how to best spill a node and determine costs for that
756  */
757 static void determine_spill_costs(spill_env_t *env, spill_info_t *spillinfo)
758 {
759         ir_node       *to_spill = spillinfo->to_spill;
760         const ir_node *insn     = skip_Proj_const(to_spill);
761         ir_node       *spill_block;
762         spill_t       *spill;
763         double         spill_execfreq;
764
765         /* already calculated? */
766         if (spillinfo->spill_costs >= 0)
767                 return;
768
769         assert(!arch_irn_is(insn, dont_spill));
770         assert(!be_is_Reload(insn));
771
772         /* some backends have virtual noreg/unknown nodes that are not scheduled
773          * and simply always available.
774          * TODO: this is kinda hairy, the NoMem is correct for an Unknown as Phi
775          * predecessor (of a PhiM) but this test might match other things too...
776          */
777         if (!sched_is_scheduled(insn)) {
778                 /* override spillinfos or create a new one */
779                 spill_t *spill = OALLOC(&env->obst, spill_t);
780                 spill->after = NULL;
781                 spill->next  = NULL;
782                 spill->spill = new_NoMem();
783
784                 spillinfo->spills      = spill;
785                 spillinfo->spill_costs = 0;
786
787                 DB((dbg, LEVEL_1, "don't spill %+F use NoMem\n", to_spill));
788                 return;
789         }
790
791         spill_block    = get_nodes_block(insn);
792         spill_execfreq = get_block_execfreq(env->exec_freq, spill_block);
793
794         if (is_Phi(to_spill) && ir_nodeset_contains(&env->mem_phis, to_spill)) {
795                 /* TODO calculate correct costs...
796                  * (though we can't remat this node anyway so no big problem) */
797                 spillinfo->spill_costs = env->spill_cost * spill_execfreq;
798                 return;
799         }
800
801         if (spillinfo->spills != NULL) {
802                 spill_t *s;
803                 double   spills_execfreq;
804
805                 /* calculate sum of execution frequencies of individual spills */
806                 spills_execfreq = 0;
807                 s               = spillinfo->spills;
808                 for ( ; s != NULL; s = s->next) {
809                         ir_node *spill_block = get_block(s->after);
810                         double   freq = get_block_execfreq(env->exec_freq, spill_block);
811
812                         spills_execfreq += freq;
813                 }
814
815                 DB((dbg, LEVEL_1, "%+F: latespillcosts %f after def: %f\n", to_spill,
816                     spills_execfreq * env->spill_cost,
817                     spill_execfreq * env->spill_cost));
818
819                 /* multi-/latespill is advantageous -> return*/
820                 if (spills_execfreq < spill_execfreq) {
821                         DB((dbg, LEVEL_1, "use latespills for %+F\n", to_spill));
822                         spillinfo->spill_costs = spills_execfreq * env->spill_cost;
823                         return;
824                 }
825         }
826
827         /* override spillinfos or create a new one */
828         spill        = OALLOC(&env->obst, spill_t);
829         spill->after = skip_keeps_phis(to_spill);
830         spill->next  = NULL;
831         spill->spill = NULL;
832
833         spillinfo->spills      = spill;
834         spillinfo->spill_costs = spill_execfreq * env->spill_cost;
835         DB((dbg, LEVEL_1, "spill %+F after definition\n", to_spill));
836 }
837
838 void make_spill_locations_dominate_irn(spill_env_t *env, ir_node *irn)
839 {
840         const spill_info_t *si = get_spillinfo(env, irn);
841         ir_node *start_block   = get_irg_start_block(get_irn_irg(irn));
842         int n_blocks           = get_Block_dom_max_subtree_pre_num(start_block);
843         bitset_t *reloads      = bitset_alloca(n_blocks);
844         reloader_t *r;
845         spill_t *s;
846
847         if (si == NULL)
848                 return;
849
850         /* Fill the bitset with the dominance pre-order numbers
851          * of the blocks the reloads are located in. */
852         for (r = si->reloaders; r != NULL; r = r->next) {
853                 ir_node *bl = get_nodes_block(r->reloader);
854                 bitset_set(reloads, get_Block_dom_tree_pre_num(bl));
855         }
856
857         /* Now, cancel out all the blocks that are dominated by each spill.
858          * If the bitset is not empty after that, we have reloads that are
859          * not dominated by any spill. */
860         for (s = si->spills; s != NULL; s = s->next) {
861                 ir_node *bl = get_nodes_block(s->after);
862                 int start   = get_Block_dom_tree_pre_num(bl);
863                 int end     = get_Block_dom_max_subtree_pre_num(bl);
864
865                 bitset_clear_range(reloads, start, end);
866         }
867
868         if (!bitset_is_empty(reloads))
869                 be_add_spill(env, si->to_spill, si->to_spill);
870 }
871
872 void be_insert_spills_reloads(spill_env_t *env)
873 {
874         const ir_exec_freq    *exec_freq = env->exec_freq;
875         spill_info_t          *si;
876         ir_nodeset_iterator_t  iter;
877         ir_node               *node;
878
879         be_timer_push(T_RA_SPILL_APPLY);
880
881         /* create all phi-ms first, this is needed so, that phis, hanging on
882            spilled phis work correctly */
883         foreach_ir_nodeset(&env->mem_phis, node, iter) {
884                 spill_info_t *info = get_spillinfo(env, node);
885                 spill_node(env, info);
886         }
887
888         /* process each spilled node */
889         for (si = set_first(env->spills); si; si = set_next(env->spills)) {
890                 reloader_t *rld;
891                 ir_node  *to_spill        = si->to_spill;
892                 ir_mode  *mode            = get_irn_mode(to_spill);
893                 ir_node **copies          = NEW_ARR_F(ir_node*, 0);
894                 double    all_remat_costs = 0; /** costs when we would remat all nodes */
895                 int       force_remat     = 0;
896
897                 DBG((dbg, LEVEL_1, "\nhandling all reloaders of %+F:\n", to_spill));
898
899                 determine_spill_costs(env, si);
900
901                 /* determine possibility of rematerialisations */
902                 if (be_do_remats) {
903                         /* calculate cost savings for each indivial value when it would
904                            be rematted instead of reloaded */
905                         for (rld = si->reloaders; rld != NULL; rld = rld->next) {
906                                 double   freq;
907                                 int      remat_cost;
908                                 int      remat_cost_delta;
909                                 ir_node *block;
910                                 ir_node *reloader = rld->reloader;
911
912                                 if (rld->rematted_node != NULL) {
913                                         DBG((dbg, LEVEL_2, "\tforced remat %+F before %+F\n",
914                                              rld->rematted_node, reloader));
915                                         continue;
916                                 }
917                                 if (rld->remat_cost_delta >= REMAT_COST_INFINITE) {
918                                         DBG((dbg, LEVEL_2, "\treload before %+F is forbidden\n",
919                                              reloader));
920                                         all_remat_costs = REMAT_COST_INFINITE;
921                                         continue;
922                                 }
923
924                                 remat_cost  = check_remat_conditions_costs(env, to_spill,
925                                                                            reloader, 0);
926                                 if (remat_cost >= REMAT_COST_INFINITE) {
927                                         DBG((dbg, LEVEL_2, "\tremat before %+F not possible\n",
928                                              reloader));
929                                         rld->remat_cost_delta = REMAT_COST_INFINITE;
930                                         all_remat_costs       = REMAT_COST_INFINITE;
931                                         continue;
932                                 }
933
934                                 remat_cost_delta      = remat_cost - env->reload_cost;
935                                 rld->remat_cost_delta = remat_cost_delta;
936                                 block                 = is_Block(reloader) ? reloader : get_nodes_block(reloader);
937                                 freq                  = get_block_execfreq(exec_freq, block);
938                                 all_remat_costs      += remat_cost_delta * freq;
939                                 DBG((dbg, LEVEL_2, "\tremat costs delta before %+F: "
940                                      "%d (rel %f)\n", reloader, remat_cost_delta,
941                                      remat_cost_delta * freq));
942                         }
943                         if (all_remat_costs < REMAT_COST_INFINITE) {
944                                 /* we don't need the costs for the spill if we can remat
945                                    all reloaders */
946                                 all_remat_costs -= si->spill_costs;
947
948                                 DBG((dbg, LEVEL_2, "\tspill costs %d (rel %f)\n",
949                                      env->spill_cost, si->spill_costs));
950                         }
951
952                         if (all_remat_costs < 0) {
953                                 DBG((dbg, LEVEL_1, "\nforcing remats of all reloaders (%f)\n",
954                                      all_remat_costs));
955                                 force_remat = 1;
956                         }
957                 }
958
959                 /* go through all reloads for this spill */
960                 for (rld = si->reloaders; rld != NULL; rld = rld->next) {
961                         ir_node *copy; /* a reload is a "copy" of the original value */
962
963                         if (rld->rematted_node != NULL) {
964                                 copy = rld->rematted_node;
965                                 sched_add_before(rld->reloader, copy);
966                         } else if (be_do_remats &&
967                                         (force_remat || rld->remat_cost_delta < 0)) {
968                                 copy = do_remat(env, to_spill, rld->reloader);
969                         } else {
970                                 /* make sure we have a spill */
971                                 spill_node(env, si);
972
973                                 /* create a reload, use the first spill for now SSA
974                                  * reconstruction for memory comes below */
975                                 assert(si->spills != NULL);
976                                 copy = be_reload(si->reload_cls, rld->reloader, mode,
977                                                  si->spills->spill);
978 #ifdef FIRM_STATISTICS
979                                 env->reload_count++;
980 #endif
981                         }
982
983                         DBG((dbg, LEVEL_1, " %+F of %+F before %+F\n",
984                              copy, to_spill, rld->reloader));
985                         ARR_APP1(ir_node*, copies, copy);
986                 }
987
988                 /* if we had any reloads or remats, then we need to reconstruct the
989                  * SSA form for the spilled value */
990                 if (ARR_LEN(copies) > 0) {
991                         be_ssa_construction_env_t senv;
992                         /* be_lv_t *lv = be_get_irg_liveness(env->irg); */
993
994                         be_ssa_construction_init(&senv, env->irg);
995                         be_ssa_construction_add_copy(&senv, to_spill);
996                         be_ssa_construction_add_copies(&senv, copies, ARR_LEN(copies));
997                         be_ssa_construction_fix_users(&senv, to_spill);
998
999 #if 0
1000                         /* no need to enable this as long as we invalidate liveness
1001                            after this function... */
1002                         be_ssa_construction_update_liveness_phis(&senv);
1003                         be_liveness_update(to_spill);
1004                         len = ARR_LEN(copies);
1005                         for (i = 0; i < len; ++i) {
1006                                 be_liveness_update(lv, copies[i]);
1007                         }
1008 #endif
1009                         be_ssa_construction_destroy(&senv);
1010                 }
1011                 /* need to reconstruct SSA form if we had multiple spills */
1012                 if (si->spills != NULL && si->spills->next != NULL) {
1013                         spill_t *spill;
1014                         int      spill_count = 0;
1015
1016                         be_ssa_construction_env_t senv;
1017
1018                         be_ssa_construction_init(&senv, env->irg);
1019                         spill = si->spills;
1020                         for ( ; spill != NULL; spill = spill->next) {
1021                                 /* maybe we rematerialized the value and need no spill */
1022                                 if (spill->spill == NULL)
1023                                         continue;
1024                                 be_ssa_construction_add_copy(&senv, spill->spill);
1025                                 spill_count++;
1026                         }
1027                         if (spill_count > 1) {
1028                                 /* all reloads are attached to the first spill, fix them now */
1029                                 be_ssa_construction_fix_users(&senv, si->spills->spill);
1030                         }
1031
1032                         be_ssa_construction_destroy(&senv);
1033                 }
1034
1035                 DEL_ARR_F(copies);
1036                 si->reloaders = NULL;
1037         }
1038
1039         stat_ev_dbl("spill_spills", env->spill_count);
1040         stat_ev_dbl("spill_reloads", env->reload_count);
1041         stat_ev_dbl("spill_remats", env->remat_count);
1042         stat_ev_dbl("spill_spilled_phis", env->spilled_phi_count);
1043
1044         /* Matze: In theory be_ssa_construction should take care of the liveness...
1045          * try to disable this again in the future */
1046         be_liveness_invalidate(be_get_irg_liveness(env->irg));
1047
1048         be_remove_dead_nodes_from_schedule(env->irg);
1049
1050         be_timer_pop(T_RA_SPILL_APPLY);
1051 }
1052
1053 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spill);
1054 void be_init_spill(void)
1055 {
1056         FIRM_DBG_REGISTER(dbg, "firm.be.spill");
1057 }