ldstopt.c 59 KB
Newer Older
Christian Würdig's avatar
Christian Würdig committed
1
2
/*
 * This file is part of libFirm.
3
 * Copyright (C) 2012 University of Karlsruhe.
Christian Würdig's avatar
Christian Würdig committed
4
5
 */

Michael Beck's avatar
Michael Beck committed
6
7
8
9
/**
 * @file
 * @brief   Load/Store optimizations.
 * @author  Michael Beck
Michael Beck's avatar
Michael Beck committed
10
 */
11
#include <string.h>
Michael Beck's avatar
Michael Beck committed
12

13
#include "entity_t.h"
14
#include "error.h"
15
#include "iroptimize.h"
16
17
18
#include "irnode_t.h"
#include "irgraph_t.h"
#include "irmode_t.h"
19
#include "type_t.h"
20
21
22
23
#include "iropt_t.h"
#include "ircons_t.h"
#include "irgmod.h"
#include "irgwalk.h"
24
#include "irtools.h"
25
26
27
28
#include "tv_t.h"
#include "dbginfo_t.h"
#include "iropt_dbg.h"
#include "irflag_t.h"
29
#include "array.h"
30
#include "irhooks.h"
Michael Beck's avatar
BugFix:    
Michael Beck committed
31
#include "iredges.h"
32
#include "irmemory.h"
33
#include "irnodehashmap.h"
34
#include "irgopt.h"
35
#include "set.h"
Matthias Braun's avatar
Matthias Braun committed
36
#include "be.h"
37
38
39
40
#include "debug.h"

/** The debug handle. */
DEBUG_ONLY(static firm_dbg_module_t *dbg;)
41

42
#define MAX_PROJ MAX(MAX((long)pn_Load_max, (long)pn_Store_max), (long)pn_Call_max)
Michael Beck's avatar
Michael Beck committed
43

44
enum changes_t {
45
46
	DF_CHANGED = 1,       /**< data flow changed */
	CF_CHANGED = 2,       /**< control flow changed */
47
48
};

Michael Beck's avatar
Michael Beck committed
49
50
51
/**
 * walker environment
 */
52
typedef struct walk_env_t {
53
54
	struct obstack obst;          /**< list of all stores */
	unsigned changes;             /**< a bitmask of graph changes */
Michael Beck's avatar
Michael Beck committed
55
56
} walk_env_t;

57
/** A Load/Store info. */
58
typedef struct ldst_info_t {
59
	ir_node  *projs[MAX_PROJ+1];  /**< list of Proj's of this node */
60
61
62
	ir_node  *exc_block;          /**< the exception block if available */
	int      exc_idx;             /**< predecessor index in the exception block */
	unsigned visited;             /**< visited counter for breaking loops */
Michael Beck's avatar
Michael Beck committed
63
64
} ldst_info_t;

65
/**
66
 * flags for control flow.
67
68
 */
enum block_flags_t {
69
70
	BLOCK_HAS_COND = 1,      /**< Block has conditional control flow */
	BLOCK_HAS_EXC  = 2       /**< Block has exceptional control flow */
71
72
73
};

/**
74
 * a Block info.
75
 */
76
typedef struct block_info_t {
77
	unsigned flags;               /**< flags for the block */
78
79
} block_info_t;

80
81
82
83
84
85
86
/** the master visited flag for loop detection. */
static unsigned master_visited = 0;

#define INC_MASTER()       ++master_visited
#define MARK_NODE(info)    (info)->visited = master_visited
#define NODE_VISITED(info) (info)->visited >= master_visited

Michael Beck's avatar
Michael Beck committed
87
88
89
/**
 * get the Load/Store info of a node
 */
90
91
static ldst_info_t *get_ldst_info(ir_node *node, struct obstack *obst)
{
92
	ldst_info_t *info = (ldst_info_t*)get_irn_link(node);
Michael Beck's avatar
Michael Beck committed
93

94
	if (! info) {
95
		info = OALLOCZ(obst, ldst_info_t);
96
97
98
		set_irn_link(node, info);
	}
	return info;
99
}
Michael Beck's avatar
Michael Beck committed
100

101
102
103
/**
 * get the Block info of a node
 */
104
105
static block_info_t *get_block_info(ir_node *node, struct obstack *obst)
{
106
	block_info_t *info = (block_info_t*)get_irn_link(node);
107

108
	if (! info) {
109
		info = OALLOCZ(obst, block_info_t);
110
111
112
		set_irn_link(node, info);
	}
	return info;
113
}
114

Michael Beck's avatar
Michael Beck committed
115
/**
Michael Beck's avatar
Michael Beck committed
116
 * update the projection info for a Load/Store
Michael Beck's avatar
Michael Beck committed
117
 */
118
static unsigned update_projs(ldst_info_t *info, ir_node *proj)
Michael Beck's avatar
Michael Beck committed
119
{
120
	long nr = get_Proj_proj(proj);
Michael Beck's avatar
Michael Beck committed
121

122
	assert(0 <= nr && nr <= MAX_PROJ && "Wrong proj from LoadStore");
Michael Beck's avatar
Michael Beck committed
123

124
125
126
127
128
129
130
131
132
	if (info->projs[nr]) {
		/* there is already one, do CSE */
		exchange(proj, info->projs[nr]);
		return DF_CHANGED;
	}
	else {
		info->projs[nr] = proj;
		return 0;
	}
133
}
Michael Beck's avatar
Michael Beck committed
134
135

/**
136
137
138
139
140
 * update the exception block info for a Load/Store node.
 *
 * @param info   the load/store info struct
 * @param block  the exception handler block for this load/store
 * @param pos    the control flow input of the block
Michael Beck's avatar
Michael Beck committed
141
 */
142
static unsigned update_exc(ldst_info_t *info, ir_node *block, int pos)
Michael Beck's avatar
Michael Beck committed
143
{
144
	assert(info->exc_block == NULL && "more than one exception block found");
Michael Beck's avatar
Michael Beck committed
145

146
147
148
	info->exc_block = block;
	info->exc_idx   = pos;
	return 0;
149
}
Michael Beck's avatar
Michael Beck committed
150
151

/**
152
 * walker, collects all Proj/Load/Store/Call/CopyB nodes
153
 *
154
 * walks from Start -> End
Michael Beck's avatar
Michael Beck committed
155
 */
Michael Beck's avatar
Michael Beck committed
156
static void collect_nodes(ir_node *node, void *env)
Michael Beck's avatar
Michael Beck committed
157
{
158
159
	walk_env_t  *wenv   = (walk_env_t *)env;
	unsigned     opcode = get_irn_opcode(node);
160

161
	if (opcode == iro_Proj) {
Andreas Fried's avatar
Andreas Fried committed
162
		ir_node *pred   = get_Proj_pred(node);
163
		opcode = get_irn_opcode(pred);
164

165
		if (opcode == iro_Load || opcode == iro_Store || opcode == iro_Call) {
Andreas Fried's avatar
Andreas Fried committed
166
			ldst_info_t *ldst_info = get_ldst_info(pred, &wenv->obst);
167
168
169
170

			wenv->changes |= update_projs(ldst_info, node);

			/*
171
172
173
174
175
			 * Place the Proj's to the same block as the
			 * predecessor Load. This is always ok and prevents
			 * "non-SSA" form after optimizations if the Proj
			 * is in a wrong block.
			 */
Andreas Fried's avatar
Andreas Fried committed
176
177
			ir_node *blk      = get_nodes_block(node);
			ir_node *pred_blk = get_nodes_block(pred);
178
179
180
181
182
			if (blk != pred_blk) {
				wenv->changes |= DF_CHANGED;
				set_nodes_block(node, pred_blk);
			}
		}
183
	} else if (opcode == iro_Block) {
184
185
186
		int i;

		for (i = get_Block_n_cfgpreds(node) - 1; i >= 0; --i) {
Andreas Fried's avatar
Andreas Fried committed
187
188
189
			int      is_exc = 0;
			ir_node *proj   = get_Block_cfgpred(node, i);
			ir_node *pred   = proj;
190

191
192
			if (is_Proj(proj)) {
				pred   = get_Proj_pred(proj);
Matthias Braun's avatar
Matthias Braun committed
193
				is_exc = is_x_except_Proj(proj);
194
			}
195
196
197
198
199

			/* ignore Bad predecessors, they will be removed later */
			if (is_Bad(pred))
				continue;

Andreas Fried's avatar
Andreas Fried committed
200
201
			ir_node      *pred_block = get_nodes_block(pred);
			block_info_t *bl_info    = get_block_info(pred_block, &wenv->obst);
202

203
			if (is_fragile_op(pred) && is_exc)
204
205
206
207
				bl_info->flags |= BLOCK_HAS_EXC;
			else if (is_irn_forking(pred))
				bl_info->flags |= BLOCK_HAS_COND;

208
209
			opcode = get_irn_opcode(pred);
			if (is_exc && (opcode == iro_Load || opcode == iro_Store || opcode == iro_Call)) {
Andreas Fried's avatar
Andreas Fried committed
210
				ldst_info_t *ldst_info = get_ldst_info(pred, &wenv->obst);
211
212
213
214

				wenv->changes |= update_exc(ldst_info, node, i);
			}
		}
215
216
217
	} else if (opcode == iro_CopyB) {
		/* Just initialize a ldst_info for the CopyB node. */
		(void) get_ldst_info(node, &wenv->obst);
218
	}
219
}
Michael Beck's avatar
Michael Beck committed
220

Michael Beck's avatar
Michael Beck committed
221
/**
222
 * Returns an entity if the address ptr points to a constant one.
223
224
225
226
 *
 * @param ptr  the address
 *
 * @return an entity or NULL
Michael Beck's avatar
Michael Beck committed
227
 */
228
static ir_entity *find_constant_entity(ir_node *ptr)
Michael Beck's avatar
Michael Beck committed
229
{
230
	for (;;) {
231
232
		if (is_Address(ptr)) {
			return get_Address_entity(ptr);
233
		} else if (is_Sel(ptr)) {
234
235
236
237
			ir_entity *ent = get_Sel_entity(ptr);
			ir_type   *tp  = get_entity_owner(ent);

			/* Do not fiddle with polymorphism. */
238
			if (is_Class_type(tp) &&
yb9976's avatar
yb9976 committed
239
				(get_entity_n_overwrites(ent) != 0 || get_entity_n_overwrittenby(ent) != 0))
240
241
242
243
				return NULL;

			if (is_Array_type(tp)) {
				/* check bounds */
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
				ir_node   *index = get_Sel_index(ptr, 0);
				ir_tarval *tv    = computed_value(index);

				/* check if the index is constant */
				if (!tarval_is_constant(tv))
					return NULL;

				ir_node   *size  = get_array_size(tp);
				ir_tarval *tsize = computed_value(size);

				if (!tarval_is_constant(tsize))
					return NULL;

				if (tarval_cmp(tv, tsize) != ir_relation_less)
					return NULL;
				/* ok, bounds check finished */
260
261
			}

Matthias Braun's avatar
Matthias Braun committed
262
			if (get_entity_linkage(ent) & IR_LINKAGE_CONSTANT)
263
264
265
266
				return ent;

			/* try next */
			ptr = get_Sel_ptr(ptr);
267
268
269
270
271
272
273
274
275
276
277
278
		} 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 */
279
			if (!is_Address(ptr) && !is_Align(ptr) && !is_Offset(ptr) && !is_Sel(ptr) && !is_Size(ptr))
280
281
282
283
284
				return NULL;
		} else if (is_Sub(ptr)) {
			ir_node *l = get_Sub_left(ptr);
			ir_node *r = get_Sub_right(ptr);

285
			if (get_irn_mode(l) == get_irn_mode(ptr) && is_Const(r))
286
287
288
289
				ptr = l;
			else
				return NULL;
			/* for now, we support only one substraction, reassoc should fold all others */
290
			if (!is_Address(ptr) && !is_Align(ptr) && !is_Offset(ptr) && !is_Sel(ptr) && !is_Size(ptr))
291
				return NULL;
292
293
294
		} else
			return NULL;
	}
295
}
Michael Beck's avatar
Michael Beck committed
296

297
/* forward */
298
static void reduce_node_usage(ir_node *ptr);
299
300

/**
Christoph Mallon's avatar
Christoph Mallon committed
301
 * Update a Load that may have lost its users.
302
 */
303
304
static void handle_load_update(ir_node *load)
{
305
	ldst_info_t *info = (ldst_info_t*)get_irn_link(load);
306

307
308
309
	/* do NOT touch volatile loads for now */
	if (get_Load_volatility(load) == volatility_is_volatile)
		return;
310

311
312
313
	if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
		ir_node *ptr = get_Load_ptr(load);
		ir_node *mem = get_Load_mem(load);
314

Christoph Mallon's avatar
Christoph Mallon committed
315
		/* a Load whose value is neither used nor exception checked, remove it */
Andreas Zwinkau's avatar
Andreas Zwinkau committed
316
		exchange(info->projs[pn_Load_M], mem);
317
		if (info->projs[pn_Load_X_regular])
318
			exchange(info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
319
		kill_node(load);
320
		reduce_node_usage(ptr);
321
	}
322
}
323
324

/**
325
 * A use of a node has vanished. Check if this was a Proj
326
327
 * node and update the counters.
 */
328
static void reduce_node_usage(ir_node *ptr)
329
{
330
331
332
333
334
	ir_node *pred;
	if (!is_Proj(ptr))
		return;
	if (get_irn_n_edges(ptr) > 0)
		return;
335

336
337
338
	/* this Proj is dead now */
	pred = get_Proj_pred(ptr);
	if (is_Load(pred)) {
339
		ldst_info_t *info = (ldst_info_t*)get_irn_link(pred);
340
		info->projs[get_Proj_proj(ptr)] = NULL;
341

342
343
		/* this node lost its result proj, handle that */
		handle_load_update(pred);
344
	}
345
}
346

347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/**
 * Kill a Load or Store and all other nodes which are not needed after
 * it has been killed.
 */
static void kill_and_reduce_usage(ir_node *node) {
	ir_node *ptr;
	ir_node *value = NULL;

	switch(get_irn_opcode(node)) {
	case iro_Load:
		ptr = get_Load_ptr(node);
		break;
	case iro_Store:
		ptr   = get_Store_ptr(node);
		value = get_Store_value(node);
		break;
	default:
		panic("Cannot handle node %+F", node);
	}

	kill_node(node);
	reduce_node_usage(ptr);
	if (value != NULL) {
		reduce_node_usage(value);
	}
}

374
375
376
377
/**
 * Check, if an already existing value of mode old_mode can be converted
 * into the needed one new_mode without loss.
 */
378
379
static int can_use_stored_value(ir_mode *old_mode, ir_mode *new_mode)
{
380
	if (old_mode == new_mode)
381
382
		return true;

Andreas Fried's avatar
Andreas Fried committed
383
384
	unsigned old_size = get_mode_size_bits(old_mode);
	unsigned new_size = get_mode_size_bits(new_mode);
385
386

	/* if both modes are two-complement ones, we can always convert the
387
388
389
	   Stored value into the needed one. (on big endian machines we currently
	   only support this for modes of same size) */
	if (old_size >= new_size &&
390
		  get_mode_arithmetic(old_mode) == irma_twos_complement &&
391
392
393
394
395
396
397
		  get_mode_arithmetic(new_mode) == irma_twos_complement &&
		  (!be_get_backend_param()->byte_order_big_endian
	        || old_size == new_size)) {
		return true;
	}
	return false;
}
398

Michael Beck's avatar
Michael Beck committed
399
/**
400
 * Check whether a Call is at least pure, i.e. does only read memory.
401
 */
402
403
static unsigned is_Call_pure(ir_node *call)
{
404
405
406
407
408
409
	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 */
410
411
412
		ir_entity *callee = get_Call_callee(call);
		if (callee != NULL) {
			prop = get_entity_additional_properties(callee);
413
414
415
		}
	}
	return (prop & (mtp_property_const|mtp_property_pure)) != 0;
416
}
417

Michael Beck's avatar
Michael Beck committed
418
static ir_node *get_base_and_offset(ir_node *ptr, long *pOffset)
419
{
Michael Beck's avatar
Michael Beck committed
420
421
	ir_mode *mode  = get_irn_mode(ptr);
	long    offset = 0;
422
423

	/* TODO: long might not be enough, we should probably use some tarval thingy... */
Michael Beck's avatar
Michael Beck committed
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
	for (;;) {
		if (is_Add(ptr)) {
			ir_node *l = get_Add_left(ptr);
			ir_node *r = get_Add_right(ptr);

			if (get_irn_mode(l) != mode || !is_Const(r))
				break;

			offset += get_tarval_long(get_Const_tarval(r));
			ptr     = l;
		} else if (is_Sub(ptr)) {
			ir_node *l = get_Sub_left(ptr);
			ir_node *r = get_Sub_right(ptr);

			if (get_irn_mode(l) != mode || !is_Const(r))
				break;

			offset -= get_tarval_long(get_Const_tarval(r));
			ptr     = l;
		} else if (is_Sel(ptr)) {
			ir_entity *ent = get_Sel_entity(ptr);
			ir_type   *tp  = get_entity_owner(ent);

			if (is_Array_type(tp)) {
				/* only one dimensional arrays yet */
				if (get_Sel_n_indexs(ptr) != 1)
					break;
yb9976's avatar
yb9976 committed
451
				ir_node *index = get_Sel_index(ptr, 0);
Michael Beck's avatar
Michael Beck committed
452
453
454
455
456
457
458
				if (! is_Const(index))
					break;

				tp = get_entity_type(ent);
				if (get_type_state(tp) != layout_fixed)
					break;

yb9976's avatar
yb9976 committed
459
				int size = get_type_size_bytes(tp);
Michael Beck's avatar
Michael Beck committed
460
461
462
463
464
465
466
467
				offset += size * get_tarval_long(get_Const_tarval(index));
			} else {
				if (get_type_state(tp) != layout_fixed)
					break;
				offset += get_entity_offset(ent);
			}
			ptr = get_Sel_ptr(ptr);
		} else
468
469
470
			break;
	}

Michael Beck's avatar
Michael Beck committed
471
472
	*pOffset = offset;
	return ptr;
473
474
}

Michael Beck's avatar
Michael Beck committed
475
static int try_load_after_store(ir_node *load,
476
477
478
		ir_node *load_base_ptr, long load_offset, ir_node *store)
{
	ir_node *store_ptr      = get_Store_ptr(store);
Michael Beck's avatar
Michael Beck committed
479
480
	long     store_offset;
	ir_node *store_base_ptr = get_base_and_offset(store_ptr, &store_offset);
481
482
483
484

	if (load_base_ptr != store_base_ptr)
		return 0;

Andreas Fried's avatar
Andreas Fried committed
485
486
487
488
489
490
	ir_mode *load_mode      = get_Load_mode(load);
	long     load_mode_len  = get_mode_size_bytes(load_mode);
	ir_mode *store_mode     = get_irn_mode(get_Store_value(store));
	long     store_mode_len = get_mode_size_bytes(store_mode);
	long     delta          = load_offset - store_offset;
	ir_node *store_value    = get_Store_value(store);
491

yb9976's avatar
yb9976 committed
492
	/* Ensure that Load is completely contained in Store. */
493
494
	if (delta < 0 || delta+load_mode_len > store_mode_len)
		return 0;
495

496
497
498
499
500
501
502
503
504
505
506
507
	if (store_mode != load_mode) {
		if (get_mode_arithmetic(store_mode) == irma_twos_complement &&
		    get_mode_arithmetic(load_mode)  == irma_twos_complement) {

			/* produce a shift to adjust offset delta */
			unsigned const shift = be_get_backend_param()->byte_order_big_endian
				? store_mode_len - load_mode_len - delta
				: delta;
			if (shift != 0) {
				ir_graph *const irg  = get_irn_irg(load);
				ir_node  *const cnst = new_r_Const_long(irg, mode_Iu, shift * 8);
				store_value = new_r_Shr(get_nodes_block(load),
yb9976's avatar
yb9976 committed
508
				                        store_value, cnst, store_mode);
509
			}
510

511
512
513
514
515
			store_value = new_r_Conv(get_nodes_block(load), store_value, load_mode);
		} else {
			/* we would need some kind of bitcast node here */
			return 0;
		}
516
517
	}

Michael Beck's avatar
Michael Beck committed
518
519
	DBG_OPT_RAW(load, store_value);

Andreas Fried's avatar
Andreas Fried committed
520
	ldst_info_t *info = (ldst_info_t*)get_irn_link(load);
521
522
523
	if (info->projs[pn_Load_M])
		exchange(info->projs[pn_Load_M], get_Load_mem(load));

Andreas Fried's avatar
Andreas Fried committed
524
	int res = 0;
525
526
	/* no exception */
	if (info->projs[pn_Load_X_except]) {
527
		ir_graph *irg = get_irn_irg(load);
Matthias Braun's avatar
Matthias Braun committed
528
		exchange( info->projs[pn_Load_X_except], new_r_Bad(irg, mode_X));
529
530
531
		res |= CF_CHANGED;
	}
	if (info->projs[pn_Load_X_regular]) {
532
		exchange( info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
533
534
535
536
537
538
		res |= CF_CHANGED;
	}

	if (info->projs[pn_Load_res])
		exchange(info->projs[pn_Load_res], store_value);

539
	kill_and_reduce_usage(load);
540
541
542
	return res | DF_CHANGED;
}

yb9976's avatar
yb9976 committed
543
544
static ir_node *try_update_ptr_CopyB(ir_node *load, ir_node *load_base_ptr,
                                     long load_offset, ir_node *copyB)
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
{
	ir_node *copyB_dst = get_CopyB_dst(copyB);
	long     dst_offset;
	ir_node *dst_base_ptr = get_base_and_offset(copyB_dst, &dst_offset);

	if (load_base_ptr != dst_base_ptr) {
		return NULL;
	}

	/*
	 * There are quite a few offsets here, please do not get
	 * confused: The CopyB node copies n_copy bytes from
	 * (src_base_ptr + src_offset) to (dst_base_ptr + dst_offset)
	 * (calculated in bytes; no pointer arithmetic). The Load
	 * loads from (dst_base_ptr + load_offset). This is translated
	 * into load_src_offset, which points to the same data in the
	 * CopyB's source array, if it is within its bounds.
	 */
	ir_type *copyB_type      = get_CopyB_type(copyB);
	long     n_copy          = get_type_size_bytes(copyB_type);

	ir_node *copyB_src       = get_CopyB_src(copyB);
	long     src_offset;
	ir_node *src_base_ptr    = get_base_and_offset(copyB_src, &src_offset);

	long     load_src_offset = src_offset - dst_offset + load_offset;

	ir_mode *load_mode       = get_Load_mode(load);
	long     load_size       = get_mode_size_bytes(load_mode);

	if (load_src_offset + load_size > n_copy
yb9976's avatar
yb9976 committed
576
		|| load_src_offset < src_offset) {
577
578
579
580
581
582
583
584
585
586
587
588
		return NULL;
	}

	/*
	 * Everything is OK, we can replace
	 *   ptr = (load_base_ptr + load_offset)
	 * with
	 *   new_load_ptr = (src_base_ptr + load_src_offset)
	 */
	ir_graph *irg          = get_irn_irg(load);
	ir_node  *block        = get_nodes_block(load);
	ir_node  *new_load_ptr = new_r_Add(block,
yb9976's avatar
yb9976 committed
589
590
591
	                                   src_base_ptr,
	                                   new_r_Const_long(irg, mode_Is, load_src_offset),
	                                   mode_P);
592
593
594
595

	return new_load_ptr;
}

596
597
598
599
/**
 * Follow the memory chain as long as there are only Loads,
 * alias free Stores, and constant Calls and try to replace the
 * current Load by a previous ones.
Michael Beck's avatar
Michael Beck committed
600
601
602
603
604
605
 * Note that in unreachable loops it might happen that we reach
 * load again, as well as we can fall into a cycle.
 * We break such cycles using a special visited flag.
 *
 * INC_MASTER() must be called before dive into
 */
606
607
static unsigned follow_Mem_chain(ir_node *load, ir_node *curr)
{
Michael Beck's avatar
Michael Beck committed
608
	unsigned    res = 0;
609
	ldst_info_t *info = (ldst_info_t*)get_irn_link(load);
Michael Beck's avatar
Michael Beck committed
610
611
612
613
	ir_node     *pred;
	ir_node     *ptr       = get_Load_ptr(load);
	ir_node     *mem       = get_Load_mem(load);
	ir_mode     *load_mode = get_Load_mode(load);
614
615

	for (pred = curr; load != pred; ) {
616
		ldst_info_t *pred_info = (ldst_info_t*)get_irn_link(pred);
617
618

		/*
619
620
		 * a Load immediately after a Store -- a read after write.
		 * We may remove the Load, if both Load & Store does not have an
Matthias Braun's avatar
Matthias Braun committed
621
		 * exception handler OR they are in the same Block. In the latter
622
623
624
625
626
		 * case the Load cannot throw an exception when the previous Store was
		 * quiet.
		 *
		 * Why we need to check for Store Exception? If the Store cannot
		 * be executed (ROM) the exception handler might simply jump into
Matthias Braun's avatar
Matthias Braun committed
627
		 * the load Block :-(
628
629
		 * We could make it a little bit better if we would know that the
		 * exception handler of the Store jumps directly to the end...
630
		 */
631
632
		if (is_Store(pred) && ((pred_info->projs[pn_Store_X_except] == NULL
				&& info->projs[pn_Load_X_except] == NULL)
Matthias Braun's avatar
Matthias Braun committed
633
				|| get_nodes_block(load) == get_nodes_block(pred)))
634
		{
Michael Beck's avatar
Michael Beck committed
635
636
637
638
639
			long    load_offset;
			ir_node *base_ptr = get_base_and_offset(ptr, &load_offset);
			int     changes   = try_load_after_store(load, base_ptr, load_offset, pred);

			if (changes != 0)
640
				return res | changes;
641

642
		} else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
643
		           can_use_stored_value(get_Load_mode(pred), load_mode)) {
644
645
			/*
			 * a Load after a Load -- a read after read.
Matthias Braun's avatar
Matthias Braun committed
646
647
648
649
			 * We may remove the second Load, if it does not have an exception
			 * handler OR they are in the same Block. In the later case
			 * the Load cannot throw an exception when the previous Load was
			 * quiet.
650
			 *
Matthias Braun's avatar
Matthias Braun committed
651
652
653
			 * Here, there is no need to check if the previous Load has an
			 * exception hander because they would have exact the same
			 * exception...
654
655
656
			 *
			 * TODO: implement load-after-load with different mode for big
			 *       endian
657
			 */
Matthias Braun's avatar
Matthias Braun committed
658
659
			if (info->projs[pn_Load_X_except] == NULL
					|| get_nodes_block(load) == get_nodes_block(pred)) {
660
661
				DBG_OPT_RAR(load, pred);

662
663
664
665
				/* the result is used */
				if (info->projs[pn_Load_res]) {
					if (pred_info->projs[pn_Load_res] == NULL) {
						/* create a new Proj again */
666
						pred_info->projs[pn_Load_res] = new_r_Proj(pred, get_Load_mode(pred), pn_Load_res);
667
					}
Andreas Fried's avatar
Andreas Fried committed
668
					ir_node *value = pred_info->projs[pn_Load_res];
669
670
671

					/* add an convert if needed */
					if (get_Load_mode(pred) != load_mode) {
672
						value = new_r_Conv(get_nodes_block(load), value, load_mode);
673
674
					}

675
					exchange(info->projs[pn_Load_res], value);
676
677
				}

678
679
680
				if (info->projs[pn_Load_M])
					exchange(info->projs[pn_Load_M], mem);

681
682
				/* no exception */
				if (info->projs[pn_Load_X_except]) {
683
					ir_graph *irg = get_irn_irg(load);
Matthias Braun's avatar
Matthias Braun committed
684
					exchange(info->projs[pn_Load_X_except], new_r_Bad(irg, mode_X));
685
686
					res |= CF_CHANGED;
				}
687
				if (info->projs[pn_Load_X_regular]) {
688
					exchange( info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
689
690
					res |= CF_CHANGED;
				}
691

692
				kill_and_reduce_usage(load);
693
694
695
696
				return res |= DF_CHANGED;
			}
		}

697
		if (is_Store(pred)) {
698
			/* check if we can pass through this store */
699
700
			ir_alias_relation rel = get_alias_relation(
				get_Store_ptr(pred),
701
702
703
				get_type_for_mode(get_irn_mode(get_Store_value(pred))),
				ptr,
				get_type_for_mode(load_mode));
704
			/* if the might be an alias, we cannot pass this Store */
Michael Beck's avatar
Michael Beck committed
705
			if (rel != ir_no_alias)
706
707
				break;
			pred = skip_Proj(get_Store_mem(pred));
708
		} else if (is_Load(pred)) {
709
			pred = skip_Proj(get_Load_mem(pred));
710
711
712
713
714
715
716
717
718
		} else if (is_Call(pred)) {
			if (is_Call_pure(pred)) {
				/* The called graph is at least pure, so there are no Store's
				   in it. We can handle it like a Load and skip it. */
				pred = skip_Proj(get_Call_mem(pred));
			} else {
				/* there might be Store's in the graph, stop here */
				break;
			}
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
		} else if (is_CopyB(pred)) {
			/*
			 * We cannot replace the Load with another
			 * Load from the CopyB's source directly,
			 * because there may be Stores in between,
			 * destroying the source data. However, we can
			 * use the source address from this point
			 * onwards for further optimizations.
			 */
			long     load_offset;
			ir_node *base_ptr = get_base_and_offset(ptr, &load_offset);
			ir_node *new_ptr  = try_update_ptr_CopyB(load, base_ptr, load_offset, pred);

			if (new_ptr) {
				ptr = new_ptr;
				/*
				 * Special case: If new_ptr points to
				 * a constant, we *can* replace the
				 * Load immediately.
				 */
				if (find_constant_entity(new_ptr)) {
					set_Load_ptr(load, new_ptr);
					return res | DF_CHANGED;
				}
			} else {
				ir_alias_relation rel = get_alias_relation(
					get_CopyB_dst(pred),
					get_CopyB_type(pred),
					ptr,
					get_type_for_mode(load_mode));
				if (rel != ir_no_alias)
					break;
			}

			pred = skip_Proj(get_CopyB_mem(pred));

755
756
757
758
759
760
761
762
763
764
765
		} else {
			/* follow only Load chains */
			break;
		}

		/* check for cycles */
		if (NODE_VISITED(pred_info))
			break;
		MARK_NODE(pred_info);
	}

766
	if (is_Sync(pred)) {
767
768
769
770
771
772
		int i;

		/* handle all Sync predecessors */
		for (i = get_Sync_n_preds(pred) - 1; i >= 0; --i) {
			res |= follow_Mem_chain(load, skip_Proj(get_Sync_pred(pred, i)));
			if (res)
773
				return res;
774
775
776
777
		}
	}

	return res;
778
}
Michael Beck's avatar
Michael Beck committed
779

780
781
ir_node *can_replace_load_by_const(const ir_node *load, ir_node *c)
{
782
783
784
785
	ir_mode  *c_mode = get_irn_mode(c);
	ir_mode  *l_mode = get_Load_mode(load);
	ir_node  *block  = get_nodes_block(load);
	dbg_info *dbgi   = get_irn_dbg_info(load);
786
	ir_node  *res    = duplicate_subgraph(dbgi, c, block);
787
788
789
790
791

	if (c_mode != l_mode) {
		/* check, if the mode matches OR can be easily converted info */
		if (is_reinterpret_cast(c_mode, l_mode)) {
			/* copy the value from the const code irg and cast it */
792
			res = new_rd_Conv(dbgi, block, res, l_mode);
Andreas Zwinkau's avatar
Andreas Zwinkau committed
793
794
		} else {
			return NULL;
795
796
797
		}
	}
	return res;
798
}
799

Michael Beck's avatar
Michael Beck committed
800
801
/**
 * optimize a Load
802
803
 *
 * @param load  the Load node
Michael Beck's avatar
Michael Beck committed
804
 */
805
static unsigned optimize_load(ir_node *load)
Michael Beck's avatar
Michael Beck committed
806
{
807
	ldst_info_t *info = (ldst_info_t*)get_irn_link(load);
Michael Beck's avatar
Michael Beck committed
808
	unsigned    res = 0;
809
810
811
812
813
814

	/* do NOT touch volatile loads for now */
	if (get_Load_volatility(load) == volatility_is_volatile)
		return 0;

	/* the address of the load to be optimized */
Andreas Fried's avatar
Andreas Fried committed
815
	ir_node *ptr = get_Load_ptr(load);
816
817

	/* The mem of the Load. Must still be returned after optimization. */
Andreas Fried's avatar
Andreas Fried committed
818
	ir_node *mem = get_Load_mem(load);
819

820
821
822
	if (info->projs[pn_Load_res] == NULL
			&& info->projs[pn_Load_X_except] == NULL) {
		/* the value is never used and we don't care about exceptions, remove */
823
824
		exchange(info->projs[pn_Load_M], mem);

825
826
		if (info->projs[pn_Load_X_regular]) {
			/* should not happen, but if it does, remove it */
827
			exchange(info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
828
829
			res |= CF_CHANGED;
		}
830
		kill_and_reduce_usage(load);
831
832
833
		return res | DF_CHANGED;
	}

Matthias Braun's avatar
Matthias Braun committed
834
	/* check if we can determine the entity that will be loaded */
Andreas Fried's avatar
Andreas Fried committed
835
	ir_entity *ent = find_constant_entity(ptr);
Matthias Braun's avatar
Matthias Braun committed
836
837
838
839
840
	if (ent != NULL
			&& get_entity_visibility(ent) != ir_visibility_external) {
		/* a static allocation that is not external: there should be NO
		 * exception when loading even if we cannot replace the load itself.
		 */
Christoph Mallon's avatar
Christoph Mallon committed
841

Matthias Braun's avatar
Matthias Braun committed
842
843
844
845
846
847
848
849
850
851
852
853
		/* no exception, clear the info field as it might be checked later again */
		if (info->projs[pn_Load_X_except]) {
			ir_graph *irg = get_irn_irg(load);
			exchange(info->projs[pn_Load_X_except], new_r_Bad(irg, mode_X));
			info->projs[pn_Load_X_except] = NULL;
			res |= CF_CHANGED;
		}
		if (info->projs[pn_Load_X_regular]) {
			exchange(info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
			info->projs[pn_Load_X_regular] = NULL;
			res |= CF_CHANGED;
		}
854
855
856
	}

	/* Check, if the address of this load is used more than once.
Michael Beck's avatar
Michael Beck committed
857
	 * If not, more load cannot be removed in any case. */
Andreas Fried's avatar
Andreas Fried committed
858
	long dummy;
859
	if (get_irn_n_edges(ptr) <= 1 && get_irn_n_edges(get_base_and_offset(ptr, &dummy)) <= 1)
860
861
862
863
864
865
866
867
868
869
870
871
		return res;

	/*
	 * follow the memory chain as long as there are only Loads
	 * and try to replace current Load or Store by a previous one.
	 * Note that in unreachable loops it might happen that we reach
	 * load again, as well as we can fall into a cycle.
	 * We break such cycles using a special visited flag.
	 */
	INC_MASTER();
	res = follow_Mem_chain(load, skip_Proj(mem));
	return res;
872
}
Michael Beck's avatar
Michael Beck committed
873

874
875
876
877
878
879
880
/**
 * Check whether a value of mode new_mode would completely overwrite a value
 * of mode old_mode in memory.
 */
static int is_completely_overwritten(ir_mode *old_mode, ir_mode *new_mode)
{
	return get_mode_size_bits(new_mode) >= get_mode_size_bits(old_mode);
881
}
882

883
884
885
886
887
888
889
890
891
892
893
894
/**
 * Check whether small is a part of large (starting at same address).
 */
static int is_partially_same(ir_node *small, ir_node *large)
{
	ir_mode *sm = get_irn_mode(small);
	ir_mode *lm = get_irn_mode(large);

	/* FIXME: Check endianness */
	return is_Conv(small) && get_Conv_op(small) == large
	    && get_mode_size_bytes(sm) < get_mode_size_bytes(lm)
	    && get_mode_arithmetic(sm) == irma_twos_complement
895
	    && get_mode_arithmetic(lm) == irma_twos_complement;
896
}
897

Michael Beck's avatar
Michael Beck committed
898
/**
899
 * follow the memory chain as long as there are only Loads and alias free Stores.
Michael Beck's avatar
Michael Beck committed
900
901
902
 *
 * INC_MASTER() must be called before dive into
 */
903
static unsigned follow_Mem_chain_for_Store(ir_node *store, ir_node *curr, bool had_split)
904
{
905
	unsigned res = 0;
906
	ldst_info_t *info = (ldst_info_t*)get_irn_link(store);
907
908
909
910
911
912
913
914
	ir_node *pred;
	ir_node *ptr = get_Store_ptr(store);
	ir_node *mem = get_Store_mem(store);
	ir_node *value = get_Store_value(store);
	ir_mode *mode  = get_irn_mode(value);
	ir_node *block = get_nodes_block(store);

	for (pred = curr; pred != store;) {
915
		ldst_info_t *pred_info = (ldst_info_t*)get_irn_link(pred);
916
917
918
919
920
921

		/*
		 * BEWARE: one might think that checking the modes is useless, because
		 * if the pointers are identical, they refer to the same object.
		 * This is only true in strong typed languages, not is C were the following
		 * is possible *(ir_type1 *)p = a; *(ir_type2 *)p = b ...
922
923
924
		 * However, if the size of the mode that is written is bigger or equal the
		 * size of the old one, the old value is completely overwritten and can be
		 * killed ...
925
		 */
926
		if (is_Store(pred) && !had_split && get_Store_ptr(pred) == ptr &&
yb9976's avatar
yb9976 committed
927
		    get_nodes_block(pred) == block) {
928
			/*
Matthias Braun's avatar
Matthias Braun committed
929
			 * a Store after a Store in the same Block -- a write after write.
930
931
932
933
934
935
			 */

			/*
			 * We may remove the first Store, if the old value is completely
			 * overwritten or the old value is a part of the new value,
			 * and if it does not have an exception handler.
936
937
938
			 *
			 * TODO: What, if both have the same exception handler ???
			 */
939
940
941
942
943
			if (get_Store_volatility(pred) != volatility_is_volatile
			        && !pred_info->projs[pn_Store_X_except]) {
				ir_node *predvalue = get_Store_value(pred);
				ir_mode *predmode  = get_irn_mode(predvalue);

944
				if (is_completely_overwritten(predmode, mode)
945
946
				        || is_partially_same(predvalue, value)) {
					DBG_OPT_WAW(pred, store);
947
					DB((dbg, LEVEL_1, "  killing store %+F (override by %+F)\n", pred, store));
948
					exchange(pred_info->projs[pn_Store_M], get_Store_mem(pred));
949
					kill_and_reduce_usage(pred);
950
951
952
953
954
955
956
957
958
959
960
961
962
963
					return DF_CHANGED;
				}
			}

			/*
			 * We may remove the Store, if the old value already contains
			 * the new value, and if it does not have an exception handler.
			 *
			 * TODO: What, if both have the same exception handler ???
			 */
			if (get_Store_volatility(store) != volatility_is_volatile
			        && !info->projs[pn_Store_X_except]) {
				ir_node *predvalue = get_Store_value(pred);

964
				if (is_partially_same(value, predvalue)) {
965
					DBG_OPT_WAW(pred, store);
966
					DB((dbg, LEVEL_1, "  killing store %+F (override by %+F)\n", pred, store));
967
					exchange(info->projs[pn_Store_M], mem);
968
					kill_and_reduce_usage(store);
969
970
					return DF_CHANGED;
				}
971
			}
972
		} else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
973
974
		           value == pred_info->projs[pn_Load_res]) {
			/*
975
976
977
978
			 * a Store of a value just loaded from the same address
			 * -- a write after read.
			 * We may remove the Store, if it does not have an exception
			 * handler.
979
980
981
			 */
			if (! info->projs[pn_Store_X_except]) {
				DBG_OPT_WAR(store, pred);
982
				DB((dbg, LEVEL_1, "  killing store %+F (read %+F from same address)\n", store, pred));
983
				exchange(info->projs[pn_Store_M], mem);
984
				kill_and_reduce_usage(store);
985
986
987
988
				return DF_CHANGED;
			}
		}

989
		if (is_Store(pred)) {
Michael Beck's avatar
Michael Beck committed
990
			/* check if we can pass through this store */
991
992
			ir_alias_relation rel = get_alias_relation(
				get_Store_ptr(pred),
993
994
995
				get_type_for_mode(get_irn_mode(get_Store_value(pred))),
				ptr,
				get_type_for_mode(mode));
996
			/* if the might be an alias, we cannot pass this Store */
Michael Beck's avatar
Michael Beck committed
997
			if (rel != ir_no_alias)
998
999
				break;
			pred = skip_Proj(get_Store_mem(pred));
1000
		} else if (is_Load(pred)) {
For faster browsing, not all history is shown. View entire blame