scalar_replace.c 19.3 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   Scalar replacement of compounds.
 * @author  Beyhan Veliev, Michael Beck
Michael Beck's avatar
Michael Beck committed
10
 */
11
#include <stdbool.h>
12
#include <string.h>
Michael Beck's avatar
Michael Beck committed
13
14

#include "array.h"
15
16
17
#include "be.h"
#include "debug.h"
#include "error.h"
Michael Beck's avatar
Michael Beck committed
18
#include "hashptr.h"
19
20
#include "ircons_t.h"
#include "irflag_t.h"
Michael Beck's avatar
Michael Beck committed
21
#include "irgmod.h"
22
#include "irgwalk.h"
Michael Beck's avatar
Michael Beck committed
23
#include "irnode_t.h"
24
25
26
27
28
29
30
#include "iroptimize.h"
#include "irouts.h"
#include "opt_init.h"
#include "pset.h"
#include "scalar_replace.h"
#include "set.h"
#include "tv.h"
31
#include "util.h"
32
#include "xmalloc.h"
Michael Beck's avatar
Michael Beck committed
33

34
35
36
37
38
39
40
41
42
static unsigned get_vnum(const ir_node *node)
{
	return (unsigned)PTR_TO_INT(get_irn_link(node));
}

static void set_vnum(ir_node *node, unsigned vnum)
{
	set_irn_link(node, INT_TO_PTR(vnum));
}
Michael Beck's avatar
Michael Beck committed
43

44
/**
Michael Beck's avatar
Michael Beck committed
45
 * A path element entry: it is either an entity
Michael Beck's avatar
Michael Beck committed
46
 * or a tarval, because we evaluate only constant array
47
48
49
 * accesses like a.b.c[8].d
 */
typedef union {
Michael Beck's avatar
Michael Beck committed
50
	ir_entity *ent;
Matthias Braun's avatar
Matthias Braun committed
51
	ir_tarval *tv;
52
} path_elem_t;
Michael Beck's avatar
Michael Beck committed
53

54
55
/**
 * An access path, used to assign value numbers
56
 * to variables that will be scalar replaced.
57
 */
58
typedef struct path_t {
59
60
61
	unsigned    vnum;     /**< The value number. */
	size_t      path_len; /**< The length of the access path. */
	path_elem_t path[];   /**< The path. */
62
63
} path_t;

64
/** The size of a path in bytes. */
65
66
static size_t path_size(path_t *p)
{
67
	return sizeof(*p) + sizeof(p->path[0])*p->path_len;
68
}
Michael Beck's avatar
Michael Beck committed
69

70
typedef struct scalars_t {
Michael Beck's avatar
Michael Beck committed
71
	ir_entity *ent;              /**< A entity for scalar replacement. */
72
73
} scalars_t;

74
DEBUG_ONLY(static firm_dbg_module_t *dbg;)
75
76

/**
Michael Beck's avatar
Michael Beck committed
77
78
79
 * Compare two pathes.
 *
 * @return 0 if they are identically
80
 */
81
82
static int path_cmp(const void *elt, const void *key, size_t size)
{
83
	(void)size;
84
85
	const path_t *p1 = (const path_t*)elt;
	const path_t *p2 = (const path_t*)key;
Matthias Braun's avatar
Matthias Braun committed
86
87
	/* we can use memcmp here, because identical tarvals should have identical
	 * addresses */
Michael Beck's avatar
Michael Beck committed
88
	return memcmp(p1->path, p2->path, p1->path_len * sizeof(p1->path[0]));
89
90
91
}

/**
Michael Beck's avatar
Michael Beck committed
92
93
94
 * Compare two elements of the scalars_t set.
 *
 * @return 0 if they are identically
95
 */
96
97
static int ent_cmp(const void *elt, const void *key, size_t size)
{
98
	(void)size;
99
100
	const scalars_t *c1 = (const scalars_t*)elt;
	const scalars_t *c2 = (const scalars_t*)key;
Michael Beck's avatar
Michael Beck committed
101
	return c1->ent != c2->ent;
102
103
104
}

/**
Michael Beck's avatar
Michael Beck committed
105
 * Calculate a hash value for a path.
106
 */
107
108
static unsigned path_hash(const path_t *path)
{
Michael Beck's avatar
Michael Beck committed
109
	unsigned hash = 0;
Matthias Braun's avatar
Matthias Braun committed
110
	for (unsigned i = 0; i < path->path_len; ++i)
Michael Beck's avatar
Michael Beck committed
111
		hash ^= (unsigned)PTR_TO_INT(path->path[i].ent);
112

Michael Beck's avatar
Michael Beck committed
113
	return hash >> 4;
114
115
116
}

/**
117
 * Returns non-zero, if all indices of a Sel node are constants.
118
 *
Michael Beck's avatar
Michael Beck committed
119
 * @param sel  the Sel node that will be checked
120
 */
121
static bool is_const_sel(ir_node *sel)
122
{
Matthias Braun's avatar
Matthias Braun committed
123
	for (int i = 0, n = get_Sel_n_indexs(sel); i < n; ++i) {
Michael Beck's avatar
Michael Beck committed
124
		ir_node *idx = get_Sel_index(sel, i);
125
		if (!is_Const(idx))
126
			return false;
Michael Beck's avatar
Michael Beck committed
127
	}
128
	return true;
129
130
}

131
/**
132
133
134
135
 * Return true if a Conv node converting from mode @p from to mode @p to
 * would have only bits from the source in the result.
 * Put another way, the conv produces the same value as a load/store pair:
 * Conv(val[mode_from], mode_to) == Load(Store(M, val[mode_from]), mode_to)
136
 */
137
static bool conv_is_bitcast(ir_mode *from, ir_mode *to)
138
{
139
140
141
142
143
144
145
146
147
148
	if (from == to)
		return true;

	if (get_mode_arithmetic(from) != irma_twos_complement
	    || get_mode_arithmetic(to) != irma_twos_complement)
		return false;
	unsigned from_size = get_mode_size_bits(from);
	unsigned to_size   = get_mode_size_bits(to);
	return from_size == to_size
	    || (to_size < from_size && !be_is_big_endian());
149
150
}

Michael Beck's avatar
Michael Beck committed
151
/*
Michael Beck's avatar
Michael Beck committed
152
 * Returns non-zero, if the address of an entity
153
 * represented by a Sel node (or its successor Sels) is taken.
154
 */
155
bool is_address_taken(ir_node *sel)
156
{
157
	if (!is_const_sel(sel))
158
		return true;
Michael Beck's avatar
Michael Beck committed
159

Matthias Braun's avatar
Matthias Braun committed
160
	for (unsigned i = get_irn_n_outs(sel); i-- > 0; ) {
Michael Beck's avatar
Michael Beck committed
161
162
163
		ir_node *succ = get_irn_out(sel, i);

		switch (get_irn_opcode(succ)) {
Matthias Braun's avatar
Matthias Braun committed
164
		case iro_Load: {
165
166
			/* do not remove volatile variables */
			if (get_Load_volatility(succ) == volatility_is_volatile)
167
				return true;
Michael Beck's avatar
Michael Beck committed
168
			/* check if this load is not a hidden conversion */
Matthias Braun's avatar
Matthias Braun committed
169
170
171
			ir_mode   *mode  = get_Load_mode(succ);
			ir_entity *ent   = get_Sel_entity(sel);
			ir_mode   *emode = get_type_mode(get_entity_type(ent));
172
			if (emode == NULL || !conv_is_bitcast(emode, mode))
173
				return true;
Michael Beck's avatar
Michael Beck committed
174
			break;
Matthias Braun's avatar
Matthias Braun committed
175
		}
Michael Beck's avatar
Michael Beck committed
176

Matthias Braun's avatar
Matthias Braun committed
177
		case iro_Store: {
Michael Beck's avatar
Michael Beck committed
178
			/* check that Sel is not the Store's value */
Matthias Braun's avatar
Matthias Braun committed
179
			ir_node *value = get_Store_value(succ);
Michael Beck's avatar
Michael Beck committed
180
			if (value == sel)
181
				return true;
182
183
			/* do not remove volatile variables */
			if (get_Store_volatility(succ) == volatility_is_volatile)
184
				return true;
Michael Beck's avatar
Michael Beck committed
185
			/* check if this Store is not a hidden conversion */
Matthias Braun's avatar
Matthias Braun committed
186
187
188
			ir_mode   *mode  = get_irn_mode(value);
			ir_entity *ent   = get_Sel_entity(sel);
			ir_mode   *emode = get_type_mode(get_entity_type(ent));
189
			if (emode == NULL || !conv_is_bitcast(mode, emode))
190
				return true;
Michael Beck's avatar
Michael Beck committed
191
			break;
Matthias Braun's avatar
Matthias Braun committed
192
		}
Michael Beck's avatar
Michael Beck committed
193
194

		case iro_Sel: {
Michael Beck's avatar
Michael Beck committed
195
			ir_entity *entity = get_Sel_entity(succ);
196
197
			/* we can't handle unions correctly yet -> address taken */
			if (is_Union_type(get_entity_owner(entity)))
198
				return true;
199

Michael Beck's avatar
Michael Beck committed
200
			/* Check the Sel successor of Sel */
Matthias Braun's avatar
Matthias Braun committed
201
			bool res = is_address_taken(succ);
Michael Beck's avatar
Michael Beck committed
202
			if (res)
203
				return true;
Michael Beck's avatar
Michael Beck committed
204
205
206
207
208
209
210
211
212
213
			break;
		}

		case iro_Call:
			/* The address of an entity is given as a parameter.
			 * As long as we do not have analyses that can tell what
			 * is done with parameters, think is taken.
			 * One special case: If the Call type tells that it's a
			 * value parameter, the address is NOT taken.
			 */
214
			return true;
Michael Beck's avatar
Michael Beck committed
215

216
		case iro_Id: {
Matthias Braun's avatar
Matthias Braun committed
217
			bool res = is_address_taken(succ);
218
			if (res)
219
				return true;
220
221
222
			break;
		}

223
224
		case iro_Tuple:
			/* Non-optimized Tuple, happens in inlining */
Matthias Braun's avatar
Matthias Braun committed
225
			for (int input_nr = get_Tuple_n_preds(succ); input_nr-- > 0; ) {
226
				ir_node *pred = get_Tuple_pred(succ, input_nr);
Matthias Braun's avatar
Matthias Braun committed
227
228
229
230
231
232
233
234
235
236
				if (pred != sel)
					continue;
				/* we found one input */
				for (unsigned k = get_irn_n_outs(succ); k-- > 0; ) {
					ir_node *proj = get_irn_out(succ, k);

					if (is_Proj(proj) && get_Proj_proj(proj) == input_nr) {
						bool res = is_address_taken(proj);
						if (res)
							return true;
237
238
239
240
241
					}
				}
			}
			break;

Michael Beck's avatar
Michael Beck committed
242
243
		default:
			/* another op, the address is taken */
244
			return true;
Michael Beck's avatar
Michael Beck committed
245
246
		}
	}
247
	return false;
248
249
}

250
251
252
253
254
255
256
257
258
259
/* we need a special address that serves as an address taken marker */
static char _x;
static void *ADDRESS_TAKEN = &_x;

typedef enum leaf_state_t {
	POSSIBLE_LEAF        = 0,
	HAS_CHILD_LOAD_STORE = (1u << 0),
	HAS_CHILD_SELS       = (1u << 1),
} leaf_state_t;

260
/**
261
 * Link all leaf Sels with the entity.
262
263
264
265
 *
 * @param ent  the entity that will be scalar replaced
 * @param sel  a Sel node that selects some fields of this entity
 */
266
static leaf_state_t link_all_leaf_sels(ir_entity *ent, ir_node *sel)
267
{
268
269
	/** A leaf Sel is a Sel that is used directly by a Load or Store. */
	leaf_state_t state = POSSIBLE_LEAF;
Matthias Braun's avatar
Matthias Braun committed
270
	for (unsigned i = get_irn_n_outs(sel); i-- > 0; ) {
Michael Beck's avatar
Michael Beck committed
271
272
		ir_node *succ = get_irn_out(sel, i);

273
274
275
276
		if (is_Load(succ) || is_Store(succ)) {
			state |= HAS_CHILD_LOAD_STORE;
			continue;
		}
Michael Beck's avatar
Michael Beck committed
277
		if (is_Sel(succ)) {
278
			state |= link_all_leaf_sels(ent, succ) | HAS_CHILD_SELS;
279
		} else if (is_Id(succ)) {
280
281
282
283
284
285
286
287
288
			state |= link_all_leaf_sels(ent, succ);
		} else {
			assert(is_End(succ));
		}
	}
	if (state & HAS_CHILD_SELS) {
		/* Sel is not a leaf, if it has load/stores bail out */
		if (state & HAS_CHILD_LOAD_STORE) {
			set_entity_link(ent, ADDRESS_TAKEN);
Michael Beck's avatar
Michael Beck committed
289
		}
290
		return state;
Michael Beck's avatar
Michael Beck committed
291
292
	}

293
	/* if we are here, then we have found a leaf Sel */
Michael Beck's avatar
Michael Beck committed
294

295
296
	/* beware of Id's */
	sel = skip_Id(sel);
297

298
299
300
301
302
303
304
305
306
307
308
	void *link = get_entity_link(ent);
	if (link == ADDRESS_TAKEN)
		return HAS_CHILD_LOAD_STORE | HAS_CHILD_SELS;

	/* we know we are at a leaf, because this function is only called if
	 * the address is NOT taken, so sel's successor(s) must be Loads or
	 * Stores */
	set_irn_link(sel, link);
	set_entity_link(ent, sel);
	return state;
}
309
310

/**
Michael Beck's avatar
Michael Beck committed
311
 * Find possible scalar replacements.
312
313
314
315
316
 *
 * @param irg  an IR graph
 *
 * This function finds variables on the (members of the) frame type
 * that can be scalar replaced, because their address is never taken.
317
 * If such a variable is found, its entity link will hold a list of all
Michael Beck's avatar
Michael Beck committed
318
319
320
 * Sel nodes, that selects the atomic fields of this entity.
 * Otherwise, the link will be ADDRESS_TAKEN or NULL.
 *
321
 * @return  true if at least one entity could be replaced potentially
322
 */
323
static bool find_possible_replacements(ir_graph *irg)
324
{
Matthias Braun's avatar
Matthias Braun committed
325
326
	/* First, clear the link field of all interesting entities. */
	ir_type *frame_tp = get_irg_frame_type(irg);
327
328
	for (size_t i = get_class_n_members(frame_tp); i-- > 0;) {
		ir_entity *ent = get_class_member(frame_tp, i);
329
		set_entity_link(ent, NULL);
Michael Beck's avatar
Michael Beck committed
330
331
	}

332
333
	/* check for inner functions:
	 * FIXME: need a way to get the argument position for the static link */
Matthias Braun's avatar
Matthias Braun committed
334
	long static_link_arg = 0;
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
	for (size_t i = get_class_n_members(frame_tp); i-- > 0;) {
		ir_entity *ent = get_class_member(frame_tp, i);
		if (!is_method_entity(ent))
			continue;

		ir_graph *inner_irg = get_entity_irg(ent);
		ir_node  *args;
		assure_irg_properties(inner_irg, IR_GRAPH_PROPERTY_CONSISTENT_OUTS
									   | IR_GRAPH_PROPERTY_NO_TUPLES);
		args = get_irg_args(inner_irg);
		for (unsigned j = get_irn_n_outs(args); j-- > 0; ) {
			ir_node *arg = get_irn_out(args, j);
			if (get_Proj_proj(arg) != static_link_arg)
				continue;

			for (unsigned k = get_irn_n_outs(arg); k-- > 0; ) {
				ir_node *succ = get_irn_out(arg, k);
				if (!is_Sel(succ))
					continue;
				ir_entity *ent = get_Sel_entity(succ);
				if (get_entity_owner(ent) == frame_tp) {
					/* found an access to the outer frame */
					set_entity_link(ent, ADDRESS_TAKEN);
358
359
360
361
362
				}
			}
		}
	}

363
364
	/* Check the ir_graph for Sel nodes. If the entity of Sel isn't a scalar
	 * replacement set the link of this entity to ADDRESS_TAKEN. */
Matthias Braun's avatar
Matthias Braun committed
365
366
	ir_node *irg_frame = get_irg_frame(irg);
	int      res       = 0;
Matthias Braun's avatar
Matthias Braun committed
367
	for (unsigned i = get_irn_n_outs(irg_frame); i-- > 0; ) {
Michael Beck's avatar
Michael Beck committed
368
		ir_node *succ = get_irn_out(irg_frame, i);
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
		if (!is_Sel(succ))
			continue;

		/* we are only interested in entities on the frame, NOT on the value
		 * type */
		ir_entity *ent = get_Sel_entity(succ);
		if (get_entity_owner(ent) != frame_tp)
			continue;
		if (get_entity_link(ent) == ADDRESS_TAKEN)
			continue;

		/* we can handle arrays, structs and atomic types yet */
		ir_type *ent_type = get_entity_type(ent);
		if (is_aggregate_type(ent_type) || is_atomic_type(ent_type)) {
			if (is_address_taken(succ)) {
				 /* killing one */
				if (get_entity_link(ent))
					--res;
				set_entity_link(ent, ADDRESS_TAKEN);
			} else {
				/* possible found one */
				if (get_entity_link(ent) == NULL)
					++res;
				link_all_leaf_sels(ent, succ);
Michael Beck's avatar
Michael Beck committed
393
394
395
396
			}
		}
	}

397
	return res != 0;
398
399
400
}

/**
401
 * Return a path from the Sel node "sel" to its root.
Michael Beck's avatar
Michael Beck committed
402
403
404
 *
 * @param sel  the Sel node
 * @param len  the length of the path so far
405
 */
406
static path_t *find_path(ir_node *sel, size_t len)
407
{
Michael Beck's avatar
Michael Beck committed
408
	/* the current Sel node will add some path elements */
Matthias Braun's avatar
Matthias Braun committed
409
	int n = get_Sel_n_indexs(sel);
Michael Beck's avatar
Michael Beck committed
410
	len += n + 1;
411

Matthias Braun's avatar
Matthias Braun committed
412
413
	path_t  *res;
	ir_node *pred = get_Sel_ptr(sel);
414
	if (!is_Sel(pred)) {
Michael Beck's avatar
Michael Beck committed
415
		/* we found the root */
416
		res = XMALLOCF(path_t, path, len);
Michael Beck's avatar
Michael Beck committed
417
		res->path_len = len;
Matthias Braun's avatar
Matthias Braun committed
418
	} else {
Michael Beck's avatar
Michael Beck committed
419
		res = find_path(pred, len);
Matthias Braun's avatar
Matthias Braun committed
420
	}
421

Michael Beck's avatar
Michael Beck committed
422
	assert(len <= res->path_len);
Matthias Braun's avatar
Matthias Braun committed
423
	size_t pos = res->path_len - len;
Michael Beck's avatar
Michael Beck committed
424
	res->path[pos++].ent = get_Sel_entity(sel);
Matthias Braun's avatar
Matthias Braun committed
425
	for (int i = 0; i < n; ++i) {
Michael Beck's avatar
Michael Beck committed
426
		ir_node *index = get_Sel_index(sel, i);
427

Michael Beck's avatar
Michael Beck committed
428
429
430
		res->path[pos++].tv = get_Const_tarval(index);
	}
	return res;
431
432
433
434
}


/**
435
 * Allocate value numbers for the leafs in our found entities.
436
 *
Michael Beck's avatar
Michael Beck committed
437
 * @param sels  a set that will contain all Sels that have a value number
438
439
440
441
442
443
444
 * @param ent   the entity that will be scalar replaced
 * @param vnum  the first value number we can assign
 * @param modes a flexible array, containing all the modes of
 *              the value numbers.
 *
 * @return the next free value number
 */
445
446
static unsigned allocate_value_numbers(pset *sels, ir_entity *ent,
                                       unsigned vnum, ir_mode ***modes)
447
{
Michael Beck's avatar
Michael Beck committed
448
	set *pathes = new_set(path_cmp, 8);
449

450
	DB((dbg, SET_LEVEL_3, "  Visiting Sel nodes of entity %+F\n", ent));
Michael Beck's avatar
Michael Beck committed
451
	/* visit all Sel nodes in the chain of the entity */
452
	for (ir_node *sel = (ir_node*)get_entity_link(ent), *next; sel != NULL;
Matthias Braun's avatar
Matthias Braun committed
453
	     sel = next) {
454
		next = (ir_node*)get_irn_link(sel);
455

Michael Beck's avatar
Michael Beck committed
456
457
		/* we must mark this sel for later */
		pset_insert_ptr(sels, sel);
Michael Beck's avatar
Michael Beck committed
458

Matthias Braun's avatar
Matthias Braun committed
459
460
		path_t *key  = find_path(sel, 0);
		path_t *path = set_find(path_t, pathes, key, path_size(key), path_hash(key));
461

462
		if (path != NULL) {
463
			set_vnum(sel, path->vnum);
464
465
			DB((dbg, SET_LEVEL_3, "  %+F represents value %u\n", sel, path->vnum));
		} else {
Michael Beck's avatar
Michael Beck committed
466
			key->vnum = vnum++;
467

yb9976's avatar
yb9976 committed
468
			(void)set_insert(path_t, pathes, key, path_size(key), path_hash(key));
469

470
			set_vnum(sel, key->vnum);
471
472
			DB((dbg, SET_LEVEL_3, "  %+F represents value %u\n", sel, key->vnum));

473
			ARR_EXTO(ir_mode *, *modes, (key->vnum + 15) & ~15);
474

Michael Beck's avatar
Michael Beck committed
475
			(*modes)[key->vnum] = get_type_mode(get_entity_type(get_Sel_entity(sel)));
476

Michael Beck's avatar
Michael Beck committed
477
			assert((*modes)[key->vnum] && "Value is not atomic");
Michael Beck's avatar
Michael Beck committed
478
479

#ifdef DEBUG_libfirm
Michael Beck's avatar
Michael Beck committed
480
			/* Debug output */
Matthias Braun's avatar
Matthias Braun committed
481
482
483
484
485
486
			DB((dbg, SET_LEVEL_2, "  %s", get_entity_name(key->path[0].ent)));
			for (unsigned i = 1; i < key->path_len; ++i) {
				if (is_entity(key->path[i].ent))
					DB((dbg, SET_LEVEL_2, ".%s", get_entity_name(key->path[i].ent)));
				else
					DB((dbg, SET_LEVEL_2, "[%ld]", get_tarval_long(key->path[i].tv)));
Michael Beck's avatar
Michael Beck committed
487
			}
Matthias Braun's avatar
Matthias Braun committed
488
			DB((dbg, SET_LEVEL_2, " = %u (%s)\n", PTR_TO_INT(get_irn_link(sel)), get_mode_name((*modes)[key->vnum])));
Michael Beck's avatar
Michael Beck committed
489
#endif /* DEBUG_libfirm */
Michael Beck's avatar
Michael Beck committed
490
491
492
		}
		free(key);
	}
493

Michael Beck's avatar
Michael Beck committed
494
495
496
	del_set(pathes);
	set_entity_link(ent, NULL);
	return vnum;
497
498
499
500
501
}

/**
 * environment for memory walker
 */
502
typedef struct env_t {
503
504
505
	unsigned  nvals;   /**< number of values */
	ir_mode **modes;   /**< the modes of the values */
	pset     *sels;    /**< A set of all Sel nodes that have a value number */
506
507
508
} env_t;

/**
509
 * topological post-walker.
510
 */
511
static void walker(ir_node *node, void *ctx)
512
{
513
	env_t    *env = (env_t*)ctx;
Michael Beck's avatar
Michael Beck committed
514

515
	if (is_Load(node)) {
Michael Beck's avatar
Michael Beck committed
516
		/* a load, check if we can resolve it */
Matthias Braun's avatar
Matthias Braun committed
517
		ir_node *addr = get_Load_ptr(node);
518
		if (!is_Sel(addr))
Michael Beck's avatar
Michael Beck committed
519
			return;
520
		if (!pset_find_ptr(env->sels, addr))
Michael Beck's avatar
Michael Beck committed
521
522
523
			return;

		/* ok, we have a Load that will be replaced */
Matthias Braun's avatar
Matthias Braun committed
524
		unsigned vnum = get_vnum(addr);
525
		assert(vnum < env->nvals);
Michael Beck's avatar
Michael Beck committed
526

527
		DB((dbg, SET_LEVEL_3, "replacing %+F by value %u\n", node, vnum));
Michael Beck's avatar
Michael Beck committed
528

529
530
		ir_node  *block = get_nodes_block(node);
		ir_graph *irg   = get_Block_irg(block);
531
		set_r_cur_block(irg, block);
532

Michael Beck's avatar
Michael Beck committed
533
		/* check, if we can replace this Load */
534
		ir_node *val = get_r_value(irg, vnum, env->modes[vnum]);
Michael Beck's avatar
Michael Beck committed
535

536
537
538
539
540
541
542
		/* Beware: A Load can contain a hidden conversion in Firm.
		This happens for instance in the following code:

		 int i;
		 unsigned j = *(unsigned *)&i;

		Handle this here. */
543
544
545
546
		ir_mode *load_mode = get_Load_mode(node);
		ir_mode *val_mode  = get_irn_mode(val);
		if (load_mode != val_mode)
			val = new_rd_Conv(get_irn_dbg_info(node), block, val, load_mode);
547

Matthias Braun's avatar
Matthias Braun committed
548
		ir_node *mem = get_Load_mem(node);
549
		ir_node *in[pn_Load_max+1] = {
550
551
552
			[pn_Load_M]         = mem,
			[pn_Load_res]       = val,
		};
553
554
555
556
557
558
559
560
		assert(pn_Load_M == 0 && pn_Load_res == 1);
		int n_in = 2;
		if (ir_throws_exception(node)) {
			in[pn_Load_X_regular] = new_r_Jmp(block);
			in[pn_Load_X_except]  = new_r_Bad(irg, mode_X);
			n_in = 4;
		}
		turn_into_tuple(node, n_in, in);
561
	} else if (is_Store(node)) {
Michael Beck's avatar
Michael Beck committed
562
		/* a Store always can be replaced */
Matthias Braun's avatar
Matthias Braun committed
563
		ir_node *addr = get_Store_ptr(node);
564
		if (!is_Sel(addr))
Michael Beck's avatar
Michael Beck committed
565
			return;
566
		if (!pset_find_ptr(env->sels, addr))
Michael Beck's avatar
Michael Beck committed
567
568
			return;

Matthias Braun's avatar
Matthias Braun committed
569
		unsigned vnum = get_vnum(addr);
570
		assert(vnum < env->nvals);
Michael Beck's avatar
Michael Beck committed
571

572
		DB((dbg, SET_LEVEL_3, "replacing %+F by value %u\n", node, vnum));
Michael Beck's avatar
Michael Beck committed
573

Matthias Braun's avatar
Matthias Braun committed
574
		ir_node *block = get_nodes_block(node);
575
		ir_graph *irg  = get_Block_irg(block);
576
		set_r_cur_block(irg, block);
577

Michael Beck's avatar
Michael Beck committed
578
		/* Beware: A Store can contain a hidden conversion in Firm. */
Matthias Braun's avatar
Matthias Braun committed
579
		ir_node *val = get_Store_value(node);
580
581
582
583
		ir_mode *store_mode = get_irn_mode(val);
		ir_mode *val_mode   = env->modes[vnum];
		if (store_mode != val_mode)
			val = new_rd_Conv(get_irn_dbg_info(node), block, val, val_mode);
Michael Beck's avatar
Michael Beck committed
584

585
		set_r_value(irg, vnum, val);
Michael Beck's avatar
Michael Beck committed
586

Matthias Braun's avatar
Matthias Braun committed
587
		ir_node *mem = get_Store_mem(node);
588
		ir_node *in[pn_Store_max+1] = {
589
590
			[pn_Store_M]         = mem,
		};
591
592
593
594
595
596
597
598
		assert(pn_Store_M == 0);
		int n_in = 1;
		if (ir_throws_exception(node)) {
			in[pn_Store_X_regular] = new_r_Jmp(block);
			in[pn_Store_X_except]  = new_r_Bad(irg, mode_X);
			n_in = 3;
		}
		turn_into_tuple(node, n_in, in);
Michael Beck's avatar
Michael Beck committed
599
	}
600
601
602
}

/**
603
 * Make scalar replacement.
604
 *
Michael Beck's avatar
Michael Beck committed
605
606
 * @param sels    A set containing all Sel nodes that have a value number
 * @param nvals   The number of scalars.
Michael Beck's avatar
Michael Beck committed
607
608
 * @param modes   A flexible array, containing all the modes of
 *                the value numbers.
609
 */
610
static void do_scalar_replacements(ir_graph *irg, pset *sels, unsigned nvals,
611
                                   ir_mode **modes)
612
{
613
	ssa_cons_start(irg, (int)nvals);
614

Michael Beck's avatar
Michael Beck committed
615
616
617
618
	/*
	 * second step: walk over the graph blockwise in topological order
	 * and fill the array as much as possible.
	 */
619
	DB((dbg, SET_LEVEL_3, "Substituting Loads and Stores in %+F\n", irg));
Matthias Braun's avatar
Matthias Braun committed
620
621
622
623
	env_t env;
	env.nvals = nvals;
	env.modes = modes;
	env.sels  = sels;
624
	irg_walk_blkwise_graph(irg, NULL, walker, &env);
Michael Beck's avatar
Michael Beck committed
625

626
	ssa_cons_finish(irg);
627
628
629
630
631
}

/*
 * Find possible scalar replacements
 *
Michael Beck's avatar
Michael Beck committed
632
 * @param irg  The current ir graph.
Michael Beck's avatar
Michael Beck committed
633
 */
634
void scalar_replacement_opt(ir_graph *irg)
635
{
Matthias Braun's avatar
Matthias Braun committed
636
637
638
	assure_irg_properties(irg, IR_GRAPH_PROPERTY_NO_UNREACHABLE_CODE
	                         | IR_GRAPH_PROPERTY_CONSISTENT_OUTS
	                         | IR_GRAPH_PROPERTY_NO_TUPLES);
639

640
	/* we use the link field to store the VNUM */
641
	ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
642
	irp_reserve_resources(irp, IRP_RESOURCE_ENTITY_LINK);
643

Michael Beck's avatar
Michael Beck committed
644
	/* Find possible scalar replacements */
645
	bool changed = false;
Michael Beck's avatar
Michael Beck committed
646
	if (find_possible_replacements(irg)) {
647
		DB((dbg, SET_LEVEL_1, "Scalar Replacement: %+F\n", irg));
Michael Beck's avatar
Michael Beck committed
648
649

		/* Insert in set the scalar replacements. */
Matthias Braun's avatar
Matthias Braun committed
650
651
652
653
654
655
		ir_node  *irg_frame = get_irg_frame(irg);
		unsigned  nvals     = 0;
		ir_mode **modes     = NEW_ARR_F(ir_mode *, 16);
		set      *set_ent   = new_set(ent_cmp, 8);
		pset     *sels      = pset_new_ptr(8);
		ir_type  *frame_tp  = get_irg_frame_type(irg);
Michael Beck's avatar
Michael Beck committed
656

Matthias Braun's avatar
Matthias Braun committed
657
		for (unsigned i = get_irn_n_outs(irg_frame); i-- > 0; ) {
Michael Beck's avatar
Michael Beck committed
658
			ir_node *succ = get_irn_out(irg_frame, i);
659
660
			if (!is_Sel(succ))
				continue;
Michael Beck's avatar
Michael Beck committed
661

662
663
664
665
666
667
			/* we are only interested in entities on the frame, NOT
			   parameters */
			ir_entity *ent = get_Sel_entity(succ);
			if (get_entity_owner(ent) != frame_tp
				|| is_parameter_entity(ent))
				continue;
668

669
670
671
			if (get_entity_link(ent) == NULL
				|| get_entity_link(ent) == ADDRESS_TAKEN)
				continue;
Michael Beck's avatar
Michael Beck committed
672

673
674
675
			scalars_t key;
			key.ent = ent;
			(void)set_insert(scalars_t, set_ent, &key, sizeof(key), hash_ptr(key.ent));
Michael Beck's avatar
Michael Beck committed
676

677
#ifdef DEBUG_libfirm
678
			ir_type *ent_type = get_entity_type(ent);
Michael Beck's avatar
Michael Beck committed
679

680
681
682
683
684
685
686
687
			if (is_Array_type(ent_type)) {
				DB((dbg, SET_LEVEL_1, "  found array %s\n", get_entity_name(ent)));
			} else if (is_compound_type(ent_type)) {
				DB((dbg, SET_LEVEL_1, "  found struct %s\n", get_entity_name(ent)));
			} else if (is_atomic_type(ent_type))
				DB((dbg, SET_LEVEL_1, "  found atomic value %s\n", get_entity_name(ent)));
			else {
				panic("Neither an array nor a struct or atomic value found in scalar replace");
Michael Beck's avatar
Michael Beck committed
688
			}
689
690
691
#endif

			nvals = allocate_value_numbers(sels, ent, nvals, &modes);
Michael Beck's avatar
Michael Beck committed
692
693
		}

694
		DB((dbg, SET_LEVEL_1, "  %u values will be needed\n", nvals));
Michael Beck's avatar
Michael Beck committed
695
696

		/* If scalars were found. */
697
		if (nvals > 0) {
698
			do_scalar_replacements(irg, sels, nvals, modes);
Michael Beck's avatar
Michael Beck committed
699

700
			foreach_set(set_ent, scalars_t, value) {
701
				free_entity(value->ent);
Michael Beck's avatar
Michael Beck committed
702
703
			}

704
			changed = true;
Michael Beck's avatar
Michael Beck committed
705
		}
706
707
708
		del_pset(sels);
		del_set(set_ent);
		DEL_ARR_F(modes);
Michael Beck's avatar
Michael Beck committed
709
710
	}

711
	ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
712
	irp_free_resources(irp, IRP_RESOURCE_ENTITY_LINK);
713

714
715
	confirm_irg_properties(irg, changed ? IR_GRAPH_PROPERTIES_NONE
	                                    : IR_GRAPH_PROPERTIES_ALL);
Michael Beck's avatar
Michael Beck committed
716
}
717

718
719
void firm_init_scalar_replace(void)
{
720
721
	FIRM_DBG_REGISTER(dbg, "firm.opt.scalar_replace");
}