bespillutil: Remove the unusd function be_add_reload_at_end().
[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  */
26 #include "config.h"
27
28 #include <stdlib.h>
29 #include <stdbool.h>
30
31 #include "pset.h"
32 #include "irnode_t.h"
33 #include "ircons_t.h"
34 #include "iredges_t.h"
35 #include "irbackedge_t.h"
36 #include "irprintf.h"
37 #include "ident_t.h"
38 #include "type_t.h"
39 #include "entity_t.h"
40 #include "debug.h"
41 #include "irgwalk.h"
42 #include "array.h"
43 #include "pdeq.h"
44 #include "execfreq.h"
45 #include "irnodeset.h"
46 #include "error.h"
47
48 #include "bearch.h"
49 #include "belive_t.h"
50 #include "besched.h"
51 #include "bespill.h"
52 #include "bespillutil.h"
53 #include "belive_t.h"
54 #include "benode.h"
55 #include "bechordal_t.h"
56 #include "statev_t.h"
57 #include "bessaconstr.h"
58 #include "beirg.h"
59 #include "beirgmod.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         bool        spilled_phi; /* true when the whole Phi has been spilled and
96                                     will be replaced with a PhiM. false if only the
97                                     value of the Phi gets spilled */
98 };
99
100 struct spill_env_t {
101         const arch_env_t *arch_env;
102         ir_graph         *irg;
103         struct obstack    obst;
104         int               spill_cost;     /**< the cost of a single spill node */
105         int               reload_cost;    /**< the cost of a reload node */
106         set              *spills;         /**< all spill_info_t's, which must be
107                                                placed */
108         spill_info_t    **mem_phis;       /**< set of all spilled phis. */
109
110         unsigned          spill_count;
111         unsigned          reload_count;
112         unsigned          remat_count;
113         unsigned          spilled_phi_count;
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 = (const spill_info_t*)x;
122         const spill_info_t *yy = (const spill_info_t*)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(spill_info_t, 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                 info.spilled_phi = false;
145                 res = set_insert(spill_info_t, 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         env->mem_phis       = NEW_ARR_F(spill_info_t*, 0);
160         env->spill_cost     = arch_env->spill_cost;
161         env->reload_cost    = arch_env->reload_cost;
162         obstack_init(&env->obst);
163
164         env->spill_count       = 0;
165         env->reload_count      = 0;
166         env->remat_count       = 0;
167         env->spilled_phi_count = 0;
168
169         return env;
170 }
171
172 void be_delete_spill_env(spill_env_t *env)
173 {
174         del_set(env->spills);
175         DEL_ARR_F(env->mem_phis);
176         obstack_free(&env->obst, NULL);
177         free(env);
178 }
179
180 /*
181  *  ____  _                  ____      _                 _
182  * |  _ \| | __ _  ___ ___  |  _ \ ___| | ___   __ _  __| |___
183  * | |_) | |/ _` |/ __/ _ \ | |_) / _ \ |/ _ \ / _` |/ _` / __|
184  * |  __/| | (_| | (_|  __/ |  _ <  __/ | (_) | (_| | (_| \__ \
185  * |_|   |_|\__,_|\___\___| |_| \_\___|_|\___/ \__,_|\__,_|___/
186  *
187  */
188
189 void be_add_spill(spill_env_t *env, ir_node *to_spill, ir_node *after)
190 {
191         spill_info_t  *spill_info = get_spillinfo(env, to_spill);
192         spill_t       *spill;
193         spill_t       *s;
194         spill_t       *last;
195
196         assert(!arch_irn_is(skip_Proj_const(to_spill), dont_spill));
197         DB((dbg, LEVEL_1, "Add spill of %+F after %+F\n", to_spill, after));
198
199         /* Just for safety make sure that we do not insert the spill in front of a phi */
200         assert(!is_Phi(sched_next(after)));
201
202         /* spills that are dominated by others are not needed */
203         last = NULL;
204         s    = spill_info->spills;
205         for ( ; s != NULL; s = s->next) {
206                 /* no need to add this spill if it is dominated by another */
207                 if (value_dominates(s->after, after)) {
208                         DB((dbg, LEVEL_1, "...dominated by %+F, not added\n", s->after));
209                         return;
210                 }
211                 /* remove spills that we dominate */
212                 if (value_dominates(after, s->after)) {
213                         DB((dbg, LEVEL_1, "...remove old spill at %+F\n", s->after));
214                         if (last != NULL) {
215                                 last->next         = s->next;
216                         } else {
217                                 spill_info->spills = s->next;
218                         }
219                 } else {
220                         last = s;
221                 }
222         }
223
224         spill         = OALLOC(&env->obst, spill_t);
225         spill->after  = after;
226         spill->next   = spill_info->spills;
227         spill->spill  = NULL;
228
229         spill_info->spills = spill;
230 }
231
232 void be_add_reload2(spill_env_t *env, ir_node *to_spill, ir_node *before,
233                 ir_node *can_spill_after, const arch_register_class_t *reload_cls,
234                 int allow_remat)
235 {
236         spill_info_t  *info;
237         reloader_t    *rel;
238
239         assert(!arch_irn_is(skip_Proj_const(to_spill), dont_spill));
240
241         info = get_spillinfo(env, to_spill);
242
243         if (is_Phi(to_spill)) {
244                 int i, arity;
245
246                 /* create spillinfos for the phi arguments */
247                 for (i = 0, arity = get_irn_arity(to_spill); i < arity; ++i) {
248                         ir_node *arg = get_irn_n(to_spill, i);
249                         get_spillinfo(env, arg);
250                 }
251         }
252
253         assert(!is_Proj(before) && !be_is_Keep(before));
254
255         /* put reload into list */
256         rel                   = OALLOC(&env->obst, reloader_t);
257         rel->next             = info->reloaders;
258         rel->reloader         = before;
259         rel->rematted_node    = NULL;
260         rel->can_spill_after  = can_spill_after;
261         rel->remat_cost_delta = allow_remat ? 0 : REMAT_COST_INFINITE;
262
263         info->reloaders  = rel;
264         assert(info->reload_cls == NULL || info->reload_cls == reload_cls);
265         info->reload_cls = reload_cls;
266
267         DBG((dbg, LEVEL_1, "creating spillinfo for %+F, will be reloaded before %+F, may%s be rematerialized\n",
268                 to_spill, before, allow_remat ? "" : " not"));
269 }
270
271 void be_add_reload(spill_env_t *senv, ir_node *to_spill, ir_node *before,
272                    const arch_register_class_t *reload_cls, int allow_remat)
273 {
274         be_add_reload2(senv, to_spill, before, to_spill, reload_cls, allow_remat);
275
276 }
277
278 ir_node *be_get_end_of_block_insertion_point(const ir_node *block)
279 {
280         ir_node *last = sched_last(block);
281
282         /* we might have keeps behind the jump... */
283         while (be_is_Keep(last)) {
284                 last = sched_prev(last);
285                 assert(!sched_is_end(last));
286         }
287
288         assert(is_cfop(last));
289
290         /* add the reload before the (cond-)jump */
291         return last;
292 }
293
294 /**
295  * determine final spill position: it should be after all phis, keep nodes
296  * and behind nodes marked as prolog
297  */
298 static ir_node *determine_spill_point(ir_node *node)
299 {
300         node = skip_Proj(node);
301         while (true) {
302                 ir_node *next = sched_next(node);
303                 if (!is_Phi(next) && !be_is_Keep(next) && !be_is_CopyKeep(next))
304                         break;
305                 node = next;
306         }
307         return node;
308 }
309
310 /**
311  * Returns the point at which you can insert a node that should be executed
312  * before block @p block when coming from pred @p pos.
313  */
314 static ir_node *get_block_insertion_point(ir_node *block, int pos)
315 {
316         ir_node *predblock;
317
318         /* simply add the reload to the beginning of the block if we only have 1
319          * predecessor. We don't need to check for phis as there can't be any in a
320          * block with only 1 pred. */
321         if (get_Block_n_cfgpreds(block) == 1) {
322                 assert(!is_Phi(sched_first(block)));
323                 return sched_first(block);
324         }
325
326         /* We have to reload the value in pred-block */
327         predblock = get_Block_cfgpred_block(block, pos);
328         return be_get_end_of_block_insertion_point(predblock);
329 }
330
331 void be_add_reload_on_edge(spill_env_t *env, ir_node *to_spill, ir_node *block,
332                            int pos, const arch_register_class_t *reload_cls,
333                            int allow_remat)
334 {
335         ir_node *before = get_block_insertion_point(block, pos);
336         be_add_reload(env, to_spill, before, reload_cls, allow_remat);
337 }
338
339 void be_spill_phi(spill_env_t *env, ir_node *node)
340 {
341         ir_node *block;
342         int i, arity;
343         spill_info_t *info;
344
345         assert(is_Phi(node));
346
347         info              = get_spillinfo(env, node);
348         info->spilled_phi = true;
349         ARR_APP1(spill_info_t*, env->mem_phis, info);
350
351         /* create spills for the phi arguments */
352         block = get_nodes_block(node);
353         for (i = 0, arity = get_irn_arity(node); i < arity; ++i) {
354                 ir_node *arg = get_irn_n(node, i);
355                 ir_node *insert;
356
357                 /* some backends have virtual noreg/unknown nodes that are not scheduled
358                  * and simply always available. */
359                 if (!sched_is_scheduled(arg)) {
360                         ir_node *pred_block = get_Block_cfgpred_block(block, i);
361                         insert = be_get_end_of_block_insertion_point(pred_block);
362                         insert = sched_prev(insert);
363                 } else {
364                         insert = determine_spill_point(arg);
365                 }
366
367                 be_add_spill(env, arg, insert);
368         }
369 }
370
371 /*
372  *   ____                _         ____        _ _ _
373  *  / ___|_ __ ___  __ _| |_ ___  / ___| _ __ (_) | |___
374  * | |   | '__/ _ \/ _` | __/ _ \ \___ \| '_ \| | | / __|
375  * | |___| | |  __/ (_| | ||  __/  ___) | |_) | | | \__ \
376  *  \____|_|  \___|\__,_|\__\___| |____/| .__/|_|_|_|___/
377  *                                      |_|
378  */
379
380 static void determine_spill_costs(spill_env_t *env, spill_info_t *spillinfo);
381
382 /**
383  * Creates a spill.
384  *
385  * @param senv      the spill environment
386  * @param irn       the node that should be spilled
387  * @param ctx_irn   an user of the spilled node
388  *
389  * @return a be_Spill node
390  */
391 static void spill_irn(spill_env_t *env, spill_info_t *spillinfo)
392 {
393         ir_node       *to_spill = spillinfo->to_spill;
394         const ir_node *insn     = skip_Proj_const(to_spill);
395         spill_t *spill;
396
397         /* determine_spill_costs must have been run before */
398         assert(spillinfo->spill_costs >= 0);
399
400         /* some backends have virtual noreg/unknown nodes that are not scheduled
401          * and simply always available. */
402         if (!sched_is_scheduled(insn)) {
403                 /* override spillinfos or create a new one */
404                 ir_graph *irg = get_irn_irg(to_spill);
405                 spillinfo->spills->spill = get_irg_no_mem(irg);
406                 DB((dbg, LEVEL_1, "don't spill %+F use NoMem\n", to_spill));
407                 return;
408         }
409
410         DBG((dbg, LEVEL_1, "spilling %+F ... \n", to_spill));
411         spill = spillinfo->spills;
412         for ( ; spill != NULL; spill = spill->next) {
413                 ir_node *after = spill->after;
414                 after = determine_spill_point(after);
415
416                 spill->spill = arch_env_new_spill(env->arch_env, to_spill, after);
417                 DB((dbg, LEVEL_1, "\t%+F after %+F\n", spill->spill, after));
418                 env->spill_count++;
419         }
420         DBG((dbg, LEVEL_1, "\n"));
421 }
422
423 static void spill_node(spill_env_t *env, spill_info_t *spillinfo);
424
425 /**
426  * If the first usage of a Phi result would be out of memory
427  * there is no sense in allocating a register for it.
428  * Thus we spill it and all its operands to the same spill slot.
429  * Therefore the phi/dataB becomes a phi/Memory
430  *
431  * @param senv      the spill environment
432  * @param phi       the Phi node that should be spilled
433  * @param ctx_irn   an user of the spilled node
434  */
435 static void spill_phi(spill_env_t *env, spill_info_t *spillinfo)
436 {
437         ir_graph *irg   = env->irg;
438         ir_node  *phi   = spillinfo->to_spill;
439         ir_node  *block = get_nodes_block(phi);
440         ir_node  *unknown;
441         ir_node **ins;
442         spill_t  *spill;
443         int       i;
444         int       arity;
445
446         assert(is_Phi(phi));
447         assert(!get_opt_cse());
448         DBG((dbg, LEVEL_1, "spilling Phi %+F:\n", phi));
449
450         /* build a new PhiM */
451         arity   = get_irn_arity(phi);
452         ins     = ALLOCAN(ir_node*, arity);
453         unknown = new_r_Unknown(irg, mode_M);
454         for (i = 0; i < arity; ++i) {
455                 ins[i] = unknown;
456         }
457
458         /* override or replace spills list... */
459         spill         = OALLOC(&env->obst, spill_t);
460         spill->after  = determine_spill_point(phi);
461         spill->spill  = be_new_Phi(block, arity, ins, mode_M, arch_no_register_req);
462         spill->next   = NULL;
463         sched_add_after(block, spill->spill);
464
465         spillinfo->spills = spill;
466         env->spilled_phi_count++;
467
468         for (i = 0; i < arity; ++i) {
469                 ir_node      *arg      = get_irn_n(phi, i);
470                 spill_info_t *arg_info = get_spillinfo(env, arg);
471
472                 determine_spill_costs(env, arg_info);
473                 spill_node(env, arg_info);
474
475                 set_irn_n(spill->spill, i, arg_info->spills->spill);
476         }
477         DBG((dbg, LEVEL_1, "... done spilling Phi %+F, created PhiM %+F\n", phi,
478              spill->spill));
479 }
480
481 /**
482  * Spill a node.
483  *
484  * @param senv      the spill environment
485  * @param to_spill  the node that should be spilled
486  */
487 static void spill_node(spill_env_t *env, spill_info_t *spillinfo)
488 {
489         /* node is already spilled */
490         if (spillinfo->spills != NULL && spillinfo->spills->spill != NULL)
491                 return;
492
493         if (spillinfo->spilled_phi) {
494                 spill_phi(env, spillinfo);
495         } else {
496                 spill_irn(env, spillinfo);
497         }
498 }
499
500 /*
501  *
502  *  ____                      _            _       _ _
503  * |  _ \ ___ _ __ ___   __ _| |_ ___ _ __(_) __ _| (_)_______
504  * | |_) / _ \ '_ ` _ \ / _` | __/ _ \ '__| |/ _` | | |_  / _ \
505  * |  _ <  __/ | | | | | (_| | ||  __/ |  | | (_| | | |/ /  __/
506  * |_| \_\___|_| |_| |_|\__,_|\__\___|_|  |_|\__,_|_|_/___\___|
507  *
508  */
509
510 /**
511  * Tests whether value @p arg is available before node @p reloader
512  * @returns 1 if value is available, 0 otherwise
513  */
514 static int is_value_available(spill_env_t *env, const ir_node *arg,
515                               const ir_node *reloader)
516 {
517         if (is_Unknown(arg) || is_NoMem(arg))
518                 return 1;
519
520         if (be_is_Spill(skip_Proj_const(arg)))
521                 return 1;
522
523         if (arg == get_irg_frame(env->irg))
524                 return 1;
525
526         (void)reloader;
527
528         if (get_irn_mode(arg) == mode_T)
529                 return 0;
530
531         /*
532          * Ignore registers are always available
533          */
534         if (arch_irn_is_ignore(arg))
535                 return 1;
536
537         return 0;
538 }
539
540 /**
541  * Check if a node is rematerializable. This tests for the following conditions:
542  *
543  * - The node itself is rematerializable
544  * - All arguments of the node are available or also rematerialisable
545  * - The costs for the rematerialisation operation is less or equal a limit
546  *
547  * Returns the costs needed for rematerialisation or something
548  * >= REMAT_COST_INFINITE if remat is not possible.
549  */
550 static int check_remat_conditions_costs(spill_env_t *env,
551                 const ir_node *spilled, const ir_node *reloader, int parentcosts)
552 {
553         int i, arity;
554         int argremats;
555         int costs = 0;
556         const ir_node *insn = skip_Proj_const(spilled);
557
558         assert(!be_is_Spill(insn));
559         if (!arch_irn_is(insn, rematerializable))
560                 return REMAT_COST_INFINITE;
561
562         if (be_is_Reload(insn)) {
563                 costs += 2;
564         } else {
565                 costs += arch_get_op_estimated_cost(insn);
566         }
567         if (parentcosts + costs >= env->reload_cost + env->spill_cost) {
568                 return REMAT_COST_INFINITE;
569         }
570         /* never rematerialize a node which modifies the flags.
571          * (would be better to test whether the flags are actually live at point
572          * reloader...)
573          */
574         if (arch_irn_is(insn, modify_flags)) {
575                 return REMAT_COST_INFINITE;
576         }
577
578         argremats = 0;
579         for (i = 0, arity = get_irn_arity(insn); i < arity; ++i) {
580                 ir_node *arg = get_irn_n(insn, i);
581
582                 if (is_value_available(env, arg, reloader))
583                         continue;
584
585                 /* we have to rematerialize the argument as well */
586                 ++argremats;
587                 if (argremats > 1) {
588                         /* we only support rematerializing 1 argument at the moment,
589                          * as multiple arguments could increase register pressure */
590                         return REMAT_COST_INFINITE;
591                 }
592
593                 costs += check_remat_conditions_costs(env, arg, reloader,
594                                                       parentcosts + costs);
595                 if (parentcosts + costs >= env->reload_cost + env->spill_cost)
596                         return REMAT_COST_INFINITE;
597         }
598
599         return costs;
600 }
601
602 /**
603  * Re-materialize a node.
604  *
605  * @param env       the spill environment
606  * @param spilled   the node that was spilled
607  * @param reloader  a irn that requires a reload
608  */
609 static ir_node *do_remat(spill_env_t *env, ir_node *spilled, ir_node *reloader)
610 {
611         int i, arity;
612         ir_node *res;
613         ir_node *bl;
614         ir_node **ins;
615
616         if (is_Block(reloader)) {
617                 bl = reloader;
618         } else {
619                 bl = get_nodes_block(reloader);
620         }
621
622         ins = ALLOCAN(ir_node*, get_irn_arity(spilled));
623         for (i = 0, arity = get_irn_arity(spilled); i < arity; ++i) {
624                 ir_node *arg = get_irn_n(spilled, i);
625
626                 if (is_value_available(env, arg, reloader)) {
627                         ins[i] = arg;
628                 } else {
629                         ins[i] = do_remat(env, arg, reloader);
630                         /* don't count the argument rematerialization as an extra remat */
631                         --env->remat_count;
632                 }
633         }
634
635         /* create a copy of the node */
636         res = new_ir_node(get_irn_dbg_info(spilled), env->irg, bl,
637                           get_irn_op(spilled), get_irn_mode(spilled),
638                           get_irn_arity(spilled), ins);
639         copy_node_attr(env->irg, spilled, res);
640         arch_env_mark_remat(env->arch_env, res);
641
642         DBG((dbg, LEVEL_1, "Insert remat %+F of %+F before reloader %+F\n", res, spilled, reloader));
643
644         if (! is_Proj(res)) {
645                 /* insert in schedule */
646                 sched_reset(res);
647                 sched_add_before(reloader, res);
648                 ++env->remat_count;
649         }
650
651         return res;
652 }
653
654 double be_get_spill_costs(spill_env_t *env, ir_node *to_spill, ir_node *before)
655 {
656         ir_node *block = get_nodes_block(before);
657         double   freq  = get_block_execfreq(block);
658         (void) to_spill;
659
660         return env->spill_cost * freq;
661 }
662
663 unsigned be_get_reload_costs_no_weight(spill_env_t *env, const ir_node *to_spill,
664                                        const ir_node *before)
665 {
666         if (be_do_remats) {
667                 /* is the node rematerializable? */
668                 unsigned costs = check_remat_conditions_costs(env, to_spill, before, 0);
669                 if (costs < (unsigned) env->reload_cost)
670                         return costs;
671         }
672
673         return env->reload_cost;
674 }
675
676 double be_get_reload_costs(spill_env_t *env, ir_node *to_spill, ir_node *before)
677 {
678         ir_node *block = get_nodes_block(before);
679         double   freq  = get_block_execfreq(block);
680
681         if (be_do_remats) {
682                 /* is the node rematerializable? */
683                 int costs = check_remat_conditions_costs(env, to_spill, before, 0);
684                 if (costs < env->reload_cost)
685                         return costs * freq;
686         }
687
688         return env->reload_cost * freq;
689 }
690
691 int be_is_rematerializable(spill_env_t *env, const ir_node *to_remat,
692                            const ir_node *before)
693 {
694         return check_remat_conditions_costs(env, to_remat, before, 0) < REMAT_COST_INFINITE;
695 }
696
697 double be_get_reload_costs_on_edge(spill_env_t *env, ir_node *to_spill,
698                                    ir_node *block, int pos)
699 {
700         ir_node *before = get_block_insertion_point(block, pos);
701         return be_get_reload_costs(env, to_spill, before);
702 }
703
704 ir_node *be_new_spill(ir_node *value, ir_node *after)
705 {
706         ir_graph                    *irg       = get_irn_irg(value);
707         ir_node                     *frame     = get_irg_frame(irg);
708         const arch_register_class_t *cls       = arch_get_irn_reg_class(value);
709         const arch_register_class_t *cls_frame = arch_get_irn_reg_class(frame);
710         ir_node                     *block     = get_block(after);
711         ir_node                     *spill
712                 = be_new_Spill(cls, cls_frame, block, frame, value);
713
714         sched_add_after(after, spill);
715         return spill;
716 }
717
718 ir_node *be_new_reload(ir_node *value, ir_node *spill, ir_node *before)
719 {
720         ir_graph *irg   = get_irn_irg(value);
721         ir_node  *frame = get_irg_frame(irg);
722         ir_node  *block = get_block(before);
723         const arch_register_class_t *cls       = arch_get_irn_reg_class(value);
724         const arch_register_class_t *cls_frame = arch_get_irn_reg_class(frame);
725         ir_mode                     *mode      = get_irn_mode(value);
726         ir_node  *reload;
727
728         assert(be_is_Spill(spill) || is_Phi(spill));
729         assert(get_irn_mode(spill) == mode_M);
730
731         reload = be_new_Reload(cls, cls_frame, block, frame, spill, mode);
732         sched_add_before(before, reload);
733
734         return reload;
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 = get_irg_no_mem(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(spill_block);
786
787         if (spillinfo->spilled_phi) {
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(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         size_t n_mem_phis = ARR_LEN(env->mem_phis);
868         size_t i;
869
870         be_timer_push(T_RA_SPILL_APPLY);
871
872         /* create all phi-ms first, this is needed so, that phis, hanging on
873            spilled phis work correctly */
874         for (i = 0; i < n_mem_phis; ++i) {
875                 spill_info_t *info = env->mem_phis[i];
876                 spill_node(env, info);
877         }
878
879         /* process each spilled node */
880         foreach_set(env->spills, spill_info_t, si) {
881                 ir_node  *to_spill        = si->to_spill;
882                 ir_node **copies          = NEW_ARR_F(ir_node*, 0);
883                 double    all_remat_costs = 0; /** costs when we would remat all nodes */
884                 bool      force_remat     = false;
885                 reloader_t *rld;
886
887                 DBG((dbg, LEVEL_1, "\nhandling all reloaders of %+F:\n", to_spill));
888
889                 determine_spill_costs(env, si);
890
891                 /* determine possibility of rematerialisations */
892                 if (be_do_remats) {
893                         /* calculate cost savings for each indivial value when it would
894                            be rematted instead of reloaded */
895                         for (rld = si->reloaders; rld != NULL; rld = rld->next) {
896                                 double   freq;
897                                 int      remat_cost;
898                                 int      remat_cost_delta;
899                                 ir_node *block;
900                                 ir_node *reloader = rld->reloader;
901
902                                 if (rld->rematted_node != NULL) {
903                                         DBG((dbg, LEVEL_2, "\tforced remat %+F before %+F\n",
904                                              rld->rematted_node, reloader));
905                                         continue;
906                                 }
907                                 if (rld->remat_cost_delta >= REMAT_COST_INFINITE) {
908                                         DBG((dbg, LEVEL_2, "\treload before %+F is forbidden\n",
909                                              reloader));
910                                         all_remat_costs = REMAT_COST_INFINITE;
911                                         continue;
912                                 }
913
914                                 remat_cost  = check_remat_conditions_costs(env, to_spill,
915                                                                            reloader, 0);
916                                 if (remat_cost >= REMAT_COST_INFINITE) {
917                                         DBG((dbg, LEVEL_2, "\tremat before %+F not possible\n",
918                                              reloader));
919                                         rld->remat_cost_delta = REMAT_COST_INFINITE;
920                                         all_remat_costs       = REMAT_COST_INFINITE;
921                                         continue;
922                                 }
923
924                                 remat_cost_delta      = remat_cost - env->reload_cost;
925                                 rld->remat_cost_delta = remat_cost_delta;
926                                 block                 = is_Block(reloader) ? reloader : get_nodes_block(reloader);
927                                 freq                  = get_block_execfreq(block);
928                                 all_remat_costs      += remat_cost_delta * freq;
929                                 DBG((dbg, LEVEL_2, "\tremat costs delta before %+F: "
930                                      "%d (rel %f)\n", reloader, remat_cost_delta,
931                                      remat_cost_delta * freq));
932                         }
933                         if (all_remat_costs < REMAT_COST_INFINITE) {
934                                 /* we don't need the costs for the spill if we can remat
935                                    all reloaders */
936                                 all_remat_costs -= si->spill_costs;
937
938                                 DBG((dbg, LEVEL_2, "\tspill costs %d (rel %f)\n",
939                                      env->spill_cost, si->spill_costs));
940                         }
941
942                         if (all_remat_costs < 0) {
943                                 DBG((dbg, LEVEL_1, "\nforcing remats of all reloaders (%f)\n",
944                                      all_remat_costs));
945                                 force_remat = true;
946                         }
947                 }
948
949                 /* go through all reloads for this spill */
950                 for (rld = si->reloaders; rld != NULL; rld = rld->next) {
951                         ir_node *copy; /* a reload is a "copy" of the original value */
952
953                         if (rld->rematted_node != NULL) {
954                                 copy = rld->rematted_node;
955                                 sched_add_before(rld->reloader, copy);
956                         } else if (be_do_remats &&
957                                         (force_remat || rld->remat_cost_delta < 0)) {
958                                 copy = do_remat(env, to_spill, rld->reloader);
959                         } else {
960                                 /* make sure we have a spill */
961                                 spill_node(env, si);
962
963                                 /* create a reload, use the first spill for now SSA
964                                  * reconstruction for memory comes below */
965                                 assert(si->spills != NULL);
966                                 copy = arch_env_new_reload(env->arch_env, si->to_spill,
967                                                            si->spills->spill, rld->reloader);
968                                 env->reload_count++;
969                         }
970
971                         DBG((dbg, LEVEL_1, " %+F of %+F before %+F\n",
972                              copy, to_spill, rld->reloader));
973                         ARR_APP1(ir_node*, copies, copy);
974                 }
975
976                 /* if we had any reloads or remats, then we need to reconstruct the
977                  * SSA form for the spilled value */
978                 if (ARR_LEN(copies) > 0) {
979                         be_ssa_construction_env_t senv;
980                         /* be_lv_t *lv = be_get_irg_liveness(env->irg); */
981
982                         be_ssa_construction_init(&senv, env->irg);
983                         be_ssa_construction_add_copy(&senv, to_spill);
984                         be_ssa_construction_add_copies(&senv, copies, ARR_LEN(copies));
985                         be_ssa_construction_fix_users(&senv, to_spill);
986
987 #if 0
988                         /* no need to enable this as long as we invalidate liveness
989                            after this function... */
990                         be_ssa_construction_update_liveness_phis(&senv);
991                         be_liveness_update(to_spill);
992                         len = ARR_LEN(copies);
993                         for (i = 0; i < len; ++i) {
994                                 be_liveness_update(lv, copies[i]);
995                         }
996 #endif
997                         be_ssa_construction_destroy(&senv);
998                 }
999                 /* need to reconstruct SSA form if we had multiple spills */
1000                 if (si->spills != NULL && si->spills->next != NULL) {
1001                         spill_t *spill;
1002                         int      spill_count = 0;
1003
1004                         be_ssa_construction_env_t senv;
1005
1006                         be_ssa_construction_init(&senv, env->irg);
1007                         spill = si->spills;
1008                         for ( ; spill != NULL; spill = spill->next) {
1009                                 /* maybe we rematerialized the value and need no spill */
1010                                 if (spill->spill == NULL)
1011                                         continue;
1012                                 be_ssa_construction_add_copy(&senv, spill->spill);
1013                                 spill_count++;
1014                         }
1015                         if (spill_count > 1) {
1016                                 /* all reloads are attached to the first spill, fix them now */
1017                                 be_ssa_construction_fix_users(&senv, si->spills->spill);
1018                         }
1019
1020                         be_ssa_construction_destroy(&senv);
1021                 }
1022
1023                 DEL_ARR_F(copies);
1024                 si->reloaders = NULL;
1025         }
1026
1027         stat_ev_dbl("spill_spills", env->spill_count);
1028         stat_ev_dbl("spill_reloads", env->reload_count);
1029         stat_ev_dbl("spill_remats", env->remat_count);
1030         stat_ev_dbl("spill_spilled_phis", env->spilled_phi_count);
1031
1032         /* Matze: In theory be_ssa_construction should take care of the liveness...
1033          * try to disable this again in the future */
1034         be_invalidate_live_sets(env->irg);
1035
1036         be_remove_dead_nodes_from_schedule(env->irg);
1037
1038         be_timer_pop(T_RA_SPILL_APPLY);
1039 }
1040
1041 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spill)
1042 void be_init_spill(void)
1043 {
1044         FIRM_DBG_REGISTER(dbg, "firm.be.spill");
1045 }