vile / scheme / native_bindings_d_vile_native.c.v
419 lines · 406 sloc · 16.37 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3// Binding helpers have fresh VM locations on every call. Flatten only helpers
4// whose values cannot escape their creating activation; no closure or location
5// from this private IR is ever published to the VM or another native graph.
6struct NativeBindingLowering {
7mut:
8 function &Function
9 prepared map[u64]&Function
10 loop_roots map[u64]bool
11 active []NativeBindingLoop
12 transformed int
13 allow_named_loops bool
14}
15
16struct NativeBindingCall {
17 constructor int = -1
18 producer int = -1
19 consumer int = -1
20 wind_before int = -1
21 wind_body int = -1
22 wind_after int = -1
23 values bool
24}
25
26struct NativeValuesDestination {
27 base int
28 arity int = -1
29}
30
31// These negative tokens are private to the nonescape proof. A guard-only
32// global load is emitted as an inert marker only after every use is checked.
33const native_values_operator = -1
34const native_cwv_operator = -2
35const native_wind_operator = -3
36const native_control_guard = -365
37
38fn native_control_operator(p &Procedure) int {
39 if !isnil(p.env) { return 0 }
40 if p.mode == .values { return native_values_operator }
41 if p.mode != .closure || isnil(p.function) { return 0 }
42 f := p.function
43 if !isnil(f.code) || f.rest || !isnil(f.star)
44 || f.goops_next_slot >= 0 || f.goops_needs_next || f.capture_depth != 0
45 || f.children.len != 0 || f.constants.len != 0 || f.names.len != 0
46 || f.global_slots.len != 0 || f.failures.len != 0 || f.instructions.len != 5 { return 0 }
47 x := f.instructions
48 if f.params == 3 && f.slot_count == 5 && x[0].op == .wind_init
49 && x[1].op == .wind_enter && x[2].op == .wind_leave
50 && x[3].op == .wind_finish && x[4].op == .ret {
51 for ins in x { if ins.a != 0 || ins.b != 0 { return 0 } }
52 return native_wind_operator
53 }
54 if f.params != 2 || f.slot_count != 2 { return 0 }
55 if x[0].op != .local || x[0].a != 0 || x[0].b != 1
56 || x[1].op != .local || x[1].a != 0 || x[1].b != 0
57 || x[2].op != .call || x[3].op != .call_values_tail || x[4].op != .ret { return 0 }
58 for ins in x[2..] { if ins.a != 0 || ins.b != 0 { return 0 } }
59 return native_cwv_operator
60}
61
62fn native_binding_operator(mut vm VM, f &Function, ins Instruction) !int {
63 slot := native_global_slot(mut vm, f, ins)!
64 value := if slot >= 0 { vm.globals[slot] } else { vm.pristine_standard(-slot - 2) }
65 if value.tag != .procedure { return 0 }
66 vm.check_callable_owner(value)!
67 return native_control_operator(value.procedure_pointer())
68}
69
70fn native_binding_calls(mut vm VM, f &Function, destination NativeValuesDestination) ![]NativeBindingCall {
71 depths := native_stack_depths(f)!
72 mut states := [][]int{len: f.instructions.len}
73 mut visited := []bool{len: f.instructions.len}
74 mut calls := []NativeBindingCall{len: f.instructions.len}
75 mut queue := [0]
76 visited[0] = true
77 for qi := 0; qi < queue.len; qi++ {
78 if queue.len > 16384 { return error('binding control flow too complex') }
79 pc := queue[qi]
80 ins := f.instructions[pc]
81 a := int(ins.a)
82 mut after := states[pc].clone()
83 match ins.op {
84 .closure, .scope_function { after << pc + 1 }
85 .constant, .local { after << 0 }
86 .global, .global_reference { after << native_binding_operator(mut vm, f, ins)! }
87 .drop { after.delete_last() }
88 .duplicate { after << after.last() }
89 .swap {
90 n := after.len
91 t := after[n - 1]
92 after[n - 1] = after[n - 2]
93 after[n - 2] = t
94 }
95 .define_local, .assign_local, .jump_false, .and_jump, .or_jump {
96 if after.last() != 0 { return error('binding helper escapes as data') }
97 if ins.op == .jump_false { after.delete_last() }
98 }
99 .implicit_call {
100 if after.last() < 0 { return error('implicit control operator') }
101 if after.last() > 0 {
102 calls[pc] = NativeBindingCall{constructor: after.last() - 1}
103 if a != 0 {
104 if after.len != 1 { return error('binding implicit tail stack') }
105 continue
106 }
107 after[after.len - 1] = 0
108 }
109 }
110 .call, .tail_call, .scope_call, .scope_tail {
111 argc := a
112 base := after.len - argc - 1
113 operator := after[base]
114 if operator == native_wind_operator {
115 if argc != 3 || after[base + 1] <= 0 || after[base + 2] <= 0 || after[base + 3] <= 0 {
116 return error('wind callbacks are not private')
117 }
118 calls[pc] = NativeBindingCall{wind_before: after[base + 1] - 1,
119 wind_body: after[base + 2] - 1, wind_after: after[base + 3] - 1}
120 } else if operator == native_cwv_operator {
121 if argc != 2 || after[base + 1] <= 0 || after[base + 2] <= 0 {
122 return error('values callbacks are not private')
123 }
124 calls[pc] = NativeBindingCall{producer: after[base + 1] - 1, consumer: after[base + 2] - 1}
125 } else {
126 for value in after[base + 1..] {
127 if value != 0 { return error('binding helper passed as an argument') }
128 }
129 if operator == native_values_operator {
130 if ins.op != .tail_call || destination.arity != argc { return error('values escape private producer') }
131 calls[pc] = NativeBindingCall{values: true}
132 } else if operator > 0 {
133 calls[pc] = NativeBindingCall{constructor: operator - 1}
134 }
135 }
136 if ins.op in [.scope_call, .scope_tail] && calls[pc].constructor < 0 {
137 return error('unknown scope helper')
138 }
139 if ins.op in [.tail_call, .scope_tail] {
140 if depths[pc] != argc + 1 { return error('binding tail stack') }
141 continue
142 }
143 after.trim(base + 1)
144 after[base] = 0
145 }
146 .ret {
147 if after.len != 1 || after[0] != 0 { return error('binding helper returned') }
148 continue
149 }
150 .jump {}
151 else { return error('unsupported binding instruction ${ins.op}') }
152 }
153 mut nexts := []int{}
154 match ins.op {
155 .jump { nexts << a }
156 .jump_false, .and_jump, .or_jump { nexts << [a, pc + 1] }
157 else { nexts << pc + 1 }
158 }
159 for branch, next in nexts {
160 mut outgoing := after.clone()
161 if ins.op in [.and_jump, .or_jump] && branch == 1 { outgoing.delete_last() }
162 if !visited[next] {
163 states[next] = outgoing
164 visited[next] = true
165 queue << next
166 } else {
167 for i, value in outgoing {
168 if value != states[next][i] {
169 return error('ambiguous binding helper identity')
170 }
171 }
172 }
173 }
174 }
175 return calls
176}
177
178fn native_lower_bindings(mut vm VM, f &Function, allow_named_loops bool) !&Function {
179 if f.instructions.len == 0 || f.instructions.len > 4096 { return error('binding function too large') }
180 // Flatten a named loop within its caller. When the compiler wrapper itself
181 // is the entry, its existing loop-body closure has the smaller native IR.
182 if native_named_wrapper(f) { return error('prefer native loop-body entry') }
183 mut needed := false
184 for ins in f.instructions {
185 if ins.op in [.closure, .scope_function] { needed = true; break }
186 }
187 if !needed { return f }
188 mut lowering := NativeBindingLowering{allow_named_loops: allow_named_loops, function: &Function{
189 code: f.code, params: f.params, slot_count: f.slot_count
190 }}
191 prepared := lowering.prepare(f)!
192 lowering.function.slot_count = prepared.slot_count
193 _ := lowering.body(mut vm, prepared, [0], true, 0, NativeValuesDestination{})!
194 return lowering.function
195}
196
197fn (mut b NativeBindingLowering) append(ins Instruction) !int {
198 if b.function.instructions.len >= 4096 { return error('expanded binding graph too large') }
199 pc := b.function.instructions.len
200 b.function.instructions << ins
201 return pc
202}
203
204fn (mut b NativeBindingLowering) body(mut vm VM, f &Function, frames []int, root_return bool, barrier int, destination NativeValuesDestination) ![]int {
205 if frames.len > 64 || f.instructions.len == 0 || f.instructions.len > 4096
206 || f.rest || !isnil(f.star) || f.goops_next_slot >= 0
207 || voidptr(f.code) != voidptr(b.function.code) || f.slot_count > 64 || f.params > 8 {
208 return error('unsupported binding helper')
209 }
210 calls := native_binding_calls(mut vm, f, destination)!
211 depths := native_stack_depths(f)!
212 constants := b.function.constants.len
213 names := b.function.names.len
214 b.function.constants << f.constants
215 b.function.names << f.names
216 for slot in f.global_slots {
217 b.function.global_slots << if slot < -1 { slot - constants } else { slot }
218 }
219 // Constructors become an inert private stack marker. It is proved to be
220 // consumed only as a call operator or dropped before entering this emitter.
221 marker := b.function.constants.len
222 b.function.constants << unspecified()
223 uninit := b.function.constants.len
224 b.function.constants << Value{tag: .uninitialized}
225 active_count := b.active.len
226 defer { b.active.trim(active_count) }
227 if u64(f) in b.loop_roots {
228 b.active << NativeBindingLoop{function: f, base: frames.last(), entry: b.function.instructions.len, barrier: barrier}
229 b.reset_locals(f, frames.last(), uninit)!
230 }
231 mut mapping := []int{len: f.instructions.len, init: -1}
232 mut jumps := []int{}
233 mut targets := []int{}
234 mut exits := []int{}
235 for pc, original in f.instructions {
236 if depths[pc] < 0 { continue }
237 mapping[pc] = b.function.instructions.len
238 mut ins := original
239 match ins.op {
240 .closure, .scope_function {
241 ins = Instruction{...ins, op: .constant, a: i32(marker), b: 0}
242 }
243 .constant { ins = Instruction{...ins, a: i32(constants + ins.a)} }
244 .global, .global_reference {
245 guard := native_binding_operator(mut vm, f, ins)! != 0
246 ins = Instruction{...ins, a: i32(names + ins.a), b: if guard { native_control_guard } else { ins.b }}
247 }
248 .local, .define_local, .assign_local {
249 depth := int(ins.a)
250 if depth < frames.len {
251 ins = Instruction{...ins, a: 0, b: i32(frames[frames.len - 1 - depth] + ins.b)}
252 } else {
253 ins = Instruction{...ins, a: i32(depth - frames.len + 1)}
254 }
255 }
256 .jump, .jump_false, .and_jump, .or_jump {
257 jumps << b.function.instructions.len
258 targets << int(ins.a)
259 }
260 .call, .tail_call, .scope_call, .scope_tail, .implicit_call {
261 tail := ins.op in [.tail_call, .scope_tail] || (ins.op == .implicit_call && ins.a != 0)
262 if calls[pc].values {
263 b.move_arguments(ins, int(ins.a), destination.base)!
264 exits << b.append(Instruction{...ins, op: .jump, a: -1, b: 0})!
265 continue
266 }
267 if calls[pc].wind_before >= 0 {
268 // These private callbacks cannot capture, reenter or otherwise
269 // observe the extent: unsupported effects decline the whole graph.
270 // All speculative mutations retain the native transaction path.
271 callbacks := [b.prepare(f.children[int(f.instructions[calls[pc].wind_before].a)])!,
272 b.prepare(f.children[int(f.instructions[calls[pc].wind_body].a)])!,
273 b.prepare(f.children[int(f.instructions[calls[pc].wind_after].a)])!]
274 mut bases := []int{}
275 for callback in callbacks {
276 if callback.params != 0 || b.function.slot_count + callback.slot_count + 1 > 64 {
277 return error('wind callback arity or width')
278 }
279 bases << b.function.slot_count
280 b.function.slot_count += callback.slot_count
281 }
282 result_slot := b.function.slot_count
283 b.function.slot_count++
284 for _ in 0 .. 4 { _ := b.append(Instruction{...ins, op: .drop, a: 0, b: 0})! }
285 for i, callback in callbacks {
286 b.reset_locals(callback, bases[i], uninit)!
287 mut nested := frames.clone()
288 nested << bases[i]
289 callback_exits := b.body(mut vm, callback, nested, false, barrier + 1,
290 if i == 1 { NativeValuesDestination{base: result_slot, arity: 1} } else { NativeValuesDestination{} })!
291 for exit in callback_exits {
292 b.function.instructions[exit] = Instruction{...b.function.instructions[exit], a: i32(b.function.instructions.len)}
293 }
294 if i != 1 { _ := b.append(Instruction{...ins, op: .drop, a: 0, b: 0})! }
295 }
296 _ := b.append(Instruction{...ins, op: .local, a: 0, b: i32(result_slot)})!
297 if tail {
298 if root_return { _ := b.append(Instruction{...ins, op: .ret, a: 0, b: 0})! } else {
299 b.scalar_destination(ins, destination)!
300 exits << b.append(Instruction{...ins, op: .jump, a: -1, b: 0})!
301 }
302 }
303 continue
304 }
305 if calls[pc].producer >= 0 {
306 producer := b.prepare(f.children[int(f.instructions[calls[pc].producer].a)])!
307 consumer := b.prepare(f.children[int(f.instructions[calls[pc].consumer].a)])!
308 if producer.params != 0 || consumer.params > 8
309 || b.function.slot_count + producer.slot_count + consumer.slot_count > 64 { return error('values callback width') }
310 producer_base := b.function.slot_count
311 consumer_base := producer_base + producer.slot_count
312 b.function.slot_count += producer.slot_count + consumer.slot_count
313 for _ in 0 .. 3 { _ := b.append(Instruction{...ins, op: .drop, a: 0, b: 0})! }
314 b.reset_locals(producer, producer_base, uninit)!
315 mut producer_frames := frames.clone()
316 producer_frames << producer_base
317 producer_exits := b.body(mut vm, producer, producer_frames, false, barrier + 1,
318 NativeValuesDestination{base: consumer_base, arity: consumer.params})!
319 for exit in producer_exits {
320 b.function.instructions[exit] = Instruction{...b.function.instructions[exit], a: i32(b.function.instructions.len)}
321 }
322 b.reset_locals(consumer, consumer_base, uninit)!
323 mut consumer_frames := frames.clone()
324 consumer_frames << consumer_base
325 consumer_exits := b.body(mut vm, consumer, consumer_frames, tail && root_return,
326 if tail { barrier } else { barrier + 1 }, if tail { destination } else { NativeValuesDestination{} })!
327 if tail { exits << consumer_exits } else {
328 for exit in consumer_exits {
329 b.function.instructions[exit] = Instruction{...b.function.instructions[exit], a: i32(b.function.instructions.len)}
330 }
331 }
332 continue
333 }
334 if calls[pc].constructor >= 0 {
335 constructor := f.instructions[calls[pc].constructor]
336 child := b.prepare(f.children[int(constructor.a)])!
337 argc := if ins.op == .implicit_call { 0 } else { int(ins.a) }
338 if child.params != argc { return error('binding arity') }
339 mut recursive := -1
340 for i, active in b.active {
341 if voidptr(active.function) == voidptr(child) { recursive = i; break }
342 }
343 if recursive >= 0 {
344 active := b.active[recursive]
345 if !tail || barrier != active.barrier { return error('non-tail private recursion') }
346 b.move_arguments(ins, argc, active.base)!
347 _ := b.append(Instruction{...ins, op: .jump, a: i32(active.entry), b: 0})!
348 continue
349 }
350 if b.function.slot_count + child.slot_count > 64 {
351 return error('binding arity or width')
352 }
353 base := b.function.slot_count
354 b.function.slot_count += child.slot_count
355 // Move evaluated arguments before resetting only this activation.
356 b.move_arguments(ins, argc, base)!
357 if u64(child) !in b.loop_roots { b.reset_locals(child, base, uninit)! }
358
359 mut nested := frames.clone()
360 nested << base
361 child_exits := b.body(mut vm, child, nested, tail && root_return, if tail { barrier } else { barrier + 1 },
362 if tail { destination } else { NativeValuesDestination{} })!
363 if tail {
364 exits << child_exits
365 } else {
366 for exit in child_exits {
367 b.function.instructions[exit] = Instruction{...b.function.instructions[exit], a: i32(b.function.instructions.len)}
368 }
369 }
370 continue
371 }
372 if ins.op == .implicit_call {
373 if !root_return { ins = Instruction{...ins, a: 0} }
374 } else if tail && !root_return {
375 _ := b.append(Instruction{...ins, op: .call})!
376 b.scalar_destination(ins, destination)!
377 exits << b.append(Instruction{...ins, op: .jump, a: -1, b: 0})!
378 continue
379 }
380 }
381 .ret {
382 if !root_return {
383 b.scalar_destination(ins, destination)!
384 exits << b.append(Instruction{...ins, op: .jump, a: -1, b: 0})!
385 continue
386 }
387 }
388 else {}
389 }
390 _ := b.append(ins)!
391 }
392 for i, pc in jumps {
393 if mapping[targets[i]] < 0 { return error('unreachable binding target') }
394 b.function.instructions[pc] = Instruction{...b.function.instructions[pc], a: i32(mapping[targets[i]])}
395 }
396 return exits
397}
398
399fn (mut b NativeBindingLowering) scalar_destination(ins Instruction, destination NativeValuesDestination) ! {
400 if destination.arity < 0 { return }
401 if destination.arity != 1 { return error('scalar producer arity') }
402 _ := b.append(Instruction{...ins, op: .define_local, a: 0, b: i32(destination.base)})!
403 _ := b.append(Instruction{...ins, op: .drop, a: 0, b: 0})!
404}
405
406// Called with the metadata arena active. Original bytecode remains immutable;
407// only lowered tables needed to re-resolve guarded bindings outlive scratch.
408fn native_retain_resolver(lowered &Function, original &Function) &Function {
409 if voidptr(lowered) == voidptr(original) { return original }
410 return &Function{
411 code: original.code
412 params: original.params
413 slot_count: lowered.slot_count
414 instructions: lowered.instructions.clone()
415 constants: lowered.constants.clone()
416 names: lowered.names.clone()
417 global_slots: lowered.global_slots.clone()
418 }
419}
420