vile / scheme / native_execution_d_vile_native.c.v
1122 lines · 1078 sloc · 40.77 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import os
4import strings
5import dl
6import math
7import arena
8
9$if !macos || freestanding {
10 $compile_error('native execution currently requires a hosted macOS C build')
11}
12
13// Graph inspection borrows live procedures only during compilation. Plans
14// retain code identities and selectors, never captured procedure environments.
15enum NativeProviderKind {
16 root
17 global
18 argument
19 capture
20}
21
22struct NativeProvider {
23 kind NativeProviderKind
24 parent int
25 depth int
26 slot int
27}
28
29struct NativeNode {
30 provider NativeProvider
31 procedure Value
32mut:
33 function &Function = unsafe { nil }
34}
35
36struct NativeGraph {
37mut:
38 nodes []NativeNode
39 instructions int
40 captures int
41 uses_vectors bool
42 uses_bytevectors bool
43 uses_text bool
44 uses_not bool
45 writes_vectors bool
46 writes_captures bool
47}
48
49fn native_graph(mut vm VM, root Value, arguments []Value) !NativeGraph {
50 mut graph := NativeGraph{ nodes: [NativeNode{ procedure: root }] }
51 for i, value in arguments {
52 if value.tag == .procedure {
53 graph.nodes << NativeNode{ provider: NativeProvider{kind: .argument, slot: i}, procedure: value }
54 }
55 }
56 mut globals := map[int]bool{}
57 mut index := 0
58 for index < graph.nodes.len {
59 node := graph.nodes[index]
60 if node.procedure.tag != .procedure { return error('non-procedure call') }
61 vm.check_callable_owner(node.procedure)!
62 p := node.procedure.procedure_pointer()
63 if p.mode != .closure || isnil(p.function.code) || p.function.code.builtin_root
64 || p.function.rest || !isnil(p.function.star) || p.function.goops_next_slot >= 0 {
65 return error('unsupported callable protocol')
66 }
67 // A function-argument loop can instead enter through its existing VM
68 // closure, where the callback becomes a guarded capture. Keep that
69 // smaller loop entry rather than widening it with the caller's locals.
70 allow_named_loops := index != 0 || !arguments.any(it.tag == .procedure)
71 f := native_lower_bindings(mut vm, p.function, allow_named_loops)!
72 graph.nodes[index].function = f
73 graph.instructions += f.instructions.len
74 if graph.instructions > 4096 || graph.nodes.len > 32 { return error('graph too large') }
75 depths := native_stack_depths(f)!
76 for pc, instruction in f.instructions {
77 if depths[pc] < 0 { continue }
78 match instruction.op {
79 .constant {
80 value := f.constants[int(instruction.a)]
81 if value.tag !in [.integer, .real, .boolean, .nil, .unspecified, .uninitialized, .character] {
82 return error('non-scalar constant')
83 }
84 }
85 .global, .global_reference {
86 mut slot := -1
87 if instruction.op == .global_reference {
88 mut resolver := Machine{ function: f }
89 resolved, _ := resolver.global_reference_slot(mut vm, int(instruction.a))!
90 slot = resolved
91 } else {
92 slot = f.global_slots[int(instruction.a)]
93 if slot < 0 {
94 slot = vm.global_index_in(f.code.namespace, f.names[int(instruction.a)])!
95 }
96 }
97 value := if slot >= 0 {
98 vm.globals[slot]
99 } else {
100 vm.pristine_standard(-slot - 2)
101 }
102 if value.tag != .procedure {
103 _ := native_input_scalar(value) or { return error('unsupported global value') }
104 graph.captures++
105 if graph.captures > 1024 { return error('too many native captures') }
106 continue
107 }
108 vm.check_callable_owner(value)!
109 target := value.procedure_pointer()
110 if instruction.b == native_control_guard {
111 if native_control_operator(target) == 0 { return error('changed private control operator') }
112 continue
113 }
114 if target.mode == .primitive {
115 if !isnil(target.env) || target.primitive !in [.add, .subtract, .multiply,
116 .num_eq, .less, .greater, .less_equal, .greater_equal, .cons, .car,
117 .cdr, .nullp, .pairp, .quotient, .remainder, .modulo, .inexact_to_exact,
118 .vector_ref, .vector_set, .vector_length, .bytevector_ref, .bytevector_set, .bytevector_length,
119 .string_ref, .string_length, .char_to_integer, .not] {
120 return error('unsupported primitive or extension')
121 }
122 if target.primitive in [.vector_ref, .vector_set, .vector_length] { graph.uses_vectors = true }
123 if target.primitive in [.bytevector_ref, .bytevector_set, .bytevector_length] { graph.uses_bytevectors = true }
124 if target.primitive in [.string_ref, .string_length] { graph.uses_text = true }
125 if target.primitive == .not { graph.uses_not = true }
126 if target.primitive in [.vector_set, .bytevector_set] { graph.writes_vectors = true }
127 } else if target.mode == .closure {
128 if slot !in globals {
129 globals[slot] = true
130 graph.nodes << NativeNode{ provider: NativeProvider{kind: .global, slot: slot}, procedure: value }
131 }
132 } else {
133 return error('effectful or unsupported global')
134 }
135 }
136 .local {
137 if instruction.a > 0 {
138 value := native_capture_value(p, int(instruction.a), int(instruction.b)) or {
139 return error('missing captured slot')
140 }
141 if value.tag == .procedure {
142 mut known := false
143 for candidate in graph.nodes {
144 if candidate.procedure.pointer() == value.pointer() { known = true; break }
145 }
146 if !known {
147 graph.nodes << NativeNode{provider: NativeProvider{kind: .capture, parent: index,
148 depth: int(instruction.a), slot: int(instruction.b)}, procedure: value}
149 }
150 } else {
151 _ := native_input_scalar(value) or { return error('unsupported captured value') }
152 }
153 graph.captures++
154 if graph.captures > 1024 { return error('too many native captures') }
155 }
156 }
157 .define_local {
158 if instruction.a != 0 { return error('captured definition') }
159 }
160 .assign_local {
161 if instruction.a > 0 {
162 value := native_capture_value(p, int(instruction.a), int(instruction.b)) or { return error('missing capture assignment') }
163 if value.tag !in [.integer, .real, .boolean, .nil, .unspecified] { return error('non-scalar capture assignment') }
164 graph.captures++
165 if graph.captures > 1024 { return error('too many native captures') }
166 graph.writes_captures = true
167 }
168 }
169 .drop, .duplicate, .swap, .jump, .jump_false, .and_jump, .or_jump, .call,
170 .tail_call, .implicit_call, .ret {
171 }
172 else { return error('unsupported instruction ${instruction.op}') }
173 }
174 }
175 index++
176 }
177 return graph
178}
179
180fn native_procedure_target(graph NativeGraph, node int, value Value) int {
181 if value.pointer() == graph.nodes[node].procedure.pointer() { return node }
182 for i, provider in graph.nodes {
183 if provider.procedure.pointer() == value.pointer() { return i }
184 }
185 return -1
186}
187
188fn native_capture_value(p &Procedure, depth int, slot int) ?Value {
189 mut cursor := EnvironmentRef{ value: p.env }
190 for _ in 1 .. depth {
191 if isnil(cursor.value) { return none }
192 cursor = EnvironmentRef{ value: cursor.value.parent }
193 }
194 if isnil(cursor.value) || slot < 0 || slot >= cursor.value.slots.len { return none }
195 return cursor.value.slots[slot]
196}
197
198fn native_global_slot(mut vm VM, f &Function, instruction Instruction) !int {
199 if instruction.op == .global_reference {
200 mut resolver := Machine{ function: f }
201 slot, _ := resolver.global_reference_slot(mut vm, int(instruction.a))!
202 return slot
203 }
204 slot := f.global_slots[int(instruction.a)]
205 if slot >= 0 { return slot }
206 return vm.global_index_in(f.code.namespace, f.names[int(instruction.a)])
207}
208
209fn native_stack_depths(f &Function) ![]int {
210 mut depths := []int{len: f.instructions.len, init: -1}
211 mut queue := [0]
212 depths[0] = 0
213 for qi := 0; qi < queue.len; qi++ {
214 pc := queue[qi]
215 instruction := f.instructions[pc]
216 before := depths[pc]
217 need := match instruction.op {
218 .drop, .duplicate, .jump_false, .and_jump, .or_jump, .ret, .define_local,
219 .assign_local, .implicit_call {
220 1
221 }
222 .swap { 2 }
223 .call, .tail_call, .scope_call, .scope_tail { int(instruction.a) + 1 }
224 else { 0 }
225 }
226 if need < 0 || before < need { return error('native stack underflow') }
227 mut after := before
228 match instruction.op {
229 .constant, .global, .global_reference, .local, .duplicate, .closure, .scope_function { after++ }
230 .drop, .jump_false { after-- }
231 .call, .scope_call { after -= int(instruction.a) }
232 .tail_call, .scope_tail, .ret { continue }
233 else {}
234 }
235 if after < 0 || after > 256 { return error('invalid native stack depth') }
236 mut successors := []int{}
237 mut heights := []int{}
238 match instruction.op {
239 .jump {
240 successors << int(instruction.a)
241 heights << after
242 }
243 .jump_false {
244 successors << [int(instruction.a), pc + 1]
245 heights << [after, after]
246 }
247 .and_jump, .or_jump {
248 successors << [int(instruction.a), pc + 1]
249 heights << [before, before - 1]
250 }
251 else {
252 successors << pc + 1
253 heights << after
254 }
255 }
256 for i, next in successors {
257 if next < 0 || next >= depths.len { return error('invalid native jump') }
258 if depths[next] == -1 {
259 depths[next] = heights[i]
260 queue << next
261 } else if depths[next] != heights[i] {
262 return error('inconsistent native stack merge')
263 }
264 }
265 }
266 return depths
267}
268
269fn native_i64_literal(n i64) string {
270 if n == exact_min { return '(-INT64_C(9223372036854775807)-1)' }
271 return 'INT64_C(${n})'
272}
273
274fn native_emit(mut vm VM, graph NativeGraph, layout []NativeCapture) !string {
275 mut code := strings.new_builder(8192)
276 code.write_string($embed_file('native_abi.h').to_string())
277 for primitive in [Primitive.add, .subtract, .multiply, .num_eq, .less, .greater, .less_equal,
278 .greater_equal, .cons, .car, .cdr, .nullp, .pairp, .quotient, .remainder, .modulo, .inexact_to_exact,
279 .vector_ref, .vector_set, .vector_length, .bytevector_ref, .bytevector_set, .bytevector_length,
280 .string_ref, .string_length, .char_to_integer] {
281 code.writeln('#define P_${primitive.str().to_upper()} ${int(primitive)}')
282 }
283 if graph.uses_not { code.writeln('#define P_NOT ${int(Primitive.not)}') }
284 if graph.uses_vectors || graph.uses_bytevectors || graph.uses_text { code.writeln('#define VILE_NATIVE_VECTORS 1') }
285 if graph.writes_captures { code.writeln('#define VILE_NATIVE_CAPTURE_WRITES 1') }
286 code.write_string($embed_file('native_runtime.h').to_string())
287 // Keep integer-only IR separate: merging real arithmetic into its loops
288 // prevents the C optimizer from retaining proven integer result tags.
289 mixed_required := native_real_literals(graph) || graph.uses_vectors
290 params := graph.nodes[0].function.params
291 floating_possible := mixed_required || params > 0 || graph.captures > 0
292 if !mixed_required { native_emit_functions(mut code, mut vm, graph, layout, false)! }
293 if floating_possible { native_emit_functions(mut code, mut vm, graph, layout, true)! }
294 code.writeln('void native_entry(V*caps,V*args,void*pool,int64_t pairs,const VileNativeHostApi*api,VileNativeVectorJournal*journal,V*out){')
295 if graph.uses_vectors || graph.uses_bytevectors || graph.uses_text {
296 code.writeln('Ctx c={.caps=caps,.next=(Pair*)pool,.end=pool?(Pair*)pool+pairs:0,.api=api,.journal=journal};')
297 } else {
298 code.writeln('Ctx c={.caps=caps,.next=(Pair*)pool,.end=pool?(Pair*)pool+pairs:0};')
299 }
300 arguments := native_arguments('args', 0, params)
301 if mixed_required {
302 code.writeln('*out=f0(&c,0${arguments});')
303 } else if !floating_possible {
304 code.writeln('*out=i0(&c,0${arguments});')
305 } else {
306 code.writeln('int floating=0;')
307 code.writeln('for(int i=0;i<${params}&&!floating;i++)floating=args[i].k==REAL;')
308 code.writeln('for(int i=0;i<${graph.captures}&&!floating;i++)floating=caps[i].k==REAL;')
309 code.writeln('*out=floating?f0(&c,0${arguments}):i0(&c,0${arguments});')
310 }
311 code.writeln('}')
312 return code.str()
313}
314
315fn native_real_literals(graph NativeGraph) bool {
316 for node in graph.nodes {
317 for value in node.function.constants {
318 if value.tag == .real { return true }
319 }
320 }
321 return false
322}
323
324fn native_emit_functions(mut code strings.Builder, mut vm VM, graph NativeGraph, layout []NativeCapture, floating bool) ! {
325 prefix := if floating { 'f' } else { 'i' }
326 apply_name := if floating { 'apply' } else { 'integer_apply' }
327 primitive_name := if floating { 'prim' } else { 'integer_prim' }
328 for i, node in graph.nodes {
329 code.writeln('static V ${prefix}${i}(Ctx*,int${native_parameters(node.function.params)});')
330 }
331 code.writeln('static inline V ${apply_name}(Ctx*c,V p,int n,V*a,int d){if(p.k!=FN)return fail();if(p.x<0)return ${primitive_name}(c,(int)(-p.x-1),n,a);switch(p.x){')
332 for i, node in graph.nodes {
333 code.writeln('case ${i}:return n==${node.function.params}?${prefix}${i}(c,d+1${native_arguments('a', 0, node.function.params)}):fail();')
334 }
335 code.writeln('default:return fail();}}')
336 mut captures := 0
337 for ni, node in graph.nodes {
338 p := node.procedure.procedure_pointer()
339 f := node.function
340 if f.params > 8 || f.slot_count > 64 { return error('native function too wide') }
341 depths := native_stack_depths(f)!
342 callees := native_callees(mut vm, graph, ni)!
343 argument_callees := native_argument_callees(graph, ni)
344 code.writeln('static V ${prefix}${ni}(Ctx*c,int d${native_parameters(f.params)}){if(d>512)return fail();V in[8],s[256],v[64];')
345 for i in 0 .. f.params { code.writeln('in[${i}]=arg${i};') }
346 code.writeln('entry:;')
347 // Internal calls and self tail jumps can supply other procedure IDs.
348 // Check the specialization on every function entry, before using it.
349 for i, target in argument_callees {
350 if target != native_unknown_callee {
351 code.writeln('if(in[${i}].k!=FN||in[${i}].x!=${target})return fail();')
352 }
353 }
354 for i in 0 .. f.slot_count { code.writeln('v[${i}]=val(0,UNINIT);') }
355 for i in 0 .. f.params { code.writeln('v[${i}]=in[${i}];') }
356 for pc, instruction in f.instructions {
357 h := depths[pc]
358 if h < 0 { continue }
359 a, b := int(instruction.a), int(instruction.b)
360 known := callees[pc]
361 code.writeln('L${pc}:;')
362 match instruction.op {
363 .constant {
364 x := f.constants[a]
365 literal := match x.tag {
366 .integer { 'val(${native_i64_literal(x.whole())},INT)' }
367 .real { 'val(${native_i64_literal(i64(math.f64_bits(x.floating())))},REAL)' }
368 .character { 'val(${native_i64_literal(x.whole())},CHARACTER)' }
369 .boolean { 'val(${if x.is_true() { 1 } else { 0 }},BOOL)' }
370 .nil { 'val(0,LIST)' }
371 .unspecified { 'val(0,UNSPEC)' }
372 .uninitialized { 'val(0,UNINIT)' }
373 else { return error('unsupported native literal') }
374 }
375 code.writeln('s[${h}]=${literal};')
376 }
377 .global, .global_reference {
378 slot := native_global_slot(mut vm, f, instruction)!
379 value := if slot >= 0 {
380 vm.globals[slot]
381 } else {
382 vm.pristine_standard(-slot - 2)
383 }
384 if value.tag != .procedure {
385 code.writeln('s[${h}]=c->caps[${captures}];')
386 captures++
387 continue
388 }
389 target := value.procedure_pointer()
390 if instruction.b == native_control_guard {
391 code.writeln('s[${h}]=val(0,UNSPEC);')
392 continue
393 }
394 mut id := -1 - int(target.primitive)
395 if target.mode == .closure {
396 id = -999
397 for j, n in graph.nodes {
398 if n.provider.kind == .global && n.provider.slot == slot {
399 id = j
400 break
401 }
402 }
403 if id == -999 { return error('missing native callee') }
404 }
405 code.writeln('s[${h}]=val(${id},FN);')
406 }
407 .local {
408 if a == 0 {
409 code.writeln('if(v[${b}].k==UNINIT)return fail();s[${h}]=v[${b}];')
410 } else {
411 mut cursor := EnvironmentRef{ value: p.env }
412 for _ in 1 .. a { cursor = EnvironmentRef{ value: cursor.value.parent } }
413 if captures >= 1024 { return error('too many captures') }
414 ci := layout[captures].alias
415 captures++
416 value := native_capture_value(p, a, b) or { return error('missing captured slot') }
417 if value.tag == .procedure {
418 target := native_procedure_target(graph, ni, value)
419 if target < 0 { return error('missing captured procedure') }
420 // The live identity is guarded before entry; only its code ID
421 // is constant, while the provider's environment stays live.
422 code.writeln('s[${h}]=val(${target},FN);')
423 } else {
424 code.writeln('s[${h}]=c->caps[${ci}];')
425 }
426 }
427 }
428 .define_local, .assign_local {
429 if a == 0 {
430 code.writeln('v[${b}]=s[${h - 1}];s[${h - 1}]=val(0,UNSPEC);')
431 } else {
432 ci := layout[captures].alias
433 captures++
434 code.writeln('{V x=s[${h - 1}];if(!(x.k==INT||x.k==REAL||x.k==BOOL||x.k==UNSPEC||(x.k==LIST&&x.x==0)))return fail();c->caps[${ci}]=x;s[${h - 1}]=val(0,UNSPEC);}')
435 }
436 }
437 .drop {}
438 .duplicate { code.writeln('s[${h}]=s[${h - 1}];') }
439 .swap { code.writeln('{V t=s[${h - 1}];s[${h - 1}]=s[${h - 2}];s[${h - 2}]=t;}') }
440 .jump { code.writeln('goto L${a};') }
441 .jump_false { code.writeln('if(!truth(s[${h - 1}]))goto L${a};') }
442 .and_jump { code.writeln('if(!truth(s[${h - 1}]))goto L${a};') }
443 .or_jump { code.writeln('if(truth(s[${h - 1}]))goto L${a};') }
444 .implicit_call {
445 code.writeln('if(s[${h - 1}].k==FN){')
446 if a != 0 && f.params == 0 {
447 code.writeln('if(s[${h - 1}].x==${ni})goto entry;')
448 }
449 expression := native_application(graph, known, 0, h, floating)
450 if a != 0 {
451 code.writeln('return ${expression};}')
452 } else {
453 code.writeln('s[${h - 1}]=${expression};if(s[${h - 1}].k==ERR)return fail();}')
454 }
455 }
456 .call {
457 if native_integer(mut code, known, a, h - a, false, floating) { continue }
458 expression := native_application(graph, known, a, h - a, floating)
459 code.writeln('s[${h - a - 1}]=${expression};if(s[${h - a - 1}].k==ERR)return fail();')
460 }
461 .tail_call {
462 base := h - a - 1
463 if native_integer(mut code, known, a, base + 1, true, floating) { continue }
464 if a == f.params {
465 if known == ni {
466 for i in 0 .. a { code.writeln('in[${i}]=s[${base + 1 + i}];') }
467 code.writeln('goto entry;')
468 continue
469 }
470 if known == native_unknown_callee {
471 code.writeln('if(s[${base}].k==FN&&s[${base}].x==${ni}){')
472 for i in 0 .. a { code.writeln('in[${i}]=s[${base + 1 + i}];') }
473 code.writeln('goto entry;}')
474 }
475 }
476 expression := native_application(graph, known, a, base + 1, floating)
477 code.writeln('return ${expression};')
478 }
479 .ret { code.writeln('return s[${h - 1}];') }
480 else { return error('unsupported emitted instruction') }
481 }
482 }
483 code.writeln('return fail();}')
484 }
485
486}
487
488#flag -I @VMODROOT/scheme
489#include "native_bridge.h"
490
491@[typedef]
492struct C.VileNativeValue {
493 x i64
494 k i64
495}
496
497@[typedef]
498struct C.VileNativeVectorWrite {
499 vector voidptr
500 index i64
501 original [2]u64
502}
503
504@[typedef]
505struct C.VileNativeVectorJournal {
506mut:
507 entries &C.VileNativeVectorWrite
508 count i64
509 capacity i64
510}
511
512@[typedef]
513struct C.VileNativeHostApi {
514 context voidptr
515 vector fn (voidptr, &C.VileNativeVectorJournal, i64, &C.VileNativeValue, i64, &C.VileNativeValue)
516 finish fn (voidptr, &C.VileNativeVectorJournal, &C.VileNativeValue)
517}
518
519fn C.vile_native_invoke(voidptr, &C.VileNativeValue, &C.VileNativeValue, voidptr, i64, &C.VileNativeHostApi, i64, &C.VileNativeValue)
520fn C.mkdtemp(&char) &char
521
522struct NativeBinding {
523 node int
524 pc int
525 slot int
526 mode ProcedureKind
527 primitive Primitive
528 target int = -1
529}
530
531struct NativeCapture {
532 node int
533 depth int
534 slot int
535 target int = -1
536 pc int = -1
537 alias int
538mut:
539 written bool
540}
541
542struct NativePlan {
543 root &Function
544 nodes []&Function
545 resolvers []&Function
546 providers []NativeProvider
547 argument_targets [8]int
548 bindings []NativeBinding
549 captures []NativeCapture
550 capture_writes []int
551 handle voidptr
552 entry voidptr
553 uses_pairs bool
554 reads_pairs bool
555 writes_vectors bool
556mut:
557 disabled bool
558 pair_inputs_rejected bool
559 guards_valid bool
560 guard_revision u64
561 guard_bindings u64
562 guard_syntax u64
563}
564
565struct NativeVectorBucket {
566mut:
567 epoch u64
568 index int
569}
570
571struct NativeScope {
572mut:
573 metadata arena.Arena
574 scratch arena.Arena
575 plans []NativePlan
576 rejected []&Function
577 directory string
578 hits u64
579 deopts u64
580 cache_hits u64
581 compilations u64
582 compiler string
583 compiler_context string
584 compiler_identity string
585 cache_root string
586 // Native calls cannot reenter the VM. Fill the live prefix on entry;
587 // generated code reads only the capture selectors in its own plan.
588 capture_values [1024]C.VileNativeValue
589 capture_cells [1024]NativeCaptureCell
590 capture_plan &NativePlan = unsafe { nil }
591 vector_buckets [2048]NativeVectorBucket
592 vector_epoch u64
593 binding_revision u64
594 guard_checks u64
595 pair_input_rejections u64
596 pair_nodes_visited u64
597}
598
599// with_native_execution compiles eligible graphs within this synchronous
600// host scope. No procedure environment or dynamic-library handle
601// survives this scope; the VM never owns borrowed scope/arena storage.
602pub fn (mut vm VM) with_native_execution(work EvaluationFn) !Value {
603 vm.ready()!
604 if !isnil(vm.native_execution_scope) || !vm.native_execution_allowed() { return work(mut vm) }
605 mut scope := NativeScope{ metadata: arena.new(), scratch: arena.new() }
606 defer {
607 vm.native_execution_scope = unsafe { nil }
608 for plan in scope.plans { dl.close(plan.handle) }
609 if scope.directory != '' { os.rmdir_all(scope.directory) or {} }
610 scope.scratch.free()
611 scope.metadata.free()
612 }
613 vm.native_execution_scope = voidptr(&scope)
614 return work(mut vm)
615}
616
617struct NativeScalar {
618 x i64
619 k i64
620}
621
622// Zero is not a native value kind. Return it for unsupported handles without
623// an optional payload buffer on every vector read. Callers reject it before
624// passing the scalar to generated code.
625fn native_scalar(value Value) NativeScalar {
626 return match value.tag {
627 .integer { NativeScalar{ x: value.whole(), k: 1 } }
628 .real { NativeScalar{ x: i64(math.f64_bits(value.floating())), k: 7 } }
629 .boolean { NativeScalar{ x: if value.is_true() { 1 } else { 0 }, k: 2 } }
630 .nil { NativeScalar{ x: 0, k: 3 } }
631 .unspecified { NativeScalar{ x: 0, k: 5 } }
632 .vector { NativeScalar{ x: i64(u64(value.pointer())), k: if value.read_only { 9 } else { 8 } } }
633 .bytevector { NativeScalar{ x: i64(u64(value.pointer())), k: if value.read_only { 11 } else { 10 } } }
634 .string { NativeScalar{ x: i64(u64(value.pointer())), k: if value.read_only { 13 } else { 12 } } }
635 .character { NativeScalar{ x: value.whole(), k: 14 } }
636 else { NativeScalar{} }
637 }
638}
639
640fn native_compile(mut vm VM, mut scope NativeScope, root Value, arguments []Value) ?NativePlan {
641 // All graph/transient procedure values die with this scratch reset. Binding
642 // resolution can update compiler caches, but publishes no scratch allocations.
643 scope.scratch.push()
644 defer {
645 scope.scratch.pop()
646 scope.scratch.reset()
647 }
648 graph := native_graph(mut vm, root, arguments) or { return none }
649 for node in graph.nodes {
650 f := node.procedure.procedure_pointer().function
651 if f.code.allocation_owner != vm.allocation_owner { return none }
652 }
653 layout := native_capture_layout(mut vm, graph) or { return none }
654 if !native_capture_entry_worthwhile(graph, layout) { return none }
655 code := native_emit(mut vm, graph, layout) or { return none }
656 library := native_build_library(mut scope, code) or { return none }
657 handle, entry := library.handle, library.entry
658
659 // Only immutable function identities and binding/capture selectors survive.
660 // They refer exclusively to this VM's retained allocation owner.
661 scope.metadata.push()
662 defer { scope.metadata.pop() }
663 mut nodes := []&Function{}
664 mut resolvers := []&Function{}
665 mut providers := []NativeProvider{}
666 mut argument_targets := [8]int{}
667 mut bindings := []NativeBinding{}
668 captures := layout.clone()
669 mut capture_writes := []int{}
670 for i, capture in captures { if capture.written { capture_writes << i } }
671 mut uses_pairs := false
672 mut reads_pairs := false
673 for ni, node in graph.nodes {
674 f := node.function
675 nodes << node.procedure.procedure_pointer().function
676 resolvers << native_retain_resolver(f, node.procedure.procedure_pointer().function)
677 providers << node.provider
678 if node.provider.kind == .argument { argument_targets[node.provider.slot] = ni }
679 depths := native_stack_depths(f) or { dl.close(handle); return none }
680 for pc, instruction in f.instructions {
681 if depths[pc] < 0 { continue }
682 if instruction.op in [.global, .global_reference] {
683 slot := native_global_slot(mut vm, f, instruction) or {
684 dl.close(handle)
685 return none
686 }
687 value := if slot >= 0 { vm.globals[slot] } else { vm.pristine_standard(-slot - 2) }
688 if value.tag != .procedure {
689 continue
690 }
691 p := value.procedure_pointer()
692 if p.mode == .primitive && p.primitive == .cons { uses_pairs = true }
693 if p.mode == .primitive && p.primitive in [.car, .cdr] { reads_pairs = true }
694 // The private bridge uses a reserved negative target instead of
695 // adding per-binding storage; values is identified by its mode.
696 mut target := if instruction.b == native_control_guard && p.mode == .closure { native_control_operator(p) } else { -1 }
697 if p.mode == .closure && target !in [native_cwv_operator, native_wind_operator] {
698 for j, n in graph.nodes {
699 if n.provider.kind == .global && n.provider.slot == slot {
700 target = j
701 break
702 }
703 }
704 }
705 bindings << NativeBinding{ node: ni, pc: pc, slot: slot, mode: p.mode, primitive: p.primitive, target: target }
706 }
707
708 }
709 }
710 return NativePlan{ root: root.procedure_pointer().function, nodes: nodes, resolvers: resolvers, providers: providers, argument_targets: argument_targets, bindings: bindings, captures: captures, capture_writes: capture_writes, handle: handle, entry: entry, uses_pairs: uses_pairs, reads_pairs: reads_pairs, writes_vectors: graph.writes_vectors }
711}
712
713@[inline]
714fn (vm &VM) native_execution_allowed() bool {
715 return sizeof(Value) == 16 && vm.options.max_steps == 0 && vm.options.max_frames == 0
716 && vm.options.max_open_files == none && vm.options.compile_list_limits == none
717 && isnil(vm.owner.bounded_files) && (isnil(vm.system) || isnil(vm.system.evaluation))
718 && v_arena_current() == vm.allocation_owner
719}
720
721fn (mut m Machine) try_native_execution(mut vm VM, root Value, base int, argc int) ?Value {
722 if isnil(vm.native_execution_scope) { return none }
723 p := root.procedure_pointer()
724 mut scope := unsafe { &NativeScope(vm.native_execution_scope) }
725 mut selected := -1
726 for i in 0 .. scope.plans.len {
727 if voidptr(scope.plans[i].root) == voidptr(p.function) {
728 selected = i
729 break
730 }
731 }
732 // A rejected graph cannot execute native code in this scope. Check that
733 // existing decision before inspecting argument tags or the active allocator.
734 // Existing plans retain their direct path without scanning other rejections.
735 if selected < 0 {
736 for rejected in scope.rejected {
737 if voidptr(rejected) == voidptr(p.function) { return none }
738 }
739 } else if scope.plans[selected].disabled {
740 return none
741 }
742 if !vm.native_execution_allowed() || m.goops_pending_next.tag != .unspecified {
743 return none
744 }
745 if p.mode != .closure || isnil(p.function.code) || p.function.code.allocation_owner != vm.allocation_owner
746 || argc > 8 {
747 return none
748 }
749 mut args := [8]C.VileNativeValue{}
750 // Entry arity is at most eight. Plans are published only after graph/layout
751 // validation proves at most 32 providers and 1024 captures. The local unsafe
752 // accesses below use those fixed capacities; dynamic VM arrays stay checked.
753 mut has_pair_inputs := false
754 for i in 0 .. argc {
755 value := m.stack[base + 1 + i]
756 if value.tag == .procedure {
757 provider := value.procedure_pointer()
758 if provider.mode != .closure || voidptr(provider.owner) != voidptr(vm.owner) { return none }
759 } else {
760 if value.tag == .pair {
761 if selected >= 0 && scope.plans[selected].pair_inputs_rejected { return none }
762 has_pair_inputs = true
763 }
764 scalar := native_input_scalar(value) or { return none }
765 unsafe { args[i] = C.VileNativeValue{ x: scalar.x, k: scalar.k } }
766 }
767 }
768 if selected < 0 {
769 if scope.plans.len >= 16 || scope.rejected.len >= 128 { return none }
770 plan := native_compile(mut vm, mut scope, root, m.arguments(base + 1)) or {
771 scope.metadata.push()
772 scope.rejected << p.function
773 scope.metadata.pop()
774 return none
775 }
776 selected = scope.plans.len
777 scope.metadata.push()
778 scope.plans << plan
779 scope.metadata.pop()
780 }
781 mut plan := &scope.plans[selected]
782 guards_current := plan.guards_valid && plan.guard_revision == scope.binding_revision
783 && plan.guard_bindings == vm.binding_epoch && plan.guard_syntax == vm.owner.syntax_generation
784 && vm.owner.syntax_generation < ~u64(0)
785 mut providers := [32]Value{}
786 providers[0] = root
787 for i in 1 .. plan.nodes.len {
788 selector := plan.providers[i]
789 value := match selector.kind {
790 .global { vm.globals[selector.slot] }
791 .argument { m.stack[base + 1 + selector.slot] }
792 .capture {
793 parent := unsafe { providers[selector.parent] }
794 if parent.tag != .procedure { return none }
795 native_capture_value(parent.procedure_pointer(), selector.depth, selector.slot) or { return none }
796 }
797 else { return none }
798 }
799 // Dynamic providers always validate, even when global guards are cached.
800 if selector.kind != .global || !guards_current {
801 if value.tag != .procedure { return none }
802 provider := value.procedure_pointer()
803 if voidptr(provider.owner) != voidptr(vm.owner) || provider.mode != .closure
804 || voidptr(provider.function) != voidptr(plan.nodes[i]) { return none }
805 }
806 unsafe { providers[i] = value }
807 }
808 for i in 0 .. argc {
809 target := unsafe { plan.argument_targets[i] }
810 if m.stack[base + 1 + i].tag == .procedure {
811 if target <= 0 { return none }
812 unsafe { args[i] = C.VileNativeValue{ x: target, k: 4 } }
813 } else if target > 0 { return none }
814 }
815 if !guards_current {
816 plan.guards_valid = false
817 scope.guard_checks++
818 for i in 0 .. plan.nodes.len {
819 if i > 0 && plan.providers[i].kind != .global { continue }
820 value := unsafe { providers[i] }
821 if value.tag != .procedure { return none }
822 provider := value.procedure_pointer()
823 if voidptr(provider.owner) != voidptr(vm.owner) || provider.mode != .closure || voidptr(provider.function) != voidptr(plan.nodes[i]) {
824 return none
825 }
826 }
827 for binding in plan.bindings {
828 f := plan.resolvers[binding.node]
829 slot := native_global_slot(mut vm, f, f.instructions[binding.pc]) or { return none }
830 if slot != binding.slot { return none }
831 value := if slot >= 0 { vm.globals[slot] } else { vm.pristine_standard(-slot - 2) }
832 if value.tag != .procedure { return none }
833 target := value.procedure_pointer()
834 if voidptr(target.owner) != voidptr(vm.owner) || target.mode != binding.mode { return none }
835 if target.mode == .values {
836 if native_control_operator(target) != native_values_operator { return none }
837 } else if binding.target in [native_cwv_operator, native_wind_operator] {
838 if native_control_operator(target) != binding.target { return none }
839 } else if target.mode == .primitive {
840 if !isnil(target.env) || target.primitive != binding.primitive { return none }
841 } else if binding.target < 0 || voidptr(target.function) != voidptr(plan.nodes[binding.target]) {
842 return none
843 }
844 }
845 }
846 defer {
847 for i in 0 .. plan.captures.len { unsafe { scope.capture_values[i] = C.VileNativeValue{} } }
848 for i in plan.capture_writes { unsafe { scope.capture_cells[i] = NativeCaptureCell{} } }
849 scope.capture_plan = unsafe { nil }
850 }
851 if plan.capture_writes.len > 0 && !scope.prepare_capture_writes(plan, &providers[0]) { return none }
852 for i, selector in plan.captures {
853 value := if selector.depth == 0 {
854 f := plan.resolvers[selector.node]
855 if !guards_current {
856 resolved := native_global_slot(mut vm, f, f.instructions[selector.pc]) or { return none }
857 if resolved != selector.slot { plan.guards_valid = false; return none }
858 }
859 if selector.slot >= 0 { vm.globals[selector.slot] } else { vm.pristine_standard(-selector.slot - 2) }
860 } else {
861 provider := unsafe { providers[selector.node] }
862 native_capture_value(provider.procedure_pointer(), selector.depth, selector.slot) or { return none }
863 }
864 if selector.target >= 0 {
865 provider := unsafe { providers[selector.target] }
866 if value.tag != .procedure
867 || voidptr(value.procedure_pointer()) != voidptr(provider.procedure_pointer()) {
868 return none
869 }
870 unsafe { scope.capture_values[i] = C.VileNativeValue{ x: selector.target, k: 4 } }
871 continue
872 }
873 if value.tag == .pair {
874 if plan.pair_inputs_rejected { return none }
875 has_pair_inputs = true
876 }
877 scalar := native_input_scalar(value) or { return none }
878 unsafe { scope.capture_values[i] = C.VileNativeValue{ x: scalar.x, k: scalar.k } }
879 }
880 if !guards_current {
881 plan.guards_valid = true
882 plan.guard_revision = scope.binding_revision
883 plan.guard_bindings = vm.binding_epoch
884 plan.guard_syntax = vm.owner.syntax_generation
885 }
886 // Predicates or ignored inputs do not justify copying a list. Keep those
887 // entries on the VM path while preserving scalar/nil entries of this plan.
888 if has_pair_inputs && !plan.reads_pairs { return none }
889 mut pool := voidptr(unsafe { nil })
890 pooled := plan.uses_pairs || has_pair_inputs
891 if pooled {
892 if sizeof(C.VileNativePair) != 16 { return none }
893 scope.scratch.push()
894 pool = unsafe { malloc(native_pair_capacity * int(sizeof(C.VileNativePair))) }
895 }
896 defer {
897 if pooled { scope.scratch.pop(); scope.scratch.reset() }
898 }
899 mut imported := 0
900 if has_pair_inputs { imported = scope.import_pair_inputs(mut plan, &args[0], argc, pool) or { return none } }
901 remaining := native_pair_capacity - imported
902 cells := unsafe { &C.VileNativePair(pool) }
903 allocation_pool := if imported == 0 { pool } else { unsafe { voidptr(&cells[imported]) } }
904 if plan.writes_vectors { scope.begin_vector_transaction() }
905 if plan.capture_writes.len > 0 { scope.capture_plan = plan }
906 api := C.VileNativeHostApi{ context: voidptr(scope), vector: native_vector_io, finish: native_vector_finish }
907 mut out := C.VileNativeValue{}
908 unsafe { C.vile_native_invoke(plan.entry, &scope.capture_values[0], &args[0], allocation_pool, remaining, &api, (if plan.writes_vectors { i64(1) } else { 0 }) | (if plan.capture_writes.len > 0 { i64(2) } else { 0 }), &out) }
909 match out.k {
910 3, 8, 9, 10, 11, 12, 13, 14 {
911 result := native_host_value(out)
912 if result.tag != .uninitialized {
913 scope.hits++
914 return result
915 }
916 }
917 1 {
918 scope.hits++
919 return integer(out.x)
920 }
921 2 {
922 scope.hits++
923 return boolean(out.x != 0)
924 }
925 7 {
926 scope.hits++
927 return real(math.f64_from_bits(u64(out.x)))
928 }
929 5 {
930 scope.hits++
931 return unspecified()
932 }
933 else {}
934 }
935 scope.deopts++
936 // A limit or unsupported result must not repeat speculative work on every
937 // recursive interpreter call after replay starts. Mutations are already undone.
938 scope.plans[selected].disabled = true
939 return none
940}
941
942// Debug counters for verification outside the measured interval.
943pub fn (vm &VM) native_execution_stats() (u64, u64) {
944 if isnil(vm.native_execution_scope) { return 0, 0 }
945 scope := unsafe { &NativeScope(vm.native_execution_scope) }
946 return scope.hits, scope.deopts
947}
948
949const native_unknown_callee = -2000000000
950
951fn native_callee_id(mut vm VM, graph NativeGraph, f &Function, instruction Instruction) !int {
952 if instruction.b == native_control_guard { return native_unknown_callee }
953 slot := native_global_slot(mut vm, f, instruction)!
954 value := if slot >= 0 { vm.globals[slot] } else { vm.pristine_standard(-slot - 2) }
955 if value.tag != .procedure { return native_unknown_callee }
956 p := value.procedure_pointer()
957 if p.mode == .primitive { return -1 - int(p.primitive) }
958 for i, node in graph.nodes { if node.provider.kind == .global && node.provider.slot == slot { return i } }
959 return error('missing native callee')
960}
961
962// Guarded global and captured procedure loads introduce known identities.
963// Merges retain an identity only when every incoming stack agrees. Calls
964// invalidate their result; parameters, local slots and scalar captures stay
965// conservative. No captured environment or VM pointer enters generated code.
966// Root procedure arguments already have guarded providers. An unchanged local
967// can use that provider directly; the emitted entry check also covers calls
968// back into this function from inside the native graph.
969fn native_argument_callees(graph NativeGraph, node int) []int {
970 f := graph.nodes[node].function
971 mut targets := []int{len: f.params, init: native_unknown_callee}
972 if node != 0 { return targets }
973 for i, candidate in graph.nodes {
974 if candidate.provider.kind == .argument { targets[candidate.provider.slot] = i }
975 }
976 for ins in f.instructions {
977 if ins.op in [.define_local, .assign_local] && ins.a == 0 && ins.b >= 0 && ins.b < f.params {
978 targets[int(ins.b)] = native_unknown_callee
979 }
980 }
981 return targets
982}
983
984fn native_callees(mut vm VM, graph NativeGraph, node int) ![]int {
985 p := graph.nodes[node].procedure.procedure_pointer()
986 f := graph.nodes[node].function
987 argument_callees := native_argument_callees(graph, node)
988 mut states := [][]int{len: f.instructions.len}
989 mut visited := []bool{len: f.instructions.len}
990 mut queue := [0]
991 mut callees := []int{len: f.instructions.len, init: native_unknown_callee}
992 visited[0] = true
993 for qi := 0; qi < queue.len; qi++ {
994 if queue.len > 16384 { return error('native control flow too complex') }
995 pc := queue[qi]
996 instruction := f.instructions[pc]
997 a := int(instruction.a)
998 mut after := states[pc].clone()
999 match instruction.op {
1000 .global, .global_reference { after << native_callee_id(mut vm, graph, f, instruction)! }
1001 .constant { after << native_unknown_callee }
1002 .local {
1003 mut known := native_unknown_callee
1004 if instruction.a == 0 && instruction.b >= 0 && instruction.b < argument_callees.len {
1005 known = argument_callees[int(instruction.b)]
1006 } else if instruction.a > 0 {
1007 value := native_capture_value(p, int(instruction.a), int(instruction.b)) or { return error('missing captured slot') }
1008 if value.tag == .procedure {
1009 known = native_procedure_target(graph, node, value)
1010 if known < 0 { return error('missing captured procedure') }
1011 }
1012 }
1013 after << known
1014 }
1015 .duplicate { after << after.last() }
1016 .swap {
1017 n := after.len
1018 temporary := after[n - 1]
1019 after[n - 1] = after[n - 2]
1020 after[n - 2] = temporary
1021 }
1022 .drop, .jump_false { after.delete_last() }
1023 .define_local, .assign_local { after[after.len - 1] = native_unknown_callee }
1024 .implicit_call {
1025 callees[pc] = after.last()
1026 after[after.len - 1] = native_unknown_callee
1027 }
1028 .call, .tail_call {
1029 base := after.len - a - 1
1030 callees[pc] = after[base]
1031 if instruction.op == .tail_call { continue }
1032 after.trim(base + 1)
1033 after[base] = native_unknown_callee
1034 }
1035 .ret { continue }
1036 else {}
1037 }
1038 mut nexts := []int{}
1039 match instruction.op {
1040 .jump { nexts << a }
1041 .jump_false, .and_jump, .or_jump { nexts << [a, pc + 1] }
1042 else { nexts << pc + 1 }
1043 }
1044 for branch, next in nexts {
1045 mut outgoing := after.clone()
1046 if instruction.op in [.and_jump, .or_jump] && branch == 1 { outgoing.delete_last() }
1047 if !visited[next] {
1048 states[next] = outgoing
1049 visited[next] = true
1050 queue << next
1051 } else {
1052 mut changed := false
1053 for j, value in outgoing {
1054 if states[next][j] != value && states[next][j] != native_unknown_callee {
1055 states[next][j] = native_unknown_callee
1056 changed = true
1057 }
1058 }
1059 if changed { queue << next }
1060 }
1061 }
1062 }
1063 return callees
1064}
1065
1066fn native_application(graph NativeGraph, callee int, argc int, start int, floating bool) string {
1067 prefix := if floating { 'f' } else { 'i' }
1068 apply_name := if floating { 'apply' } else { 'integer_apply' }
1069 primitive_name := if floating { 'prim' } else { 'integer_prim' }
1070 if callee == native_unknown_callee { return '${apply_name}(c,s[${start - 1}],${argc},&s[${start}],d)' }
1071 if callee < 0 { return '${primitive_name}(c,${-callee - 1},${argc},&s[${start}])' }
1072 if argc != graph.nodes[callee].function.params { return 'fail()' }
1073 return '${prefix}${callee}(c,d+1${native_arguments('s', start, argc)})'
1074}
1075
1076fn native_parameters(count int) string {
1077 mut out := ''
1078 for i in 0 .. count { out += ',V arg${i}' }
1079 return out
1080}
1081
1082fn native_arguments(array_name string, start int, count int) string {
1083 mut out := ''
1084 for i in 0 .. count { out += ',${array_name}[${start + i}]' }
1085 return out
1086}
1087
1088// A proven, unextended integer primitive can return from this pure graph on
1089// failure directly. Successful operations construct only the actual result
1090// tag, avoiding a merged error-value tag at every arithmetic call site.
1091fn native_integer(mut code strings.Builder, callee int, argc int, start int, tail bool, floating bool) bool {
1092 if argc != 2 || callee >= 0 || callee == native_unknown_callee { return false }
1093 // Callee IDs originate only from admitted Primitive values in the graph.
1094 primitive := unsafe { Primitive(-callee - 1) }
1095 if primitive !in [.add, .subtract, .multiply, .num_eq, .less, .greater, .less_equal,
1096 .greater_equal] {
1097 return false
1098 }
1099 a, b, target := start, start + 1, start - 1
1100 if floating { code.writeln('if(s[${a}].k==INT&&s[${b}].k==INT){') }
1101 else { code.writeln('if(s[${a}].k!=INT||s[${b}].k!=INT)return fail();') }
1102 if primitive in [.add, .subtract, .multiply] {
1103 operation := match primitive {
1104 .add { 'add' }
1105 .subtract { 'sub' }
1106 else { 'mul' }
1107 }
1108 code.writeln('{int64_t z;if(__builtin_${operation}_overflow(s[${a}].x,s[${b}].x,&z))return fail();s[${target}]=val(z,INT);}')
1109 } else {
1110 operation := match primitive {
1111 .num_eq { '==' }
1112 .less { '<' }
1113 .greater { '>' }
1114 .less_equal { '<=' }
1115 else { '>=' }
1116 }
1117 code.writeln('s[${target}]=val(s[${a}].x${operation}s[${b}].x,BOOL);')
1118 }
1119 if floating { code.writeln('}else{s[${target}]=prim(c,${int(primitive)},2,&s[${a}]);if(s[${target}].k==ERR)return fail();}') }
1120 if tail { code.writeln('return s[${target}];') }
1121 return true
1122}
1123