Skip to content
← Back

src/ir/emitter/srm_method_body_emitter.ghul

1
@@IF.dotnet()
2
3
namespace IR.Emitter is
4
use System.Reflection.Metadata.BlobBuilder
5
use System.Reflection.Metadata.EntityHandle
6
use System.Reflection.Metadata.Ecma335.InstructionEncoder
7
use System.Reflection.Metadata.Ecma335.ControlFlowBuilder
8
use System.Reflection.Metadata.Ecma335.LabelHandle
9
use System.Reflection.Metadata.ILOpCode
10
11
use Semantic.Types.Type
12
13
// Instruction-level surface for one method body. Backed by SRM's
14
// InstructionEncoder; `flush` hands the encoded body to the owning
15
// assembly emitter's method body stream and returns the body offset
16
// that AddMethodDefinition takes directly (not a handle).
17
//
18
// Locals are addressed by name here even though the encoded
19
// instructions address them by slot index. Names like `result.0`
20
// are invented all over generate-il and the IR values, so taking
21
// them as given keeps the slot numbering in one place rather than
22
// threading it through every site that declares a local.
23
class SRM_METHOD_BODY_EMITTER is
24
_encoder: InstructionEncoder
25
26
// Only looked up, never enumerated: slots are numbered in the
27
// order locals are declared.
28
_local_slots: Collections.MAP[IR.LOCAL, int]
29
_local_types: Collections.LIST[Type]
30
31
// IR label to the encoder's own label. A branch can name a
32
// label the walk has not reached yet - every forward jump does,
33
// and a loop's exit is always one - so the handle is defined on
34
// first mention from either side and the encoder patches the
35
// offsets in when the body is serialized.
36
//
37
// Keyed on the label itself. Label ids restart per pass and per
38
// class, and labels are also made while a body is encoded, so
39
// neither an id nor a rendered name tells two labels apart: a
40
// shared key merges two labels into one handle, and a branch
41
// then lands wherever the other label was marked. The map is
42
// only looked up, never enumerated, and handles are defined in
43
// order of first mention, so the label's hash code never reaches
44
// the output.
45
_labels: Collections.MAP[IR.LABEL, LabelHandle]
46
47
// Protected-region boundaries. SRM takes four labels per
48
// region rather than a nesting, so each boundary has to be
49
// marked as the walk passes it and held until both ends are
50
// known. These labels have no
51
// IR.LABEL behind them - nothing branches to them - so they
52
// are numbered here rather than sharing `_labels`.
53
_region_labels: Collections.LIST[LabelHandle]
54
55
// Source positions for this body, in emission order, or null in
56
// a build that was not asked for debug information.
57
_sequence_points: Collections.LIST[SRM_SEQUENCE_POINT]?
58
59
// Open `@IL.output` regions awaiting their end offset (a stack so
60
// nested regions close innermost-first), and the completed ranges.
61
_il_output_stack: Collections.LIST[(string, int, int)]
62
_il_outputs: Collections.LIST[SRM_IL_OUTPUT_RANGE]?
63
64
// The instructions so far that can leave the evaluation stack
65
// deeper than they found it, and whether any handler is entered
66
// with the exception already on the stack. See max_stack.
67
_pushes: int
68
_has_catch: bool
69
70
init() is
71
_encoder = InstructionEncoder(BlobBuilder(32), ControlFlowBuilder())
72
73
_local_slots = Collections.MAP[IR.LOCAL, int]()
74
_local_types = Collections.LIST[Type]()
75
_labels = Collections.MAP[IR.LABEL, LabelHandle]()
76
_region_labels = Collections.LIST[LabelHandle]()
77
_il_output_stack = Collections.LIST[(string, int, int)]()
78
si
79
80
// Marks the current position and returns a handle on it that
81
// `add_catch_region` / `add_finally_region` take. An int rather
82
// than the SRM label so the walk that decides where regions
83
// begin and end needs no metadata types of its own.
84
mark_region_boundary() -> int is
85
let handle = _encoder.define_label()
86
87
_encoder.mark_label(handle)
88
89
_region_labels.add(handle)
90
91
return _region_labels.count - 1
92
si
93
94
// Regions must be added innermost first: ECMA-335 requires the
95
// ordering and the runtime relies on it, but nothing validates
96
// it, so getting it wrong yields an assembly that loads and
97
// then runs the wrong handler. Each `try` adds its own region
98
// as it closes, which puts an inner one ahead of the outer one
99
// that contains it.
100
add_catch_region(
101
try_start: int,
102
try_end: int,
103
handler_start: int,
104
handler_end: int,
105
catch_type: EntityHandle
106
) is
107
// Only called for a method that has a try/catch, so the
108
// encoder was built with a control-flow builder.
109
_has_catch = true
110
111
_encoder.control_flow_builder!.add_catch_region(
112
_region_labels[try_start],
113
_region_labels[try_end],
114
_region_labels[handler_start],
115
_region_labels[handler_end],
116
catch_type)
117
si
118
119
add_finally_region(
120
try_start: int,
121
try_end: int,
122
handler_start: int,
123
handler_end: int
124
) is
125
// Only called for a method that has a try/finally, so the
126
// encoder was built with a control-flow builder.
127
_encoder.control_flow_builder!.add_finally_region(
128
_region_labels[try_start],
129
_region_labels[try_end],
130
_region_labels[handler_start],
131
_region_labels[handler_end])
132
si
133
134
_label(label: IR.LABEL) -> LabelHandle is
135
if _labels.contains_key(label) then
136
return _labels[label]
137
fi
138
139
let handle = _encoder.define_label()
140
141
_labels[label] = handle
142
143
return handle
144
si
145
146
mark_label(label: IR.LABEL) is
147
_encoder.mark_label(_label(label))
148
si
149
150
branch(op_code: ILOpCode, label: IR.LABEL) is
151
_encoder.branch(op_code, _label(label))
152
si
153
154
// Declaring the same local twice is not an error: at least one
155
// value declares its temp on both arms of a branch. The first
156
// declaration gives the local its slot.
157
declare_local(local: IR.LOCAL) -> int is
158
if _local_slots.contains_key(local) then
159
return _local_slots[local]
160
fi
161
162
let slot = _local_types.count
163
164
_local_types.add(local.type)
165
_local_slots[local] = slot
166
167
return slot
168
si
169
170
// A load of a local that was never declared means whatever built
171
// it did not declare it. Failing here names the local, which is a
172
// far shorter path to the culprit than the invalid program it
173
// would otherwise produce.
174
_slot(local: IR.LOCAL) -> int is
175
assert _local_slots.contains_key(local) else
176
"local '{local.name}' is loaded but never declared"
177
178
return _local_slots[local]
179
si
180
181
has_locals: bool => _local_types.count > 0
182
local_types: Collections.List[Type] => _local_types
183
184
ldloc(local: IR.LOCAL) is _push(); _encoder.load_local(_slot(local)); si
185
stloc(local: IR.LOCAL) is _encoder.store_local(_slot(local)); si
186
ldloca(local: IR.LOCAL) is _push(); _encoder.load_local_address(_slot(local)); si
187
188
ldarg(index: int) is _push(); _encoder.load_argument(index); si
189
starg(index: int) is _encoder.store_argument(index); si
190
ldarga(index: int) is _push(); _encoder.load_argument_address(index); si
191
192
ldstr(metadata: SRM_ASSEMBLY_EMITTER, value: string) is
193
_push()
194
_encoder.load_string(metadata.get_or_add_user_string(value))
195
si
196
197
ldc_i4(value: int) is _push(); _encoder.load_constant_i4(value); si
198
ldc_i8(value: long) is _push(); _encoder.load_constant_i8(value); si
199
ldc_r4(value: single) is _push(); _encoder.load_constant_r4(value); si
200
ldc_r8(value: double) is _push(); _encoder.load_constant_r8(value); si
201
ldnull() is _push(); _encoder.op_code(ILOpCode.LDNULL); si
202
203
call(target: EntityHandle) is _push(); _encoder.call(target); si
204
205
// Prefixes the following call with the type its receiver is
206
// reached through, which is how a call on a value whose type is
207
// a type parameter dispatches without the caller knowing whether
208
// that parameter will be a value or a reference type.
209
constrained(type: EntityHandle) is
210
_encoder.op_code(ILOpCode.CONSTRAINED)
211
_encoder.token(type)
212
si
213
call_virtual(target: EntityHandle) is _push(); _encoder.op_code(ILOpCode.CALLVIRT); _encoder.token(target); si
214
new_object(constructor: EntityHandle) is _push(); _encoder.op_code(ILOpCode.NEWOBJ); _encoder.token(constructor); si
215
216
ldfld(`field: EntityHandle) is _field_instruction(ILOpCode.LDFLD, `field); si
217
ldflda(`field: EntityHandle) is _field_instruction(ILOpCode.LDFLDA, `field); si
218
stfld(`field: EntityHandle) is _field_instruction(ILOpCode.STFLD, `field); si
219
ldsfld(`field: EntityHandle) is _field_instruction(ILOpCode.LDSFLD, `field); si
220
ldsflda(`field: EntityHandle) is _field_instruction(ILOpCode.LDSFLDA, `field); si
221
stsfld(`field: EntityHandle) is _field_instruction(ILOpCode.STSFLD, `field); si
222
223
_field_instruction(op_code: ILOpCode, `field: EntityHandle) is
224
if op_code == ILOpCode.LDSFLD \/ op_code == ILOpCode.LDSFLDA then
225
_push()
226
fi
227
228
_encoder.op_code(op_code)
229
_encoder.token(`field)
230
si
231
232
ldtoken(type: EntityHandle) is _push(); _encoder.op_code(ILOpCode.LDTOKEN); _encoder.token(type); si
233
234
box(type: EntityHandle) is _encoder.op_code(ILOpCode.BOX); _encoder.token(type); si
235
size_of(type: EntityHandle) is _encoder.op_code(ILOpCode.SIZEOF); _encoder.token(type); si
236
unbox_any(type: EntityHandle) is _encoder.op_code(ILOpCode.UNBOX_ANY); _encoder.token(type); si
237
cast_class(type: EntityHandle) is _encoder.op_code(ILOpCode.CASTCLASS); _encoder.token(type); si
238
is_instance(type: EntityHandle) is _encoder.op_code(ILOpCode.ISINST); _encoder.token(type); si
239
240
new_array(element_type: EntityHandle) is
241
_encoder.op_code(ILOpCode.NEWARR)
242
_encoder.token(element_type)
243
si
244
245
store_element(element_type: EntityHandle) is
246
_encoder.op_code(ILOpCode.STELEM)
247
_encoder.token(element_type)
248
si
249
250
load_element(element_type: EntityHandle) is
251
_encoder.op_code(ILOpCode.LDELEM)
252
_encoder.token(element_type)
253
si
254
255
load_element_address(element_type: EntityHandle) is
256
_encoder.op_code(ILOpCode.LDELEMA)
257
_encoder.token(element_type)
258
si
259
260
load_object(type: EntityHandle) is _encoder.op_code(ILOpCode.LDOBJ); _encoder.token(type); si
261
store_object(type: EntityHandle) is _encoder.op_code(ILOpCode.STOBJ); _encoder.token(type); si
262
263
load_function_pointer(method: EntityHandle) is
264
_push()
265
_encoder.op_code(ILOpCode.LDFTN)
266
_encoder.token(method)
267
si
268
269
load_virtual_function_pointer(method: EntityHandle) is
270
_encoder.op_code(ILOpCode.LDVIRTFTN)
271
_encoder.token(method)
272
si
273
274
op(op_code: ILOpCode) is
275
if _is_push(op_code) then
276
_push()
277
fi
278
279
_encoder.op_code(op_code)
280
si
281
282
ret() is _encoder.op_code(ILOpCode.RET); si
283
284
// An upper bound on the evaluation stack depth anywhere in the
285
// body, for the header's max stack. The depth only grows at an
286
// instruction that pushes more than it pops, and by at most one
287
// there. Every path to an instruction arrives at the same depth,
288
// so a path that repeats an instruction has come back to the
289
// depth it had the first time, and no path can go deeper than
290
// one push from each such instruction. A catch handler starts
291
// with its exception on the stack, which is one more.
292
//
293
// A body that declares a large max stack is never inlined by the
294
// JIT, however small it is, so the bound has to be tight for
295
// small bodies rather than a generous constant.
296
max_stack: int => _pushes + (if _has_catch then 1 else 0 fi)
297
298
_push() is
299
_pushes = _pushes + 1
300
si
301
302
// The instructions that can leave the stack deeper than they found
303
// it. A call or newobj can push one more than it pops at most; every
304
// opcode not listed pops at least as much as it pushes.
305
_is_push(op_code: ILOpCode) -> bool =>
306
case op_code
307
when
308
ILOpCode.LDARG_0, ILOpCode.LDARG_1, ILOpCode.LDARG_2, ILOpCode.LDARG_3,
309
ILOpCode.LDARG_S, ILOpCode.LDARG, ILOpCode.LDARGA_S, ILOpCode.LDARGA,
310
ILOpCode.LDLOC_0, ILOpCode.LDLOC_1, ILOpCode.LDLOC_2, ILOpCode.LDLOC_3,
311
ILOpCode.LDLOC_S, ILOpCode.LDLOC, ILOpCode.LDLOCA_S, ILOpCode.LDLOCA,
312
ILOpCode.LDNULL, ILOpCode.LDSTR, ILOpCode.DUP,
313
ILOpCode.LDC_I4_M1, ILOpCode.LDC_I4_0, ILOpCode.LDC_I4_1, ILOpCode.LDC_I4_2,
314
ILOpCode.LDC_I4_3, ILOpCode.LDC_I4_4, ILOpCode.LDC_I4_5, ILOpCode.LDC_I4_6,
315
ILOpCode.LDC_I4_7, ILOpCode.LDC_I4_8, ILOpCode.LDC_I4_S, ILOpCode.LDC_I4,
316
ILOpCode.LDC_I8, ILOpCode.LDC_R4, ILOpCode.LDC_R8,
317
ILOpCode.LDSFLD, ILOpCode.LDSFLDA, ILOpCode.LDTOKEN, ILOpCode.LDFTN,
318
ILOpCode.ARGLIST, ILOpCode.SIZEOF,
319
ILOpCode.CALL, ILOpCode.CALLI, ILOpCode.CALLVIRT, ILOpCode.NEWOBJ
320
then
321
true
322
else
323
false
324
esac
325
326
// Note that the instructions emitted from here on belong to a
327
// new source position. Called once per statement.
328
mark_sequence_point(location: Source.LOCATION) is
329
if !_sequence_points? then
330
_sequence_points = Collections.LIST[SRM_SEQUENCE_POINT]()
331
fi
332
333
let sequence_points = _sequence_points
334
335
let offset = _encoder.offset
336
337
// Two statements can start at the same offset when the
338
// first emits nothing. A sequence-point record after the
339
// first has to advance the offset - a zero delta is the
340
// document-change marker - so the later position replaces
341
// the earlier rather than being appended after it.
342
if sequence_points.count > 0 /\
343
sequence_points[sequence_points.count - 1].il_offset == offset
344
then
345
sequence_points.remove_at(sequence_points.count - 1)
346
fi
347
348
sequence_points.add(
349
SRM_SEQUENCE_POINT(
350
offset,
351
IO.Path.get_full_path(location.file_name),
352
location.start_line,
353
location.start_column,
354
location.end_line,
355
// A sequence point's end column is exclusive, and a
356
// LOCATION's is not.
357
location.end_column + 1))
358
si
359
360
// An `@IL.output` pragma opens a region whose emitted instructions
361
// the IL test runner extracts. Only the byte-offset range is
362
// recorded here; the ranges leave with the method as a custom
363
// attribute written by SRM_STRUCTURE_WALK._write_method.
364
begin_il_output(path: string, sequence: int) is
365
_il_output_stack.add((path, _encoder.offset, sequence))
366
si
367
368
end_il_output() is
369
let top = _il_output_stack[_il_output_stack.count - 1]
370
371
_il_output_stack.remove_at(_il_output_stack.count - 1)
372
373
if !_il_outputs? then
374
_il_outputs = Collections.LIST[SRM_IL_OUTPUT_RANGE]()
375
fi
376
377
_il_outputs.add(
378
SRM_IL_OUTPUT_RANGE(top.`0, top.`1, _encoder.offset, top.`2))
379
si
380
381
il_outputs: Collections.List[SRM_IL_OUTPUT_RANGE]? => _il_outputs
382
383
flush(assembly_emitter: SRM_ASSEMBLY_EMITTER) -> int is
384
let offset = assembly_emitter.add_method_body(_encoder, self)
385
386
if let points = _sequence_points then
387
assembly_emitter.set_sequence_points(offset, points)
388
fi
389
390
return offset
391
si
392
393
// The instruction bytes encoded so far. The body is not complete
394
// until it is flushed, which is what fixes branch offsets, so
395
// this is what has been emitted rather than what will be run.
396
encoded: ubyte[] => _encoder.code_builder.to_array()
397
si
398
si