File: Layout.cpp

package info (click to toggle)
storm-lang 0.7.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 52,028 kB
  • sloc: ansic: 261,471; cpp: 140,432; sh: 14,891; perl: 9,846; python: 2,525; lisp: 2,504; asm: 860; makefile: 678; pascal: 70; java: 52; xml: 37; awk: 12
file content (580 lines) | stat: -rw-r--r-- 18,774 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
#include "stdafx.h"
#include "Layout.h"
#include "Exception.h"
#include "Asm.h"
#include "Arena.h"
#include "../Binary.h"
#include "../Layout.h"
#include "../FnState.h"

namespace code {
	namespace x64 {

		// Number used for inactive variables.
		static const Nat INACTIVE = 0xFFFFFFFF;

#define TRANSFORM(x) { op::x, &Layout::x ## Tfm }

		const OpEntry<Layout::TransformFn> Layout::transformMap[] = {
			TRANSFORM(prolog),
			TRANSFORM(epilog),
			TRANSFORM(beginBlock),
			TRANSFORM(endBlock),
			TRANSFORM(jmpBlock),
			TRANSFORM(activate),

			TRANSFORM(fnRet),
			TRANSFORM(fnRetRef),
		};


		Layout::Layout(const Arena *arena) : arena(arena) {}

		void Layout::before(Listing *dest, Listing *src) {
			// Initialize some state.
			block = Block();
			usingEH = src->exceptionAware();

			// Compute the layout of all parameters.
			params = arena->createParams(src->member);
			params->result(src->result);
			Array<Var> *p = src->allParams();
			for (Nat i = 0; i < p->count(); i++) {
				params->add(i, src->paramDesc(p->at(i)));
			}

			// Figure out which registers we need to spill.
			toPreserve = allUsedRegs(src);
			for (RegSet::Iter i = arena->dirtyRegs->begin(), end = arena->dirtyRegs->end(); i != end; ++i)
				toPreserve->remove(*i);

			// Compute the layout.
			layout = computeLayout(src, params, toPreserve->count());

			// Initialize the 'activated' array.
			Array<Var> *vars = src->allVars();
			activated = new (this) Array<Nat>(vars->count(), 0);
			activationId = 0;

			for (Nat i = 0; i < vars->count(); i++) {
				Var var = vars->at(i);
				if (src->freeOpt(var) & freeInactive)
					activated->at(var.key()) = INACTIVE;
			}

			// The EH table.
			activeBlocks = new (this) Array<ActiveBlock>();
		}

		void Layout::during(Listing *dest, Listing *src, Nat line) {
			static OpTable<TransformFn> t(transformMap, ARRAY_COUNT(transformMap));

			Instr *i = src->at(line);
			TransformFn f = t[i->op()];
			if (f) {
				(this->*f)(dest, src, line);
			} else {
				*dest << i->alter(resolve(src, i->dest()), resolve(src, i->src()));
			}
		}

		void Layout::after(Listing *dest, Listing *src) {
			*dest << alignAs(Size::sPtr);
			*dest << dest->meta();

			// Offset between RBP and RSP.
			// Note: always aligned, so LSB is clear.
			*dest << dat(ptrConst(-layout->last()));

			// Output metadata table.
			Array<Var> *vars = src->allVars();

			for (nat i = 0; i < vars->count(); i++) {
				Var &v = vars->at(i);
				Operand fn = src->freeFn(v);
				if (fn.empty())
					*dest << dat(ptrConst(Offset(0)));
				else
					*dest << dat(src->freeFn(v));
				*dest << dat(intConst(layout->at(v.key())));
				*dest << dat(natConst(activated->at(v.key())));

				// This happens sometimes in code generation, for example when a variable definition is never
				// reached. As such, we should not complain too much about it. It was useful for debugging
				// the initial migration, however.
				// if (activated->at(v.key()) == INACTIVE)
				// 	// Dont be too worried about zero-sized variables.
				// 	if (v.size() != Size())
				// 		throw new (this) VariableActivationError(v, S("Never activated."));
			}

			// Output the table containing active blocks. Used by the exception handling mechanism.
			*dest << alignAs(Size::sPtr);
			// Table contents. Each 'row' is 8 bytes.
			for (Nat i = 0; i < activeBlocks->count(); i++) {
				const ActiveBlock &a = activeBlocks->at(i);
				*dest << lblOffset(a.pos);
				*dest << dat(natConst(code::encodeFnState(a.block.key(), a.activated)));
			}

			// Table size.
			*dest << dat(ptrConst(activeBlocks->count()));
		}

		Operand Layout::resolve(Listing *src, const Operand &op) {
			return resolve(src, op, op.size());
		}

		Operand Layout::resolve(Listing *src, const Operand &op, const Size &size) {
			if (op.type() != opVariable)
				return op;

			Var v = op.var();
			if (!src->accessible(v, block))
				throw new (this) VariableUseError(v, block);
			return xRel(size, ptrFrame, op.offsetRef() + layout->at(v.key()));
		}

		static bool spillAlways(const Param &, const Offset &) {
			return true;
		}

		void Layout::spillParams(Listing *dest) {
			spillParams(dest, &spillAlways);
		}

		void Layout::spillParams(Listing *dest, SpillPredicate p) {
			Array<Var> *all = dest->allParams();

			for (Nat i = 0; i < params->registerCount(); i++) {
				Param info = params->registerParam(i);
				if (info.size() == Size())
					continue; // Not used.
				if (info.id() == Param::returnId()) {
					Offset to = resultParam();
					if ((*p)(info, to))
						*dest << mov(ptrRel(ptrFrame, resultParam()), params->registerSrc(i));
					continue;
				}

				Offset to = layout->at(all->at(info.id()).key());
				to += Offset(info.offset());

				// Skip if predicate says so.
				if (!(*p)(info, to))
					continue;

				Size size(info.size());
				Reg r = asSize(params->registerSrc(i), size);
				if (r == noReg) {
					// Size not natively supported. Round up!
					size += Size::sInt.alignment();
					r = asSize(params->registerSrc(i), size);
				}
				*dest << mov(xRel(size, ptrFrame, to), r);
			}
		}

		void Layout::prologTfm(Listing *dest, Listing *src, Nat line) {
			// Generate the prolog. Generates push and mov to set up a basic stack frame. Also emits
			// proper unwind data.
			emitProlog(dest);

			// Initialize the root block.
			initBlock(dest, dest->root(), rax);
		}

		void Layout::epilogTfm(Listing *dest, Listing *src, Nat line) {
			epilog(dest, src, line, true);
		}

		void Layout::epilog(Listing *dest, Listing *src, Nat line, Bool preserveRax) {
			// Destroy blocks. Note: we shall not modify 'block' nor alter the exception table as
			// this may be an early return from the function.
			Block oldBlock = block;
			for (Block now = block; now != Block(); now = src->parent(now)) {
				destroyBlock(dest, now, preserveRax, false);
			}
			block = oldBlock;

			emitEpilog(dest);
		}

		void Layout::beginBlockTfm(Listing *dest, Listing *src, Nat line) {
			Instr *instr = src->at(line);
			// Note: register is added in the previous pass.
			Reg freeReg = noReg;
			if (instr->dest().type() == opRegister)
				freeReg = instr->dest().reg();

			initBlock(dest, instr->src().block(), freeReg);
		}

		void Layout::endBlockTfm(Listing *dest, Listing *src, Nat line) {
			destroyBlock(dest, src->at(line)->src().block(), false, true);
		}

		void Layout::jmpBlockTfm(Listing *dest, Listing *src, Nat line) {
			// Destroy blocks until we find 'to'.
			Block to = src->at(line)->src().block();

			// We shall not modify the block level after we're done, so we must restore it.
			Block oldBlock = block;
			for (Block now = block; now != to; now = src->parent(now)) {
				if (now == Block()) {
					Str *msg = TO_S(this, S("The block ") << to << S(" is not a parent of ") << oldBlock << S("."));
					throw new (this) BlockEndError(msg);
				}

				destroyBlock(dest, now, false, false);
			}

			*dest << jmp(src->at(line)->dest().label());
			block = oldBlock;
		}

		void Layout::activateTfm(Listing *dest, Listing *src, Nat line) {
			Var var = src->at(line)->src().var();
			Nat &id = activated->at(var.key());

			if (id == 0)
				throw new (this) VariableActivationError(var, S("must be marked with 'freeInactive'."));
			if (id != INACTIVE)
				throw new (this) VariableActivationError(var, S("already activated."));

			id = ++activationId;

			// We only need to update the block id if this impacts exception handling.
			if (src->freeOpt(var) & freeOnException) {
				// We might need a nop here if the last was a call.
				padCallWithNop(dest);

				Label lbl = dest->label();
				*dest << lbl;
				activeBlocks->push(ActiveBlock(block, activationId, lbl));
			}
		}

		// Zero the memory of a variable. 'initReg' should be true if we need to set <reg> to 0
		// before using it as our zero. 'initReg' will be set to false, so that it is easy to use
		// zeroVar in a loop, causing only the first invocation to emit '<reg> := 0'.
		static void zeroVar(Listing *dest, Offset start, Size size, Reg reg, Bool &initReg) {
			nat s64 = size.size64();
			if (s64 == 0)
				return;

			reg = asSize(reg, Size::sLong);

			// Note: We could use: and <dest>, 0 - that can be encoded compactly and does not
			// require additional registers! This is what some versions of MSVC does.
			if (initReg) {
				*dest << bxor(reg, reg);
				initReg = false;
			}

			// Note: We need to be careful not to overshoot too much. We might have a stack of
			// booleans that fill up 2 or 3 bytes. Using a 4 byte fill then would potentially
			// overwrite some data.
			nat pos = 0;
			while (pos < s64) {
				if (s64 - pos >= 8) {
					*dest << mov(longRel(ptrFrame, start + Offset(pos)), reg);
					pos += 8;
				} else if (s64 - pos >= 4) {
					*dest << mov(intRel(ptrFrame, start + Offset(pos)), asSize(reg, Size::sInt));
					pos += 4;
				} else {
					*dest << mov(byteRel(ptrFrame, start + Offset(pos)), asSize(reg, Size::sByte));
					pos += 1;
				}
			}
		}

		void Layout::initBlock(Listing *dest, Block init, Operand tempSpace) {
			if (block != dest->parent(init)) {
				Str *msg = TO_S(engine(), S("Can not begin ") << init << S(" unless the current is ")
								<< dest->parent(init) << S(". Current is ") << block);
				throw new (this) BlockBeginError(msg);
			}

			block = init;

			Array<Var> *vars = dest->allVars(init);

			// Figure out which register to use for zero:
			Reg zeroReg = noReg;
			Bool initZeroReg = true;
			Bool pushed = false;

			if (tempSpace.type() == opRegister) {
				zeroReg = tempSpace.reg();
			} else if (tempSpace != Operand()) {
				// Spill register to memory:
				if (vars->any()) {
					*dest << mov(tempSpace, ptrA);
					zeroReg = ptrA;
				}
			} else {
				// Note: Not viable on Windows, but preprocessing step ensures we never get here.
				if (vars->any()) {
					zeroReg = ptrA;
					*dest << push(ptrA);
					pushed = true;
				}
			}

			// Go in reverse to make linear accesses in memory when we're using big variables.
			for (Nat i = vars->count(); i > 0; i--) {
				Var v = vars->at(i - 1);

				// Don't initialize parameters or variables that we don't need to initialize.
				if (!dest->isParam(v) && (dest->freeOpt(v) & freeNoInit) == 0)
					zeroVar(dest, layout->at(v.key()), v.size(), zeroReg, initZeroReg);
			}

			// Restore any register if necessary:
			if (pushed || !initZeroReg) {
				if (tempSpace.type() == opRegister) {
					// Nothing to do.
				} else if (tempSpace != Operand()) {
					*dest << mov(ptrA, tempSpace);
				} else {
					*dest << pop(ptrA);
				}
			}

			if (true || usingEH) { // We need info for active updates.
				padCallWithNop(dest);

				// Remember where the block started.
				Label lbl = dest->label();
				*dest << lbl;
				activeBlocks->push(ActiveBlock(block, activationId, lbl));
			}
		}

		void Layout::destroyBlock(Listing *dest, Block destroy, Bool preserveRax, Bool table) {
			if (destroy != block)
				throw new (this) BlockEndError();

			Bool savedResult = false;
			Array<Var> *vars = dest->allVars(destroy);
			// Destroy in reverse order.
			for (Nat i = vars->count(); i > 0; i--) {
				Var v = vars->at(i - 1);

				Operand dtor = dest->freeFn(v);
				FreeOpt when = dest->freeOpt(v);

				if (!dtor.empty() && (when & freeOnBlockExit) == freeOnBlockExit) {
					// Should we destroy it right now?
					if (activated->at(v.key()) > activationId)
						continue;

					if (preserveRax && !savedResult) {
						saveResult(dest);
						savedResult = true;
					}

					Reg firstParam = params->registerSrc(0);

					// Note: code in WindowsLayout.cpp ensures that we have enough shadow space here.
					if (when & freeIndirection) {
						if (when & freePtr) {
							*dest << mov(firstParam, resolve(dest, v, Size::sPtr));
							*dest << call(dtor, Size());
						} else {
							*dest << mov(firstParam, resolve(dest, v, Size::sPtr));
							*dest << mov(asSize(firstParam, v.size()), xRel(v.size(), firstParam, Offset()));
							*dest << call(dtor, Size());
						}
					} else {
						if (when & freePtr) {
							*dest << lea(firstParam, resolve(dest, v));
							*dest << call(dtor, Size());
						} else {
							*dest << mov(asSize(firstParam, v.size()), resolve(dest, v));
							*dest << call(dtor, Size());
						}
					}
					// TODO: Zero memory to avoid multiple destruction in rare cases?
				}
			}

			if (savedResult) {
				restoreResult(dest);
			}

			block = dest->parent(block);
			if ((true || usingEH) && table) { // Need this for active updates.
				padCallWithNop(dest);

				Label lbl = dest->label();
				*dest << lbl;
				activeBlocks->push(ActiveBlock(block, activationId, lbl));
			}
		}

		// Memcpy using mov instructions. Note: rdx does not need to be preserved,
		// and does never contain a part of the result on any of the supported ABIs.
		static void movMemcpy(Listing *to, Reg dest, Reg src, Size size) {
			Nat total = size.size64();
			Nat offset = 0;

			for (; offset + 8 <= total; offset += 8) {
				*to << mov(rdx, longRel(src, Offset(offset)));
				*to << mov(longRel(dest, Offset(offset)), rdx);
			}

			for (; offset + 4 <= total; offset += 4) {
				*to << mov(edx, intRel(src, Offset(offset)));
				*to << mov(intRel(dest, Offset(offset)), edx);
			}

			for (; offset + 1 <= total; offset += 1) {
				*to << mov(dl, byteRel(src, Offset(offset)));
				*to << mov(byteRel(dest, Offset(offset)), dl);
			}
		}

		// Put the return value into registers. Assumes 'srcPtr' contains a pointer to the struct to
		// be returned. 'srcPtr' can not be 'rdx'.
		static void returnSimple(Listing *dest, const Result &result, SimpleDesc *type,
								Reg srcPtr, Offset resultParam) {

			assert(!same(srcPtr, rdx));

			if (result.memoryRegister() != noReg) {
				*dest << mov(result.memoryRegister(), ptrRel(ptrFrame, resultParam));
				// Inline a memcpy using mov instructions.
				movMemcpy(dest, result.memoryRegister(), srcPtr, type->size());
			} else {
				for (Nat i = 0; i < result.registerCount(); i++) {
					Reg r = result.registerAt(i);
					*dest << mov(r, xRel(size(r), srcPtr, Offset(result.registerOffset(i))));
				}
			}
		}

		static void returnPrimitive(Listing *dest, PrimitiveDesc *p, const Operand &value, Reg target) {
			switch (p->v.kind()) {
			case primitive::none:
				break;
			case primitive::integer:
			case primitive::pointer:
				if (value.type() == opRegister && same(value.reg(), target)) {
					// Already at the correct place!
				} else {
					// A simple 'mov' is enough!
					*dest << mov(asSize(target, value.size()), value);
				}
				break;
			case primitive::real:
				// A simple 'mov' will do!
				*dest << mov(asSize(target, value.size()), value);
				break;
			}
		}

		void Layout::fnRetTfm(Listing *dest, Listing *src, Nat line) {
			Operand value = resolve(src, src->at(line)->src());
			if (value.size() != dest->result->size()) {
				StrBuf *msg = new (this) StrBuf();
				*msg << S("Wrong size passed to fnRet. Got: ");
				*msg << value.size();
				*msg << S(" but expected ");
				*msg << dest->result->size() << S(".");
				throw new (this) InvalidValue(msg->toS());
			}

			// Handle the return value.
			if (PrimitiveDesc *p = as<PrimitiveDesc>(src->result)) {
				if (params->result().registerCount() > 0)
					returnPrimitive(dest, p, value, params->result().registerAt(0));
			} else if (ComplexDesc *c = as<ComplexDesc>(src->result)) {
				// Note: Windows-specific pre-processing ensures we have shadow space here.
				// Call the copy-ctor.
				*dest << lea(params->registerSrc(1), value);
				*dest << mov(params->registerSrc(0), ptrRel(ptrFrame, resultParam()));
				*dest << call(c->ctor, Size());
				// Set 'rax' to the address of the return value.
				*dest << mov(ptrA, ptrRel(ptrFrame, resultParam()));
			} else if (SimpleDesc *s = as<SimpleDesc>(src->result)) {
				if (params->result().memoryRegister() != noReg) {
					// Just copy using memcpy. We also need to set 'ptrA' accordingly.
					// Note: ptrC is always safe to use in this context, both on Windows and Posix.
					*dest << lea(ptrC, value);
					*dest << mov(ptrA, ptrRel(ptrFrame, resultParam()));
					movMemcpy(dest, ptrA, ptrC, s->size());
				} else {
					Reg r = params->registerSrc(0);
					*dest << lea(r, value);
					returnSimple(dest, params->result(), s, r, resultParam());
				}
			} else {
				assert(false);
			}

			// Note: We could avoid some pain while calling dtors by placing code "inside" the
			// epilog codegen. For example, we could load 'resultParam' just before the epilog.
			epilogTfm(dest, src, line);
			*dest << ret(Size()); // We will not analyze registers anymore, Size() is fine.
		}

		static void returnPrimitiveRef(Listing *dest, PrimitiveDesc *p, const Operand &value, Reg target) {
			Size s(p->v.size());
			switch (p->v.kind()) {
			case primitive::none:
				break;
			case primitive::integer:
			case primitive::pointer:
				// Always two 'mov'.
				*dest << mov(asSize(target, Size::sPtr), value);
				*dest << mov(asSize(target, s), xRel(s, target, Offset()));
				break;
			case primitive::real:
				// Note: ptrA is safe as temporary here.
				*dest << mov(ptrA, value);
				*dest << mov(asSize(target, s), xRel(s, ptrA, Offset()));
				break;
			}
		}

		void Layout::fnRetRefTfm(Listing *dest, Listing *src, Nat line) {
			Operand value = resolve(src, src->at(line)->src());

			// Handle the return value.
			if (PrimitiveDesc *p = as<PrimitiveDesc>(src->result)) {
				if (params->result().registerCount() > 0)
					returnPrimitiveRef(dest, p, value, params->result().registerAt(0));
			} else if (ComplexDesc *c = as<ComplexDesc>(src->result)) {
				// Call the copy-ctor.
				*dest << mov(params->registerSrc(1), value);
				*dest << mov(params->registerSrc(0), ptrRel(ptrFrame, resultParam()));
				*dest << call(c->ctor, Size());
				// Set 'rax' to the address of the return value.
				*dest << mov(ptrA, ptrRel(ptrFrame, resultParam()));
			} else if (SimpleDesc *s = as<SimpleDesc>(src->result)) {
				if (params->result().memoryRegister() != noReg) {
					// Just copy using memcpy. We also need to set 'ptrA' accordingly.
					// Note: ptrC is always safe to use here!
					*dest << mov(ptrC, value);
					*dest << mov(ptrA, ptrRel(ptrFrame, resultParam()));
					movMemcpy(dest, ptrA, ptrC, s->size());
				} else {
					Reg r = params->registerSrc(0);
					*dest << mov(r, value);
					returnSimple(dest, params->result(), s, r, resultParam());
				}
			} else {
				assert(false);
			}

			// Note: We could avoid some pain while calling dtors by placing code "inside" the
			// epilog codegen. For example, we could load 'resultParam' just before the epilog.
			epilogTfm(dest, src, line);
			*dest << ret(Size()); // We will not analyze registers anymore, Size() is fine.
		}

	}
}