opt_ldst.c 43.9 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
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
 * 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   Dataflow driven Load/Store optimizations, uses some ideas from
 *          VanDrunen's LEPRE
 * @author  Michael Beck
 * @version $Id$
 */
#include "config.h"

#include "irnode_t.h"
#include "irflag_t.h"
#include "array_t.h"
#include "ircons.h"
#include "irdom.h"
#include "irgmod.h"
#include "irgwalk.h"
#include "irouts.h"
#include "irgraph.h"
#include "irgopt.h"
#include "irnodemap.h"
#include "raw_bitset.h"
#include "debug.h"
#include "error.h"

/**
45
 * Mapping an address to an dense ID.
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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
94
95
96
97
98
99
100
101
 */
typedef struct address_entry_t {
	unsigned id;          /**< The ID */
} address_entry;

/**
 * Memop-flags.
 */
enum memop_flags {
	FLAG_KILL_LOADS  =  1, /**< KILL all Loads */
	FLAG_KILL_STORES =  2, /**< KILL all Stores */
	FLAG_KILLED_NODE =  4, /**< this node was killed */
	FLAG_EXCEPTION   =  8, /**< this node has exception flow */
	FLAG_IGNORE      = 16, /**< ignore this node (volatile or other) */
	/** this memop KILLS all addresses */
	FLAG_KILL_ALL    = FLAG_KILL_LOADS|FLAG_KILL_STORES
};

/**
 * A value: This represents a value stored at a given address in
 * memory. Do not confuse with values from value numbering.
 */
typedef struct value_t value_t;
struct value_t {
	ir_node  *address;    /**< the address of this value */
	ir_node  *value;      /**< the value itself */
	ir_mode  *mode;       /**< the mode of the value */
	unsigned id;          /**< address id */
};

/**
 * A memop describes an memory-related operation.
 * These are Loads/Store and all other ops that might modify
 * memory (Calls, CopyB) or causing exceptions.
 */
typedef struct memop_t memop_t;
struct memop_t {
	value_t  value;      /**< the value of this memop: only defined for Load/Store */
	ir_node  *node;      /**< the memory op itself */
	ir_node  *mem;       /**< the memory FROM this node */
	ir_node  *replace;   /**< the replacement node if this memop is replaced */
	memop_t  *next;      /**< links to the next memory op in the block in forward order. */
	memop_t  *prev;      /**< links to the previous memory op in the block in forward order. */
	unsigned flags;      /**< memop flags */
};

/**
 * Additional data for every basic block.
 */
typedef struct block_t block_t;
struct block_t {
	memop_t  *memop_forward;     /**< topologically sorted list of memory ops in this block */
	memop_t  *memop_backward;    /**< last memop in the list */
	unsigned *avail_out;         /**< out-set of available addresses */
	memop_t  **id_2_memop_avail; /**< maps avail address ids to memops */
	unsigned *anticL_in;         /**< in-set of anticipated Load addresses */
Michael Beck's avatar
Michael Beck committed
102
	memop_t  **id_2_memop_antic; /**< maps anticipated address ids to memops */
103
104
105
106
107
108
109
110
111
112
	ir_node  *block;             /**< the associated block */
	block_t  *forward_next;      /**< next block entry for forward iteration */
	block_t  *backward_next;     /**< next block entry for backward iteration */
	memop_t  *avail;             /**< used locally for the avail map */
};

/**
 * Metadata for this pass.
 */
typedef struct ldst_env_t {
Michael Beck's avatar
Michael Beck committed
113
114
115
116
117
118
119
120
121
122
123
124
	struct obstack  obst;              /**< obstack for temporary data */
	ir_nodemap_t    adr_map;           /**< Map addresses to */
	block_t         *forward;          /**< Inverse post-order list of all blocks Start->End */
	block_t         *backward;         /**< Inverse post-order list of all blocks End->Start */
	ir_node         *start_bl;         /**< start block of the current graph */
	ir_node         *end_bl;           /**< end block of the current graph */
	unsigned        *curr_set;         /**< current set of addresses */
	memop_t         **curr_id_2_memop; /**< current map of address ids to memops */
	unsigned        curr_adr_id;       /**< number for address mapping */
	unsigned        n_mem_ops;         /**< number of memory operations (Loads/Stores) */
	unsigned        rbs_size;          /**< size of all bitsets in bytes */
	int             changed;           /**< Flags for changed graph state */
125
126
127
128
129
130
131
132
133
134
135
136
137
138
} ldst_env;

#ifdef DEBUG_libfirm

static firm_dbg_module_t *dbg;

/* the one and only environment */
static ldst_env env;

/**
 * Dumps the block list.
 *
 * @param ldst environment
 */
Michael Beck's avatar
Michael Beck committed
139
static void dump_block_list(ldst_env *env) {
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
	block_t *entry;
	memop_t *op;
	int     i;

	for (entry = env->forward; entry != NULL; entry = entry->forward_next) {
		DB((dbg, LEVEL_2, "%+F {", entry->block));

		i = 0;
		for (op = entry->memop_forward; op != NULL; op = op->next) {
			if (i == 0) {
				DB((dbg, LEVEL_2, "\n\t"));
			}			DB((dbg, LEVEL_2, "%+F", op->node));
			if ((op->flags & FLAG_KILL_ALL) == FLAG_KILL_ALL)
				DB((dbg, LEVEL_2, "X"));
			else if (op->flags & FLAG_KILL_LOADS)
				DB((dbg, LEVEL_2, "L"));
			else if (op->flags & FLAG_KILL_STORES)
				DB((dbg, LEVEL_2, "S"));
			DB((dbg, LEVEL_2, ", "));

			i = (i + 1) & 3;
		}
		DB((dbg, LEVEL_2, "\n}\n\n"));
	}
}

/**
 * Dumps the current set.
 *
 * @param bl   current block
 * @param s    name of the set
 */
static void dump_curr(block_t *bl, const char *s) {
	unsigned pos = 0;
	unsigned end = env.n_mem_ops * 2 - 1;
	int      i;

	DB((dbg, LEVEL_2, "%s[%+F] = {", s, bl->block));
	i = 0;
	for (pos = rbitset_next(env.curr_set, pos, 1); pos != end; pos = rbitset_next(env.curr_set, pos + 1, 1)) {
Michael Beck's avatar
Michael Beck committed
180
		memop_t *op = env.curr_id_2_memop[pos];
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195

		if (i == 0) {
			DB((dbg, LEVEL_2, "\n\t"));
		}
		DB((dbg, LEVEL_2, "<%+F, %+F>, ", op->value.address, op->value.value));
		i = (i + 1) & 3;
	}
	DB((dbg, LEVEL_2, "\n}\n"));
}

#else
#define dump_block_list()
#define dump_curr(bl, s)
#endif /* DEBUG_libfirm */

196
197
198
199
200
201
202
203
204
205
206
207
208
/** Get the block entry for a block node */
static block_t *get_block_entry(const ir_node *block) {
	assert(is_Block(block));

	return get_irn_link(block);
}

/** Get the memop entry for a memory operation node */
static memop_t *get_irn_memop(const ir_node *irn) {
	assert(! is_Block(irn));
	return get_irn_link(irn);
}

209
210
211
212
213
214
215
216
/**
 * Walk over the memory edges from definition to users.
 *
 * @param irn   start node
 * @param pre   pre walker function
 * @param post  post walker function
 * @param ctx   context parameter for the walker functions
 */
Michael Beck's avatar
Michael Beck committed
217
static void walk_memory(ir_node *irn, irg_walk_func *pre, irg_walk_func *post, void *ctx) {
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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
	int     i;
	ir_mode *mode;

	mark_irn_visited(irn);

	if (pre)
		pre(irn, ctx);

	mode = get_irn_mode(irn);
	if (mode == mode_M) {
		/* every successor uses memory */
		for (i = get_irn_n_outs(irn) - 1; i >= 0; --i) {
			ir_node *succ = get_irn_out(irn, i);

			if (! irn_visited(succ))
				walk_memory(succ, pre, post, ctx);
		}
	} else if (mode == mode_T) {
		/* only some Proj's uses memory */
		for (i = get_irn_n_outs(irn) - 1; i >= 0; --i) {
			ir_node *proj = get_irn_out(irn, i);

			if (get_irn_mode(proj) == mode_M && ! irn_visited(proj))
				walk_memory(proj, pre, post, ctx);
		}
	}
	if (post)
		post(irn, ctx);
}

/**
 * Walks over all memory nodes of a graph.
 *
 * @param irg   a graph
 * @param pre   pre walker function
 * @param post  post walker function
 * @param ctx   context parameter for the walker functions
 */
static void walk_memory_irg(ir_graph *irg, irg_walk_func pre, irg_walk_func post, void *ctx) {
	inc_irg_visited(irg);

	ir_reserve_resources(irg, IR_RESOURCE_IRN_VISITED);

	/*
	 * there are two possible sources for memory: initial_mem and nomem
	 * we ignore nomem as this should NOT change the memory
	 */
	walk_memory(get_irg_initial_mem(irg), pre, post, ctx);

	ir_free_resources(irg, IR_RESOURCE_IRN_VISITED);
}

/**
 * Block walker: allocate an block entry for every block.
 */
static void prepare_blocks(ir_node *block, void *ctx) {
	block_t *entry = obstack_alloc(&env.obst, sizeof(*entry));

	(void) ctx;

	entry->memop_forward    = NULL;
	entry->memop_backward   = NULL;
	entry->avail_out        = NULL;
	entry->id_2_memop_avail = NULL;
	entry->anticL_in        = NULL;
Michael Beck's avatar
Michael Beck committed
283
	entry->id_2_memop_antic = NULL;
284
285
286
287
288
289
290
	entry->block            = block;
	entry->forward_next     = env.forward;
	entry->backward_next    = NULL;
	entry->avail            = NULL;
	set_irn_link(block, entry);

	/* create the list in inverse order */
291
292
293
	env.forward  = entry;
	/* remember temporary the last one */
	env.backward = entry;
294
295
296
297
298
299
300
301
302
}

/**
 * Block walker: create backward links for the memops of a block.
 */
static void collect_backward(ir_node *block, void *ctx) {
	block_t *entry = get_block_entry(block);
	memop_t *last, *op;

303
	(void)ctx;
304

305
306
307
308
309
310
311
312
313
314
315
	/*
	 * Do NOT link in the end block yet. We want it to be
	 * the first in the list. This is NOT guaranteed by the walker
	 * if we have endless loops.
	 */
	if (block != env.end_bl) {
		entry->backward_next = env.backward;

		/* create the list in inverse order */
		env.backward = entry;
	}
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342

	/* create backward links for all memory ops */
	last = NULL;
	for (op = entry->memop_forward; op != NULL; op = op->next) {
		op->prev = last;
		last     = op;
	}
	entry->memop_backward = last;
}

/**
 * Allocate a memop.
 *
 * @param irn  the IR-node representing the memop
 */
static memop_t *alloc_memop(ir_node *irn) {
	memop_t *m = obstack_alloc(&env.obst, sizeof(*m));

	m->value.address = NULL;
	m->value.value   = NULL;
	m->value.mode    = NULL;

	m->node          = irn;
	m->replace       = NULL;
	m->next          = NULL;
	m->flags         = 0;

343
	set_irn_link(irn, m);
344
345
346
	return m;
}

Michael Beck's avatar
Michael Beck committed
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/**
 * Create a memop for a Phi-replacement.
 *
 * @param op   the memop to clone
 * @param phi  the Phi-node representing the new value
 */
static memop_t *clone_memop_phi(memop_t *op, ir_node *phi) {
	memop_t *m = obstack_alloc(&env.obst, sizeof(*m));

	m->value         = op->value;
	m->value.value   = phi;

	m->node          = phi;
	m->replace       = NULL;
	m->next          = NULL;
	m->flags         = 0;

	set_irn_link(phi, m);
	return m;
}

368
369
370
371
372
373
/**
 * Register an address and allocate an ID for it.
 *
 * @param adr  the IR-node representing the address
 */
static unsigned register_address(ir_node *adr) {
374
375
376
377
378
379
380
381
382
383
384
385
386
387
	address_entry *entry;

	/* skip Confirms and Casts */
restart:
	if (is_Confirm(adr)) {
		adr = get_Confirm_value(adr);
		goto restart;
	}
	if (is_Cast(adr)) {
		adr = get_Cast_op(adr);
		goto restart;
	}

	entry = ir_nodemap_get(&env.adr_map, adr);
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
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

	if (entry == NULL) {
		/* new address */
		entry = obstack_alloc(&env.obst, sizeof(*entry));

		entry->id = env.curr_adr_id++;
		ir_nodemap_insert(&env.adr_map, adr, entry);
	}
	return entry->id;
}

/**
 * Return the memory properties of a call node.
 *
 * @param call  the call node
 *
 * return a bitset of mtp_property_const and mtp_property_pure
 */
static unsigned get_Call_memory_properties(ir_node *call) {
	ir_type *call_tp = get_Call_type(call);
	unsigned prop = get_method_additional_properties(call_tp);

	/* check first the call type */
	if ((prop & (mtp_property_const|mtp_property_pure)) == 0) {
		/* try the called entity */
		ir_node *ptr = get_Call_ptr(call);

		if (is_Global(ptr)) {
			ir_entity *ent = get_Global_entity(ptr);

			prop = get_entity_additional_properties(ent);
		}
	}
	return prop & (mtp_property_const|mtp_property_pure);
}

/**
 * Update a memop for a Load.
 *
 * @param m  the memop
 */
static void update_Load_memop(memop_t *m) {
	int     i;
	ir_node *load = m->node;
	ir_node *adr  = get_Load_ptr(load);

	if (get_Load_volatility(load) == volatility_is_volatile)
		m->flags |= FLAG_IGNORE;

	m->value.address = adr;

	for (i = get_irn_n_outs(load) - 1; i >= 0; --i) {
		ir_node *proj = get_irn_out(load, i);

442
443
444
445
		/* beware of keep edges */
		if (is_End(proj))
			continue;

446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
		switch (get_Proj_proj(proj)) {
		case pn_Load_res:
			m->value.value = proj;
			m->value.mode  = get_irn_mode(proj);
			break;
		case pn_Load_X_except:
			m->flags |= FLAG_EXCEPTION;
			break;
		case pn_Load_M:
			m->mem = proj;
			break;
		}
	}

	if (m->value.value != NULL && !(m->flags & FLAG_IGNORE)) {
		/* only create an address if this node is NOT killed immediately or ignored */
		m->value.id = register_address(adr);
		++env.n_mem_ops;
	} else {
		/* no user, KILL it */
		m->flags |= FLAG_KILLED_NODE;
	}
}

/**
 * Update a memop for a Store.
 *
 * @param m  the memop
 */
static void update_Store_memop(memop_t *m) {
	int     i;
	ir_node *store = m->node;
	ir_node *adr   = get_Store_ptr(store);

	if (get_Store_volatility(store) == volatility_is_volatile) {
		m->flags |= FLAG_IGNORE;
	} else {
		/* only create an address if this node is NOT ignored */
		m->value.id = register_address(adr);
		++env.n_mem_ops;
	}

	m->value.address = adr;

	for (i = get_irn_n_outs(store) - 1; i >= 0; --i) {
		ir_node *proj = get_irn_out(store, i);

493
494
495
496
		/* beware of keep edges */
		if (is_End(proj))
			continue;

497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
		switch (get_Proj_proj(proj)) {
		case pn_Store_X_except:
			m->flags |= FLAG_EXCEPTION;
			break;
		case pn_Store_M:
			m->mem = proj;
			break;
		}
	}
	m->value.value = get_Store_value(store);
	m->value.mode  = get_irn_mode(m->value.value);
}

/**
 * Update a memop for a Call.
 *
 * @param m  the memop
 */
static void update_Call_memop(memop_t *m) {
	ir_node  *call = m->node;
	unsigned prop  = get_Call_memory_properties(call);
	int      i;

	if (prop & mtp_property_const) {
		/* A constant call did NOT use memory at all, we
		   can kick it from the list. */
	} else if (prop & mtp_property_pure) {
		/* pure calls READ memory */
		m->flags = FLAG_KILL_STORES;
	} else
		m->flags = FLAG_KILL_ALL;

	for (i = get_irn_n_outs(call) - 1; i >= 0; --i) {
		ir_node *proj = get_irn_out(call, i);

532
533
534
535
		/* beware of keep edges */
		if (is_End(proj))
			continue;

536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
		switch (get_Proj_proj(proj)) {
		case pn_Call_X_except:
			m->flags |= FLAG_EXCEPTION;
			break;
		case pn_Call_M_regular:
			m->mem = proj;
			break;
		}
	}
}

/**
 * Update a memop for a Div/Mod/Quot/DivMod.
 *
 * @param m  the memop
 */
static void update_DivOp_memop(memop_t *m) {
	ir_node *div = m->node;
	int     i;

	for (i = get_irn_n_outs(div) - 1; i >= 0; --i) {
		ir_node *proj = get_irn_out(div, i);

559
560
561
562
		/* beware of keep edges */
		if (is_End(proj))
			continue;

563
564
565
566
567
568
569
570
571
572
573
		switch (get_Proj_proj(proj)) {
		case pn_Generic_X_except:
			m->flags |= FLAG_EXCEPTION;
			break;
		case pn_Generic_M_regular:
			m->mem = proj;
			break;
		}
	}
}

Michael Beck's avatar
Michael Beck committed
574
575
576
577
578
579
580
581
582
583
/**
 * Update a memop for a Phi.
 *
 * @param m  the memop
 */
static void update_Phi_memop(memop_t *m) {
	/* the Phi is it's own mem */
	m->mem = m->node;
}

584
585
586
587
588
589
590
591
/**
 * Memory walker: collect all memory ops and build topological lists.
 */
static void collect_memops(ir_node *irn, void *ctx) {
	memop_t  *op;
	ir_node  *block;
	block_t  *entry;

Michael Beck's avatar
Michael Beck committed
592
	(void) ctx;
593
594
595
596
597
598
599
600
601
602
603
	if (is_Proj(irn)) {
		/* we can safely ignore ProjM's except the initial memory */
		if (irn != get_irg_initial_mem(current_ir_graph))
			return;
	}

	op    = alloc_memop(irn);
	block = get_nodes_block(irn);
	entry = get_block_entry(block);

	if (is_Phi(irn)) {
Michael Beck's avatar
Michael Beck committed
604
		update_Phi_memop(op);
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
		/* Phis must be always placed first */
		op->next = entry->memop_forward;
		entry->memop_forward = op;
		if (entry->memop_backward == NULL)
			entry->memop_backward = op;
	} else {
		switch (get_irn_opcode(irn)) {
		case iro_Load:
			update_Load_memop(op);
			break;
		case iro_Store:
			update_Store_memop(op);
			break;
		case iro_Call:
			update_Call_memop(op);
			break;
		case iro_Sync:
		case iro_Pin:
			op->mem = irn;
			break;
		case iro_Proj:
			/* initial memory */
			op->mem = irn;
			break;
		case iro_Return:
		case iro_End:
			/* we can those to find the memory edge */
			break;
		case iro_Div:
		case iro_DivMod:
		case iro_Quot:
		case iro_Mod:
			update_DivOp_memop(op);
			break;

		case iro_Builtin:
			/* TODO: handle some builtins */
		default:
			/* unsupported operation */
			op->flags = FLAG_KILL_ALL;
		}


		/* all other should be placed last */
		if (entry->memop_backward == NULL) {
			entry->memop_forward = entry->memop_backward = op;
		} else {
			entry->memop_backward->next = op;
			entry->memop_backward       = op;
		}
	}
}

/**
 * Find an address in the current set.
 *
 * @param bl     the block
 * @param value  the value to be searched for
 */
static memop_t *find_address(const block_t *bl, const value_t *value) {
	if (rbitset_is_set(env.curr_set, value->id)) {
Michael Beck's avatar
Michael Beck committed
666
		memop_t *res = env.curr_id_2_memop[value->id];
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702

		if (res->value.mode == value->mode)
			return res;
		/* allow hidden casts */
		if (get_mode_arithmetic(res->value.mode) == irma_twos_complement &&
		    get_mode_arithmetic(value->mode) == irma_twos_complement &&
		    get_mode_size_bits(res->value.mode) == get_mode_size_bits(value->mode))
			return res;
	}
	return NULL;
}

/**
 * Find an address in the avail_out set.
 *
 * @param bl     the block
 * @param value  the value to be searched for
 */
static memop_t *find_address_avail(const block_t *bl, const value_t *value) {
	if (rbitset_is_set(bl->avail_out, value->id)) {
		memop_t *res = bl->id_2_memop_avail[value->id];

		if (res->value.mode == value->mode)
			return res;
		/* allow hidden casts */
		if (get_mode_arithmetic(res->value.mode) == irma_twos_complement &&
		    get_mode_arithmetic(value->mode) == irma_twos_complement &&
		    get_mode_size_bits(res->value.mode) == get_mode_size_bits(value->mode))
			return res;
	}
	return NULL;
}

/**
 * Kill all Loads from the current set.
 */
Michael Beck's avatar
Michael Beck committed
703
static void kill_all_loads(void) {
704
705
706
707
	unsigned pos = 0;
	unsigned end = env.n_mem_ops * 2 - 1;

	for (pos = rbitset_next(env.curr_set, pos, 1); pos != end; pos = rbitset_next(env.curr_set, pos + 1, 1)) {
Michael Beck's avatar
Michael Beck committed
708
		memop_t *op = env.curr_id_2_memop[pos];
709
710
711
712
713
714
715
716
717

		if (! is_Store(op->node))
			rbitset_clear(env.curr_set, pos);
	}
}

/**
 * Kill all Stores from the current set.
 */
Michael Beck's avatar
Michael Beck committed
718
static void kill_all_stores(void) {
719
720
721
722
	unsigned pos = 0;
	unsigned end = env.n_mem_ops * 2 - 1;

	for (pos = rbitset_next(env.curr_set, pos, 1); pos != end; pos = rbitset_next(env.curr_set, pos + 1, 1)) {
Michael Beck's avatar
Michael Beck committed
723
		memop_t *op = env.curr_id_2_memop[pos];
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745

		if (is_Store(op->node))
			rbitset_clear(env.curr_set, pos);
	}
}

/**
 * Kill all addresses from the current set.
 */
static void kill_all(void) {
	rbitset_clear_all(env.curr_set, env.rbs_size);

	/* set sentinel */
	rbitset_set(env.curr_set, env.rbs_size - 1);
}


/**
 * Kill Stores that are not alias free due to a Load value from the current set.
 *
 * @param value  the Load value
 */
Michael Beck's avatar
Michael Beck committed
746
static void kill_stores(const value_t *value) {
747
748
749
750
	unsigned pos = 0;
	unsigned end = env.n_mem_ops * 2 - 1;

	for (pos = rbitset_next(env.curr_set, pos, 1); pos != end; pos = rbitset_next(env.curr_set, pos + 1, 1)) {
Michael Beck's avatar
Michael Beck committed
751
		memop_t *op = env.curr_id_2_memop[pos];
752
753
754
755
756

		if (is_Store(op->node)) {
			if (ir_no_alias != get_alias_relation(current_ir_graph, value->address, value->mode,
			                                      op->value.address, op->value.mode)) {
				rbitset_clear(env.curr_set, pos);
Michael Beck's avatar
Michael Beck committed
757
				env.curr_id_2_memop[pos] = NULL;
758
759
760
761
762
763
764
765
766
767
			}
		}
	}
}

/**
 * Kill memops that are not alias free due to a Store value from the current set.
 *
 * @param value  the Store value
 */
Michael Beck's avatar
Michael Beck committed
768
static void kill_memops(const value_t *value) {
769
770
771
772
	unsigned pos = 0;
	unsigned end = env.n_mem_ops * 2 - 1;

	for (pos = rbitset_next(env.curr_set, pos, 1); pos != end; pos = rbitset_next(env.curr_set, pos + 1, 1)) {
Michael Beck's avatar
Michael Beck committed
773
		memop_t *op = env.curr_id_2_memop[pos];
774
775
776
777

		if (ir_no_alias != get_alias_relation(current_ir_graph, value->address, value->mode,
			                                  op->value.address, op->value.mode)) {
			rbitset_clear(env.curr_set, pos);
Michael Beck's avatar
Michael Beck committed
778
			env.curr_id_2_memop[pos] = NULL;
779
780
781
782
783
784
785
786
787
		}
	}
}

/**
 * Add the value of a memop to the current set.
 *
 * @param op  the memory op
 */
Michael Beck's avatar
Michael Beck committed
788
static void add_memop(memop_t *op) {
789
	rbitset_set(env.curr_set, op->value.id);
Michael Beck's avatar
Michael Beck committed
790
	env.curr_id_2_memop[op->value.id] = op;
791
792
793
794
795
796
797
798
799
800
801
802
803
}

/**
 * Add the value of a memop to the avail_out set.
 *
 * @param bl  the block
 * @param op  the memory op
 */
static void add_memop_avail(block_t *bl, memop_t *op) {
	rbitset_set(bl->avail_out, op->value.id);
	bl->id_2_memop_avail[op->value.id] = op;
}

Michael Beck's avatar
Michael Beck committed
804
805
806
807
808
809
810
811
812
813
814
/**
 * Update a value of a memop to the avail_out set.
 *
 * @param bl  the block
 * @param op  the memory op
 */
static void update_memop_avail(block_t *bl, memop_t *op) {
	if (rbitset_is_set(bl->avail_out, op->value.id))
		bl->id_2_memop_avail[op->value.id] = op;
}

815
816
817
818
819
820
/**
 * Add a Conv if needed.
 */
static ir_node *conv_to(ir_node *irn, ir_mode *mode) {
	if (get_irn_mode(irn) != mode) {
		ir_node *block = get_nodes_block(irn);
Moritz Kroll's avatar
Moritz Kroll committed
821
		return new_r_Conv(current_ir_graph, block, irn, mode);
822
823
824
825
	}
	return irn;
}

826
/**
827
 * build a phi definition for a value in the given block
828
829
830
831
832
833
 *
 * @param block  the block
 * @param value  the value
 *
 * @return the definition
 */
834
static ir_node *build_phi_definition(ir_node *block, const value_t *value) {
835
836
837
	ir_node **in, *phi;
	int     i, n;
	memop_t *mop;
838
	ir_mode *mode = value->mode;
839
840
841
842
843
844
845

	/* no: we need a new Phi */
	n = get_Block_n_cfgpreds(block);

	while (n == 1) {
		block = get_Block_cfgpred_block(block, 0);
		n     = get_Block_n_cfgpreds(block);
846
		mop   = find_address_avail(get_block_entry(block), value);
847

848
849
850
851
		if (mop == NULL) {
			/* this can only happen, if modes cannot be converted */
			return NULL;
		}
852
853
854
855
856
857
		value = &mop->value;
	}

	NEW_ARR_A(ir_node *, in, n);
	for (i = n - 1; i >= 0; --i) {
		ir_node *pred_bl = get_Block_cfgpred_block(block, i);
858
859
		ir_node *def_bl;

860
861
862
863
		mop = find_address_avail(get_block_entry(pred_bl), value);
		if (mop == NULL)
			return NULL;

864
865
866
		def_bl = get_nodes_block(mop->value.value);

		if (block_dominates(def_bl, pred_bl))
867
868
869
870
871
872
873
			in[i] = conv_to(mop->value.value, mode);
		else {
			ir_node *def = build_phi_definition(pred_bl, &mop->value);
			if (def == NULL)
				return NULL;
			in[i] = conv_to(def, mode);
		}
874
875
	}

876
	phi = new_r_Phi(current_ir_graph, block, n, in, mode);
877
878
879
880
	DB((dbg, LEVEL_2, "Created new Phi %+F for value %+F in block %+F\n", phi, value->value, block));
	return phi;
}

881
882
883
884
885
886
887
/**
 * find a definition for a value in the given block or above.
 *
 * @param block  the block
 * @param op     the memop: the definition must dominate it
 * @param value  the value
 *
888
 * @return the definition or NULL if modes are different
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
 */
static ir_node *find_definition(ir_node *block, const memop_t *op, const value_t *value) {
	ir_node *def_block = get_nodes_block(value->value);

	if (def_block == block) {
		/* the value is in our block: check, if it is above in the memory list */
		const memop_t *p;

		for (p = op->prev; p != NULL; p = p->prev) {
			if (!(p->flags & FLAG_KILLED_NODE) &&
			    p->value.address == value->address) {
				/* found */
				assert(p->value.value == value->value);
				return p->value.value;
			}
		}
	} else if (block_dominates(def_block, block)) {
		/* strictly dominates */
		return value->value;
	}

	return build_phi_definition(block, value);
}

913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
/**
 * Mark a Load memop to be replace by a definition
 *
 * @param op  the Load memop
 */
static void mark_replace_load(memop_t *op, ir_node *def) {
	op->replace = def;
	op->flags |= FLAG_KILLED_NODE;
	env.changed = 1;
}

/**
 * Mark a Store memop to be removed.
 *
 * @param op  the Store memop
 */
static void mark_remove_store(memop_t *op) {
	op->flags |= FLAG_KILLED_NODE;
	env.changed = 1;
}

/**
Michael Beck's avatar
Michael Beck committed
935
936
 * Do forward dataflow analysis on the given block and calculate the
 * GEN and KILL in the current (avail) set.
937
938
939
 *
 * @param bl  the block
 */
Michael Beck's avatar
Michael Beck committed
940
static void calc_gen_kill_avail(block_t *bl) {
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
	memop_t *op;
	ir_node *def;

	for (op = bl->memop_forward; op != NULL; op = op->next) {
		switch (get_irn_opcode(op->node)) {
		case iro_Phi:
			/* meet */
			break;
		case iro_Sync:
			/* join */
			break;
		case iro_Load:
			if (! (op->flags & (FLAG_KILLED_NODE|FLAG_IGNORE))) {
				/* do we have this already? */
				memop_t *other = find_address(bl, &op->value);
				if (other != NULL) {
957
					def = find_definition(bl->block, op, &other->value);
958
959
960
961
962
963
964
965
966
967
968
					if (def != NULL) {
#ifdef DEBUG_libfirm
						if (is_Store(other->node)) {
							/* RAW */
							DB((dbg, LEVEL_1, "RAW %+F <- %+F(%+F)\n", op->node, def, other->node));
						} else {
							/* RAR */
							DB((dbg, LEVEL_1, "RAR %+F <- %+F(%+F)\n", op->node, def, other->node));
						}
#endif
						mark_replace_load(op, def);
969
					} else {
970
						/* overwrite it */
Michael Beck's avatar
Michael Beck committed
971
						add_memop(op);
972
973
974
					}
				} else {
					/* add this value */
Michael Beck's avatar
Michael Beck committed
975
976
					kill_stores(&op->value);
					add_memop(op);
977
978
979
980
981
982
983
984
				}
			}
			break;
		case iro_Store:
			if (! (op->flags & (FLAG_KILLED_NODE|FLAG_IGNORE))) {
				/* do we have this store already */
				memop_t *other = find_address(bl, &op->value);
				if (other != NULL) {
Michael Beck's avatar
Michael Beck committed
985
986
987
988
989
990
991
992
993
994
995
					if (is_Store(other->node)) {
						if (op != other && get_nodes_block(other->node) == get_nodes_block(op->node)) {
							/*
							 * A WAW in the same block we can kick the first store.
							 * This is a shortcut: we know that the second Store will be anticipated
							 * then in an case.
							 */
							DB((dbg, LEVEL_1, "WAW %+F <- %+F\n", op->node, other->node));
							mark_remove_store(other);
							/* FIXME: a Load might be get freed due to this killed store */
						}
996
997
					} else if (other->value.value == op->value.value) {
						/* WAR */
998
						DB((dbg, LEVEL_1, "WAR %+F <- %+F\n", op->node, other->node));
999
1000
1001
						mark_remove_store(op);
					} else {
						/* we overwrite the value that was loaded */
Michael Beck's avatar
Michael Beck committed
1002
						add_memop(op);
1003
1004
1005
					}
				} else {
					/* add this value */
Michael Beck's avatar
Michael Beck committed
1006
1007
					kill_memops(&op->value);
					add_memop(op);
1008
1009
1010
1011
1012
1013
1014
1015
1016
				}
			}
			break;
		default:
			switch (op->flags & (FLAG_KILL_LOADS|FLAG_KILL_STORES)) {
			case FLAG_KILL_LOADS|FLAG_KILL_STORES:
				kill_all();
				break;
			case FLAG_KILL_LOADS:
Michael Beck's avatar
Michael Beck committed
1017
				kill_all_loads();
1018
1019
				break;
			case FLAG_KILL_STORES:
Michael Beck's avatar
Michael Beck committed
1020
				kill_all_stores();
1021
1022
1023
1024
1025
1026
				break;
			case 0:
				break;
			}
		}
	}
Michael Beck's avatar
Michael Beck committed
1027
}
1028

Michael Beck's avatar
Michael Beck committed
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
#define BYTE_SIZE(x)  (((x) + 7) >> 3)

/**
 * Do forward dataflow analysis on a given block to calculate the avail_out set
 * for this block only.
 *
 * @param block  the block
 */
static void forward_avail(block_t *bl) {
	/* fill the data from the current block */
	env.curr_id_2_memop = bl->id_2_memop_avail;
	env.curr_set        = bl->avail_out;

	calc_gen_kill_avail(bl);
1043
	dump_curr(bl, "Avail_out");
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
}

/**
 * Do backward dataflow analysis on a given block to calculate the antic set
 * of Loaded addresses.
 *
 * @param bl  the block
 *
 * @return non-zero if the set has changed since last iteration
 */
static int backward_antic(block_t *bl) {
	memop_t *op;
1056
	int     n = get_Block_n_cfg_outs(bl->block);
1057

1058
1059
1060
	if (n >= 1) {
		ir_node *succ    = get_Block_cfg_out(bl->block, 0);
		block_t *succ_bl = get_block_entry(succ);
1061
1062
		int i;

1063
		rbitset_cpy(env.curr_set, succ_bl->anticL_in, env.rbs_size);
Michael Beck's avatar
Michael Beck committed
1064
		memcpy(env.curr_id_2_memop, succ_bl->id_2_memop_antic, env.rbs_size * sizeof(env.curr_id_2_memop[0]));
1065

1066
1067
1068
1069
1070
1071
		for (i = n - 1; i > 0; --i) {
			ir_node *succ    = get_Block_cfg_out(bl->block, i);
			block_t *succ_bl = get_block_entry(succ);

			rbitset_and(env.curr_set, succ_bl->anticL_in, env.rbs_size);
		}
1072
1073
1074
	} else {
		/* block ends with a noreturn call */
		kill_all();
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
	}

#if 0
	/* cleanup: kill those Loads which address is not available */
	for (pos = rbitset_next(env.curr_set, pos, 1); pos != end; pos = rbitset_next(env.curr_set, pos + 1, 1)) {
		memop_t *op     = succ_bl->id_2_memop[pos];
		ir_node *ptr    = get_Load_ptr(op->node);
		ir_node *ptr_bl = get_nodes_block(ptr);

		if (!block_dominates(ptr_bl, bl->block))
			rbitset_clear(env.curr_set, pos);
	}
#endif

	dump_curr(bl, "AnticL_out");

	for (op = bl->memop_backward; op != NULL; op = op->prev) {
		switch (get_irn_opcode(op->node)) {
		case iro_Phi:
			/* meet */
			break;
		case iro_Sync:
			/* join */
			break;
		case iro_Load:
			if (! (op->flags & (FLAG_KILLED_NODE|FLAG_IGNORE))) {
				/* always add it */
Michael Beck's avatar
Michael Beck committed
1102
				add_memop(op);
1103
1104
1105
1106
1107
			}
			break;
		case iro_Store:
			if (! (op->flags & (FLAG_KILLED_NODE|FLAG_IGNORE))) {
				/* a Store: check which memops must be killed */
Michael Beck's avatar
Michael Beck committed
1108
				kill_memops(&op->value);
1109
1110
1111
1112
1113
1114
1115
1116
			}
			break;
		default:
			switch (op->flags & (FLAG_KILL_LOADS|FLAG_KILL_STORES)) {
			case FLAG_KILL_LOADS|FLAG_KILL_STORES:
				kill_all();
				break;
			case FLAG_KILL_LOADS:
Michael Beck's avatar
Michael Beck committed
1117
				kill_all_loads();
1118
1119
				break;
			case FLAG_KILL_STORES:
Michael Beck's avatar
Michael Beck committed
1120
				/*kill_all_stores();*/
1121
1122
1123
1124
1125
1126
				break;
			case 0:
				break;
			}
		}
	}
Michael Beck's avatar
Michael Beck committed
1127
1128

	memcpy(bl->id_2_memop_antic, env.curr_id_2_memop, env.rbs_size * sizeof(env.curr_id_2_memop[0]));
Michael Beck's avatar
BugFix:    
Michael Beck committed
1129
	if (! rbitset_equal(bl->anticL_in, env.curr_set, env.rbs_size)) {
1130
		/* changed */
Michael Beck's avatar
BugFix:    
Michael Beck committed
1131
		rbitset_cpy(bl->anticL_in, env.curr_set, env.rbs_size);
Michael Beck's avatar
Michael Beck committed
1132
		dump_curr(bl, "AnticL_in*");
1133
1134
		return 1;
	}
Michael Beck's avatar
Michael Beck committed
1135
	dump_curr(bl, "AnticL_in");
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
	return 0;
}

/**
 * Replace a Load memop by a already known value.
 *
 * @param op  the Load memop
 */
static void replace_load(memop_t *op) {
	ir_node *load = op->node;
	ir_node *def  = skip_Id(op->replace);
	int     i;
	ir_mode *mode;

	if (def != NULL)
Michael Beck's avatar
BugFix:    
Michael Beck committed
1151
		DB((dbg, LEVEL_1, "Replacing %+F by definition %+F\n", load, is_Proj(def) ? get_Proj_pred(def) : def));
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
	else {
		if (op->flags & FLAG_EXCEPTION) {
			/* bad: this node is unused and executed for exception only */
			DB((dbg, LEVEL_1, "Unused %+F executed for exception only ...\n", load));
			return;
		}
		DB((dbg, LEVEL_1, "Killing unused %+F\n", load));
	}
	for (i = get_irn_n_outs(load) - 1; i >= 0; --i) {
		ir_node *proj = get_irn_out(load, i);

		switch (get_Proj_proj(proj)) {
		case pn_Load_M:
			exchange(proj, get_Load_mem(load));
			break;
		case pn_Load_res:
			mode = get_irn_mode(proj);
			if (get_irn_mode(def) != mode) {
				/* a hidden cast */
				dbg_info *db    = get_irn_dbg_info(load);
				ir_node  *block = get_nodes_block(proj);
Moritz Kroll's avatar
Moritz Kroll committed
1173
				def = new_rd_Conv(db, current_ir_graph, block, def, mode);
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
			}
			exchange(proj, def);
			break;
		case pn_Load_X_except:
			exchange(proj, new_Bad());
			break;
		case pn_Load_X_regular:
			exchange(proj, new_r_Jmp(current_ir_graph, get_nodes_block(load)));
			break;
		default:
			panic("Unknown Proj from Load");
		}
	}
}

/**
 * Remove a Store memop.
 *
 * @param op  the Store memop
 */
static void remove_store(memop_t *op) {
	ir_node *store = op->node;
	int     i;

	DB((dbg, LEVEL_1, "Removing %+F\n", store));
	for (i = get_irn_n_outs(store) - 1; i >= 0; --i) {
		ir_node *proj = get_irn_out(store, i);

		switch (get_Proj_proj(proj)) {
		case pn_Store_M:
			exchange(proj, get_Store_mem(store));
			break;
		case pn_Store_X_except:
			exchange(proj, new_Bad());
			break;
		case pn_Store_X_regular:
			exchange(proj, new_r_Jmp(current_ir_graph, get_nodes_block(store)));
			break;
		default:
			panic("Unknown Proj from Store");
		}
	}
}


/**
 * Do all necessary replacements for a given block.
 *
 * @param bl  the block
 */
static void do_replacements(block_t *bl) {
	memop_t *op;

	for (op = bl->memop_forward; op != NULL; op = op->next) {
		if (op->flags & FLAG_KILLED_NODE) {
			switch (get_irn_opcode(op->node)) {
			case iro_Load:
				replace_load(op);
				break;
			case iro_Store:
				remove_store(op);
				break;
			}
		}
	}
}

/**
 * Calculate the Avail_out sets for all basic blocks.
 */
static void calcAvail(void) {
Michael Beck's avatar
Michael Beck committed
1245
1246
1247
	memop_t  **tmp_memop = env.curr_id_2_memop;
	unsigned *tmp_set    = env.curr_set;
	block_t  *bl;
1248
1249
1250
1251

	/* calculate avail_out */
	DB((dbg, LEVEL_2, "Calculate Avail_out\n"));

Michael Beck's avatar
Michael Beck committed
1252
1253
1254
1255
	/* interate over all blocks in in any order, skip the start block */
	for (bl = env.forward->forward_next; bl != NULL; bl = bl->forward_next) {
		forward_avail(bl);
	}
1256

Michael Beck's avatar
Michael Beck committed
1257
1258
1259
	/* restore the current sets */
	env.curr_id_2_memop = tmp_memop;
	env.curr_set        = tmp_set;
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
}

/**
 * Calculate the Antic_in sets for all basic blocks.
 */
static void calcAntic(void) {
	int i, need_iter;

	/* calculate antic_out */
	DB((dbg, LEVEL_2, "Calculate Antic_in\n"));
	i = 0;
	do {
		block_t *bl;

		DB((dbg, LEVEL_2, "Iteration %d:\n=========\n", i));

		need_iter = 0;

		/* over all blocks in reverse post order */
		for (bl = env.backward->backward_next; bl != NULL; bl = bl->backward_next) {
			need_iter |= backward_antic(bl);
		}
		++i;
	} while (need_iter);
	DB((dbg, LEVEL_2, "Get anticipated Load set after %d iterations\n", i));
}

/**
 * Return the node representing the last memory in a block.
 *
 * @param bl  the block
 */
static ir_node *find_first_memory(block_t *bl) {
	for (;;) {
		if (bl->memop_forward != NULL) {
			return bl->memop_forward->node;
		}
		/* if there is NO memory in this block, go to the post dominator */
		bl = get_block_entry(get_Block_ipostdom(bl->block));
	}
}

/**
 * Return the node representing the last memory in a block.
 *
 * @param bl  the block
 */
static ir_node *find_last_memory(block_t *bl) {
	for (;;) {
		if (bl->memop_backward != NULL) {
			return bl->memop_backward->mem;
		}
		/* if there is NO memory in this block, go to the dominator */
		bl = get_block_entry(get_Block_idom(bl->block));
	}
}

/**
Michael Beck's avatar
Michael Beck committed
1318
 * Reroute all memory users of old memory
1319
1320
1321
1322
1323
 * to a new memory IR-node.
 *
 * @param omem  the old memory IR-node
 * @param nmem  the new memory IR-node
 */
Michael Beck's avatar
Michael Beck committed
1324
static void reroute_all_mem_users(ir_node *omem, ir_node *nmem) {
1325
1326
1327
1328
	int i;

	for (i = get_irn_n_outs(omem) - 1; i >= 0; --i) {
		int     n_pos;
Michael Beck's avatar
Michael Beck committed
1329
		ir_node *user = get_irn_out_ex(omem, i, &n_pos);
1330

Michael Beck's avatar
Michael Beck committed
1331
		set_irn_n(user, n_pos, nmem);
1332
1333
	}

Michael Beck's avatar
Michael Beck committed
1334
	/* all edges previously point to omem now point to nmem */
1335
1336
1337
	nmem->out = omem->out;
}

Michael Beck's avatar
Michael Beck committed
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
/**
 * Reroute memory users of old memory that are dominated by a given block
 * to a new memory IR-node.
 *
 * @param omem     the old memory IR-node
 * @param nmem     the new memory IR-node
 * @param pass_bl  the block the memory must pass
 */
static void reroute_mem_through(ir_node *omem, ir_node *nmem, ir_node *pass_bl) {
	int             i, j, n = get_irn_n_outs(omem);
	ir_def_use_edge *edges = NEW_ARR_D(ir_def_use_edge, &env.obst, n + 1);

	for (i = j = 0; i < n; ++i) {
		int     n_pos;
		ir_node *user   = get_irn_out_ex(omem, i, &n_pos);
		ir_node *use_bl = get_nodes_block(user);


		if (is_Phi(user)) {
			use_bl = get_Block_cfgpred_block(use_bl, n_pos);
		}
		if (block_dominates(pass_bl, use_bl)) {
			/* found an user that is dominated */
			++j;
			edges[j].pos = n_pos;
			edges[j].use = user;

			set_irn_n(user, n_pos, nmem);
		}
	}

	/* Modify the out structure: we create a new out edge array on our
	   temporary obstack here. This should be no problem, as we invalidate the edges
	   at the end either. */
	/* first entry is used for the length */
	edges[0].pos = j;
	nmem->out = edges;
}

1377
1378
1379
/**
 * insert
 */
Michael Beck's avatar
Michael Beck committed
1380
1381
1382
static int insert_Load(block_t *bl) {
	ir_node  *block = bl->block;
	int      i, n = get_Block_n_cfgpreds(block);
1383
1384
	unsigned pos = 0;
	unsigned end = env.n_mem_ops * 2 - 1;
Michael Beck's avatar
Michael Beck committed
1385
1386
1387
	int      res = 0;
	ir_node  *pred    = get_Block_cfgpred_block(bl->block, 0);
	block_t  *pred_bl = get_block_entry(pred);
1388

Michael Beck's avatar
Michael Beck committed
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
	DB((dbg, LEVEL_3, "processing %+F\n", block));

	rbitset_cpy(env.curr_set, pred_bl->avail_out, env.rbs_size);

	if (n > 1) {
		int i, pos;

		/* more than one predecessors, calculate the join for all avail_outs */
		for (i = n - 1; i > 0; --i) {
			ir_node *pred    = skip_Proj(get_Block_cfgpred(block, i));
			block_t *pred_bl = get_block_entry(get_nodes_block(pred));

			rbitset_and(env.curr_set, pred_bl->avail_out, env.rbs_size);

			if (is_Load(pred) || is_Store(pred)) {
				/* We reached this block by an exception from a Load or Store:
				 * the memop creating the exception was NOT completed than, kill it
				 */
				memop_t *exc_op = get_irn_memop(pred);
				rbitset_clear(env.curr_set, exc_op->value.id);
			}

		}
		/* ensure that all values are in the map */
		for (pos = env.rbs_size - 1; pos >= 0; --pos) {
			if (! rbitset_is_set(env.curr_set, pos))
				env.curr_id_2_memop[pos] = NULL;
			else {
				for (i = n - 1; i >= 0; --i) {
					ir_node *pred    = get_Block_cfgpred_block(bl->block, i);
					block_t *pred_bl = get_block_entry(pred);

					if (pred_bl->id_2_memop_avail[pos] != NULL) {
						env.curr_id_2_memop[pos] = pred_bl->id_2_memop_avail[pos];
						break;
					}
				}
			}
		}
	} else {
		/* only one predecessor, simply copy the map */
		memcpy(env.curr_id_2_memop, pred_bl->id_2_memop_avail, env.rbs_size * sizeof(bl->id_2_memop_avail[0]));
	}
1432
1433


Michael Beck's avatar
Michael Beck committed
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
	/* recalculate avail by gen and kill */
	calc_gen_kill_avail(bl);

	if (!rbitset_equal(bl->avail_out, env.curr_set, env.rbs_size)) {
		/* the avail set has changed */
		rbitset_cpy(bl->avail_out, env.curr_set, env.rbs_size);
		memcpy(bl->id_2_memop_avail, env.curr_id_2_memop, env.rbs_size * sizeof(env.curr_id_2_memop[0]));
		dump_curr(bl, "Avail_out*");
		res = 1;
	}

	if (n <= 1)
		return res;

	/* check for partly redundant values */
1449
	for (pos = rbitset_next(bl->anticL_in, pos, 1); pos != end; pos = rbitset_next(bl->anticL_in, pos + 1, 1)) {
Michael Beck's avatar
Michael Beck committed
1450
		memop_t *op = bl->id_2_memop_antic[pos];
1451
1452
		int     have_some, all_same;
		ir_node *first;
1453
1454
1455
1456
1457

		assert(is_Load(op->node));

		if (op->flags & FLAG_KILLED_NODE)
			continue;
Michael Beck's avatar
Michael Beck committed
1458
		DB((dbg, LEVEL_3, "anticipated %+F\n", op->node));
1459
1460

		have_some  = 0;
1461
1462
		all_same   = 1;
		first      = 0;
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
		for (i = n - 1; i >= 0; --i) {
			ir_node *pred    = get_Block_cfgpred_block(block, i);
			block_t *pred_bl = get_block_entry(pred);
			memop_t *e       = find_address_avail(pred_bl, &op->value);

			if (e == NULL) {
				ir_node *block = get_nodes_block(op->value.address);
				if (! block_dominates(block, pred)) {
					/* cannot place a copy here */
					have_some = 0;
					break;
				}
Michael Beck's avatar
Michael Beck committed
1475
				DB((dbg, LEVEL_3, "%+F is not available in predecessor %+F\n", op->node, pred));
1476
				pred_bl->avail = NULL;
1477
				all_same       = 0;
1478
1479
1480
			} else {
				pred_bl->avail = e;
				have_some      = 1;
Michael Beck's avatar
Michael Beck committed
1481
				DB((dbg, LEVEL_3, "%+F is available for %+F in predecessor %+F\n", e->node, op->node, pred));
1482
1483
1484
1485
				if (first == NULL)
					first = e->node;
				else if (first != e->node)
					all_same = 0;
1486
1487
			}
		}
1488
		if (have_some && !all_same) {
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
			ir_mode *mode = op->value.mode;
			ir_node **in, *phi;

			NEW_ARR_A(ir_node *, in, n);

			for (i = n - 1; i >= 0; --i) {
				ir_node *pred    = get_Block_cfgpred_block(block, i);
				block_t *pred_bl = get_block_entry(pred);

				if (pred_bl->avail == NULL) {
					/* create a new Load here and make to make it fully redundant */
					dbg_info *db       = get_irn_dbg_info(op->node);
					ir_node  *last_mem = find_last_memory(pred_bl);
					ir_node  *load, *def;
					memop_t  *new_op;

Michael Beck's avatar
Michael Beck committed
1505
					assert(last_mem != NULL);
1506
1507
					load = new_rd_Load(db, current_ir_graph, pred, last_mem, op->value.address, mode, cons_none);
					def  = new_r_Proj(current_ir_graph, pred, load, mode, pn_Load_res);
Michael Beck's avatar
Michael Beck committed
1508
					DB((dbg, LEVEL_1, "Created new %+F in %+F for party redundant %+F\n", load, pred, op->node));
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519

					new_op                = alloc_memop(load);
					new_op->mem           = new_r_Proj(current_ir_graph, pred, load, mode_M, pn_Load_M);
					new_op->value.address = op->value.address;
					new_op->value.id      = op->value.id;
					new_op->value.mode    = mode;
					new_op->value.value   = def;

					new_op->prev            = pred_bl->memop_backward;
					pred_bl->memop_backward = new_op;

Michael Beck's avatar
BugFix:    
Michael Beck committed
1520
					if (get_nodes_block(last_mem) == pred) {
Michael Beck's avatar
Michael Beck committed
1521
1522
1523
1524
1525
1526
1527
						/* We have add a new last memory op in pred block.
						   If pred had already a last mem, reroute all memory
						   users. */
						reroute_all_mem_users(last_mem, new_op->mem);
					} else {
						/* reroute only those memory going through the pre block */
						reroute_mem_through(last_mem, new_op->mem, pred);
Michael Beck's avatar
BugFix:    
Michael Beck committed
1528
					}
1529
1530
1531
1532
1533
1534
1535
1536

					/* we added this load at the end, so it will be avail anyway */
					add_memop_avail(pred_bl, new_op);
					pred_bl->avail = new_op;
				}
				in[i] = pred_bl->avail->value.value;
			}
			phi = new_r_Phi(current_ir_graph, block, n, in, mode);
Michael Beck's avatar
Michael Beck committed
1537
			DB((dbg, LEVEL_1, "Created new %+F in %+F for now redundant %+F\n", phi, block, op->node));
1538
1539
1540
1541
1542
1543
1544

			if (get_nodes_block(op->node) == block) {
				/* The redundant node was in the current block:
				   In that case, DO NOT update avail_out. If it was NOT
				   avail although it is executed in this bLock, it is killed by a later
				   instruction.
				 */
Michael Beck's avatar
Michael Beck committed
1545
1546
1547
1548
1549
				memop_t *phi_op = clone_memop_phi(op, phi);

				update_memop_avail(bl, phi_op);

				mark_replace_load(op, phi);
1550
			} else {
Michael Beck's avatar
Michael Beck committed
1551
1552
1553
1554
				/* The redundant node is NOT in the current block and anticipated. */
				memop_t *phi_op = clone_memop_phi(op, phi);

				add_memop_avail(bl, phi_op);
1555

Michael Beck's avatar
Michael Beck committed
1556
1557
				/* propagate it downwards */
				res = 1;
1558
			}
Michael Beck's avatar
Michael Beck committed
1559
1560
			/* clear it so we do not found it the next iteration */
			rbitset_clear(bl->anticL_in, pos);
1561
1562
		}
	}
Michael Beck's avatar
Michael Beck committed
1563
	return res;
1564
1565
1566
1567
1568
1569
1570
}

/**
 * Insert Loads upwards.
 */
static void insert_Loads_upwards(void) {
	int i, need_iter;
Michael Beck's avatar
Michael Beck committed
1571
	block_t *bl;
1572

Michael Beck's avatar
Michael Beck committed
1573
	/* recalculate antic_out and insert Loads */
1574
	DB((dbg, LEVEL_2, "Inserting Loads\n"));
Michael Beck's avatar
Michael Beck committed
1575

1576
1577
1578
1579
1580
	i = 0;
	do {
		DB((dbg, LEVEL_2, "Iteration %d:\n=========\n", i));

		need_iter = 0;
Michael Beck's avatar
Michael Beck committed
1581
1582
1583
1584
1585

		/* over all blocks in reverse post order, skip the start block */
		for (bl = env.forward->forward_next; bl != NULL; bl = bl->forward_next) {
			need_iter |= insert_Load(bl);
		}
1586
1587
		++i;
	} while (need_iter);
Michael Beck's avatar
Michael Beck committed
1588

1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
	DB((dbg, LEVEL_2, "Finished Load inserting after %d iterations\n", i));
}

int opt_ldst(ir_graph *irg) {
	block_t  *bl;
	ir_graph *rem = current_ir_graph;

	current_ir_graph = irg;

	FIRM_DBG_REGISTER(dbg, "firm.opt.ldst");
Michael Beck's avatar
Michael Beck committed
1599
//	firm_dbg_set_mask(dbg, -1);
1600
1601
1602
1603
1604
1605

	DB((dbg, LEVEL_1, "\nDoing Load/Store optimization on %+F\n", irg));

	/* we need landing pads */
	remove_critical_cf_edges(irg);

1606
1607
	dump_ir_block_graph(irg, "-XXX");

1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
	if (get_opt_alias_analysis()) {
		assure_irg_entity_usage_computed(irg);
		assure_irp_globals_entity_usage_computed();
	}

	obstack_init(&env.obst);
	ir_nodemap_init(&env.adr_map);

	env.forward     = NULL;
	env.backward    = NULL;
	env.curr_adr_id = 0;
	env.n_mem_ops   = 0;
	env.changed     = 0;
	env.start_bl    = get_irg_start_block(irg);
1622
	env.end_bl      = get_irg_end_block(irg);
1623
1624
1625
1626
1627
1628
1629
1630

	assure_doms(irg);
	assure_irg_outs(irg);

	ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);

	/* first step: allocate block entries: produces an
	   inverse post-order list for the CFG */
1631
	set_irn_link(env.end_bl, NULL);
1632
1633
	irg_out_block_walk(get_irg_start_block(irg), NULL, prepare_blocks, NULL);

1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
	if (get_block_entry(env.end_bl) == NULL) {
		/*
		 * The end block is NOT reachable due to endless loops
		 * or no_return calls. Ensure that it is initialized.
		 * Note that this places the entry for the end block first, so we must fix this.
		 * env.backwards points to th last block for this purpose.
		 */
		prepare_blocks(env.end_bl, NULL);

		bl               = env.forward;
		env.forward      = bl->forward_next;
		bl->forward_next = NULL;

		env.backward->forward_next = bl;
	}

1650
1651
1652
	/* second step: find and sort all memory ops */
	walk_memory_irg(irg, collect_memops, NULL, NULL);

Michael Beck's avatar
BugFix:    
Michael Beck committed
1653
1654
1655
1656
1657
	if (env.n_mem_ops == 0) {
		/* no memory ops */
		goto end;
	}

1658
	/* create the backward links */
1659
	env.backward = NULL;
1660
1661
	irg_block_walk_graph(irg, NULL, collect_backward, NULL);

1662
1663
1664
1665
1666
	/* link the end block in */
	bl = get_block_entry(env.end_bl);
	bl->backward_next = env.backward;
	env.backward      = bl;

1667
1668
	/* check that we really start with the start / end block */
	assert(env.forward->block  == env.start_bl);
1669
	assert(env.backward->block == env.end_bl);
1670
1671
1672
1673
1674
1675
1676

	/* create address sets: we know that 2 * n_mem_ops - 1 is an upper bound for all possible addresses */
	env.rbs_size = 2 * env.n_mem_ops;

	/* create the current set */
	env.curr_set = rbitset_obstack_alloc(&env.obst, env.rbs_size);
	rbitset_set(env.curr_set, env.rbs_size - 1);
Michael Beck's avatar
Michael Beck committed
1677
1678
	env.curr_id_2_memop = NEW_ARR_D(memop_t *, &env.obst, env.rbs_size);
	memset(env.curr_id_2_memop, 0, env.rbs_size * sizeof(env.curr_id_2_memop[0]));
1679
1680
1681
1682
1683
1684
1685

	for (bl = env.forward; bl != NULL; bl = bl->forward_next) {
		/* set sentinel bits */
		bl->avail_out  = rbitset_obstack_alloc(&env.obst, env.rbs_size);
		rbitset_set(bl->avail_out, env.rbs_size - 1);

		bl->id_2_memop_avail = NEW_ARR_D(memop_t *, &env.obst, env.rbs_size);
Michael Beck's avatar
Michael Beck committed
1686
		memset(bl->id_2_memop_avail, 0, env.rbs_size * sizeof(bl->id_2_memop_avail[0]));
1687
1688
1689
1690

		bl->anticL_in  = rbitset_obstack_alloc(&env.obst, env.rbs_size);
		rbitset_set(bl->anticL_in, env.rbs_size - 1);

Michael Beck's avatar
Michael Beck committed
1691
1692
		bl->id_2_memop_antic = NEW_ARR_D(memop_t *, &env.obst, env.rbs_size);
		memset(bl->id_2_memop_antic, 0, env.rbs_size * sizeof(bl->id_2_memop_antic[0]));
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
	}

//	dump_block_list(&env);

	calcAvail();
	calcAntic();

	insert_Loads_upwards();

	if (env.changed) {
		/* over all blocks in reverse post order */
		for (bl = env.forward; bl != NULL; bl = bl->forward_next) {
			do_replacements(bl);
		}

Michael Beck's avatar
Michael Beck committed
1708
1709
1710
		/* not only invalidate but free them. We might allocate new out arrays
		   on our obstack which will be deleted yet. */
		free_irg_outs(irg);
1711
1712
		set_irg_entity_usage_state(irg, ir_entity_usage_not_computed);
	}
Michael Beck's avatar
BugFix:    
Michael Beck committed
1713
end:
1714
1715
1716
1717
1718

	ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
	ir_nodemap_destroy(&env.adr_map);
	obstack_free(&env.obst, NULL);

Michael Beck's avatar
Michael Beck committed
1719
1720
	dump_ir_block_graph(irg, "-YYY");

1721
1722
1723
1724
	current_ir_graph = rem;

	return env.changed != 0;
}