opt_ldst.c 63.2 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
/*
 * 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"
Michael Beck's avatar
Michael Beck committed
39
40
#include "iropt.h"
#include "iroptimize.h"
41
42
43
44
45
#include "irnodemap.h"
#include "raw_bitset.h"
#include "debug.h"
#include "error.h"

46
47
48
/* maximum number of output Proj's */
#define MAX_PROJ (pn_Load_max > pn_Store_max ? pn_Load_max : pn_Store_max)

49
/**
50
 * Mapping an address to an dense ID.
51
52
53
54
55
56
57
58
59
 */
typedef struct address_entry_t {
	unsigned id;          /**< The ID */
} address_entry;

/**
 * Memop-flags.
 */
enum memop_flags {
60
61
62
63
	FLAG_KILL_ALL    = 1, /**< KILL all addresses */
	FLAG_KILLED_NODE = 2, /**< this node was killed */
	FLAG_EXCEPTION   = 4, /**< this node has exception flow */
	FLAG_IGNORE      = 8, /**< ignore this node (volatile or other) */
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
};

/**
 * 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 */
92
	ir_node  *projs[MAX_PROJ]; /**< Projs of this memory op */
93
94
95
96
97
98
99
100
101
102
103
104
};

/**
 * 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
105
	memop_t  **id_2_memop_antic; /**< maps anticipated address ids to memops */
106
107
108
109
	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 */
110
	memop_t  **trans_results;    /**< used to cached translated nodes due antic calculation. */
111
112
113
114
115
116
};

/**
 * Metadata for this pass.
 */
typedef struct ldst_env_t {
Michael Beck's avatar
Michael Beck committed
117
118
119
120
121
122
123
124
125
126
127
	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 */
128
	int             max_cfg_preds;     /**< maximum number of block cfg predecessors */
Michael Beck's avatar
Michael Beck committed
129
	int             changed;           /**< Flags for changed graph state */
130
131
132
#ifdef DEBUG_libfirm
	ir_node         **id_2_address;    /**< maps an id to the used address */
#endif
133
134
} ldst_env;

135
136
137
/* the one and only environment */
static ldst_env env;

138
139
140
141
142
143
144
145
146
#ifdef DEBUG_libfirm

static firm_dbg_module_t *dbg;

/**
 * Dumps the block list.
 *
 * @param ldst environment
 */
Michael Beck's avatar
Michael Beck committed
147
static void dump_block_list(ldst_env *env) {
148
149
150
151
152
153
154
155
156
157
158
159
160
161
	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"));
162
163
			else if (op->flags & FLAG_KILL_ALL)
				DB((dbg, LEVEL_2, "K"));
164
165
166
167
168
169
			DB((dbg, LEVEL_2, ", "));

			i = (i + 1) & 3;
		}
		DB((dbg, LEVEL_2, "\n}\n\n"));
	}
170
}  /* dump_block_list */
171
172
173
174
175
176
177
178

/**
 * Dumps the current set.
 *
 * @param bl   current block
 * @param s    name of the set
 */
static void dump_curr(block_t *bl, const char *s) {
179
	unsigned end = env.rbs_size - 1;
180
	unsigned pos;
181
182
183
184
	int      i;

	DB((dbg, LEVEL_2, "%s[%+F] = {", s, bl->block));
	i = 0;
185
	for (pos = rbitset_next(env.curr_set, 0, 1); pos < end; pos = rbitset_next(env.curr_set, pos + 1, 1)) {
Michael Beck's avatar
Michael Beck committed
186
		memop_t *op = env.curr_id_2_memop[pos];
187
188
189
190

		if (i == 0) {
			DB((dbg, LEVEL_2, "\n\t"));
		}
191

192
193
194
195
		DB((dbg, LEVEL_2, "<%+F, %+F>, ", op->value.address, op->value.value));
		i = (i + 1) & 3;
	}
	DB((dbg, LEVEL_2, "\n}\n"));
196
}  /* dump_curr */
197
198

#else
199
200
201
202
203
204
205
static void dump_block_list(ldst_env *env) {
	(void) env;
}
static void dump_curr(block_t *bl, const char *s) {
	(void) bl;
	(void) s;
}
206
207
#endif /* DEBUG_libfirm */

208
209
210
211
212
/** 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);
213
}  /* get_block_entry */
214
215
216
217
218

/** 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);
219
}  /* get_irn_memop */
220

221
222
/**
 * Walk over the memory edges from definition to users.
Michael Beck's avatar
Michael Beck committed
223
 * This ensures, that even operation without memory output are found.
224
225
226
227
228
229
 *
 * @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
230
static void walk_memory(ir_node *irn, irg_walk_func *pre, irg_walk_func *post, void *ctx) {
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
	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);
259
}  /* walk_memory */
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280

/**
 * 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);
281
}  /* walk_memory_irg */
282
283

/**
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
 * Register an address and allocate a (sparse, 0..n) ID for it.
 *
 * @param adr  the IR-node representing the address
 *
 * @return the allocated id
 */
static unsigned register_address(ir_node *adr) {
	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);

	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);

		DB((dbg, LEVEL_3, "ADDRESS %+F has ID %u\n", adr, entry->id));
#ifdef DEBUG_libfirm
		ARR_APP1(ir_node *, env.id_2_address, adr);
#endif
	}
	return entry->id;
}  /* register_address */


/**
 * translate an address through a Phi node into a given predecessor
 * block.
 *
 * @param address  the address
 * @param block    the block
 * @param pos      the position of the predecessor in block
 */
static ir_node *phi_translate(ir_node *address, const ir_node *block, int pos) {
	if (is_Phi(address) && get_nodes_block(address) == block)
		address = get_Phi_pred(address, pos);
	return address;
}  /* phi_translate */

/**
 * Walker: allocate an block entry for every block
 * and register all potential addresses.
339
 */
340
static void prepare_blocks(ir_node *irn, void *ctx) {
341
	(void)ctx;
342

343
	if (is_Block(irn)) {
344
345
346
347
348
349
350
351
352
		block_t *entry = obstack_alloc(&env.obst, sizeof(*entry));
		int     n;

		entry->memop_forward    = NULL;
		entry->memop_backward   = NULL;
		entry->avail_out        = NULL;
		entry->id_2_memop_avail = NULL;
		entry->anticL_in        = NULL;
		entry->id_2_memop_antic = NULL;
353
		entry->block            = irn;
354
355
356
		entry->forward_next     = NULL;
		entry->backward_next    = NULL;
		entry->avail            = NULL;
357
358
		entry->trans_results    = NULL;
		set_irn_link(irn, entry);
359

360
		set_Block_phis(irn, NULL);
361
362

		/* use block marks to track unreachable blocks */
363
		set_Block_mark(irn, 0);
364

365
		n = get_Block_n_cfgpreds(irn);
366
367
		if (n > env.max_cfg_preds)
			env.max_cfg_preds = n;
368
369
370
371
372
373
374
375
376
377
378
	} else {
		ir_mode *mode = get_irn_mode(irn);

		if (mode_is_reference(mode)) {
			/*
			 * Register ALL possible addresses: this is overkill yet but
			 * simpler then doing it for all possible translated addresses
			 * (which would be sufficient in the moment.
			 */
			(void)register_address(irn);
		}
379
	}
380
}  /* prepare_blocks */
381
382
383
384
385

/**
 * Post-Walker, link in all Phi's
 */
static void link_phis(ir_node *irn, void *ctx) {
386
	(void)ctx;
387

388
389
390
391
	if (is_Phi(irn)) {
		ir_node *block = get_nodes_block(irn);
		add_Block_phi(block, irn);
	}
392
}  /* link_phis */
393
394
395
396
397
398
399
400

/**
 * Block walker: creates the inverse post-order list for the CFG.
 */
static void inverse_post_order(ir_node *block, void *ctx) {
	block_t *entry = get_block_entry(block);

	(void)ctx;
401

402
403
404
	/* mark this block IS reachable from start */
	set_Block_mark(block, 1);

405
	/* create the list in inverse order */
406
407
408
409
410
411
	entry->forward_next = env.forward;
	env.forward         = entry;

	/* remember the first visited (last in list) entry, needed for later */
	if (env.backward == NULL)
		env.backward = entry;
412
}  /* inverse_post_order */
413
414
415
416
417
418
419
420

/**
 * 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;

421
	(void)ctx;
422

423
424
425
426
427
428
429
430
431
432
433
	/*
	 * 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;
	}
434
435
436
437
438
439
440
441

	/* 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;
442
}  /* collect_backward */
443
444
445
446

/**
 * Allocate a memop.
 *
447
448
449
450
 * @param irn  the IR-node representing the memop or NULL
 *             if this is a translated (virtual) memop
 *
 * @return the allocated memop
451
452
453
454
455
456
457
458
459
 */
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;
Michael Beck's avatar
Michael Beck committed
460
	m->mem           = NULL;
461
462
463
464
	m->replace       = NULL;
	m->next          = NULL;
	m->flags         = 0;

465
466
	memset(m->projs, 0, sizeof(m->projs));

467
468
	if (irn != NULL)
		set_irn_link(irn, m);
469
	return m;
470
}  /* alloc_memop */
471

Michael Beck's avatar
Michael Beck committed
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/**
 * 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;
491
}  /* clone_memop_phi */
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515

/**
 * 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);
516
}  /* get_Call_memory_properties */
517

Michael Beck's avatar
Michael Beck committed
518
519
520
521
522
523
524
/**
 * Returns an entity if the address ptr points to a constant one.
 *
 * @param ptr  the address
 *
 * @return an entity or NULL
 */
525
static ir_entity *find_constant_entity(ir_node *ptr) {
Michael Beck's avatar
Michael Beck committed
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
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
666
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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
	for (;;) {
		if (is_SymConst(ptr) && get_SymConst_kind(ptr) == symconst_addr_ent) {
			return get_SymConst_entity(ptr);
		} else if (is_Sel(ptr)) {
			ir_entity *ent = get_Sel_entity(ptr);
			ir_type   *tp  = get_entity_owner(ent);

			/* Do not fiddle with polymorphism. */
			if (is_Class_type(get_entity_owner(ent)) &&
				((get_entity_n_overwrites(ent)    != 0) ||
				(get_entity_n_overwrittenby(ent) != 0)   ) )
				return NULL;

			if (is_Array_type(tp)) {
				/* check bounds */
				int i, n;

				for (i = 0, n = get_Sel_n_indexs(ptr); i < n; ++i) {
					ir_node *bound;
					tarval *tlower, *tupper;
					ir_node *index = get_Sel_index(ptr, i);
					tarval *tv     = computed_value(index);

					/* check if the index is constant */
					if (tv == tarval_bad)
						return NULL;

					bound  = get_array_lower_bound(tp, i);
					tlower = computed_value(bound);
					bound  = get_array_upper_bound(tp, i);
					tupper = computed_value(bound);

					if (tlower == tarval_bad || tupper == tarval_bad)
						return NULL;

					if (tarval_cmp(tv, tlower) & pn_Cmp_Lt)
						return NULL;
					if (tarval_cmp(tupper, tv) & pn_Cmp_Lt)
						return NULL;

					/* ok, bounds check finished */
				}
			}

			if (variability_constant == get_entity_variability(ent))
				return ent;

			/* try next */
			ptr = get_Sel_ptr(ptr);
		} else if (is_Add(ptr)) {
			ir_node *l = get_Add_left(ptr);
			ir_node *r = get_Add_right(ptr);

			if (get_irn_mode(l) == get_irn_mode(ptr) && is_Const(r))
				ptr = l;
			else if (get_irn_mode(r) == get_irn_mode(ptr) && is_Const(l))
				ptr = r;
			else
				return NULL;

			/* for now, we support only one addition, reassoc should fold all others */
			if (! is_SymConst(ptr) && !is_Sel(ptr))
				return NULL;
		} else if (is_Sub(ptr)) {
			ir_node *l = get_Sub_left(ptr);
			ir_node *r = get_Sub_right(ptr);

			if (get_irn_mode(l) == get_irn_mode(ptr) &&	is_Const(r))
				ptr = l;
			else
				return NULL;
			/* for now, we support only one subtraction, reassoc should fold all others */
			if (! is_SymConst(ptr) && !is_Sel(ptr))
				return NULL;
		} else
			return NULL;
	}
}  /* find_constant_entity */

/**
 * Return the Selection index of a Sel node from dimension n
 */
static long get_Sel_array_index_long(ir_node *n, int dim) {
	ir_node *index = get_Sel_index(n, dim);
	assert(is_Const(index));
	return get_tarval_long(get_Const_tarval(index));
}  /* get_Sel_array_index_long */

/**
 * Returns the accessed component graph path for an
 * node computing an address.
 *
 * @param ptr    the node computing the address
 * @param depth  current depth in steps upward from the root
 *               of the address
 */
static compound_graph_path *rec_get_accessed_path(ir_node *ptr, int depth) {
	compound_graph_path *res = NULL;
	ir_entity           *root, *field, *ent;
	int                 path_len, pos, idx;
	tarval              *tv;
	ir_type             *tp;

	if (is_SymConst(ptr)) {
		/* a SymConst. If the depth is 0, this is an access to a global
		 * entity and we don't need a component path, else we know
		 * at least its length.
		 */
		assert(get_SymConst_kind(ptr) == symconst_addr_ent);
		root = get_SymConst_entity(ptr);
		res = (depth == 0) ? NULL : new_compound_graph_path(get_entity_type(root), depth);
	} else if (is_Sel(ptr)) {
		/* it's a Sel, go up until we find the root */
		res = rec_get_accessed_path(get_Sel_ptr(ptr), depth+1);
		if (res == NULL)
			return NULL;

		/* fill up the step in the path at the current position */
		field    = get_Sel_entity(ptr);
		path_len = get_compound_graph_path_length(res);
		pos      = path_len - depth - 1;
		set_compound_graph_path_node(res, pos, field);

		if (is_Array_type(get_entity_owner(field))) {
			assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
			set_compound_graph_path_array_index(res, pos, get_Sel_array_index_long(ptr, 0));
		}
	} else if (is_Add(ptr)) {
		ir_node *l    = get_Add_left(ptr);
		ir_node *r    = get_Add_right(ptr);
		ir_mode *mode = get_irn_mode(ptr);
		tarval  *tmp;

		if (is_Const(r) && get_irn_mode(l) == mode) {
			ptr = l;
			tv  = get_Const_tarval(r);
		} else {
			ptr = r;
			tv  = get_Const_tarval(l);
		}
ptr_arith:
		mode = get_tarval_mode(tv);
		tmp  = tv;

		/* ptr must be a Sel or a SymConst, this was checked in find_constant_entity() */
		if (is_Sel(ptr)) {
			field = get_Sel_entity(ptr);
		} else {
			field = get_SymConst_entity(ptr);
		}
		idx = 0;
		for (ent = field;;) {
			unsigned size;
			tarval   *sz, *tv_index, *tlower, *tupper;
			ir_node  *bound;

			tp = get_entity_type(ent);
			if (! is_Array_type(tp))
				break;
			ent = get_array_element_entity(tp);
			size = get_type_size_bytes(get_entity_type(ent));
			sz   = new_tarval_from_long(size, mode);

			tv_index = tarval_div(tmp, sz);
			tmp      = tarval_mod(tmp, sz);

			if (tv_index == tarval_bad || tmp == tarval_bad)
				return NULL;

			assert(get_array_n_dimensions(tp) == 1 && "multiarrays not implemented");
			bound  = get_array_lower_bound(tp, 0);
			tlower = computed_value(bound);
			bound  = get_array_upper_bound(tp, 0);
			tupper = computed_value(bound);

			if (tlower == tarval_bad || tupper == tarval_bad)
				return NULL;

			if (tarval_cmp(tv_index, tlower) & pn_Cmp_Lt)
				return NULL;
			if (tarval_cmp(tupper, tv_index) & pn_Cmp_Lt)
				return NULL;

			/* ok, bounds check finished */
			++idx;
		}
		if (! tarval_is_null(tmp)) {
			/* access to some struct/union member */
			return NULL;
		}

		/* should be at least ONE array */
		if (idx == 0)
			return NULL;

		res = rec_get_accessed_path(ptr, depth + idx);
		if (res == NULL)
			return NULL;

		path_len = get_compound_graph_path_length(res);
		pos      = path_len - depth - idx;

		for (ent = field;;) {
			unsigned size;
			tarval   *sz, *tv_index;
			long     index;

			tp = get_entity_type(ent);
			if (! is_Array_type(tp))
				break;
			ent = get_array_element_entity(tp);
			set_compound_graph_path_node(res, pos, ent);

			size = get_type_size_bytes(get_entity_type(ent));
			sz   = new_tarval_from_long(size, mode);

			tv_index = tarval_div(tv, sz);
			tv       = tarval_mod(tv, sz);

			/* worked above, should work again */
			assert(tv_index != tarval_bad && tv != tarval_bad);

			/* bounds already checked above */
			index = get_tarval_long(tv_index);
			set_compound_graph_path_array_index(res, pos, index);
			++pos;
		}
	} else if (is_Sub(ptr)) {
		ir_node *l = get_Sub_left(ptr);
		ir_node *r = get_Sub_right(ptr);

		ptr = l;
		tv  = get_Const_tarval(r);
		tv  = tarval_neg(tv);
		goto ptr_arith;
	}
	return res;
}  /* rec_get_accessed_path */

/**
 * Returns an access path or NULL.  The access path is only
 * valid, if the graph is in phase_high and _no_ address computation is used.
 */
static compound_graph_path *get_accessed_path(ir_node *ptr) {
	compound_graph_path *gr = rec_get_accessed_path(ptr, 0);
	return gr;
}  /* get_accessed_path */

typedef struct path_entry {
	ir_entity         *ent;
	struct path_entry *next;
	long              index;
} path_entry;

static ir_node *rec_find_compound_ent_value(ir_node *ptr, path_entry *next) {
	path_entry       entry, *p;
	ir_entity        *ent, *field;
	ir_initializer_t *initializer;
	tarval           *tv;
	ir_type          *tp;
	unsigned         n;

	entry.next = next;
	if (is_SymConst(ptr)) {
		/* found the root */
		ent         = get_SymConst_entity(ptr);
		initializer = get_entity_initializer(ent);
		for (p = next; p != NULL;) {
			if (initializer->kind != IR_INITIALIZER_COMPOUND)
				return NULL;
			n  = get_initializer_compound_n_entries(initializer);
			tp = get_entity_type(ent);

			if (is_Array_type(tp)) {
				ent = get_array_element_entity(tp);
				if (ent != p->ent) {
					/* a missing [0] */
					if (0 >= n)
						return NULL;
					initializer = get_initializer_compound_value(initializer, 0);
					continue;
				}
			}
			if (p->index >= (int) n)
				return NULL;
			initializer = get_initializer_compound_value(initializer, p->index);

			ent = p->ent;
			p   = p->next;
		}
		tp = get_entity_type(ent);
		while (is_Array_type(tp)) {
			ent = get_array_element_entity(tp);
			tp = get_entity_type(ent);
			/* a missing [0] */
			n  = get_initializer_compound_n_entries(initializer);
			if (0 >= n)
				return NULL;
			initializer = get_initializer_compound_value(initializer, 0);
		}

		switch (initializer->kind) {
		case IR_INITIALIZER_CONST:
			return get_initializer_const_value(initializer);
		case IR_INITIALIZER_TARVAL:
		case IR_INITIALIZER_NULL:
		default:
			return NULL;
		}
	} else if (is_Sel(ptr)) {
		entry.ent = field = get_Sel_entity(ptr);
		tp = get_entity_owner(field);
		if (is_Array_type(tp)) {
			assert(get_Sel_n_indexs(ptr) == 1 && "multi dim arrays not implemented");
			entry.index = get_Sel_array_index_long(ptr, 0) - get_array_lower_bound_int(tp, 0);
		} else {
			int i, n_members = get_compound_n_members(tp);
			for (i = 0; i < n_members; ++i) {
				if (get_compound_member(tp, i) == field)
					break;
			}
			if (i >= n_members) {
				/* not found: should NOT happen */
				return NULL;
			}
			entry.index = i;
		}
		return rec_find_compound_ent_value(get_Sel_ptr(ptr), &entry);
	}  else if (is_Add(ptr)) {
		ir_node  *l = get_Add_left(ptr);
		ir_node  *r = get_Add_right(ptr);
		ir_mode  *mode;
		unsigned pos;

		if (is_Const(r)) {
			ptr = l;
			tv  = get_Const_tarval(r);
		} else {
			ptr = r;
			tv  = get_Const_tarval(l);
		}
ptr_arith:
		mode = get_tarval_mode(tv);

		/* ptr must be a Sel or a SymConst, this was checked in find_constant_entity() */
		if (is_Sel(ptr)) {
			field = get_Sel_entity(ptr);
		} else {
			field = get_SymConst_entity(ptr);
		}

		/* count needed entries */
		pos = 0;
		for (ent = field;;) {
			tp = get_entity_type(ent);
			if (! is_Array_type(tp))
				break;
			ent = get_array_element_entity(tp);
			++pos;
		}
		/* should be at least ONE entry */
		if (pos == 0)
			return NULL;

		/* allocate the right number of entries */
		NEW_ARR_A(path_entry, p, pos);

		/* fill them up */
		pos = 0;
		for (ent = field;;) {
			unsigned size;
			tarval   *sz, *tv_index, *tlower, *tupper;
			long     index;
			ir_node  *bound;

			tp = get_entity_type(ent);
			if (! is_Array_type(tp))
				break;
			ent = get_array_element_entity(tp);
			p[pos].ent  = ent;
			p[pos].next = &p[pos + 1];

			size = get_type_size_bytes(get_entity_type(ent));
			sz   = new_tarval_from_long(size, mode);

			tv_index = tarval_div(tv, sz);
			tv       = tarval_mod(tv, sz);

			if (tv_index == tarval_bad || tv == tarval_bad)
				return NULL;

			assert(get_array_n_dimensions(tp) == 1 && "multiarrays not implemented");
			bound  = get_array_lower_bound(tp, 0);
			tlower = computed_value(bound);
			bound  = get_array_upper_bound(tp, 0);
			tupper = computed_value(bound);

			if (tlower == tarval_bad || tupper == tarval_bad)
				return NULL;

			if (tarval_cmp(tv_index, tlower) & pn_Cmp_Lt)
				return NULL;
			if (tarval_cmp(tupper, tv_index) & pn_Cmp_Lt)
				return NULL;

			/* ok, bounds check finished */
			index = get_tarval_long(tv_index);
			p[pos].index = index;
			++pos;
		}
		if (! tarval_is_null(tv)) {
			/* hmm, wrong access */
			return NULL;
		}
		p[pos - 1].next = next;
		return rec_find_compound_ent_value(ptr, p);
	} else if (is_Sub(ptr)) {
		ir_node *l = get_Sub_left(ptr);
		ir_node *r = get_Sub_right(ptr);

		ptr = l;
		tv  = get_Const_tarval(r);
		tv  = tarval_neg(tv);
		goto ptr_arith;
	}
	return NULL;
}  /* rec_find_compound_ent_value */

static ir_node *find_compound_ent_value(ir_node *ptr) {
	return rec_find_compound_ent_value(ptr, NULL);
}  /* find_compound_ent_value */

/**
 * 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_replace_load */

/**
 * 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;
}  /* mark_remove_store */

979
980
981
982
983
984
/**
 * Update a memop for a Load.
 *
 * @param m  the memop
 */
static void update_Load_memop(memop_t *m) {
Michael Beck's avatar
Michael Beck committed
985
986
987
988
	int       i;
	ir_node   *load = m->node;
	ir_node   *ptr;
	ir_entity *ent;
989
990
991
992

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

Michael Beck's avatar
Michael Beck committed
993
994
995
	ptr = get_Load_ptr(load);

	m->value.address = ptr;
996
997
998

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

1001
1002
1003
1004
		/* beware of keep edges */
		if (is_End(proj))
			continue;

1005
1006
1007
		pn = get_Proj_proj(proj);
		m->projs[pn] = proj;
		switch (pn) {
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
		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;
1018
1019
1020
1021
		case pn_Load_X_regular:
			break;
		default:
			panic("Unsupported Proj from Load %+F", proj);
1022
1023
1024
		}
	}

Michael Beck's avatar
Michael Beck committed
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
	/* check if we can determine the entity that will be loaded */
	ent = find_constant_entity(ptr);

	if (ent != NULL                                     &&
		allocation_static == get_entity_allocation(ent) &&
		visibility_external_allocated != get_entity_visibility(ent)) {
		/* a static allocation that is not external: there should be NO exception
		 * when loading even if we cannot replace the load itself. */
		ir_node *value = NULL;

		/* no exception, clear the m fields as it might be checked later again */
		if (m->projs[pn_Load_X_except]) {
			exchange(m->projs[pn_Load_X_except], new_Bad());
			m->projs[pn_Load_X_except] = NULL;
			m->flags &= ~FLAG_EXCEPTION;
			env.changed = 1;
		}
		if (m->projs[pn_Load_X_regular]) {
1043
			exchange(m->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
Michael Beck's avatar
Michael Beck committed
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
			m->projs[pn_Load_X_regular] = NULL;
			env.changed = 1;
		}

		if (variability_constant == get_entity_variability(ent)) {
			if (is_atomic_entity(ent)) {
				/* Might not be atomic after lowering of Sels.  In this case we
				 * could also load, but it's more complicated. */
				/* more simpler case: we load the content of a constant value:
				 * replace it by the constant itself */
				value = get_atomic_ent_value(ent);
			} else if (ent->has_initializer) {
				/* new style initializer */
				value = find_compound_ent_value(ptr);
			} else {
				/* old style initializer */
				compound_graph_path *path = get_accessed_path(ptr);

				if (path != NULL) {
					assert(is_proper_compound_graph_path(path, get_compound_graph_path_length(path)-1));

					value = get_compound_ent_value_by_path(ent, path);
					DB((dbg, LEVEL_1, "  Constant access at %F%F resulted in %+F\n", ent, path, value));
					free_compound_graph_path(path);
				}
			}
			if (value != NULL)
				value = can_replace_load_by_const(load, value);
		}

		if (value != NULL) {
			/* we completely replace the load by this value */
			DB((dbg, LEVEL_1, "Replacing Load %+F by constant %+F\n", m->node, value));
			mark_replace_load(m, value);
			return;
		}
	}

1082
1083
	if (m->value.value != NULL && !(m->flags & FLAG_IGNORE)) {
		/* only create an address if this node is NOT killed immediately or ignored */
Michael Beck's avatar
Michael Beck committed
1084
		m->value.id = register_address(ptr);
1085
1086
1087
		++env.n_mem_ops;
	} else {
		/* no user, KILL it */
1088
		mark_replace_load(m, NULL);
1089
	}
1090
}  /* update_Load_memop */
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113

/**
 * 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);
1114
		long    pn;
1115

1116
1117
1118
1119
		/* beware of keep edges */
		if (is_End(proj))
			continue;

1120
1121
1122
		pn = get_Proj_proj(proj);
		m->projs[pn] = proj;
		switch (pn) {
1123
1124
1125
1126
1127
1128
		case pn_Store_X_except:
			m->flags |= FLAG_EXCEPTION;
			break;
		case pn_Store_M:
			m->mem = proj;
			break;
1129
1130
1131
1132
		case pn_Store_X_regular:
			break;
		default:
			panic("Unsupported Proj from Store %+F", proj);
1133
1134
1135
1136
		}
	}
	m->value.value = get_Store_value(store);
	m->value.mode  = get_irn_mode(m->value.value);
1137
}  /* update_Store_memop */
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153

/**
 * 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 */
1154
		m->flags = 0;
1155
1156
1157
1158
1159
1160
	} 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);

1161
1162
1163
1164
		/* beware of keep edges */
		if (is_End(proj))
			continue;

1165
1166
1167
1168
1169
1170
1171
1172
1173
		switch (get_Proj_proj(proj)) {
		case pn_Call_X_except:
			m->flags |= FLAG_EXCEPTION;
			break;
		case pn_Call_M_regular:
			m->mem = proj;
			break;
		}
	}
1174
}  /* update_Call_memop */
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187

/**
 * 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);

1188
1189
1190
1191
		/* beware of keep edges */
		if (is_End(proj))
			continue;

1192
1193
1194
1195
1196
1197
1198
1199
1200
		switch (get_Proj_proj(proj)) {
		case pn_Generic_X_except:
			m->flags |= FLAG_EXCEPTION;
			break;
		case pn_Generic_M_regular:
			m->mem = proj;
			break;
		}
	}
1201
}  /* update_DivOp_memop */
1202

Michael Beck's avatar
Michael Beck committed
1203
1204
1205
1206
1207
1208
1209
1210
/**
 * 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;
1211
}  /* update_Phi_memop */
Michael Beck's avatar
Michael Beck committed
1212

1213
1214
1215
1216
1217
1218
1219
1220
/**
 * 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
1221
	(void) ctx;
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
	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
1233
		update_Phi_memop(op);
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
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
		/* 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;
		}
	}
1285
}  /* collect_memops */
1286
1287
1288
1289
1290

/**
 * Find an address in the current set.
 *
 * @param value  the value to be searched for
1291
1292
1293
1294
 *
 * @return a memop for the value or NULL if the value does
 *         not exists in the set or cannot be converted into
 *         the requested mode
1295
 */
1296
static memop_t *find_address(const value_t *value) {
1297
	if (rbitset_is_set(env.curr_set, value->id)) {
Michael Beck's avatar
Michael Beck committed
1298
		memop_t *res = env.curr_id_2_memop[value->id];
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308

		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;
1309
}  /* find_address */
1310
1311
1312
1313
1314
1315

/**
 * Find an address in the avail_out set.
 *
 * @param bl     the block
 */
Michael Beck's avatar
Michael Beck committed
1316
1317
1318
static memop_t *find_address_avail(const block_t *bl, unsigned id, const ir_mode *mode) {
	if (rbitset_is_set(bl->avail_out, id)) {
		memop_t *res = bl->id_2_memop_avail[id];
1319

Michael Beck's avatar
Michael Beck committed
1320
		if (res->value.mode == mode)
1321
1322
1323
			return res;
		/* allow hidden casts */
		if (get_mode_arithmetic(res->value.mode) == irma_twos_complement &&
Michael Beck's avatar
Michael Beck committed
1324
1325
		    get_mode_arithmetic(mode) == irma_twos_complement &&
		    get_mode_size_bits(res->value.mode) == get_mode_size_bits(mode))
1326
1327
1328
			return res;
	}
	return NULL;
1329
}  /* find_address_avail */
1330
1331
1332
1333
1334
1335
1336
1337
1338

/**
 * 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);
1339
}  /* kill_all */
1340
1341
1342
1343
1344
1345

/**
 * 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
1346
static void kill_memops(const value_t *value) {
1347
	unsigned end = env.rbs_size - 1;
1348
	unsigned pos;
1349

1350
	for (pos = rbitset_next(env.curr_set, 0, 1); pos < end; pos = rbitset_next(env.curr_set, pos + 1, 1)) {
Michael Beck's avatar
Michael Beck committed
1351
		memop_t *op = env.curr_id_2_memop[pos];
1352
1353
1354
1355

		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
1356
			env.curr_id_2_memop[pos] = NULL;
1357
			DB((dbg, LEVEL_2, "KILLING %+F because of possible alias address %+F\n", op->node, value->address));
1358
1359
		}
	}
1360
}  /* kill_memops */
1361
1362
1363
1364
1365
1366

/**
 * Add the value of a memop to the current set.
 *
 * @param op  the memory op
 */
Michael Beck's avatar
Michael Beck committed
1367
static void add_memop(memop_t *op) {
1368
	rbitset_set(env.curr_set, op->value.id);
Michael Beck's avatar
Michael Beck committed
1369
	env.curr_id_2_memop[op->value.id] = op;
1370
}  /* add_memop */
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380

/**
 * 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;
1381
}  /* add_memop_avail */
1382

Michael Beck's avatar
Michael Beck committed
1383
1384
1385
/**
 * Check, if we can convert a value of one mode to another mode
 * without changing the representation of bits.
1386
1387
1388
 *
 * @param from  the original mode
 * @param to    the destination mode
Michael Beck's avatar
Michael Beck committed
1389
1390
1391
1392
1393
1394
1395
 */
static int can_convert_to(const ir_mode *from, const ir_mode *to) {
	if (get_mode_arithmetic(from) == irma_twos_complement &&
	    get_mode_arithmetic(to) == irma_twos_complement &&
	    get_mode_size_bits(from) == get_mode_size_bits(to))
		return 1;
	return 0;
1396
}  /* can_convert_to */
Michael Beck's avatar
Michael Beck committed
1397

1398
/**
1399
1400
1401
1402
1403
1404
1405
 * Add a Conv to the requested mode if needed.
 *
 * @param irn   the IR-node to convert
 * @param mode  the destination mode
 *
 * @return the possible converted node or NULL
 *         if the conversion is not possible
1406
1407
 */
static ir_node *conv_to(ir_node *irn, ir_mode *mode) {
1408
1409
1410
	ir_mode *other = get_irn_mode(irn);
	if (other != mode) {
		/* different modes: check if conversion is possible without changing the bits */
Michael Beck's avatar
Michael Beck committed
1411
		if (can_convert_to(other, mode)) {
1412
			ir_node *block = get_nodes_block(irn);
1413
			return new_r_Conv(block, irn, mode);
1414
		}
1415
1416
		/* otherwise not possible ... yet */
		return NULL;
1417
	}
1418
	return irn;
1419
}  /* conv_to */
1420

1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
/**
 * Update the address of an value if this address was a load result
 * and the load is killed now.
 *
 * @param value  the value whose address is updated
 */
static void update_address(value_t *value) {
	if (is_Proj(value->address)) {
		ir_node *load = get_Proj_pred(value->address);

		if (is_Load(load)) {
			const memop_t *op = get_irn_memop(load);

			if (op->flags & FLAG_KILLED_NODE)
				value->address = op->replace;
		}
	}
1438
}  /* update_address */
1439

1440
/**
Michael Beck's avatar
Michael Beck committed
1441
1442
 * Do forward dataflow analysis on the given block and calculate the
 * GEN and KILL in the current (avail) set.
1443
1444
1445
 *
 * @param bl  the block
 */
Michael Beck's avatar
Michael Beck committed
1446
static void calc_gen_kill_avail(block_t *bl) {
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
	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? */
1461
1462
1463
1464
				memop_t *other;

				update_address(&op->value);
				other = find_address(&op->value);
1465
1466
				if (other != NULL && other != op) {
					def = conv_to(other->value.value, op->value.mode);
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
					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);
1478
1479
						/* do NOT change the memop table */
						continue;
1480
1481
					}
				}
1482
1483
				/* add this value */
				add_memop(op);
1484
1485
1486
			}
			break;
		case iro_Store:
1487
			if (! (op->flags & FLAG_KILLED_NODE)) {
1488
				/* do we have this store already */
1489
1490
1491
1492
				memop_t *other;

				update_address(&op->value);
				other = find_address(&op->value);
1493
				if (other != NULL) {
Michael Beck's avatar
Michael Beck committed
1494
					if (is_Store(other->node)) {
1495
1496
						if (op != other && !(other->flags & FLAG_IGNORE) &&
						    get_nodes_block(other->node) == get_nodes_block(op->node)) {
Michael Beck's avatar
Michael Beck committed
1497
1498
1499
1500
1501
							/*
							 * 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.
							 */
1502
							DB((dbg, LEVEL_1, "WAW %+F <- %+F\n", other->node, op->node));
Michael Beck's avatar
Michael Beck committed
1503
1504
1505
							mark_remove_store(other);
							/* FIXME: a Load might be get freed due to this killed store */
						}
1506
					} else if (other->value.value == op->value.value && !(op->flags & FLAG_IGNORE)) {
1507
						/* WAR */
1508
						DB((dbg, LEVEL_1, "WAR %+F <- %+F\n", op->node, other->node));
1509
						mark_remove_store(op);
1510
1511
						/* do NOT change the memop table */
						continue;
1512
1513
					}
				}
1514
1515
1516
1517
				/* KILL all possible aliases */
				kill_memops(&op->value);
				/* add this value */
				add_memop(op);
1518
1519
1520
			}
			break;
		default:
1521
			if (op->flags & FLAG_KILL_ALL)
1522
1523
1524
				kill_all();
		}
	}
1525
}  /* calc_gen_kill_avail */
1526

Michael Beck's avatar
Michael Beck committed
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
#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);
1541
	dump_curr(bl, "Avail_out");
1542
}  /* forward_avail */
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553

/**
 * 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;
1554
1555
1556
1557
1558
1559
1560
	ir_node *block = bl->block;
	int     n = get_Block_n_cfg_outs(block);

	if (n == 1) {
		ir_node  *succ    = get_Block_cfg_out(block, 0);
		block_t  *succ_bl = get_block_entry(succ);
		int      pred_pos = get_Block_cfgpred_pos(succ, block);
Michael Beck's avatar
Michael Beck committed
1561
		unsigned end      = env.rbs_size - 1;
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
		unsigned pos;

		kill_all();

		if (bl->trans_results == NULL) {
			/* allocate the translate cache */
			unsigned size = env.curr_adr_id * sizeof(bl->trans_results[0]);
			bl->trans_results = obstack_alloc(&env.obst, size);
			memset(bl->trans_results, 0, size);
		}
1572

1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
		/* check for partly redundant values */
		for (pos = rbitset_next(succ_bl->anticL_in, 0, 1);
		     pos < end;
		     pos = rbitset_next(succ_bl->anticL_in, pos + 1, 1)) {
			/*
			 * do Phi-translation here: Note that at this point the nodes are
			 * not changed, so we can safely cache the results.
			 * However: Loads of Load results ARE bad, because we have no way
			  to translate them yet ...
			 */
			memop_t *op = bl->trans_results[pos];
			if (op == NULL) {
				/* not yet translated */
				ir_node *adr, *trans_adr;

				op  = succ_bl->id_2_memop_antic[pos];
				adr = op->value.address;

				trans_adr = phi_translate(adr, succ, pred_pos);
				if (trans_adr != adr) {
					/* create a new entry for the translated one */
					memop_t *new_op;

					new_op = alloc_memop(NULL);
					new_op->value.address = trans_adr;
					new_op->value.id      = register_address(trans_adr);
					new_op->value.mode    = op->value.mode;
					new_op->node          = op->node; /* we need the node to decide if Load/Store */
					new_op->flags         = op->flags;

Michael Beck's avatar
Michael Beck committed
1603
					bl->trans_results[pos] = new_op;
1604
1605
1606
					op = new_op;
				}
			}
Michael Beck's avatar
Michael Beck committed
1607
			env.curr_id_2_memop[op->value.id] = op;
1608
1609
1610
1611
			rbitset_set(env.curr_set, op->value.id);
		}
	} else if (n > 1) {
		ir_node *succ    = get_Block_cfg_out(block, 0);
1612
		block_t *succ_bl = get_block_entry(succ);
1613
1614
		int i;

1615
		rbitset_copy(env.curr_set, succ_bl->anticL_in, env.rbs_size);
Michael Beck's avatar
Michael Beck committed
1616
		memcpy(env.curr_id_2_memop, succ_bl->id_2_memop_antic, env.rbs_size * sizeof(env.curr_id_2_memop[0]));
1617

1618
		/* Hmm: probably we want kill merges of Loads ans Stores here */
1619
1620
1621
1622
1623
1624
		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);
		}
1625
1626
1627
	} else {
		/* block ends with a noreturn call */
		kill_all();
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
	}

	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
1643
				add_memop(op);
1644
1645
1646
			}
			break;
		case iro_Store:
1647
			if (! (op->flags & FLAG_KILLED_NODE)) {
1648
				/* a Store: check which memops must be killed */
Michael Beck's avatar
Michael Beck committed
1649
				kill_memops(&op->value);
1650
1651
1652
			}
			break;
		default:
1653
			if (op->flags & FLAG_KILL_ALL)
1654
1655
1656
				kill_all();
		}
	}
Michael Beck's avatar
Michael Beck committed
1657
1658

	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
1659
	if (! rbitset_equal(bl->anticL_in, env.curr_set, env.rbs_size)) {
1660
		/* changed */
1661
		rbitset_copy(bl->anticL_in, env.curr_set, env.rbs_size);
Michael Beck's avatar
Michael Beck committed
1662
		dump_curr(bl, "AnticL_in*");
1663
1664
		return 1;
	}
Michael Beck's avatar
Michael Beck committed
1665
	dump_curr(bl, "AnticL_in");
1666
	return 0;
1667
}  /* backward_antic */
1668
1669
1670
1671
1672
1673
1674
1675
1676

/**
 * 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);
1677
	ir_node *proj;
1678
1679
1680
	ir_mode *mode;

	if (def != NULL)
Michael Beck's avatar