bespillutil.c 29.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
 *
 * This file is part of libFirm.
 *
 * This file may be distributed and/or modified under the terms of the
 * GNU General Public License version 2 as published by the Free Software
 * Foundation and appearing in the file LICENSE.GPL included in the
 * packaging of this file.
 *
 * Licensees holding valid libFirm Professional Edition licenses may use
 * this file in accordance with the libFirm Commercial License.
 * Agreement provided with the Software.
 *
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.
 */

/**
 * @file
 * @brief       implementation of the spill/reload placement abstraction layer
 * @author      Daniel Grund, Sebastian Hack, Matthias Braun
24
 * @date        29.09.2005
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 */
#include "config.h"

#include <stdlib.h>
#include <stdbool.h>

#include "pset.h"
#include "irnode_t.h"
#include "ircons_t.h"
#include "iredges_t.h"
#include "irbackedge_t.h"
#include "irprintf.h"
#include "ident_t.h"
#include "type_t.h"
#include "entity_t.h"
#include "debug.h"
#include "irgwalk.h"
#include "array.h"
#include "pdeq.h"
#include "execfreq.h"
#include "irnodeset.h"
#include "error.h"

#include "bearch.h"
#include "belive_t.h"
#include "besched.h"
#include "bespill.h"
#include "bespillutil.h"
#include "belive_t.h"
54
#include "benode.h"
55
#include "bechordal_t.h"
Matthias Braun's avatar
Matthias Braun committed
56
#include "statev_t.h"
57
58
#include "bessaconstr.h"
#include "beirg.h"
Matthias Braun's avatar
Matthias Braun committed
59
#include "beirgmod.h"
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include "beintlive_t.h"
#include "bemodule.h"
#include "be_t.h"

DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)

#define REMAT_COST_INFINITE  1000

typedef struct reloader_t reloader_t;
struct reloader_t {
	reloader_t *next;
	ir_node    *reloader;
	ir_node    *rematted_node;
	int         remat_cost_delta; /** costs needed for rematerialization,
	                                   compared to placing a reload */
};

typedef struct spill_t spill_t;
struct spill_t {
	spill_t *next;
	ir_node *after;  /**< spill has to be placed after this node (or earlier) */
	ir_node *spill;
};

typedef struct spill_info_t spill_info_t;
struct spill_info_t {
	ir_node    *to_spill;  /**< the value that should get spilled */
	reloader_t *reloaders; /**< list of places where the value should get
	                            reloaded */
	spill_t    *spills;    /**< list of latest places where spill must be
	                            placed */
	double      spill_costs; /**< costs needed for spilling the value */
	const arch_register_class_t *reload_cls; /** the register class in which the
	                                             reload should be placed */
94
95
96
	bool        spilled_phi; /* true when the whole Phi has been spilled and
	                            will be replaced with a PhiM. false if only the
	                            value of the Phi gets spilled */
97
98
99
100
101
102
103
104
105
106
};

struct spill_env_t {
	const arch_env_t *arch_env;
	ir_graph         *irg;
	struct obstack    obst;
	int               spill_cost;     /**< the cost of a single spill node */
	int               reload_cost;    /**< the cost of a reload node */
	set              *spills;         /**< all spill_info_t's, which must be
	                                       placed */
107
	spill_info_t    **mem_phis;       /**< set of all spilled phis. */
108
109
110
111
112
113
114
115
116
117
118
119

	unsigned          spill_count;
	unsigned          reload_count;
	unsigned          remat_count;
	unsigned          spilled_phi_count;
};

/**
 * Compare two spill infos.
 */
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;
	const spill_info_t *yy = (const spill_info_t*)y;
122
123
124
125
126
127
128
129
130
131
132
133
134
135
	(void) size;

	return xx->to_spill != yy->to_spill;
}

/**
 * Returns spill info for a specific value (the value that is to be spilled)
 */
static spill_info_t *get_spillinfo(const spill_env_t *env, ir_node *value)
{
	spill_info_t info, *res;
	int hash = hash_irn(value);

	info.to_spill = value;
136
	res = set_find(spill_info_t, env->spills, &info, sizeof(info), hash);
137
138
139
140
141
142

	if (res == NULL) {
		info.reloaders   = NULL;
		info.spills      = NULL;
		info.spill_costs = -1;
		info.reload_cls  = NULL;
143
		info.spilled_phi = false;
144
		res = set_insert(spill_info_t, env->spills, &info, sizeof(info), hash);
145
146
147
148
149
	}

	return res;
}

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
	env->mem_phis       = NEW_ARR_F(spill_info_t*, 0);
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
	env->spill_cost     = arch_env->spill_cost;
	env->reload_cost    = arch_env->reload_cost;
	obstack_init(&env->obst);

	env->spill_count       = 0;
	env->reload_count      = 0;
	env->remat_count       = 0;
	env->spilled_phi_count = 0;

	return env;
}

void be_delete_spill_env(spill_env_t *env)
{
	del_set(env->spills);
174
	DEL_ARR_F(env->mem_phis);
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
	obstack_free(&env->obst, NULL);
	free(env);
}

/*
 *  ____  _                  ____      _                 _
 * |  _ \| | __ _  ___ ___  |  _ \ ___| | ___   __ _  __| |___
 * | |_) | |/ _` |/ __/ _ \ | |_) / _ \ |/ _ \ / _` |/ _` / __|
 * |  __/| | (_| | (_|  __/ |  _ <  __/ | (_) | (_| | (_| \__ \
 * |_|   |_|\__,_|\___\___| |_| \_\___|_|\___/ \__,_|\__,_|___/
 *
 */

void be_add_spill(spill_env_t *env, ir_node *to_spill, ir_node *after)
{
190
191
192
193
	spill_info_t  *spill_info = get_spillinfo(env, to_spill);
	spill_t       *spill;
	spill_t       *s;
	spill_t       *last;
194

195
	assert(!arch_irn_is(skip_Proj_const(to_spill), dont_spill));
196
197
198
199
200
201
202
203
	DB((dbg, LEVEL_1, "Add spill of %+F after %+F\n", to_spill, after));

	/* Just for safety make sure that we do not insert the spill in front of a phi */
	assert(!is_Phi(sched_next(after)));

	/* spills that are dominated by others are not needed */
	last = NULL;
	s    = spill_info->spills;
204
	for ( ; s != NULL; s = s->next) {
205
		/* no need to add this spill if it is dominated by another */
206
		if (value_dominates(s->after, after)) {
207
208
209
210
			DB((dbg, LEVEL_1, "...dominated by %+F, not added\n", s->after));
			return;
		}
		/* remove spills that we dominate */
211
		if (value_dominates(after, s->after)) {
212
			DB((dbg, LEVEL_1, "...remove old spill at %+F\n", s->after));
213
			if (last != NULL) {
214
215
216
217
218
219
220
221
222
				last->next         = s->next;
			} else {
				spill_info->spills = s->next;
			}
		} else {
			last = s;
		}
	}

223
	spill         = OALLOC(&env->obst, spill_t);
224
225
226
227
228
229
230
	spill->after  = after;
	spill->next   = spill_info->spills;
	spill->spill  = NULL;

	spill_info->spills = spill;
}

231
void be_add_reload(spill_env_t *env, ir_node *to_spill, ir_node *before, const arch_register_class_t *reload_cls, int allow_remat)
232
{
233
234
	spill_info_t  *info;
	reloader_t    *rel;
235

236
	assert(!arch_irn_is(skip_Proj_const(to_spill), dont_spill));
237
238
239
240
241
242
243
244
245
246
247
248
249

	info = get_spillinfo(env, to_spill);

	if (is_Phi(to_spill)) {
		int i, arity;

		/* create spillinfos for the phi arguments */
		for (i = 0, arity = get_irn_arity(to_spill); i < arity; ++i) {
			ir_node *arg = get_irn_n(to_spill, i);
			get_spillinfo(env, arg);
		}
	}

250
	assert(!be_is_Keep(before));
251
252

	/* put reload into list */
253
	rel                   = OALLOC(&env->obst, reloader_t);
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
	rel->next             = info->reloaders;
	rel->reloader         = before;
	rel->rematted_node    = NULL;
	rel->remat_cost_delta = allow_remat ? 0 : REMAT_COST_INFINITE;

	info->reloaders  = rel;
	assert(info->reload_cls == NULL || info->reload_cls == reload_cls);
	info->reload_cls = reload_cls;

	DBG((dbg, LEVEL_1, "creating spillinfo for %+F, will be reloaded before %+F, may%s be rematerialized\n",
		to_spill, before, allow_remat ? "" : " not"));
}

ir_node *be_get_end_of_block_insertion_point(const ir_node *block)
{
	ir_node *last = sched_last(block);

	/* we might have keeps behind the jump... */
	while (be_is_Keep(last)) {
		last = sched_prev(last);
		assert(!sched_is_end(last));
	}

	assert(is_cfop(last));

	/* add the reload before the (cond-)jump */
	return last;
}

283
284
285
286
287
/**
 * determine final spill position: it should be after all phis, keep nodes
 * and behind nodes marked as prolog
 */
static ir_node *determine_spill_point(ir_node *node)
288
{
289
	node = skip_Proj(node);
290
	while (true) {
291
		ir_node *next = sched_next(node);
292
		if (!is_Phi(next) && !be_is_Keep(next) && !be_is_CopyKeep(next))
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
			break;
		node = next;
	}
	return node;
}

/**
 * Returns the point at which you can insert a node that should be executed
 * before block @p block when coming from pred @p pos.
 */
static ir_node *get_block_insertion_point(ir_node *block, int pos)
{
	ir_node *predblock;

	/* simply add the reload to the beginning of the block if we only have 1
	 * predecessor. We don't need to check for phis as there can't be any in a
	 * block with only 1 pred. */
310
	if (get_Block_n_cfgpreds(block) == 1) {
311
312
313
314
315
316
317
318
319
320
		assert(!is_Phi(sched_first(block)));
		return sched_first(block);
	}

	/* We have to reload the value in pred-block */
	predblock = get_Block_cfgpred_block(block, pos);
	return be_get_end_of_block_insertion_point(predblock);
}

void be_add_reload_on_edge(spill_env_t *env, ir_node *to_spill, ir_node *block,
321
                           int pos, const arch_register_class_t *reload_cls,
322
323
324
325
326
327
328
329
330
331
                           int allow_remat)
{
	ir_node *before = get_block_insertion_point(block, pos);
	be_add_reload(env, to_spill, before, reload_cls, allow_remat);
}

void be_spill_phi(spill_env_t *env, ir_node *node)
{
	ir_node *block;
	int i, arity;
332
	spill_info_t *info;
333
334
335

	assert(is_Phi(node));

336
337
338
	info              = get_spillinfo(env, node);
	info->spilled_phi = true;
	ARR_APP1(spill_info_t*, env->mem_phis, info);
339
340
341

	/* create spills for the phi arguments */
	block = get_nodes_block(node);
342
	for (i = 0, arity = get_irn_arity(node); i < arity; ++i) {
343
344
345
346
347
		ir_node *arg = get_irn_n(node, i);
		ir_node *insert;

		/* some backends have virtual noreg/unknown nodes that are not scheduled
		 * and simply always available. */
348
		if (!sched_is_scheduled(arg)) {
349
350
351
352
			ir_node *pred_block = get_Block_cfgpred_block(block, i);
			insert = be_get_end_of_block_insertion_point(pred_block);
			insert = sched_prev(insert);
		} else {
353
			insert = determine_spill_point(arg);
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
		}

		be_add_spill(env, arg, insert);
	}
}

/*
 *   ____                _         ____        _ _ _
 *  / ___|_ __ ___  __ _| |_ ___  / ___| _ __ (_) | |___
 * | |   | '__/ _ \/ _` | __/ _ \ \___ \| '_ \| | | / __|
 * | |___| | |  __/ (_| | ||  __/  ___) | |_) | | | \__ \
 *  \____|_|  \___|\__,_|\__\___| |____/| .__/|_|_|_|___/
 *                                      |_|
 */

static void determine_spill_costs(spill_env_t *env, spill_info_t *spillinfo);

/**
 * Creates a spill.
 *
 * @param senv      the spill environment
 * @param irn       the node that should be spilled
 * @param ctx_irn   an user of the spilled node
 *
 * @return a be_Spill node
 */
static void spill_irn(spill_env_t *env, spill_info_t *spillinfo)
{
382
383
	ir_node       *to_spill = spillinfo->to_spill;
	const ir_node *insn     = skip_Proj_const(to_spill);
384
385
386
387
388
389
390
	spill_t *spill;

	/* determine_spill_costs must have been run before */
	assert(spillinfo->spill_costs >= 0);

	/* some backends have virtual noreg/unknown nodes that are not scheduled
	 * and simply always available. */
391
	if (!sched_is_scheduled(insn)) {
392
		/* override spillinfos or create a new one */
393
		ir_graph *irg = get_irn_irg(to_spill);
394
		spillinfo->spills->spill = get_irg_no_mem(irg);
395
396
397
398
399
400
		DB((dbg, LEVEL_1, "don't spill %+F use NoMem\n", to_spill));
		return;
	}

	DBG((dbg, LEVEL_1, "spilling %+F ... \n", to_spill));
	spill = spillinfo->spills;
401
	for ( ; spill != NULL; spill = spill->next) {
402
		ir_node *after = spill->after;
403
		after = determine_spill_point(after);
404

405
		spill->spill = arch_env_new_spill(env->arch_env, to_spill, after);
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
		DB((dbg, LEVEL_1, "\t%+F after %+F\n", spill->spill, after));
		env->spill_count++;
	}
	DBG((dbg, LEVEL_1, "\n"));
}

static void spill_node(spill_env_t *env, spill_info_t *spillinfo);

/**
 * If the first usage of a Phi result would be out of memory
 * there is no sense in allocating a register for it.
 * Thus we spill it and all its operands to the same spill slot.
 * Therefore the phi/dataB becomes a phi/Memory
 *
 * @param senv      the spill environment
 * @param phi       the Phi node that should be spilled
 * @param ctx_irn   an user of the spilled node
 */
static void spill_phi(spill_env_t *env, spill_info_t *spillinfo)
{
	ir_graph *irg   = env->irg;
	ir_node  *phi   = spillinfo->to_spill;
	ir_node  *block = get_nodes_block(phi);
	ir_node  *unknown;
	ir_node **ins;
	spill_t  *spill;
	int       i;
	int       arity;

	assert(is_Phi(phi));
	assert(!get_opt_cse());
	DBG((dbg, LEVEL_1, "spilling Phi %+F:\n", phi));

	/* build a new PhiM */
	arity   = get_irn_arity(phi);
	ins     = ALLOCAN(ir_node*, arity);
	unknown = new_r_Unknown(irg, mode_M);
443
	for (i = 0; i < arity; ++i) {
444
445
446
447
		ins[i] = unknown;
	}

	/* override or replace spills list... */
448
	spill         = OALLOC(&env->obst, spill_t);
449
	spill->after  = determine_spill_point(phi);
450
	spill->spill  = be_new_Phi(block, arity, ins, mode_M, arch_no_register_req);
451
	spill->next   = NULL;
Matthias Braun's avatar
Matthias Braun committed
452
	sched_add_after(block, spill->spill);
453
454
455
456

	spillinfo->spills = spill;
	env->spilled_phi_count++;

457
	for (i = 0; i < arity; ++i) {
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
		ir_node      *arg      = get_irn_n(phi, i);
		spill_info_t *arg_info = get_spillinfo(env, arg);

		determine_spill_costs(env, arg_info);
		spill_node(env, arg_info);

		set_irn_n(spill->spill, i, arg_info->spills->spill);
	}
	DBG((dbg, LEVEL_1, "... done spilling Phi %+F, created PhiM %+F\n", phi,
	     spill->spill));
}

/**
 * Spill a node.
 *
 * @param senv      the spill environment
 * @param to_spill  the node that should be spilled
 */
static void spill_node(spill_env_t *env, spill_info_t *spillinfo)
{
	/* node is already spilled */
479
	if (spillinfo->spills != NULL && spillinfo->spills->spill != NULL)
480
481
		return;

482
	if (spillinfo->spilled_phi) {
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
		spill_phi(env, spillinfo);
	} else {
		spill_irn(env, spillinfo);
	}
}

/*
 *
 *  ____                      _            _       _ _
 * |  _ \ ___ _ __ ___   __ _| |_ ___ _ __(_) __ _| (_)_______
 * | |_) / _ \ '_ ` _ \ / _` | __/ _ \ '__| |/ _` | | |_  / _ \
 * |  _ <  __/ | | | | | (_| | ||  __/ |  | | (_| | | |/ /  __/
 * |_| \_\___|_| |_| |_|\__,_|\__\___|_|  |_|\__,_|_|_/___\___|
 *
 */

/**
 * Tests whether value @p arg is available before node @p reloader
 * @returns 1 if value is available, 0 otherwise
 */
static int is_value_available(spill_env_t *env, const ir_node *arg,
                              const ir_node *reloader)
{
506
	if (is_Unknown(arg) || is_NoMem(arg))
507
508
		return 1;

509
	if (be_is_Spill(skip_Proj_const(arg)))
510
511
		return 1;

512
	if (arg == get_irg_frame(env->irg))
513
514
515
516
		return 1;

	(void)reloader;

517
518
519
	if (get_irn_mode(arg) == mode_T)
		return 0;

520
521
522
523
524
525
	/*
	 * Ignore registers are always available
	 */
	if (arch_irn_is_ignore(arg))
		return 1;

526
	return 0;
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
}

/**
 * Check if a node is rematerializable. This tests for the following conditions:
 *
 * - The node itself is rematerializable
 * - All arguments of the node are available or also rematerialisable
 * - The costs for the rematerialisation operation is less or equal a limit
 *
 * Returns the costs needed for rematerialisation or something
 * >= REMAT_COST_INFINITE if remat is not possible.
 */
static int check_remat_conditions_costs(spill_env_t *env,
		const ir_node *spilled, const ir_node *reloader, int parentcosts)
{
	int i, arity;
	int argremats;
	int costs = 0;
545
	const ir_node *insn = skip_Proj_const(spilled);
546

547
548
	assert(!be_is_Spill(insn));
	if (!arch_irn_is(insn, rematerializable))
549
550
		return REMAT_COST_INFINITE;

551
	if (be_is_Reload(insn)) {
552
553
		costs += 2;
	} else {
554
		costs += arch_get_op_estimated_cost(insn);
555
	}
556
	if (parentcosts + costs >= env->reload_cost + env->spill_cost) {
557
558
559
		return REMAT_COST_INFINITE;
	}
	/* never rematerialize a node which modifies the flags.
560
	 * (would be better to test whether the flags are actually live at point
561
562
	 * reloader...)
	 */
563
	if (arch_irn_is(insn, modify_flags)) {
564
565
566
567
		return REMAT_COST_INFINITE;
	}

	argremats = 0;
568
	for (i = 0, arity = get_irn_arity(insn); i < arity; ++i) {
569
		ir_node *arg = get_irn_n(insn, i);
570

571
		if (is_value_available(env, arg, reloader))
572
573
574
			continue;

		/* we have to rematerialize the argument as well */
575
		++argremats;
576
		if (argremats > 1) {
577
			/* we only support rematerializing 1 argument at the moment,
578
			 * as multiple arguments could increase register pressure */
579
580
581
582
583
			return REMAT_COST_INFINITE;
		}

		costs += check_remat_conditions_costs(env, arg, reloader,
		                                      parentcosts + costs);
584
		if (parentcosts + costs >= env->reload_cost + env->spill_cost)
585
586
587
588
589
590
591
592
593
			return REMAT_COST_INFINITE;
	}

	return costs;
}

/**
 * Re-materialize a node.
 *
Michael Beck's avatar
Michael Beck committed
594
 * @param env       the spill environment
595
596
597
598
599
600
601
602
603
604
 * @param spilled   the node that was spilled
 * @param reloader  a irn that requires a reload
 */
static ir_node *do_remat(spill_env_t *env, ir_node *spilled, ir_node *reloader)
{
	int i, arity;
	ir_node *res;
	ir_node *bl;
	ir_node **ins;

605
	if (is_Block(reloader)) {
606
607
608
609
610
611
		bl = reloader;
	} else {
		bl = get_nodes_block(reloader);
	}

	ins = ALLOCAN(ir_node*, get_irn_arity(spilled));
612
	for (i = 0, arity = get_irn_arity(spilled); i < arity; ++i) {
613
614
		ir_node *arg = get_irn_n(spilled, i);

615
		if (is_value_available(env, arg, reloader)) {
616
617
618
			ins[i] = arg;
		} else {
			ins[i] = do_remat(env, arg, reloader);
619
620
			/* don't count the argument rematerialization as an extra remat */
			--env->remat_count;
621
622
623
624
625
626
627
		}
	}

	/* create a copy of the node */
	res = new_ir_node(get_irn_dbg_info(spilled), env->irg, bl,
	                  get_irn_op(spilled), get_irn_mode(spilled),
	                  get_irn_arity(spilled), ins);
628
	copy_node_attr(env->irg, spilled, res);
629
630
631
632
633
634
635
636
	arch_env_mark_remat(env->arch_env, res);

	DBG((dbg, LEVEL_1, "Insert remat %+F of %+F before reloader %+F\n", res, spilled, reloader));

	if (! is_Proj(res)) {
		/* insert in schedule */
		sched_reset(res);
		sched_add_before(reloader, res);
637
		++env->remat_count;
638
639
640
641
642
643
644
645
	}

	return res;
}

double be_get_spill_costs(spill_env_t *env, ir_node *to_spill, ir_node *before)
{
	ir_node *block = get_nodes_block(before);
646
	double   freq  = get_block_execfreq(block);
647
648
649
650
651
652
653
654
	(void) to_spill;

	return env->spill_cost * freq;
}

unsigned be_get_reload_costs_no_weight(spill_env_t *env, const ir_node *to_spill,
                                       const ir_node *before)
{
655
	if (be_do_remats) {
656
657
		/* is the node rematerializable? */
		unsigned costs = check_remat_conditions_costs(env, to_spill, before, 0);
658
		if (costs < (unsigned) env->reload_cost)
659
660
661
662
663
664
665
666
			return costs;
	}

	return env->reload_cost;
}

double be_get_reload_costs(spill_env_t *env, ir_node *to_spill, ir_node *before)
{
667
668
	ir_node *block = get_nodes_block(before);
	double   freq  = get_block_execfreq(block);
669

670
	if (be_do_remats) {
671
672
		/* is the node rematerializable? */
		int costs = check_remat_conditions_costs(env, to_spill, before, 0);
673
		if (costs < env->reload_cost)
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
			return costs * freq;
	}

	return env->reload_cost * freq;
}

int be_is_rematerializable(spill_env_t *env, const ir_node *to_remat,
                           const ir_node *before)
{
	return check_remat_conditions_costs(env, to_remat, before, 0) < REMAT_COST_INFINITE;
}

double be_get_reload_costs_on_edge(spill_env_t *env, ir_node *to_spill,
                                   ir_node *block, int pos)
{
	ir_node *before = get_block_insertion_point(block, pos);
	return be_get_reload_costs(env, to_spill, before);
}

693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
ir_node *be_new_spill(ir_node *value, ir_node *after)
{
	ir_graph                    *irg       = get_irn_irg(value);
	ir_node                     *frame     = get_irg_frame(irg);
	const arch_register_class_t *cls       = arch_get_irn_reg_class(value);
	const arch_register_class_t *cls_frame = arch_get_irn_reg_class(frame);
	ir_node                     *block     = get_block(after);
	ir_node                     *spill
		= be_new_Spill(cls, cls_frame, block, frame, value);

	sched_add_after(after, spill);
	return spill;
}

ir_node *be_new_reload(ir_node *value, ir_node *spill, ir_node *before)
{
	ir_graph *irg   = get_irn_irg(value);
	ir_node  *frame = get_irg_frame(irg);
	ir_node  *block = get_block(before);
	const arch_register_class_t *cls       = arch_get_irn_reg_class(value);
	const arch_register_class_t *cls_frame = arch_get_irn_reg_class(frame);
	ir_mode                     *mode      = get_irn_mode(value);
	ir_node  *reload;

	assert(be_is_Spill(spill) || is_Phi(spill));
	assert(get_irn_mode(spill) == mode_M);

	reload = be_new_Reload(cls, cls_frame, block, frame, spill, mode);
	sched_add_before(before, reload);

	return reload;
}

726
727
728
729
730
731
732
733
734
735
736
737
738
739
/*
 *  ___                     _     ____      _                 _
 * |_ _|_ __  ___  ___ _ __| |_  |  _ \ ___| | ___   __ _  __| |___
 *  | || '_ \/ __|/ _ \ '__| __| | |_) / _ \ |/ _ \ / _` |/ _` / __|
 *  | || | | \__ \  __/ |  | |_  |  _ <  __/ | (_) | (_| | (_| \__ \
 * |___|_| |_|___/\___|_|   \__| |_| \_\___|_|\___/ \__,_|\__,_|___/
 *
 */

/**
 * analyzes how to best spill a node and determine costs for that
 */
static void determine_spill_costs(spill_env_t *env, spill_info_t *spillinfo)
{
740
741
742
743
744
	ir_node       *to_spill = spillinfo->to_spill;
	const ir_node *insn     = skip_Proj_const(to_spill);
	ir_node       *spill_block;
	spill_t       *spill;
	double         spill_execfreq;
745
746

	/* already calculated? */
747
	if (spillinfo->spill_costs >= 0)
748
749
		return;

750
751
	assert(!arch_irn_is(insn, dont_spill));
	assert(!be_is_Reload(insn));
752
753
754
755
756
757

	/* some backends have virtual noreg/unknown nodes that are not scheduled
	 * and simply always available.
	 * TODO: this is kinda hairy, the NoMem is correct for an Unknown as Phi
	 * predecessor (of a PhiM) but this test might match other things too...
	 */
758
	if (!sched_is_scheduled(insn)) {
759
		ir_graph *irg = get_irn_irg(to_spill);
760
		/* override spillinfos or create a new one */
761
		spill_t *spill = OALLOC(&env->obst, spill_t);
762
763
		spill->after = NULL;
		spill->next  = NULL;
764
		spill->spill = get_irg_no_mem(irg);
765
766
767
768
769
770
771
772

		spillinfo->spills      = spill;
		spillinfo->spill_costs = 0;

		DB((dbg, LEVEL_1, "don't spill %+F use NoMem\n", to_spill));
		return;
	}

773
	spill_block    = get_nodes_block(insn);
774
	spill_execfreq = get_block_execfreq(spill_block);
775

776
	if (spillinfo->spilled_phi) {
777
778
779
780
781
782
		/* TODO calculate correct costs...
		 * (though we can't remat this node anyway so no big problem) */
		spillinfo->spill_costs = env->spill_cost * spill_execfreq;
		return;
	}

783
	if (spillinfo->spills != NULL) {
784
785
786
787
788
789
		spill_t *s;
		double   spills_execfreq;

		/* calculate sum of execution frequencies of individual spills */
		spills_execfreq = 0;
		s               = spillinfo->spills;
790
		for ( ; s != NULL; s = s->next) {
791
			ir_node *spill_block = get_block(s->after);
792
			double   freq = get_block_execfreq(spill_block);
793
794
795
796
797
798
799
800
801

			spills_execfreq += freq;
		}

		DB((dbg, LEVEL_1, "%+F: latespillcosts %f after def: %f\n", to_spill,
		    spills_execfreq * env->spill_cost,
		    spill_execfreq * env->spill_cost));

		/* multi-/latespill is advantageous -> return*/
802
		if (spills_execfreq < spill_execfreq) {
803
804
805
806
807
808
809
			DB((dbg, LEVEL_1, "use latespills for %+F\n", to_spill));
			spillinfo->spill_costs = spills_execfreq * env->spill_cost;
			return;
		}
	}

	/* override spillinfos or create a new one */
810
	spill        = OALLOC(&env->obst, spill_t);
811
	spill->after = determine_spill_point(to_spill);
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
	spill->next  = NULL;
	spill->spill = NULL;

	spillinfo->spills      = spill;
	spillinfo->spill_costs = spill_execfreq * env->spill_cost;
	DB((dbg, LEVEL_1, "spill %+F after definition\n", to_spill));
}

void make_spill_locations_dominate_irn(spill_env_t *env, ir_node *irn)
{
	const spill_info_t *si = get_spillinfo(env, irn);
	ir_node *start_block   = get_irg_start_block(get_irn_irg(irn));
	int n_blocks           = get_Block_dom_max_subtree_pre_num(start_block);
	bitset_t *reloads      = bitset_alloca(n_blocks);
	reloader_t *r;
	spill_t *s;

	if (si == NULL)
		return;

	/* Fill the bitset with the dominance pre-order numbers
	 * of the blocks the reloads are located in. */
	for (r = si->reloaders; r != NULL; r = r->next) {
		ir_node *bl = get_nodes_block(r->reloader);
		bitset_set(reloads, get_Block_dom_tree_pre_num(bl));
	}

	/* Now, cancel out all the blocks that are dominated by each spill.
	 * If the bitset is not empty after that, we have reloads that are
	 * not dominated by any spill. */
	for (s = si->spills; s != NULL; s = s->next) {
		ir_node *bl = get_nodes_block(s->after);
		int start   = get_Block_dom_tree_pre_num(bl);
		int end     = get_Block_dom_max_subtree_pre_num(bl);

		bitset_clear_range(reloads, start, end);
	}

	if (!bitset_is_empty(reloads))
		be_add_spill(env, si->to_spill, si->to_spill);
}

void be_insert_spills_reloads(spill_env_t *env)
{
856
857
	size_t n_mem_phis = ARR_LEN(env->mem_phis);
	size_t i;
858

859
	be_timer_push(T_RA_SPILL_APPLY);
860
861
862

	/* create all phi-ms first, this is needed so, that phis, hanging on
	   spilled phis work correctly */
863
864
	for (i = 0; i < n_mem_phis; ++i) {
		spill_info_t *info = env->mem_phis[i];
865
866
867
868
		spill_node(env, info);
	}

	/* process each spilled node */
869
	foreach_set(env->spills, spill_info_t, si) {
870
871
872
		ir_node  *to_spill        = si->to_spill;
		ir_node **copies          = NEW_ARR_F(ir_node*, 0);
		double    all_remat_costs = 0; /** costs when we would remat all nodes */
873
874
		bool      force_remat     = false;
		reloader_t *rld;
875
876
877
878
879
880

		DBG((dbg, LEVEL_1, "\nhandling all reloaders of %+F:\n", to_spill));

		determine_spill_costs(env, si);

		/* determine possibility of rematerialisations */
881
		if (be_do_remats) {
882
883
884
885
886
887
888
889
890
			/* calculate cost savings for each indivial value when it would
			   be rematted instead of reloaded */
			for (rld = si->reloaders; rld != NULL; rld = rld->next) {
				double   freq;
				int      remat_cost;
				int      remat_cost_delta;
				ir_node *block;
				ir_node *reloader = rld->reloader;

891
				if (rld->rematted_node != NULL) {
892
893
894
895
					DBG((dbg, LEVEL_2, "\tforced remat %+F before %+F\n",
					     rld->rematted_node, reloader));
					continue;
				}
896
				if (rld->remat_cost_delta >= REMAT_COST_INFINITE) {
897
898
899
900
901
902
903
904
					DBG((dbg, LEVEL_2, "\treload before %+F is forbidden\n",
					     reloader));
					all_remat_costs = REMAT_COST_INFINITE;
					continue;
				}

				remat_cost  = check_remat_conditions_costs(env, to_spill,
				                                           reloader, 0);
905
				if (remat_cost >= REMAT_COST_INFINITE) {
906
907
908
909
910
911
912
913
914
915
					DBG((dbg, LEVEL_2, "\tremat before %+F not possible\n",
					     reloader));
					rld->remat_cost_delta = REMAT_COST_INFINITE;
					all_remat_costs       = REMAT_COST_INFINITE;
					continue;
				}

				remat_cost_delta      = remat_cost - env->reload_cost;
				rld->remat_cost_delta = remat_cost_delta;
				block                 = is_Block(reloader) ? reloader : get_nodes_block(reloader);
916
				freq                  = get_block_execfreq(block);
917
918
919
920
921
				all_remat_costs      += remat_cost_delta * freq;
				DBG((dbg, LEVEL_2, "\tremat costs delta before %+F: "
				     "%d (rel %f)\n", reloader, remat_cost_delta,
				     remat_cost_delta * freq));
			}
922
			if (all_remat_costs < REMAT_COST_INFINITE) {
923
924
925
926
927
928
929
930
				/* we don't need the costs for the spill if we can remat
				   all reloaders */
				all_remat_costs -= si->spill_costs;

				DBG((dbg, LEVEL_2, "\tspill costs %d (rel %f)\n",
				     env->spill_cost, si->spill_costs));
			}

931
			if (all_remat_costs < 0) {
932
933
				DBG((dbg, LEVEL_1, "\nforcing remats of all reloaders (%f)\n",
				     all_remat_costs));
934
				force_remat = true;
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
			}
		}

		/* go through all reloads for this spill */
		for (rld = si->reloaders; rld != NULL; rld = rld->next) {
			ir_node *copy; /* a reload is a "copy" of the original value */

			if (rld->rematted_node != NULL) {
				copy = rld->rematted_node;
				sched_add_before(rld->reloader, copy);
			} else if (be_do_remats &&
					(force_remat || rld->remat_cost_delta < 0)) {
				copy = do_remat(env, to_spill, rld->reloader);
			} else {
				/* make sure we have a spill */
				spill_node(env, si);

				/* create a reload, use the first spill for now SSA
				 * reconstruction for memory comes below */
				assert(si->spills != NULL);
955
956
				copy = arch_env_new_reload(env->arch_env, si->to_spill,
				                           si->spills->spill, rld->reloader);
957
958
959
960
961
962
963
964
965
966
967
968
				env->reload_count++;
			}

			DBG((dbg, LEVEL_1, " %+F of %+F before %+F\n",
			     copy, to_spill, rld->reloader));
			ARR_APP1(ir_node*, copies, copy);
		}

		/* if we had any reloads or remats, then we need to reconstruct the
		 * SSA form for the spilled value */
		if (ARR_LEN(copies) > 0) {
			be_ssa_construction_env_t senv;
969
			/* be_lv_t *lv = be_get_irg_liveness(env->irg); */
970

971
			be_ssa_construction_init(&senv, env->irg);
972
973
974
975
976
977
978
979
980
981
			be_ssa_construction_add_copy(&senv, to_spill);
			be_ssa_construction_add_copies(&senv, copies, ARR_LEN(copies));
			be_ssa_construction_fix_users(&senv, to_spill);

#if 0
			/* no need to enable this as long as we invalidate liveness
			   after this function... */
			be_ssa_construction_update_liveness_phis(&senv);
			be_liveness_update(to_spill);
			len = ARR_LEN(copies);
982
			for (i = 0; i < len; ++i) {
983
984
985
986
987
988
989
990
991
992
993
994
				be_liveness_update(lv, copies[i]);
			}
#endif
			be_ssa_construction_destroy(&senv);
		}
		/* need to reconstruct SSA form if we had multiple spills */
		if (si->spills != NULL && si->spills->next != NULL) {
			spill_t *spill;
			int      spill_count = 0;

			be_ssa_construction_env_t senv;

995
			be_ssa_construction_init(&senv, env->irg);
996
			spill = si->spills;
997
			for ( ; spill != NULL; spill = spill->next) {
998
				/* maybe we rematerialized the value and need no spill */
999
				if (spill->spill == NULL)
1000
					continue;