ldstopt.c 59.4 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

Matthias Braun's avatar
Matthias Braun committed
44
45
typedef enum changes_t {
	NO_CHANGES = 0,
46
47
	DF_CHANGED = 1,       /**< data flow changed */
	CF_CHANGED = 2,       /**< control flow changed */
Matthias Braun's avatar
Matthias Braun committed
48
} changes_t;
49

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

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

66
/**
67
 * flags for control flow.
68
69
 */
enum block_flags_t {
Matthias Braun's avatar
Matthias Braun committed
70
71
	BLOCK_HAS_COND = 1, /**< Block has conditional control flow */
	BLOCK_HAS_EXC  = 2  /**< Block has exceptional control flow */
72
73
74
};

/**
75
 * a Block info.
76
 */
77
typedef struct block_info_t {
Matthias Braun's avatar
Matthias Braun committed
78
	unsigned flags;  /**< flags for the block */
79
80
} block_info_t;

81
/** the master visited flag for loop detection. */
Matthias Braun's avatar
Matthias Braun committed
82
static unsigned master_visited;
83
84
85
86
87

#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
88
89
90
/**
 * get the Load/Store info of a node
 */
91
92
static ldst_info_t *get_ldst_info(ir_node *node, struct obstack *obst)
{
93
	ldst_info_t *info = (ldst_info_t*)get_irn_link(node);
Matthias Braun's avatar
Matthias Braun committed
94
	if (info == NULL) {
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);
Matthias Braun's avatar
Matthias Braun committed
107
	if (info == NULL) {
108
		info = OALLOCZ(obst, block_info_t);
109
110
111
		set_irn_link(node, info);
	}
	return info;
112
}
113

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

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

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

/**
134
135
136
137
138
 * 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
139
 */
Matthias Braun's avatar
Matthias Braun committed
140
static void update_exc(ldst_info_t *info, ir_node *block, int pos)
Michael Beck's avatar
Michael Beck committed
141
{
142
143
144
	assert(info->exc_block == NULL && "more than one exception block found");
	info->exc_block = block;
	info->exc_idx   = pos;
145
}
Michael Beck's avatar
Michael Beck committed
146
147

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

157
	if (opcode == iro_Proj) {
Matthias Braun's avatar
Matthias Braun committed
158
		ir_node *pred = get_Proj_pred(node);
159
		opcode = get_irn_opcode(pred);
160

161
		if (opcode == iro_Load || opcode == iro_Store || opcode == iro_Call) {
Andreas Fried's avatar
Andreas Fried committed
162
			ldst_info_t *ldst_info = get_ldst_info(pred, &wenv->obst);
163
164
165
166

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

			/*
167
168
169
170
171
			 * 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
172
173
			ir_node *blk      = get_nodes_block(node);
			ir_node *pred_blk = get_nodes_block(pred);
174
175
176
177
178
			if (blk != pred_blk) {
				wenv->changes |= DF_CHANGED;
				set_nodes_block(node, pred_blk);
			}
		}
179
	} else if (opcode == iro_Block) {
Matthias Braun's avatar
Matthias Braun committed
180
181
		for (int i = get_Block_n_cfgpreds(node); i-- > 0; ) {
			bool     is_exc = false;
Andreas Fried's avatar
Andreas Fried committed
182
183
			ir_node *proj   = get_Block_cfgpred(node, i);
			ir_node *pred   = proj;
184
185
186
187
188

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

Matthias Braun's avatar
Matthias Braun committed
189
190
191
192
			if (is_Proj(proj)) {
				pred   = get_Proj_pred(proj);
				is_exc = is_x_except_Proj(proj);
			}
Andreas Fried's avatar
Andreas Fried committed
193
194
			ir_node      *pred_block = get_nodes_block(pred);
			block_info_t *bl_info    = get_block_info(pred_block, &wenv->obst);
195

196
			if (is_fragile_op(pred) && is_exc)
197
198
199
200
				bl_info->flags |= BLOCK_HAS_EXC;
			else if (is_irn_forking(pred))
				bl_info->flags |= BLOCK_HAS_COND;

201
			opcode = get_irn_opcode(pred);
Matthias Braun's avatar
Matthias Braun committed
202
203
			if (is_exc && (opcode == iro_Load || opcode == iro_Store
			               || opcode == iro_Call)) {
Andreas Fried's avatar
Andreas Fried committed
204
				ldst_info_t *ldst_info = get_ldst_info(pred, &wenv->obst);
205

Matthias Braun's avatar
Matthias Braun committed
206
				update_exc(ldst_info, node, i);
207
208
			}
		}
209
210
211
	} else if (opcode == iro_CopyB) {
		/* Just initialize a ldst_info for the CopyB node. */
		(void) get_ldst_info(node, &wenv->obst);
212
	}
213
}
Michael Beck's avatar
Michael Beck committed
214

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

			/* Do not fiddle with polymorphism. */
232
			if (is_Class_type(tp) &&
Matthias Braun's avatar
Matthias Braun committed
233
234
				(get_entity_n_overwrites(ent) > 0
			     || get_entity_n_overwrittenby(ent) > 0))
235
236
237
238
				return NULL;

			if (is_Array_type(tp)) {
				/* check bounds */
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
				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 */
255
256
			}

Matthias Braun's avatar
Matthias Braun committed
257
			if (get_entity_linkage(ent) & IR_LINKAGE_CONSTANT)
258
259
260
261
				return ent;

			/* try next */
			ptr = get_Sel_ptr(ptr);
262
263
264
265
266
267
268
269
270
271
272
		} 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;

Matthias Braun's avatar
Matthias Braun committed
273
274
275
			/* we support only one addition, reassoc should fold all others */
			if (!is_Address(ptr) && !is_Align(ptr) && !is_Offset(ptr)
			    && !is_Sel(ptr) && !is_Size(ptr))
276
277
278
279
280
				return NULL;
		} else if (is_Sub(ptr)) {
			ir_node *l = get_Sub_left(ptr);
			ir_node *r = get_Sub_right(ptr);

281
			if (get_irn_mode(l) == get_irn_mode(ptr) && is_Const(r))
282
283
284
				ptr = l;
			else
				return NULL;
Matthias Braun's avatar
Matthias Braun committed
285
286
287
			/* we support only one subtraction, reassoc should fold all others */
			if (!is_Address(ptr) && !is_Align(ptr) && !is_Offset(ptr)
			    && !is_Sel(ptr) && !is_Size(ptr))
288
				return NULL;
Matthias Braun's avatar
Matthias Braun committed
289
		} else {
290
			return NULL;
Matthias Braun's avatar
Matthias Braun committed
291
		}
292
	}
293
}
Michael Beck's avatar
Michael Beck committed
294

295
/* forward */
296
static void reduce_node_usage(ir_node *ptr);
297
298

/**
Christoph Mallon's avatar
Christoph Mallon committed
299
 * Update a Load that may have lost its users.
300
 */
301
302
static void handle_load_update(ir_node *load)
{
303
304
305
	/* do NOT touch volatile loads for now */
	if (get_Load_volatility(load) == volatility_is_volatile)
		return;
306

Matthias Braun's avatar
Matthias Braun committed
307
308
	ldst_info_t *info = (ldst_info_t*)get_irn_link(load);
	if (!info->projs[pn_Load_res] && !info->projs[pn_Load_X_except]) {
309
310
		ir_node *ptr = get_Load_ptr(load);
		ir_node *mem = get_Load_mem(load);
311

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

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

334
	/* this Proj is dead now */
Matthias Braun's avatar
Matthias Braun committed
335
	ir_node *pred = get_Proj_pred(ptr);
336
	if (is_Load(pred)) {
337
		ldst_info_t *info = (ldst_info_t*)get_irn_link(pred);
338
		info->projs[get_Proj_proj(ptr)] = NULL;
339

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

345
346
347
348
/**
 * Kill a Load or Store and all other nodes which are not needed after
 * it has been killed.
 */
Matthias Braun's avatar
Matthias Braun committed
349
350
static void kill_and_reduce_usage(ir_node *node)
{
351
	ir_node *ptr;
Matthias Braun's avatar
Matthias Braun committed
352
	ir_node *value;
353
354
	switch(get_irn_opcode(node)) {
	case iro_Load:
Matthias Braun's avatar
Matthias Braun committed
355
356
		ptr   = get_Load_ptr(node);
		value = NULL;
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
		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);
	}
}

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

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

	/* if both modes are two-complement ones, we can always convert the
386
387
388
	   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 &&
389
		  get_mode_arithmetic(old_mode) == irma_twos_complement &&
390
391
392
393
394
395
396
		  get_mode_arithmetic(new_mode) == irma_twos_complement &&
		  (!be_get_backend_param()->byte_order_big_endian
	        || old_size == new_size)) {
		return true;
	}
	return false;
}
397

Michael Beck's avatar
Michael Beck committed
398
/**
399
 * Check whether a Call is at least pure, i.e. does only read memory.
400
 */
Matthias Braun's avatar
Matthias Braun committed
401
static bool is_Call_pure(ir_node *call)
402
{
403
	ir_type *call_tp = get_Call_type(call);
Matthias Braun's avatar
Matthias Braun committed
404
	unsigned prop    = get_method_additional_properties(call_tp);
405
406
407
408

	/* check first the call type */
	if ((prop & (mtp_property_const|mtp_property_pure)) == 0) {
		/* try the called entity */
409
410
411
		ir_entity *callee = get_Call_callee(call);
		if (callee != NULL) {
			prop = get_entity_additional_properties(callee);
412
413
		}
	}
Matthias Braun's avatar
Matthias Braun committed
414
	return prop & (mtp_property_const|mtp_property_pure);
415
}
416

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

	/* TODO: long might not be enough, we should probably use some tarval thingy... */
Michael Beck's avatar
Michael Beck committed
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
	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)) {
Matthias Braun's avatar
Matthias Braun committed
447
				assert(get_Sel_n_indexs(ptr) == 1);
yb9976's avatar
yb9976 committed
448
				ir_node *index = get_Sel_index(ptr, 0);
Matthias Braun's avatar
Matthias Braun committed
449
				if (!is_Const(index))
Michael Beck's avatar
Michael Beck committed
450
451
					break;

Matthias Braun's avatar
Matthias Braun committed
452
453
				ir_type *element_type = get_entity_type(ent);
				if (get_type_state(element_type) != layout_fixed)
Michael Beck's avatar
Michael Beck committed
454
455
					break;

Matthias Braun's avatar
Matthias Braun committed
456
				int size = get_type_size_bytes(element_type);
Michael Beck's avatar
Michael Beck committed
457
458
459
460
461
462
463
464
				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
465
466
467
			break;
	}

Michael Beck's avatar
Michael Beck committed
468
469
	*pOffset = offset;
	return ptr;
470
471
}

Matthias Braun's avatar
Matthias Braun committed
472
473
static changes_t try_load_after_store(ir_node *load, ir_node *load_base_ptr,
                                      long load_offset, ir_node *store)
474
475
{
	ir_node *store_ptr      = get_Store_ptr(store);
Michael Beck's avatar
Michael Beck committed
476
477
	long     store_offset;
	ir_node *store_base_ptr = get_base_and_offset(store_ptr, &store_offset);
478
479

	if (load_base_ptr != store_base_ptr)
Matthias Braun's avatar
Matthias Braun committed
480
		return NO_CHANGES;
481

Andreas Fried's avatar
Andreas Fried committed
482
483
484
485
486
487
	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);
488

yb9976's avatar
yb9976 committed
489
	/* Ensure that Load is completely contained in Store. */
490
	if (delta < 0 || delta+load_mode_len > store_mode_len)
Matthias Braun's avatar
Matthias Braun committed
491
		return NO_CHANGES;
492

493
494
495
496
497
498
499
500
501
502
503
504
	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
505
				                        store_value, cnst, store_mode);
506
			}
507

508
509
510
			store_value = new_r_Conv(get_nodes_block(load), store_value, load_mode);
		} else {
			/* we would need some kind of bitcast node here */
Matthias Braun's avatar
Matthias Braun committed
511
			return NO_CHANGES;
512
		}
513
514
	}

Michael Beck's avatar
Michael Beck committed
515
516
	DBG_OPT_RAW(load, store_value);

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

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

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

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

yb9976's avatar
yb9976 committed
542
543
static ir_node *try_update_ptr_CopyB(ir_node *load, ir_node *load_base_ptr,
                                     long load_offset, ir_node *copyB)
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
{
	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);

Matthias Braun's avatar
Matthias Braun committed
574
	if (load_src_offset + load_size > n_copy || load_src_offset < src_offset) {
575
576
577
578
579
580
581
582
583
584
585
		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);
Matthias Braun's avatar
Matthias Braun committed
586
587
	ir_node  *cnst         = new_r_Const_long(irg, mode_Is, load_src_offset);
	ir_node  *new_load_ptr = new_r_Add(block, src_base_ptr, cnst, mode_P);
588
589
590
	return new_load_ptr;
}

591
592
593
594
/**
 * 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
595
596
597
598
599
600
 * 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
 */
Matthias Braun's avatar
Matthias Braun committed
601
static changes_t follow_Mem_chain(ir_node *load, ir_node *curr)
602
{
Matthias Braun's avatar
Matthias Braun committed
603
	changes_t    res  = NO_CHANGES;
604
	ldst_info_t *info = (ldst_info_t*)get_irn_link(load);
Michael Beck's avatar
Michael Beck committed
605
606
607
	ir_node     *ptr       = get_Load_ptr(load);
	ir_node     *mem       = get_Load_mem(load);
	ir_mode     *load_mode = get_Load_mode(load);
608

Matthias Braun's avatar
Matthias Braun committed
609
610
	ir_node *pred = curr;
	while (load != pred) {
611
		ldst_info_t *pred_info = (ldst_info_t*)get_irn_link(pred);
612
613

		/*
614
615
		 * 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
616
		 * exception handler OR they are in the same Block. In the latter
617
618
619
620
621
		 * 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
622
		 * the load Block :-(
623
624
		 * We could make it a little bit better if we would know that the
		 * exception handler of the Store jumps directly to the end...
625
		 */
626
627
		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
628
				|| get_nodes_block(load) == get_nodes_block(pred)))
629
		{
Matthias Braun's avatar
Matthias Braun committed
630
631
632
			long      load_offset;
			ir_node  *base_ptr = get_base_and_offset(ptr, &load_offset);
			changes_t changes  = try_load_after_store(load, base_ptr, load_offset, pred);
Michael Beck's avatar
Michael Beck committed
633

Matthias Braun's avatar
Matthias Braun committed
634
			if (changes != NO_CHANGES)
635
				return res | changes;
636
		} else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
637
		           can_use_stored_value(get_Load_mode(pred), load_mode)) {
638
639
			/*
			 * a Load after a Load -- a read after read.
Matthias Braun's avatar
Matthias Braun committed
640
641
642
643
			 * 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.
644
			 *
Matthias Braun's avatar
Matthias Braun committed
645
646
647
			 * Here, there is no need to check if the previous Load has an
			 * exception hander because they would have exact the same
			 * exception...
648
649
650
			 *
			 * TODO: implement load-after-load with different mode for big
			 *       endian
651
			 */
Matthias Braun's avatar
Matthias Braun committed
652
653
			if (info->projs[pn_Load_X_except] == NULL
					|| get_nodes_block(load) == get_nodes_block(pred)) {
654
655
				DBG_OPT_RAR(load, pred);

656
657
658
659
				/* the result is used */
				if (info->projs[pn_Load_res]) {
					if (pred_info->projs[pn_Load_res] == NULL) {
						/* create a new Proj again */
660
						pred_info->projs[pn_Load_res] = new_r_Proj(pred, get_Load_mode(pred), pn_Load_res);
661
					}
Andreas Fried's avatar
Andreas Fried committed
662
					ir_node *value = pred_info->projs[pn_Load_res];
663
664
665

					/* add an convert if needed */
					if (get_Load_mode(pred) != load_mode) {
666
						value = new_r_Conv(get_nodes_block(load), value, load_mode);
667
668
					}

669
					exchange(info->projs[pn_Load_res], value);
670
671
				}

672
673
674
				if (info->projs[pn_Load_M])
					exchange(info->projs[pn_Load_M], mem);

675
676
				/* no exception */
				if (info->projs[pn_Load_X_except]) {
677
					ir_graph *irg = get_irn_irg(load);
Matthias Braun's avatar
Matthias Braun committed
678
					exchange(info->projs[pn_Load_X_except], new_r_Bad(irg, mode_X));
679
680
					res |= CF_CHANGED;
				}
681
				if (info->projs[pn_Load_X_regular]) {
682
					exchange( info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
683
684
					res |= CF_CHANGED;
				}
685

686
				kill_and_reduce_usage(load);
687
688
689
690
				return res |= DF_CHANGED;
			}
		}

691
		if (is_Store(pred)) {
692
			/* check if we can pass through this store */
693
694
			ir_alias_relation rel = get_alias_relation(
				get_Store_ptr(pred),
695
696
697
				get_type_for_mode(get_irn_mode(get_Store_value(pred))),
				ptr,
				get_type_for_mode(load_mode));
698
			/* if the might be an alias, we cannot pass this Store */
Michael Beck's avatar
Michael Beck committed
699
			if (rel != ir_no_alias)
700
701
				break;
			pred = skip_Proj(get_Store_mem(pred));
702
		} else if (is_Load(pred)) {
703
			pred = skip_Proj(get_Load_mem(pred));
704
705
706
707
708
709
710
711
712
		} 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;
			}
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
		} 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));
748
749
750
751
752
753
754
755
756
757
758
		} else {
			/* follow only Load chains */
			break;
		}

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

759
	if (is_Sync(pred)) {
760
		/* handle all Sync predecessors */
Matthias Braun's avatar
Matthias Braun committed
761
		for (int i = get_Sync_n_preds(pred); i-- > 0; ) {
762
763
			res |= follow_Mem_chain(load, skip_Proj(get_Sync_pred(pred, i)));
			if (res)
764
				return res;
765
766
767
768
		}
	}

	return res;
769
}
Michael Beck's avatar
Michael Beck committed
770

771
772
ir_node *can_replace_load_by_const(const ir_node *load, ir_node *c)
{
773
774
775
776
	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);
777
	ir_node  *res    = duplicate_subgraph(dbgi, c, block);
778
779
780
781
782

	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 */
783
			res = new_rd_Conv(dbgi, block, res, l_mode);
Andreas Zwinkau's avatar
Andreas Zwinkau committed
784
785
		} else {
			return NULL;
786
787
788
		}
	}
	return res;
789
}
790

Michael Beck's avatar
Michael Beck committed
791
792
/**
 * optimize a Load
793
794
 *
 * @param load  the Load node
Michael Beck's avatar
Michael Beck committed
795
 */
Matthias Braun's avatar
Matthias Braun committed
796
static changes_t optimize_load(ir_node *load)
Michael Beck's avatar
Michael Beck committed
797
{
798
	ldst_info_t *info = (ldst_info_t*)get_irn_link(load);
Matthias Braun's avatar
Matthias Braun committed
799
	changes_t    res  = NO_CHANGES;
800
801
802

	/* do NOT touch volatile loads for now */
	if (get_Load_volatility(load) == volatility_is_volatile)
Matthias Braun's avatar
Matthias Braun committed
803
		return NO_CHANGES;
804
805

	/* the address of the load to be optimized */
Andreas Fried's avatar
Andreas Fried committed
806
	ir_node *ptr = get_Load_ptr(load);
807
808

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

811
812
813
	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 */
814
815
		exchange(info->projs[pn_Load_M], mem);

816
817
		if (info->projs[pn_Load_X_regular]) {
			/* should not happen, but if it does, remove it */
818
			exchange(info->projs[pn_Load_X_regular], new_r_Jmp(get_nodes_block(load)));
819
820
			res |= CF_CHANGED;
		}
821
		kill_and_reduce_usage(load);
822
823
824
		return res | DF_CHANGED;
	}

Matthias Braun's avatar
Matthias Braun committed
825
	/* check if we can determine the entity that will be loaded */
Andreas Fried's avatar
Andreas Fried committed
826
	ir_entity *ent = find_constant_entity(ptr);
Matthias Braun's avatar
Matthias Braun committed
827
828
829
830
831
	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
832

Matthias Braun's avatar
Matthias Braun committed
833
834
835
836
837
838
839
840
841
842
843
844
		/* 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;
		}
845
846
847
	}

	/* Check, if the address of this load is used more than once.
Michael Beck's avatar
Michael Beck committed
848
	 * If not, more load cannot be removed in any case. */
Andreas Fried's avatar
Andreas Fried committed
849
	long dummy;
850
	if (get_irn_n_edges(ptr) <= 1 && get_irn_n_edges(get_base_and_offset(ptr, &dummy)) <= 1)
851
852
853
854
855
856
857
858
859
860
861
862
		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;
863
}
Michael Beck's avatar
Michael Beck committed
864

865
866
867
868
869
870
871
/**
 * 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);
872
}
873

874
875
876
877
878
879
880
881
882
883
884
885
/**
 * 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
886
	    && get_mode_arithmetic(lm) == irma_twos_complement;
887
}
888

Michael Beck's avatar
Michael Beck committed
889
/**
Matthias Braun's avatar
Matthias Braun committed
890
891
 * follow the memory chain as long as there are only Loads and alias free
 * Stores.
Michael Beck's avatar
Michael Beck committed
892
893
 * INC_MASTER() must be called before dive into
 */
Matthias Braun's avatar
Matthias Braun committed
894
895
static changes_t follow_Mem_chain_for_Store(ir_node *store, ir_node *curr,
                                            bool had_split)
896
{
Matthias Braun's avatar
Matthias Braun committed
897
898
899
900
901
902
903
904
905
906
	changes_t    res   = NO_CHANGES;
	ldst_info_t *info  = (ldst_info_t*)get_irn_link(store);
	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);

	ir_node *pred = curr;
	while (pred != store) {
907
		ldst_info_t *pred_info = (ldst_info_t*)get_irn_link(pred);
908
909
910
911
912
913

		/*
		 * 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 ...
914
915
916
		 * 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 ...
917
		 */
918
		if (is_Store(pred) && !had_split && get_Store_ptr(pred) == ptr &&
yb9976's avatar
yb9976 committed
919
		    get_nodes_block(pred) == block) {
920
			/*
Matthias Braun's avatar
Matthias Braun committed
921
			 * a Store after a Store in the same Block -- a write after write.
922
923
924
925
926
927
			 */

			/*
			 * 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.
928
929
930
			 *
			 * TODO: What, if both have the same exception handler ???
			 */
931
932
933
934
935
			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);

936
				if (is_completely_overwritten(predmode, mode)
937
938
				        || is_partially_same(predvalue, value)) {
					DBG_OPT_WAW(pred, store);
939
					DB((dbg, LEVEL_1, "  killing store %+F (override by %+F)\n", pred, store));
940
					exchange(pred_info->projs[pn_Store_M], get_Store_mem(pred));
941
					kill_and_reduce_usage(pred);
942
943
944
945
946
947
948
949
950
951
952
953
954
955
					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);

956
				if (is_partially_same(value, predvalue)) {
957
					DBG_OPT_WAW(pred, store);
958
					DB((dbg, LEVEL_1, "  killing store %+F (override by %+F)\n", pred, store));
959
					exchange(info->projs[pn_Store_M], mem);
960
					kill_and_reduce_usage(store);
961
962
					return DF_CHANGED;
				}
963
			}
964
		} else if (is_Load(pred) && get_Load_ptr(pred) == ptr &&
965
966
		           value == pred_info->projs[pn_Load_res]) {
			/*
967
968
969
970
			 * 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.
971
			 */
Matthias Braun's avatar
Matthias Braun committed
972
			if (!info->projs[pn_Store_X_except]) {
973
				DBG_OPT_WAR(store, pred);
974
				DB((dbg, LEVEL_1, "  killing store %+F (read %+F from same address)\n", store, pred));
975
				exchange(info->projs[pn_Store_M], mem);
976
				kill_and_reduce_usage(store);