-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathSinglePassCompiler.v3
More file actions
3518 lines (3343 loc) · 130 KB
/
SinglePassCompiler.v3
File metadata and controls
3518 lines (3343 loc) · 130 KB
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022 Ben L. Titzer. All rights reserved.
// See LICENSE for details of Apache 2.0 license.
// Describes the register and frame configuration for the single-pass compiler.
class SpcExecEnv {
// Frame information.
var frameSize: int;
var vsp_slot: MasmAddr;
var vfp_slot: MasmAddr;
var pc_slot: MasmAddr;
var instance_slot: MasmAddr;
var inlined_instance_slot: MasmAddr;
var wasm_func_slot: MasmAddr;
var mem0_base_slot: MasmAddr;
var inlined_mem0_base_slot: MasmAddr;
var accessor_slot: MasmAddr;
// Register information.
var sp: Reg;
var func_arg: Reg;
var vsp: Reg;
var vfp: Reg;
var mem0_base: Reg;
var instance: Reg;
var runtime_arg0: Reg;
var runtime_arg1: Reg;
var runtime_arg2: Reg;
var runtime_arg3: Reg;
var runtime_arg4: Reg;
var runtime_ret0: Reg;
var runtime_ret1: Reg;
var ret_throw: Reg;
var scratch: Reg;
}
def INITIAL_VALUE_STACK_SIZE = 16;
def OUT = Trace.OUT;
def regRefCounts = Array<int>.new(128); // used for paranoid checking of regalloc state
def TMP_SLOT = 1000000000;
// Expose constants outside this file.
component SpcConsts {
// Abstract values tracked during single-pass compilation.
def NO_REG = Reg(0);
def IS_STORED: byte = 0x01;
def IS_CONST: byte = 0x02;
def IN_REG: byte = 0x04;
def TAG_STORED: byte = 0x08;
def KIND_MASK: byte = 0xF0;
def KIND_I32: byte = kindToFlags(ValueKind.I32);
def KIND_I64: byte = kindToFlags(ValueKind.I64);
def KIND_F32: byte = kindToFlags(ValueKind.F32);
def KIND_F64: byte = kindToFlags(ValueKind.F64);
def KIND_V128: byte = kindToFlags(ValueKind.V128);
def KIND_REF: byte = kindToFlags(ValueKind.REF);
def KIND_REF_U64: byte = kindToFlags(ValueKind.REF_U64);
def kinds: Array<ValueKind> = [ValueKind.I32, ValueKind.I64, ValueKind.F32, ValueKind.F64,
ValueKind.V128, ValueKind.REF, ValueKind.REF_U64];
def kindToFlags(kind: ValueKind) -> byte {
return byte.view(kind.tag) << 4;
}
}
// Shorten constants inside this file.
def NO_REG = SpcConsts.NO_REG;
def IS_STORED = SpcConsts.IS_STORED;
def IS_CONST = SpcConsts.IS_CONST;
def IN_REG = SpcConsts.IN_REG;
def TAG_STORED = SpcConsts.TAG_STORED;
def KIND_MASK = SpcConsts.KIND_MASK;
def KIND_I32 = SpcConsts.KIND_I32;
def KIND_I64 = SpcConsts.KIND_I64;
def KIND_F32 = SpcConsts.KIND_F32;
def KIND_F64 = SpcConsts.KIND_F64;
def KIND_V128 = SpcConsts.KIND_V128;
def KIND_REF = SpcConsts.KIND_REF;
def KIND_REF_U64 = SpcConsts.KIND_REF_U64;
// Compiles Wasm bytecode to machine code in a single pass via a MacroAssembler.
class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAlloc, extensions: Extension.set, limits: Limits) extends BytecodeVisitor {
def instrTracer = if(Trace.compiler, InstrTracer.new());
def config = masm.regConfig;
def regs = xenv;
def frame = xenv;
def resolver = SpcMoveResolver.new(masm);
def unrefs = Array<(Reg, int)>.new(config.regSet.regs.length);
def probeSpillMode = if(SpcTuning.probeCallFreesRegs, SpillMode.SAVE_AND_FREE_REGS, SpillMode.SAVE_ONLY);
def runtimeSpillMode = if(SpcTuning.runtimeCallFreesRegs, SpillMode.SAVE_AND_FREE_REGS, SpillMode.SAVE_ONLY);
var err: ErrorGen;
var num_unrefs = 0;
// Abstract state of the value stack
def state = SpcState.new(regAlloc);
// Other state
def trap_labels = Vector<(TrapReason, MasmLabel, Array<SpcFrame>)>.new();
var it = BytecodeIterator.new();
// Frame state (refers to the fields in the top SpcFrame in SpcState)
var module: Module;
var func: FuncDecl;
var sig: SigDecl;
var num_locals: int;
var local_base_sp: u31; // can use a Range for 0-indexing instead of from offset
var ctl_base_sp: u31; // index of the RETURN control in ctl_stack for the current frame
var success = true;
var osr_pc: int;
var osr_offset: int;
var osr_state: Array<SpcVal>;
var osr_loop_label: MasmLabel;
var osr_entry_label: MasmLabel;
var ret_label: MasmLabel;
var last_probe = 0;
var skip_to_end: bool;
var whamm_config: WhammInlineConfig;
var frames_reconstructed = false;
// XXX: hack
var handler_dest_info = Vector<SpcHandlerInfo>.new();
// tracks the last masm writer offset to generate instruction trace for each bytecode.
var codegen_offset: u64 = 0;
var intrinsified_read_probe: MemoryReadProbe = null;
new() {
masm.unimplemented = unsupported;
masm.newTrapLabel = newTrapLabel; // trap labels are per-pc
}
def gen(module: Module, func: FuncDecl, err: ErrorGen) -> bool {
this.osr_pc = -1;
this.err = err;
return Metrics.spc_time_us.run(gen0, (module, func));
}
def genOsr(module: Module, func: FuncDecl, pc: int, err: ErrorGen) -> MasmLabel {
this.osr_pc = pc;
this.err = err;
var ok = Metrics.spc_time_us.run(gen0, (module, func));
return if(ok, osr_entry_label);
}
private def gen0(module: Module, func: FuncDecl) -> bool {
if (Trace.compiler) OUT.put1("==== begin compile: %q ========================", func.render(module.names, _)).ln();
var before_code_bytes = masm.curCodeBytes();
var before_data_bytes = masm.curDataBytes();
// Reset internal state.
regAlloc.clear();
trap_labels.resize(0);
success = true;
osr_offset = -1;
osr_state = null;
handler_dest_info.clear();
handler_dest_info.resize(func.handlers.handler_dests.length);
// Reset frame state
this.module = null;
this.func = null;
this.sig = null;
this.num_locals = 0;
this.local_base_sp = 0;
// Initialize parameters, locals, and first control stack entry.
var end_label = masm.newLabel(func.cur_bytecode.length);
state.reset(func.sig, end_label);
// Push initial frame for top-level function
state.frame_stack.clear();
var initial_frame = SpcFrame.new(func, module, 0, 0, func.num_slots(), 0, masm.newLabel(func.cur_bytecode.length));
pushSpcFrame(initial_frame);
// Emit prologue, which allocates the frame and initializes various registers.
emitPrologue();
// Visit all local declarations.
it.dispatchLocalDecls(this);
if (!FeatureDisable.frameVariables && func.frame_var_tags != null) {
for (t in func.frame_var_tags) state.push(tagToKindFlags(t) | IS_CONST, NO_REG, 0);
}
// Emit function entry probe, if any.
if (!FeatureDisable.entryProbes && func.entry_probed) {
var probe = Instrumentation.getLocalProbe(module, func.func_index, 0);
withReconstructedInlinedFrames(fun =>
emitProbe0(0, probe));
}
masm.current_fid = func.func_index;
// Emit instructions.
while (it.more() && success) {
if (Trace.compiler) traceOpcodeAndStack(false);
last_probe = 0;
masm.source_loc = it.pc;
it.dispatch(this);
unrefRegs();
if (Trace.compiler && Trace.asm) {
OUT.puts("JIT code: ");
masm.printCodeBytes(OUT, before_code_bytes, masm.curCodeBytes());
before_code_bytes = masm.curCodeBytes();
OUT.ln();
}
if (Debug.compiler) checkRegAlloc();
it.next();
if (skip_to_end) doSkipToEndOfBlock();
}
// Emit trap labels.
for (i < trap_labels.length) {
var e = trap_labels[i];
var reason = e.0;
var label = e.1;
var frames = e.2;
masm.bindLabel(label);
if (frames.length > 1) {
unrefRegs();
emitReconstructStackFrames(frames);
} else {
masm.emit_mov_m_i(xenv.pc_slot, label.create_pos);
}
masm.emit_jump_to_trap_at(reason);
}
// Emit handler stubs.
if (Trace.exception) Trace.OUT.put1("Generating %d handler stubs", handler_dest_info.length).ln();
var handlers = func.handlers;
for (i < handler_dest_info.length) {
// Dummy destinations do not need a stub.
if (handlers.handler_dests[i].is_dummy) {
if (Trace.compiler) Trace.OUT.put1(" handler stub #%d: DUMMY", i).ln();
continue;
}
var info = handler_dest_info[i];
handlers.handler_dests[i].dest_label = info.dest_label;
handlers.handler_dests[i].stub_label = info.stub_label;
// TODO: impl this; this is only null when not implemented on SPC side
// - delegate
if (info.stub_label == null) continue;
masm.bindLabel(info.stub_label);
X86_64MasmLabel.!(info.stub_label).label.pos -= int.view(before_code_bytes);
if (Trace.compiler) {
Trace.OUT.put1(" handler stub #%d:", i).ln();
Trace.OUT.put1(" stub offset=+%d", X86_64MasmLabel.!(info.stub_label).label.pos).ln();
Trace.OUT.put1(" end of func=%s", if(info.func_end, "true", "false")).ln();
}
if (info.func_end) {
if (Trace.compiler) Trace.OUT.put1(" moving %d values to ($vfp)", func.sig.results.length).ln();
for (to_slot < u32.!(func.sig.results.length)) {
var from_slot = to_slot + func.num_locals;
var sv = info.merge_state[to_slot];
var fv = SpcVal(sv.kindFlags(IS_STORED), NO_REG, sv.const);
var tv = SpcVal(typeToKindFlags(func.sig.results[to_slot]) | IS_STORED, NO_REG, 0);
resolver.addMove((to_slot, tv), (from_slot, fv));
}
} else {
for (slot < u32.!(info.merge_state.length)) {
var sv = info.merge_state[slot];
if (!sv.inReg()) continue;
var fv = SpcVal(sv.kindFlags(IS_STORED), NO_REG, sv.const);
var tv = SpcVal(sv.kindFlags(IN_REG), sv.reg, sv.const);
resolver.addMove((slot, tv), (slot, fv));
}
}
emit_reload_regs();
resolver.emitMoves();
masm.emit_br(info.dest_label);
}
// Emit OSR entry.
if (osr_state != null) {
osr_entry_label = masm.newLabel(osr_pc);
emitOsrEntry(osr_entry_label, osr_state);
}
if (success) {
// Metric collection
Metrics.spc_in_bytes.val += u32.view(func.orig_bytecode.length);
Metrics.spc_code_bytes.val += (masm.curCodeBytes() - before_code_bytes);
Metrics.spc_data_bytes.val += (masm.curDataBytes() - before_data_bytes);
Metrics.spc_functions.val++;
}
return success;
}
def doSkipToEndOfBlock() {
skip_to_end = false;
var height = 0;
while (it.more() && success) {
var opcode = it.current();
match (opcode) {
BLOCK, LOOP, TRY, TRY_TABLE, IF => height++;
ELSE, CATCH, CATCH_ALL => if (height == 0) return;
END, DELEGATE => if (height-- == 0) return;
_ => ;
}
if (Trace.compiler) traceOpcodeUnreachable(true);
it.next();
}
}
def checkRegAlloc() {
if (Trace.compiler) {
OUT.puts("checkRegAlloc ");
regAlloc.render(Trace.OUT, config.regSet);
state.trace();
}
for (i < regRefCounts.length) regRefCounts[i] = 0;
for (i < state.sp) {
var sv = state.state[i];
if (sv.inReg()) {
var ri = sv.reg.index;
assert1(ri != 0, "state[%d].inReg but reg == 0", i);
assert1(ri < config.regSet.length, "state[%d], has invalid register", i);
var pool = config.poolMap.regToPool[ri];
assert1(pool >= 0 && pool < config.poolMap.numRegPools, "state[%d] has invalid register pool", i);
var poolk = config.poolMap.kindToPool[sv.kind().tag];
assert1(pool == poolk, "state[%d] differs on pool membership", i);
regRefCounts[ri]++;
}
}
for (i = 1; i < config.regSet.length; i++) {
var r = Reg(byte.view(i));
var buf = StringBuilder.new().puts("{");
regAlloc.forEachAssignment(r, appendSlots(buf, _));
var slots = buf.puts("}").toString();
if (regRefCounts[i] == 0) {
assert2(regAlloc.isFree(r), "%s should be free, got slots = %s", config.regSet.getName(r), slots);
} else {
assert2(!regAlloc.isFree(r), "%s should be allocated, got slots = %s", config.regSet.getName(r), slots);
}
}
}
def appendSlots(buf: StringBuilder, slot: int) -> StringBuilder {
if (buf.length > 1) buf.csp();
return buf.putd(slot);
}
def assert1<T>(cond: bool, msg: string, param: T) {
if (!cond) bailout(Strings.format1(msg, param));
}
def assert2<T, U>(cond: bool, msg: string, p1: T, p2: U) {
if (!cond) bailout(Strings.format2(msg, p1, p2));
}
def assert3<T, U, V>(cond: bool, msg: string, p1: T, p2: U, p3: V) {
if (!cond) bailout(Strings.format3(msg, p1, p2, p3));
}
def emitPrologue() {
// Allocate stack frame
masm.emit_subw_r_i(regs.sp, frame.frameSize);
// Spill VSP
emit_spill_vsp(regs.vsp); // XXX: track VSP-spilled state
// Spill wf: WasmFunction
masm.emit_mov_m_r(ValueKind.REF, frame.wasm_func_slot, regs.func_arg);
// Load wf.instance and spill
masm.emit_v3_WasmFunction_instance_r_r(regs.instance, regs.func_arg);
masm.emit_mov_m_r(ValueKind.REF, frame.instance_slot, regs.instance);
// Clear FrameAccessor
masm.emit_mov_m_l(frame.accessor_slot, 0); // XXX: value kind
// Clear inlined whamm instance
if (SpcTuning.inlineWhammProbes && SpcTuning.intrinsifyWhammProbe) {
masm.emit_mov_m_l(frame.inlined_instance_slot, 0);
}
// Compute VFP = VSP - sig.params.length * SLOT_SIZE
masm.emit_mov_r_r(ValueKind.REF, regs.vfp, regs.vsp); // XXX: use 3-addr adjustment of VFP
masm.emit_subw_r_i(regs.vfp, sig.params.length * masm.valuerep.slot_size);
// XXX: skip spilling of VFP
masm.emit_mov_m_r(ValueKind.REF, frame.vfp_slot, regs.vfp);
// Load instance.memories[0].start into MEM0_BASE and spill
if (module.memories.length > 0) {
// XXX: skip loading memory base if function doesn't access memory
masm.emit_v3_Instance_memories_r_r(regs.mem0_base, regs.instance);
masm.emit_v3_Array_elem_r_ri(ValueKind.REF, regs.mem0_base, regs.mem0_base, 0);
masm.emit_v3_Memory_start_r_r(regs.mem0_base, regs.mem0_base);
masm.emit_mov_m_r(ValueKind.REF, frame.mem0_base_slot, regs.mem0_base);
}
}
def visitLocalDecl(count: u32, vtc: ValueTypeCode) {
var vt = vtc.toAbstractValueType(module);
var sp = state.sp;
state.addLocals(count, vt);
if (!SpcTuning.eagerTagLocals || !masm.valuerep.tagged) return;
// eagerly tag locals
var code = ValueTypes.kind(vt).code;
for (i < count) masm.emit_mov_m_i(masm.tagAddr(sp + i), code);
}
def visitOp(opcode: Opcode) {
bailout(Strings.format1("unsupported opcode: %s", opcode.name));
}
def visitProbe(orig_op: Opcode) {
last_probe = it.pc;
if (orig_op != Opcode.LOOP && orig_op != Opcode.END) emitProbe();
}
def emitProbe() {
if (last_probe == 0) return;
var probe = Instrumentation.getLocalProbe(module, func.func_index, last_probe);
last_probe = 0;
withReconstructedInlinedFrames(fun =>
emitProbe0(it.pc, probe));
if (Trace.compiler) traceOpcodeAndStack(true);
}
def emitProbe0(pc: int, probe: Probe) {
// Check for intrinsified probes.
var spillMode = this.probeSpillMode;
match (probe) { // TODO: emit code for multiple intrinsified probes.
null => ;
x: MemoryReadProbe => if (SpcTuning.intrinsifyMemoryProbes && x.size <= 8) {
intrinsified_read_probe = x;
return;
}
x: CountProbe => if (SpcTuning.intrinsifyCountProbe) { // TODO: check for subclass override
var tmp = allocTmp(ValueKind.REF);
masm.emit_increment_CountProbe(tmp, x, 1);
return;
}
x: CountMoreProbe => if (SpcTuning.intrinsifyCountProbe) { // TODO: check for subclass override
var tmp = allocTmp(ValueKind.REF);
masm.emit_increment_CountProbe(tmp, x.c, x.increment);
return;
}
x: OperandProbe_i_v => if (SpcTuning.intrinsifyOperandProbe) {
state.emitSaveAll(resolver, probeSpillMode);
emit_compute_vsp(regs.scratch, state.sp);
emit_spill_vsp(regs.scratch);
masm.emit_store_curstack_vsp(regs.scratch);
var value_reg = masm.getV3ParamReg(ValueKind.I32, 1);
// XXX: Factor out loading slot into specific reg
var sv = state.peek();
if (sv.reg != value_reg) {
if (sv.inReg()) {
masm.emit_mov_r_r(sv.kind(), value_reg, sv.reg);
} else if (sv.isConst()) {
masm.emit_mov_r_k(sv.kind(), value_reg, sv.const);
} else {
masm.emit_mov_r_s(sv.kind(), value_reg, state.sp - 1);
}
}
masm.emit_call_OperandProbe_i_v_fire(x, value_reg);
emit_reload_regs();
if (!probeSpillMode.free_regs) state.emitRestoreAll(resolver);
return;
}
x: ExternalDebuggerBreakpointProbe => {
masm.emit_debugger_breakpoint();
return;
}
x: WhammProbe => if (SpcTuning.intrinsifyWhammProbe && WasmFunction.?(x.func)) {
emitWhammProbe(x);
return;
}
x: TracePointProbe => {
// Tracepoints are used to help debug the JIT. Saving but not freeing
// the registers has less effect on the surrounding code, making it
// less likely to hide bugs.
spillMode = SpillMode.SAVE_ONLY;
}
}
// spill everything
state.emitSaveAll(resolver, spillMode);
// compute VSP for potential frame access
emit_compute_vsp(regs.vsp, state.sp);
emit_spill_vsp(regs.vsp);
masm.emit_store_curstack_vsp(regs.vsp);
// load stack
masm.emit_get_curstack(regs.runtime_arg0);
// store %sp
masm.emit_v3_set_X86_64Stack_rsp_r_r(regs.runtime_arg0, regs.sp);
masm.emit_push_X86_64Stack_rsp_r_r(regs.runtime_arg0);
// reload WasmFunction
masm.emit_mov_r_m(ValueKind.REF, regs.runtime_arg1, frame.wasm_func_slot);
// load PC
masm.emit_mov_r_i(regs.runtime_arg2, pc);
// call runtime
masm.emit_call_runtime_Probe_instr();
// restore {stack.rsp}
masm.emit_get_curstack(regs.scratch);
masm.emit_pop_X86_64Stack_rsp_r_r(regs.scratch);
emit_reload_regs();
if (!spillMode.free_regs) state.emitRestoreAll(resolver);
}
// saves the overhead of using a runtime call by directly invoking the wasm function associated with the whamm probe
def emitWhammProbe(probe: WhammProbe) {
if (Trace.compiler) Trace.OUT.puts("emitting whamm probe\n");
// set up args and push to frame slots.
var whamm_sig = probe.sig;
var orig_sp = state.sp;
var callee_func = WasmFunction.!(probe.func);
def inline_decision = shouldInline(callee_func.decl) && SpcTuning.inlineWhammProbes; // TODO move to shouldInline
var swap_instance = false;
var swap_membase = false;
if (inline_decision) {
probe.checkSwap();
swap_instance = probe.swap_instance;
swap_membase = probe.swap_membase;
if (swap_instance) {
masm.emit_mov_r_Instance(regs.scratch, callee_func.instance);
masm.emit_mov_m_r(ValueKind.REF, frame.inlined_instance_slot, regs.scratch);
}
if (swap_membase) {
if (callee_func.instance.memories.length > 0) {
var membase = callee_func.instance.memories[0].getMemBase64();
masm.emit_mov_r_l(regs.mem0_base, i64.view(membase));
}
masm.emit_mov_m_r(ValueKind.REF, frame.inlined_mem0_base_slot, regs.mem0_base);
}
} else {
state.emitSaveAll(resolver, probeSpillMode);
}
for (i < whamm_sig.length) {
var slot_tag_addr = masm.tagAddr(state.sp + u32.view(i));
var slot_addr = masm.slotAddr(state.sp + u32.view(i));
var kind: byte;
match(whamm_sig[i]) {
FrameAccessor => {
if (inline_decision) state.emitSaveAll(resolver, probeSpillMode); // spill entire value stack.
masm.emit_call_runtime_getFrameAccessorMetaRef();
emit_reload_regs();
if (inline_decision && !probeSpillMode.free_regs) state.emitRestoreAll(resolver);
// move result to mem slot or reg, depending on inlining
if (inline_decision) {
var reg = allocRegTos(ValueKind.REF);
masm.emit_mov_r_r(ValueKind.REF, reg, xenv.runtime_ret0);
state.push(KIND_REF | IN_REG, reg, 0);
} else {
masm.emit_mov_m_r(ValueKind.REF, slot_addr, xenv.runtime_ret0);
}
kind = ValueKind.REF.code;
}
Val(val) => {
match (val) {
I31(v) => {
if (inline_decision) {
var reg = allocRegTos(ValueKind.REF);
masm.emit_mov_r_i(reg, i32.view(v) << 1);
state.push(KIND_REF | IN_REG, reg, 0);
} else {
masm.emit_mov_m_d(slot_addr, u64.view(v) << 1);
}
kind = ValueKind.REF.code;
}
I32(v) => {
if (inline_decision) {
state.push(KIND_I32 | IS_CONST, NO_REG, i32.view(v));
} else {
masm.emit_mov_m_d(slot_addr, v);
}
kind = ValueKind.I32.code;
}
I64(v) => {
if (inline_decision) {
var reg = allocRegTos(ValueKind.I64);
masm.emit_mov_r_l(reg, i64.view(v));
state.push(KIND_I64 | IN_REG, reg, 0);
} else {
masm.emit_mov_m_d(slot_addr, v);
}
kind = ValueKind.I64.code;
}
F32(v) => {
if (inline_decision) {
var reg = allocRegTos(ValueKind.F32);
masm.emit_mov_r_f32(reg, v);
state.push(KIND_F32 | IN_REG, reg, 0);
} else {
masm.emit_mov_m_d(slot_addr, v);
}
kind = ValueKind.F32.code;
}
F64(v) => {
if (inline_decision) {
var reg = allocRegTos(ValueKind.F64);
masm.emit_mov_r_d64(reg, v);
state.push(KIND_F64 | IN_REG, reg, 0);
} else {
masm.emit_mov_m_d(slot_addr, v);
}
kind = ValueKind.F64.code;
}
V128(l, h) => {
if (inline_decision) {
var reg = allocRegTos(ValueKind.V128);
masm.emit_mov_r_q(reg, l, h);
state.push(KIND_V128 | IN_REG, reg, 0);
} else {
masm.emit_mov_m_d(slot_addr, l);
masm.emit_mov_m_d(slot_addr.plus(8), h);
}
kind = ValueKind.V128.code;
}
Ref(v) => {
if (inline_decision) {
var reg = allocRegTos(ValueKind.REF);
masm.emit_mov_r_Object(reg, v);
state.push(KIND_REF | IN_REG, reg, 0);
} else {
masm.emit_mov_r_Object(regs.scratch, v);
masm.emit_mov_m_r(ValueKind.REF, slot_addr, regs.scratch);
}
kind = ValueKind.REF.code;
}
Cont(v) => {
if (inline_decision) {
var reg = allocRegTos(ValueKind.REF_U64);
masm.emit_mov_r_Cont(reg, v);
state.push(KIND_REF_U64 | IN_REG, reg, 0);
} else {
// TODO[stack-switching]: designated xmm scratch register
// masm.emit_mov_r_Cont(regs.scratch, v);
// asm.movdqu_m_s(slot_addr, regs.scratch)
}
kind = ValueKind.REF.code;
}
}
}
Operand(_, i) => {
var index = orig_sp + u32.view(i) - 1;
if (inline_decision) {
visit_LOCAL_GET(u31.view(index - local_base_sp));
} else {
masm.emit_mov_m_m(state.state[index].kind(), slot_addr, masm.slotAddr(index));
}
kind = state.state[index].kind().code;
}
Local(_, i) => {
if (inline_decision) {
visit_LOCAL_GET(u31.view(i));
} else {
masm.emit_mov_m_m(state.state[u31.view(i)].kind(), slot_addr, masm.slotAddr(u32.view(i)));
}
kind = state.state[u31.view(i)].kind().code;
}
Null => System.error("whamm", "null whamm arg!");
}
if (!inline_decision) {
masm.emit_mov_m_i(slot_tag_addr, kind);
}
}
var whamm_instance = callee_func.instance;
var func_id = callee_func.decl.func_index;
var whamm_module = whamm_instance.module;
var whamm_func_decl = callee_func.decl;
if (inline_decision) {
whamm_config = WhammInlineConfig(swap_membase, swap_instance, true);
masm.emit_mov_m_r(ValueKind.REF, frame.vfp_slot, regs.vfp);
emitInlinedCall(whamm_func_decl, probe);
whamm_config = WhammInlineConfig(false, false, false);
// Restore mem0_base after probe
if (module.memories.length > 0) {
masm.emit_mov_r_m(ValueKind.REF, regs.mem0_base, frame.mem0_base_slot);
}
} else {
var vsp_reg = allocTmpFixed(ValueKind.REF, regs.vsp);
var func_reg = allocTmpFixed(ValueKind.REF, regs.func_arg);
var tmp = allocTmp(ValueKind.REF);
// Load the target code/entrypoint.
masm.emit_mov_r_Function(func_reg, whamm_instance.functions[func_id]);
masm.emit_v3_WasmFunction_decl_r_r(tmp, func_reg);
masm.emit_v3_FuncDecl_target_code_r_r(tmp, tmp);
// adjust vsp_reg to compute the "true" VSP, accounting for args to WhammProbe's WasmFunction
emit_compute_vsp(vsp_reg, state.sp + u32.view(whamm_sig.length));
// Call to the entrypoint.
masm.emit_call_r(tmp);
emit_reload_regs();
if (!probeSpillMode.free_regs) state.emitRestoreAll(resolver);
}
}
def visit_CRASH_EXEC() {
masm.emit_intentional_crash();
}
def visit_CRASH_COMPILER() {
System.error("WizengError", "encountered crash-compiler opcode");
}
def visit_UNREACHABLE() {
emitTrap(TrapReason.UNREACHABLE);
setUnreachable();
}
def visit_NOP() {
// emit nothing
}
def visit_BLOCK(btc: BlockTypeCode) {
var pr = btc.toAbstractBlockType(module);
state.pushBlock(pr.0, pr.1, masm.newLabel(it.pc));
}
def visit_LOOP(btc: BlockTypeCode) {
var pr = btc.toAbstractBlockType(module);
state.pushLoop(pr.0, pr.1, masm.newLabel(it.pc));
var ctl_top = state.ctl_stack.peek();
state.prepareLoop(resolver);
masm.bindLabel(ctl_top.label);
emitProbe();
if (it.pc == osr_pc && !isInlined()) {
osr_state = state.ctl_stack.peek().copyMerge();
osr_loop_label = masm.newLabel(it.pc);
masm.bindLabel(osr_loop_label);
}
}
def visit_IF(btc: BlockTypeCode) {
var pr = btc.toAbstractBlockType(module);
var sv = pop();
var ctl_top = state.pushIf(pr.0, pr.1, masm.newLabel(it.pc), masm.newLabel(it.pc));
emitBrIf(sv, MasmBrCond.I32_ZERO, ctl_top.else_label, ctl_top, true, BrRepush.NONE);
}
def visit_ELSE() {
var ctl_top = state.ctl_stack.peek();
state.emitFallthru(resolver);
masm.emit_br(ctl_top.label);
masm.bindLabel(ctl_top.else_label);
state.doElse();
ctl_top.opcode = Opcode.ELSE.code;
emitProbe();
}
def visit_TRY(btc: BlockTypeCode) {
var pr = btc.toAbstractBlockType(module);
state.pushBlock(pr.0, pr.1, masm.newLabel(it.pc));
var ctl_top = state.ctl_stack.peek();
ctl_top.catch_reset_state = Arrays.range(state.state, 0, int.view(state.sp));
}
def visit_THROW(tag_index: u31) {
state.emitSaveAll(resolver, SpillMode.SAVE_AND_FREE_REGS);
emit_compute_vsp(regs.vsp, state.sp);
masm.emit_store_curstack_vsp(regs.vsp);
masm.emit_get_curstack(regs.runtime_arg0);
masm.emit_v3_set_X86_64Stack_rsp_r_r(regs.runtime_arg0, regs.sp);
masm.emit_push_X86_64Stack_rsp_r_r(regs.runtime_arg0);
emit_load_instance(regs.runtime_arg1);
masm.emit_mov_r_i(regs.runtime_arg2, tag_index);
masm.emit_call_runtime_op(Opcode.THROW);
var tag = module.tags[tag_index];
dropN(u32.!(tag.fields.length));
setUnreachable();
}
def visit_THROW_REF() {
state.emitSaveAll(resolver, SpillMode.SAVE_AND_FREE_REGS);
emit_compute_vsp(regs.vsp, state.sp);
masm.emit_store_curstack_vsp(regs.vsp);
masm.emit_get_curstack(regs.runtime_arg0);
masm.emit_v3_set_X86_64Stack_rsp_r_r(regs.runtime_arg0, regs.sp);
masm.emit_push_X86_64Stack_rsp_r_r(regs.runtime_arg0);
popFixedReg(regs.runtime_arg1);
masm.emit_call_runtime_op(Opcode.THROW_REF);
setUnreachable();
}
def visit_END() {
var ctl_top = state.ctl_stack.peek();
if (ctl_top.opcode == Opcode.LOOP.code) {
state.ctl_stack.pop();
if (!ctl_top.reachable) setUnreachable();
} else if (ctl_top.opcode == Opcode.IF.code) {
// simulate empty if-true block
state.emitFallthru(resolver);
masm.emit_br(ctl_top.label);
masm.bindLabel(ctl_top.else_label);
state.doElse();
ctl_top.opcode = Opcode.ELSE.code;
state.emitFallthru(resolver);
masm.bindLabel(ctl_top.label);
state.resetToMerge(ctl_top);
state.ctl_stack.pop();
} else if (ctl_top.opcode == Opcode.BLOCK.code || ctl_top.opcode == Opcode.ELSE.code) {
state.emitFallthru(resolver);
masm.bindLabel(ctl_top.label);
state.resetToMerge(ctl_top);
state.ctl_stack.pop();
} else if (ctl_top.opcode == Opcode.RETURN.code) {
state.emitFallthru(resolver);
masm.bindLabel(ctl_top.label);
state.resetToMerge(ctl_top);
emitProbe();
if (ctl_top.merge_count > 1) emitReturn(ctl_top);
state.ctl_stack.pop();
return;
}
emitProbe();
}
def visit_BR(depth: u31) {
var target = state.getControl(depth);
state.emitTransfer(target, resolver);
masm.emit_br(target.label);
setUnreachable();
}
def visit_BR_IF(depth: u31) {
var target = state.getControl(depth);
var sv = pop();
emitBrIf(sv, MasmBrCond.I32_NONZERO, target.label, target, state.isTransferEmpty(target), BrRepush.NONE);
}
def visit_BR_ON_NULL(depth: u31) {
var target = state.getControl(depth);
var sv = pop();
emitBrIf(sv, MasmBrCond.REF_NULL, target.label, target, state.isTransferEmpty(target), BrRepush.NOT_TAKEN);
}
def visit_BR_ON_NON_NULL(depth: u31) {
var target = state.getControl(depth);
var sv = pop();
emitBrIf(sv, MasmBrCond.REF_NONNULL, target.label, target, state.isTransferEmpty(target), BrRepush.TAKEN);
}
def visit_BR_TABLE(depths: Range<u31>) {
var sv = pop();
emitBrTable(sv, depths);
setUnreachable();
}
def visit_RETURN() {
var target = state.ctl_stack.elems[ctl_base_sp];
state.emitTransfer(target, resolver);
masm.emit_br(ret_label);
setUnreachable();
}
def visitCallDirect(op: Opcode, index: u31, tailCall: bool) {
if (op == Opcode.CALL) {
Metrics.spc_static_calls.val++;
masm.emit_inc_metric(Metrics.spc_dynamic_calls);
}
var func = module.functions[index];
// Try inlining for intra-module, non-tail calls
if (!tailCall && shouldInline(func)) {
if (Trace.compiler) Trace.OUT.put2("Inlining call to func #%d (%d bytes)", index, func.orig_bytecode.length).ln();
if (op == Opcode.CALL) {
Metrics.spc_static_inlined_calls.val++;
masm.emit_inc_metric(Metrics.spc_dynamic_inlined_calls);
}
emitInlinedCall(func, null);
return;
}
withReconstructedInlinedFrames(fun {
var retpt = masm.newLabel(it.pc), wasmcall_label = masm.newLabel(it.pc);
// Load the instance (which must happen before frame is unwound).
var vsp_reg = allocTmpFixed(ValueKind.REF, regs.vsp);
var func_reg = allocTmpFixed(ValueKind.REF, regs.func_arg);
var tmp = allocTmp(ValueKind.REF);
emit_load_instance(tmp);
// Load the function, XXX: skip and compute function from instance + code on stack?
masm.emit_v3_Instance_functions_r_r(func_reg, tmp);
masm.emit_v3_Array_elem_r_ri(ValueKind.REF, func_reg, func_reg, func.func_index);
emitCallToReg(func.sig, func_reg, vsp_reg, tmp, func.imp != null, tailCall);
});
}
def emitInlinedCall(callee_func: FuncDecl, whamm: WhammProbe) {
var sig = callee_func.sig;
var params_count = u32.view(sig.params.length);
var results_count = u32.view(sig.results.length);
var orig_sp = state.sp;
// Arguments are already on stack
// Stack: [..., arg0, arg1, ..., argN] <- sp
// We want callee's local 0 = arg0, so:
var new_local_base_sp: u31 = u31.view(orig_sp - params_count);
var new_ctl_base_sp = u31.view(state.ctl_stack.top);
var num_locals = callee_func.num_slots();
// Push a RETURN control for the inlined callee's function body.
var end_label = masm.newLabel(callee_func.cur_bytecode.length);
var func_body_ctl = state.pushFuncBody(sig.params, sig.results, end_label);
var m: Module = module;
// Whamm probe configuration
if (whamm != null) {
def whamm_sig = whamm.sig;
def whamm_wf = WasmFunction.!(whamm.func);
def whamm_instance = whamm_wf.instance;
def whamm_func_decl = whamm_wf.decl;
m = whamm_instance.module;
new_local_base_sp = u31.view(state.sp) - u31.view(whamm_sig.length); // XXX
func_body_ctl.val_stack_top = new_local_base_sp; // correct val_stack_top for whamm arg count
}
// create merge state based on outer function's base sp given inlined function's results
func_body_ctl.merge_state = state.getInMemoryMergeWithArgs(int.view(new_local_base_sp), sig.results);
func_body_ctl.merge_count = 1;
// Create and push frame for inlined function
var callee_frame = SpcFrame.new(callee_func,
m, new_local_base_sp, new_ctl_base_sp, num_locals, 0, masm.newLabel(callee_func.cur_bytecode.length));
pushSpcFrame(callee_frame);
// Emit function entry probe, if any.
// XXX expensive because frame materialization required
if (whamm == null && !FeatureDisable.entryProbes && func.entry_probed) {
var probe = Instrumentation.getLocalProbe(module, callee_func.func_index, 0);
withReconstructedInlinedFrames(fun =>
emitProbe0(0, probe));
}
// Allocate callee's non-parameter locals
it.dispatchLocalDecls(this);
// Compile callee's bytecode
if (Trace.compiler) Trace.OUT.puts(" Start inlined function body").ln();
while (it.more() && success) {
if (Trace.compiler) traceOpcodeAndStack(false);
last_probe = 0;
masm.source_loc = it.pc;
masm.current_fid = func.func_index;
it.dispatch(this);
if (Trace.compiler && Trace.asm) {
OUT.puts("JIT code: ");
masm.printCodeBytes(OUT, codegen_offset, masm.curCodeBytes());
codegen_offset = masm.curCodeBytes();
OUT.ln();
}
unrefRegs();
if (Debug.compiler) checkRegAlloc();
it.next();
if (skip_to_end) doSkipToEndOfBlock();
}
if (Trace.compiler) Trace.OUT.puts(" End inlined function body").ln();
// Check if the inlined function is unreachable (e.g., ended with UNREACHABLE, RETURN, THROW)
var inlined_reachable = state.ctl_stack.peek().reachable;
// Restore caller context by popping frame
popSpcFrame(); // Automatically restores cached fields
// Note: Control stack cleanup (popping implicit BLOCK) is handled by visit_END
// If inlined function is unreachable, no results to clean up
if (!inlined_reachable) {
if (Trace.compiler) {
Trace.OUT.puts(" Inlined function unreachable, skipping result cleanup").ln();
Trace.OUT.put3(" state.sp=%d, new_local_base_sp=%d, callee_slots=%d",
state.sp, new_local_base_sp, state.sp - new_local_base_sp).ln();
}
// Drop all callee state (params + locals, no results)
var callee_slots = state.sp - new_local_base_sp;
if (callee_slots > 0) dropN(u32.view(callee_slots));
if (Trace.compiler) Trace.OUT.put1(" After dropN: state.sp=%d", state.sp).ln();
setUnreachable();
return;
}
if (Trace.compiler) {
Trace.OUT.put1(" Inlined call complete, sp=%d", state.sp).ln();
}
}
def emitCallToReg(sig: SigDecl, func_reg: Reg, vsp_reg: Reg, tmp: Reg, checkHostCall: bool, tailCall: bool) {
var retpt = masm.newLabel(it.pc), wasmcall_label = masm.newLabel(it.pc);
// Handle the current stack state.
if (tailCall) emitMoveTailCallArgs(sig); // transfer tail call args
else state.emitSaveAll(resolver, SpillMode.SAVE_AND_FREE_REGS); // spill entire value stack
// Compute the value stack pointer.
emit_compute_vsp(vsp_reg, state.sp);
if (checkHostCall) {
// A call to imported function must first check for WasmFunction.
masm.emit_br_r(func_reg, MasmBrCond.IS_WASM_FUNC, wasmcall_label);
if (tailCall) {
masm.emit_jump_HostCallStub(); // XXX: stub relies on func_arg and VSP
} else {
masm.emit_call_HostCallStub(); // XXX: stub relies on func_arg and VSP
masm.emit_br(retpt);
}
}
// Load the target code/entrypoint.
masm.bindLabel(wasmcall_label);
masm.emit_v3_WasmFunction_decl_r_r(tmp, func_reg);
masm.emit_v3_FuncDecl_target_code_r_r(tmp, tmp);
// Call or jump to the entrypoint.
if (tailCall) {
masm.emit_jump_r(tmp);
setUnreachable();
} else {
masm.emit_call_r(tmp);
masm.bindLabel(retpt);
emit_reload_regs();
state.popArgsAndPushResults(sig);
}
}
def emitMoveTailCallArgs(sig: SigDecl) {
var p = sig.params, count = u32.!(p.length);
var base = state.sp - count;
for (i < count) { // transfer args
var tv = SpcVal(typeToKindFlags(p[i]) | IS_STORED | TAG_STORED, NO_REG, 0); // XXX: skip tag copy
var fv = state.state[base + i];
resolver.addMove((i, tv), (base + i, fv));
}
for (i < base) unrefSlot(i); // free all unused slots of frame below args
resolver.emitMoves();
state.sp = count;
// adjust frame
masm.emit_addw_r_i(regs.sp, frame.frameSize);
}