-
Notifications
You must be signed in to change notification settings - Fork 267
/
impl_amd64.go
4933 lines (4243 loc) · 197 KB
/
impl_amd64.go
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
package compiler
// This file implements the compiler for amd64/x86_64 target.
// Please refer to https://www.felixcloutier.com/x86/index.html
// if unfamiliar with amd64 instructions used here.
// Note that x86 pkg used here prefixes all the instructions with "A"
// e.g. MOVQ will be given as amd64.MOVQ.
import (
"fmt"
"math"
"runtime"
"unsafe"
"github.com/tetratelabs/wazero/internal/asm"
"github.com/tetratelabs/wazero/internal/asm/amd64"
"github.com/tetratelabs/wazero/internal/buildoptions"
"github.com/tetratelabs/wazero/internal/wasm"
"github.com/tetratelabs/wazero/internal/wazeroir"
)
var (
zero64Bit uint64 = 0
zero64BitAddress uintptr
minimum32BitSignedInt int32 = math.MinInt32
minimum32BitSignedIntAddress uintptr
maximum32BitSignedInt int32 = math.MaxInt32
maximum32BitSignedIntAddress uintptr
maximum32BitUnsignedInt uint32 = math.MaxUint32
maximum32BitUnsignedIntAddress uintptr
minimum64BitSignedInt int64 = math.MinInt64
minimum64BitSignedIntAddress uintptr
maximum64BitSignedInt int64 = math.MaxInt64
maximum64BitSignedIntAddress uintptr
maximum64BitUnsignedInt uint64 = math.MaxUint64
maximum64BitUnsignedIntAddress uintptr
float32SignBitMask uint32 = 1 << 31
float32RestBitMask = ^float32SignBitMask
float32SignBitMaskAddress uintptr
float32RestBitMaskAddress uintptr
float64SignBitMask uint64 = 1 << 63
float64RestBitMask = ^float64SignBitMask
float64SignBitMaskAddress uintptr
float64RestBitMaskAddress uintptr
float32ForMinimumSigned32bitInteger = math.Float32frombits(0xCF00_0000)
float32ForMinimumSigned32bitIntegerAddress uintptr
float64ForMinimumSigned32bitInteger = math.Float64frombits(0xC1E0_0000_0020_0000)
float64ForMinimumSigned32bitIntegerAddress uintptr
float32ForMinimumSigned64bitInteger = math.Float32frombits(0xDF00_0000)
float32ForMinimumSigned64bitIntegerAddress uintptr
float64ForMinimumSigned64bitInteger = math.Float64frombits(0xC3E0_0000_0000_0000)
float64ForMinimumSigned64bitIntegerAddress uintptr
float32ForMaximumSigned32bitIntPlusOne = math.Float32frombits(0x4F00_0000)
float32ForMaximumSigned32bitIntPlusOneAddress uintptr
float64ForMaximumSigned32bitIntPlusOne = math.Float64frombits(0x41E0_0000_0000_0000)
float64ForMaximumSigned32bitIntPlusOneAddress uintptr
float32ForMaximumSigned64bitIntPlusOne = math.Float32frombits(0x5F00_0000)
float32ForMaximumSigned64bitIntPlusOneAddress uintptr
float64ForMaximumSigned64bitIntPlusOne = math.Float64frombits(0x43E0_0000_0000_0000)
float64ForMaximumSigned64bitIntPlusOneAddress uintptr
)
func init() {
// TODO: what if these address exceed 32-bit address space? Even though AMD says 2GB memory space
// should be enough for everyone, we might end up in these circum stances. We access these variables
// via 32-bit displacement which cannot accommodate 64-bit addresses.
// https://stackoverflow.com/questions/31853189/x86-64-assembly-why-displacement-not-64-bits
zero64BitAddress = uintptr(unsafe.Pointer(&zero64Bit))
minimum32BitSignedIntAddress = uintptr(unsafe.Pointer(&minimum32BitSignedInt))
maximum32BitSignedIntAddress = uintptr(unsafe.Pointer(&maximum32BitSignedInt))
maximum32BitUnsignedIntAddress = uintptr(unsafe.Pointer(&maximum32BitUnsignedInt))
minimum64BitSignedIntAddress = uintptr(unsafe.Pointer(&minimum64BitSignedInt))
maximum64BitSignedIntAddress = uintptr(unsafe.Pointer(&maximum64BitSignedInt))
maximum64BitUnsignedIntAddress = uintptr(unsafe.Pointer(&maximum64BitUnsignedInt))
float32SignBitMaskAddress = uintptr(unsafe.Pointer(&float32SignBitMask))
float32RestBitMaskAddress = uintptr(unsafe.Pointer(&float32RestBitMask))
float64SignBitMaskAddress = uintptr(unsafe.Pointer(&float64SignBitMask))
float64RestBitMaskAddress = uintptr(unsafe.Pointer(&float64RestBitMask))
float32ForMinimumSigned32bitIntegerAddress = uintptr(unsafe.Pointer(&float32ForMinimumSigned32bitInteger))
float64ForMinimumSigned32bitIntegerAddress = uintptr(unsafe.Pointer(&float64ForMinimumSigned32bitInteger))
float32ForMinimumSigned64bitIntegerAddress = uintptr(unsafe.Pointer(&float32ForMinimumSigned64bitInteger))
float64ForMinimumSigned64bitIntegerAddress = uintptr(unsafe.Pointer(&float64ForMinimumSigned64bitInteger))
float32ForMaximumSigned32bitIntPlusOneAddress = uintptr(unsafe.Pointer(&float32ForMaximumSigned32bitIntPlusOne))
float64ForMaximumSigned32bitIntPlusOneAddress = uintptr(unsafe.Pointer(&float64ForMaximumSigned32bitIntPlusOne))
float32ForMaximumSigned64bitIntPlusOneAddress = uintptr(unsafe.Pointer(&float32ForMaximumSigned64bitIntPlusOne))
float64ForMaximumSigned64bitIntPlusOneAddress = uintptr(unsafe.Pointer(&float64ForMaximumSigned64bitIntPlusOne))
}
var (
// amd64ReservedRegisterForCallEngine: pointer to callEngine (i.e. *callEngine as uintptr)
amd64ReservedRegisterForCallEngine = amd64.REG_R13
// amd64ReservedRegisterForStackBasePointerAddress: stack base pointer's address (callEngine.stackBasePointer) in the current function call.
amd64ReservedRegisterForStackBasePointerAddress = amd64.REG_R14
// amd64ReservedRegisterForMemory: pointer to the memory slice's data (i.e. &memory.Buffer[0] as uintptr).
amd64ReservedRegisterForMemory = amd64.REG_R15
)
var (
amd64UnreservedVectorRegisters = []asm.Register{ // nolint
amd64.REG_X0, amd64.REG_X1, amd64.REG_X2, amd64.REG_X3,
amd64.REG_X4, amd64.REG_X5, amd64.REG_X6, amd64.REG_X7,
amd64.REG_X8, amd64.REG_X9, amd64.REG_X10, amd64.REG_X11,
amd64.REG_X12, amd64.REG_X13, amd64.REG_X14, amd64.REG_X15,
}
// Note that we never invoke "call" instruction,
// so we don't need to care about the calling convention.
// TODO: Maybe it is safe just save rbp, rsp somewhere
// in Go-allocated variables, and reuse these registers
// in compiled functions and write them back before returns.
amd64UnreservedGeneralPurposeRegisters = []asm.Register{ // nolint
amd64.REG_AX, amd64.REG_CX, amd64.REG_DX, amd64.REG_BX,
amd64.REG_SI, amd64.REG_DI, amd64.REG_R8, amd64.REG_R9,
amd64.REG_R10, amd64.REG_R11, amd64.REG_R12,
}
)
var (
// amd64CallingConventionModuleInstanceAddressRegister holds *wasm.ModuleInstance of the
// next executing function instance. The value is set and used when making function calls
// or function returns in the ModuleContextInitialization. See compileModuleContextInitialization.
amd64CallingConventionModuleInstanceAddressRegister = amd64.REG_R12
)
func (c *amd64Compiler) String() string {
return c.locationStack.String()
}
type amd64Compiler struct {
assembler amd64.Assembler
ir *wazeroir.CompilationResult
// locationStack holds the state of wazeroir virtual stack.
// and each item is either placed in register or the actual memory stack.
locationStack *runtimeValueLocationStack
// labels hold per wazeroir label specific information in this function.
labels map[string]*amd64LabelInfo
// stackPointerCeil is the greatest stack pointer value (from runtimeValueLocationStack) seen during compilation.
stackPointerCeil uint64
// currentLabel holds a currently compiled wazeroir label key. For debugging only.
currentLabel string
// onStackPointerCeilDeterminedCallBack hold a callback which are called when the max stack pointer is determined BEFORE generating native code.
onStackPointerCeilDeterminedCallBack func(stackPointerCeil uint64)
staticData codeStaticData
}
func newAmd64Compiler(ir *wazeroir.CompilationResult) (compiler, error) {
c := &amd64Compiler{
assembler: amd64.NewAssemblerImpl(),
locationStack: newRuntimeValueLocationStack(),
currentLabel: wazeroir.EntrypointLabel,
ir: ir,
labels: map[string]*amd64LabelInfo{},
}
return c, nil
}
// setLocationStack sets the given runtimeValueLocationStack to .locationStack field,
// while allowing us to track runtimeValueLocationStack.stackPointerCeil across multiple stacks.
// This is called when we branch into different block.
func (c *amd64Compiler) setLocationStack(newStack *runtimeValueLocationStack) {
if c.stackPointerCeil < c.locationStack.stackPointerCeil {
c.stackPointerCeil = c.locationStack.stackPointerCeil
}
c.locationStack = newStack
}
func (c *amd64Compiler) addStaticData(d []byte) {
c.staticData = append(c.staticData, d)
}
func (c *amd64Compiler) pushRuntimeValueLocationOnRegister(reg asm.Register, vt runtimeValueType) (ret *runtimeValueLocation) {
ret = c.locationStack.pushRuntimeValueLocationOnRegister(reg, vt)
c.locationStack.markRegisterUsed(reg)
return
}
func (c *amd64Compiler) pushVectorRuntimeValueLocationOnRegister(reg asm.Register) {
c.locationStack.pushRuntimeValueLocationOnRegister(reg, runtimeValueTypeV128Lo)
c.locationStack.pushRuntimeValueLocationOnRegister(reg, runtimeValueTypeV128Hi)
c.locationStack.markRegisterUsed(reg)
}
type amd64LabelInfo struct {
// initialInstruction is the initial instruction for this label so other block can jump into it.
initialInstruction asm.Node
// initialStack is the initial value location stack from which we start compiling this label.
initialStack *runtimeValueLocationStack
// labelBeginningCallbacks holds callbacks should to be called with initialInstruction
labelBeginningCallbacks []func(asm.Node)
}
func (c *amd64Compiler) label(labelKey string) *amd64LabelInfo {
ret, ok := c.labels[labelKey]
if ok {
return ret
}
c.labels[labelKey] = &amd64LabelInfo{}
return c.labels[labelKey]
}
// compileHostFunction constructs the entire code to enter the host function implementation,
// and return back to the caller.
func (c *amd64Compiler) compileHostFunction() error {
// First we must update the location stack to reflect the number of host function inputs.
c.pushFunctionParams()
if err := c.compileCallHostFunction(); err != nil {
return err
}
return c.compileReturnFunction()
}
// compile implements compiler.compile for the amd64 architecture.
func (c *amd64Compiler) compile() (code []byte, staticData codeStaticData, stackPointerCeil uint64, err error) {
// c.stackPointerCeil tracks the stack pointer ceiling (max seen) value across all runtimeValueLocationStack(s)
// used for all labels (via setLocationStack), excluding the current one.
// Hence, we check here if the final block's max one exceeds the current c.stackPointerCeil.
stackPointerCeil = c.stackPointerCeil
if stackPointerCeil < c.locationStack.stackPointerCeil {
stackPointerCeil = c.locationStack.stackPointerCeil
}
// Now that the max stack pointer is determined, we are invoking the callback.
// Note this MUST be called before Assemble() below.
if c.onStackPointerCeilDeterminedCallBack != nil {
c.onStackPointerCeilDeterminedCallBack(stackPointerCeil)
c.onStackPointerCeilDeterminedCallBack = nil
}
code, err = c.assembler.Assemble()
if err != nil {
return
}
code, err = mmapCodeSegment(code)
if err != nil {
return
}
staticData = c.staticData
return
}
func (c *amd64Compiler) pushFunctionParams() {
for _, t := range c.ir.Signature.Params {
loc := c.locationStack.pushRuntimeValueLocationOnStack()
switch t {
case wasm.ValueTypeI32:
loc.valueType = runtimeValueTypeI32
case wasm.ValueTypeI64, wasm.ValueTypeFuncref, wasm.ValueTypeExternref:
loc.valueType = runtimeValueTypeI64
case wasm.ValueTypeF32:
loc.valueType = runtimeValueTypeF32
case wasm.ValueTypeF64:
loc.valueType = runtimeValueTypeF64
case wasm.ValueTypeV128:
loc.valueType = runtimeValueTypeV128Lo
hi := c.locationStack.pushRuntimeValueLocationOnStack()
hi.valueType = runtimeValueTypeV128Hi
default:
panic("BUG")
}
}
}
// compileUnreachable implements compiler.compileUnreachable for the amd64 architecture.
func (c *amd64Compiler) compileUnreachable() error {
c.compileExitFromNativeCode(nativeCallStatusCodeUnreachable)
return nil
}
// compileSwap implements compiler.compileSwap for the amd64 architecture.
func (c *amd64Compiler) compileSwap(o *wazeroir.OperationSwap) error {
index := int(c.locationStack.sp) - 1 - o.Depth
var x1, x2 *runtimeValueLocation
if o.IsTargetVector {
x1, x2 = c.locationStack.stack[c.locationStack.sp-2], c.locationStack.stack[index]
} else {
x1, x2 = c.locationStack.peek(), c.locationStack.stack[index]
}
if err := c.compileEnsureOnGeneralPurposeRegister(x1); err != nil {
return err
}
if err := c.compileEnsureOnGeneralPurposeRegister(x2); err != nil {
return err
}
x1.register, x2.register = x2.register, x1.register
if o.IsTargetVector {
x1, x2 = c.locationStack.peek(), c.locationStack.stack[index+1]
x1.register, x2.register = x2.register, x1.register
}
return nil
}
// compileGlobalGet implements compiler.compileGlobalGet for the amd64 architecture.
func (c *amd64Compiler) compileGlobalGet(o *wazeroir.OperationGlobalGet) error {
c.maybeCompileMoveTopConditionalToFreeGeneralPurposeRegister()
intReg, err := c.allocateRegister(registerTypeGeneralPurpose)
if err != nil {
return err
}
// First, move the pointer to the global slice into the allocated register.
c.assembler.CompileMemoryToRegister(amd64.MOVQ, amd64ReservedRegisterForCallEngine, callEngineModuleContextGlobalElement0AddressOffset, intReg)
// Then, get the memory location of the target global instance's pointer.
c.assembler.CompileConstToRegister(amd64.ADDQ, 8*int64(o.Index), intReg)
// Now, move the location of the global instance into the register.
c.assembler.CompileMemoryToRegister(amd64.MOVQ, intReg, 0, intReg)
// When an integer, reuse the pointer register for the value. Otherwise, allocate a float register for it.
valueReg := intReg
var vt runtimeValueType
var inst = amd64.MOVQ
switch c.ir.Globals[o.Index].ValType {
case wasm.ValueTypeI32:
vt = runtimeValueTypeI32
case wasm.ValueTypeI64, wasm.ValueTypeExternref, wasm.ValueTypeFuncref:
vt = runtimeValueTypeI64
case wasm.ValueTypeF32:
vt = runtimeValueTypeF32
valueReg, err = c.allocateRegister(registerTypeVector)
if err != nil {
return err
}
case wasm.ValueTypeF64:
vt = runtimeValueTypeF64
valueReg, err = c.allocateRegister(registerTypeVector)
if err != nil {
return err
}
case wasm.ValueTypeV128:
inst = amd64.MOVDQU
vt = runtimeValueTypeV128Lo
valueReg, err = c.allocateRegister(registerTypeVector)
if err != nil {
return err
}
}
// Using the register holding the pointer to the target instance, move its value into a register.
c.assembler.CompileMemoryToRegister(inst, intReg, globalInstanceValueOffset, valueReg)
// Record that the retrieved global value on the top of the stack is now in a register.
if vt == runtimeValueTypeV128Lo {
c.pushVectorRuntimeValueLocationOnRegister(valueReg)
} else {
c.pushRuntimeValueLocationOnRegister(valueReg, vt)
}
return nil
}
// compileGlobalSet implements compiler.compileGlobalSet for the amd64 architecture.
func (c *amd64Compiler) compileGlobalSet(o *wazeroir.OperationGlobalSet) error {
wasmValueType := c.ir.Globals[o.Index].ValType
isV128 := wasmValueType == wasm.ValueTypeV128
// First, move the value to set into a temporary register.
val := c.locationStack.pop()
if isV128 {
// The previous val is higher 64-bits, and have to use lower 64-bit's runtimeValueLocation for allocation, etc.
val = c.locationStack.pop()
}
if err := c.compileEnsureOnGeneralPurposeRegister(val); err != nil {
return err
}
// Allocate a register to hold the memory location of the target global instance.
intReg, err := c.allocateRegister(registerTypeGeneralPurpose)
if err != nil {
return err
}
// First, move the pointer to the global slice into the allocated register.
c.assembler.CompileMemoryToRegister(amd64.MOVQ, amd64ReservedRegisterForCallEngine, callEngineModuleContextGlobalElement0AddressOffset, intReg)
// Then, get the memory location of the target global instance's pointer.
c.assembler.CompileConstToRegister(amd64.ADDQ, 8*int64(o.Index), intReg)
// Now, move the location of the global instance into the register.
c.assembler.CompileMemoryToRegister(amd64.MOVQ, intReg, 0, intReg)
// Now ready to write the value to the global instance location.
inst := amd64.MOVQ
if isV128 {
inst = amd64.MOVDQU
}
c.assembler.CompileRegisterToMemory(inst, val.register, intReg, globalInstanceValueOffset)
// Since the value is now written to memory, release the value register.
c.locationStack.releaseRegister(val)
return nil
}
// compileBr implements compiler.compileBr for the amd64 architecture.
func (c *amd64Compiler) compileBr(o *wazeroir.OperationBr) error {
c.maybeCompileMoveTopConditionalToFreeGeneralPurposeRegister()
return c.branchInto(o.Target)
}
// branchInto adds instruction necessary to jump into the given branch target.
func (c *amd64Compiler) branchInto(target *wazeroir.BranchTarget) error {
if target.IsReturnTarget() {
return c.compileReturnFunction()
} else {
labelKey := target.String()
if c.ir.LabelCallers[labelKey] > 1 {
// We can only re-use register state if when there's a single call-site.
// Release existing values on registers to the stack if there's multiple ones to have
// the consistent value location state at the beginning of label.
c.compileReleaseAllRegistersToStack()
}
// Set the initial stack of the target label, so we can start compiling the label
// with the appropriate value locations. Note we clone the stack here as we maybe
// manipulate the stack before compiler reaches the label.
targetLabel := c.label(labelKey)
if targetLabel.initialStack == nil {
// It seems unnecessary to clone as branchInto is always the tail of the current block.
// TODO: verify ^^.
targetLabel.initialStack = c.locationStack.clone()
}
jmp := c.assembler.CompileJump(amd64.JMP)
c.assignJumpTarget(labelKey, jmp)
}
return nil
}
// compileBrIf implements compiler.compileBrIf for the amd64 architecture.
func (c *amd64Compiler) compileBrIf(o *wazeroir.OperationBrIf) error {
cond := c.locationStack.pop()
var jmpWithCond asm.Node
if cond.onConditionalRegister() {
var inst asm.Instruction
switch cond.conditionalRegister {
case amd64.ConditionalRegisterStateE:
inst = amd64.JEQ
case amd64.ConditionalRegisterStateNE:
inst = amd64.JNE
case amd64.ConditionalRegisterStateS:
inst = amd64.JMI
case amd64.ConditionalRegisterStateNS:
inst = amd64.JPL
case amd64.ConditionalRegisterStateG:
inst = amd64.JGT
case amd64.ConditionalRegisterStateGE:
inst = amd64.JGE
case amd64.ConditionalRegisterStateL:
inst = amd64.JLT
case amd64.ConditionalRegisterStateLE:
inst = amd64.JLE
case amd64.ConditionalRegisterStateA:
inst = amd64.JHI
case amd64.ConditionalRegisterStateAE:
inst = amd64.JCC
case amd64.ConditionalRegisterStateB:
inst = amd64.JCS
case amd64.ConditionalRegisterStateBE:
inst = amd64.JLS
}
jmpWithCond = c.assembler.CompileJump(inst)
} else {
// Usually the comparison operand for br_if is on the conditional register,
// but in some cases, they are on the stack or register.
// For example, the following code
// i64.const 1
// local.get 1
// i64.add
// br_if ....
// will try to use the result of i64.add, which resides on the (virtual) stack,
// as the operand for br_if instruction.
if err := c.compileEnsureOnGeneralPurposeRegister(cond); err != nil {
return err
}
// Check if the value not equals zero.
c.assembler.CompileRegisterToConst(amd64.CMPQ, cond.register, 0)
// Emit jump instruction which jumps when the value does not equals zero.
jmpWithCond = c.assembler.CompileJump(amd64.JNE)
c.locationStack.markRegisterUnused(cond.register)
}
// Make sure that the next coming label is the else jump target.
thenTarget, elseTarget := o.Then, o.Else
// Here's the diagram of how we organize the instructions necessarily for brif operation.
//
// jmp_with_cond -> jmp (.Else) -> Then operations...
// |---------(satisfied)------------^^^
//
// Note that .Else branch doesn't have ToDrop as .Else is in reality
// corresponding to either If's Else block or Br_if's else block in Wasm.
// Emit for else branches
saved := c.locationStack
c.setLocationStack(saved.clone())
if elseTarget.Target.IsReturnTarget() {
if err := c.compileReturnFunction(); err != nil {
return err
}
} else {
elseLabelKey := elseTarget.Target.Label.String()
if c.ir.LabelCallers[elseLabelKey] > 1 {
// We can only re-use register state if when there's a single call-site.
// Release existing values on registers to the stack if there's multiple ones to have
// the consistent value location state at the beginning of label.
c.compileReleaseAllRegistersToStack()
}
// Set the initial stack of the target label, so we can start compiling the label
// with the appropriate value locations. Note we clone the stack here as we maybe
// manipulate the stack before compiler reaches the label.
amd64LabelInfo := c.label(elseLabelKey)
if amd64LabelInfo.initialStack == nil {
amd64LabelInfo.initialStack = c.locationStack
}
elseJmp := c.assembler.CompileJump(amd64.JMP)
c.assignJumpTarget(elseLabelKey, elseJmp)
}
// Handle then branch.
c.assembler.SetJumpTargetOnNext(jmpWithCond)
c.setLocationStack(saved)
if err := c.emitDropRange(thenTarget.ToDrop); err != nil {
return err
}
if thenTarget.Target.IsReturnTarget() {
return c.compileReturnFunction()
} else {
thenLabelKey := thenTarget.Target.Label.String()
if c.ir.LabelCallers[thenLabelKey] > 1 {
// We can only re-use register state if when there's a single call-site.
// Release existing values on registers to the stack if there's multiple ones to have
// the consistent value location state at the beginning of label.
c.compileReleaseAllRegistersToStack()
}
// Set the initial stack of the target label, so we can start compiling the label
// with the appropriate value locations. Note we clone the stack here as we maybe
// manipulate the stack before compiler reaches the label.
amd64LabelInfo := c.label(thenLabelKey)
if amd64LabelInfo.initialStack == nil {
amd64LabelInfo.initialStack = c.locationStack
}
thenJmp := c.assembler.CompileJump(amd64.JMP)
c.assignJumpTarget(thenLabelKey, thenJmp)
return nil
}
}
// compileBrTable implements compiler.compileBrTable for the amd64 architecture.
func (c *amd64Compiler) compileBrTable(o *wazeroir.OperationBrTable) error {
index := c.locationStack.pop()
// If the operation only consists of the default target, we branch into it and return early.
if len(o.Targets) == 0 {
c.locationStack.releaseRegister(index)
if err := c.emitDropRange(o.Default.ToDrop); err != nil {
return err
}
return c.branchInto(o.Default.Target)
}
// Otherwise, we jump into the selected branch.
if err := c.compileEnsureOnGeneralPurposeRegister(index); err != nil {
return err
}
tmp, err := c.allocateRegister(registerTypeGeneralPurpose)
if err != nil {
return err
}
// First, we move the length of target list into the tmp register.
c.assembler.CompileConstToRegister(amd64.MOVQ, int64(len(o.Targets)), tmp)
// Then, we compare the value with the length of targets.
c.assembler.CompileRegisterToRegister(amd64.CMPL, tmp, index.register)
// If the value is larger than the length,
// we round the index to the length as the spec states that
// if the index is larger than or equal the length of list,
// branch into the default branch.
c.assembler.CompileRegisterToRegister(amd64.CMOVQCS, tmp, index.register)
// We prepare the static data which holds the offset of
// each target's first instruction (incl. default)
// relative to the beginning of label tables.
//
// For example, if we have targets=[L0, L1] and default=L_DEFAULT,
// we emit the the code like this at [Emit the code for each targets and default branch] below.
//
// L0:
// 0x123001: XXXX, ...
// .....
// L1:
// 0x123005: YYY, ...
// .....
// L_DEFAULT:
// 0x123009: ZZZ, ...
//
// then offsetData becomes like [0x0, 0x5, 0x8].
// By using this offset list, we could jump into the label for the index by
// "jmp offsetData[index]+0x123001" and "0x123001" can be acquired by "LEA"
// instruction.
//
// Note: We store each offset of 32-bite unsigned integer as 4 consecutive bytes. So more precisely,
// the above example's offsetData would be [0x0, 0x0, 0x0, 0x0, 0x5, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0].
//
// Note: this is similar to how GCC implements Switch statements in C.
offsetData := make([]byte, 4*(len(o.Targets)+1))
c.addStaticData(offsetData)
c.assembler.CompileConstToRegister(amd64.MOVQ, int64(uintptr(unsafe.Pointer(&offsetData[0]))), tmp)
// Now we have the address of first byte of offsetData in tmp register.
// So the target offset's first byte is at tmp+index*4 as we store
// the offset as 4 bytes for a 32-byte integer.
// Here, we store the offset into the index.register.
c.assembler.CompileMemoryWithIndexToRegister(amd64.MOVL, tmp, 0, index.register, 4, index.register)
// Now we read the address of the beginning of the jump table.
// In the above example, this corresponds to reading the address of 0x123001.
c.assembler.CompileReadInstructionAddress(tmp, amd64.JMP)
// Now we have the address of L0 in tmp register, and the offset to the target label in the index.register.
// So we could achieve the br_table jump by adding them and jump into the resulting address.
c.assembler.CompileRegisterToRegister(amd64.ADDQ, index.register, tmp)
c.assembler.CompileJumpToRegister(amd64.JMP, tmp)
// We no longer need the index's register, so mark it unused.
c.locationStack.markRegisterUnused(index.register)
// [Emit the code for each targets and default branch]
labelInitialInstructions := make([]asm.Node, len(o.Targets)+1)
saved := c.locationStack
for i := range labelInitialInstructions {
// Emit the initial instruction of each target.
// We use NOP as we don't yet know the next instruction in each label.
// Assembler would optimize out this NOP during code generation, so this is harmless.
labelInitialInstructions[i] = c.assembler.CompileStandAlone(amd64.NOP)
var locationStack *runtimeValueLocationStack
var target *wazeroir.BranchTargetDrop
if i < len(o.Targets) {
target = o.Targets[i]
// Clone the location stack so the branch-specific code doesn't
// affect others.
locationStack = saved.clone()
} else {
target = o.Default
// If this is the default branch, we use the original one
// as this is the last code in this block.
locationStack = saved
}
c.setLocationStack(locationStack)
if err := c.emitDropRange(target.ToDrop); err != nil {
return err
}
if err := c.branchInto(target.Target); err != nil {
return err
}
}
c.assembler.BuildJumpTable(offsetData, labelInitialInstructions)
return nil
}
func (c *amd64Compiler) assignJumpTarget(labelKey string, jmpInstruction asm.Node) {
jmpTargetLabel := c.label(labelKey)
if jmpTargetLabel.initialInstruction != nil {
jmpInstruction.AssignJumpTarget(jmpTargetLabel.initialInstruction)
} else {
jmpTargetLabel.labelBeginningCallbacks = append(jmpTargetLabel.labelBeginningCallbacks, func(labelInitialInstruction asm.Node) {
jmpInstruction.AssignJumpTarget(labelInitialInstruction)
})
}
}
// compileLabel implements compiler.compileLabel for the amd64 architecture.
func (c *amd64Compiler) compileLabel(o *wazeroir.OperationLabel) (skipLabel bool) {
if buildoptions.IsDebugMode {
fmt.Printf("[label %s ends]\n\n", c.currentLabel)
}
labelKey := o.Label.String()
amd64LabelInfo := c.label(labelKey)
// If initialStack is not set, that means this label has never been reached.
if amd64LabelInfo.initialStack == nil {
skipLabel = true
c.currentLabel = ""
return
}
// We use NOP as a beginning of instructions in a label.
labelBegin := c.assembler.CompileStandAlone(amd64.NOP)
// Save the instructions so that backward branching
// instructions can jump to this label.
amd64LabelInfo.initialInstruction = labelBegin
// Set the initial stack.
c.setLocationStack(amd64LabelInfo.initialStack)
// Invoke callbacks to notify the forward branching
// instructions can properly jump to this label.
for _, cb := range amd64LabelInfo.labelBeginningCallbacks {
cb(labelBegin)
}
// Clear for debugging purpose. See the comment in "len(amd64LabelInfo.labelBeginningCallbacks) > 0" block above.
amd64LabelInfo.labelBeginningCallbacks = nil
if buildoptions.IsDebugMode {
fmt.Printf("[label %s (num callers=%d)]\n%s\n", labelKey, c.ir.LabelCallers[labelKey], c.locationStack)
}
c.currentLabel = labelKey
return
}
// compileCall implements compiler.compileCall for the amd64 architecture.
func (c *amd64Compiler) compileCall(o *wazeroir.OperationCall) error {
target := c.ir.Functions[o.FunctionIndex]
targetType := c.ir.Types[target]
if err := c.compileCallFunctionImpl(o.FunctionIndex, asm.NilRegister, targetType); err != nil {
return err
}
// We consumed the function parameters from the stack after call.
for i := 0; i < targetType.ParamNumInUint64; i++ {
c.locationStack.pop()
}
// Also, the function results were pushed by the call.
for _, t := range targetType.Results {
loc := c.locationStack.pushRuntimeValueLocationOnStack()
switch t {
case wasm.ValueTypeI32:
loc.valueType = runtimeValueTypeI32
case wasm.ValueTypeI64, wasm.ValueTypeFuncref, wasm.ValueTypeExternref:
loc.valueType = runtimeValueTypeI64
case wasm.ValueTypeF32:
loc.valueType = runtimeValueTypeF32
case wasm.ValueTypeF64:
loc.valueType = runtimeValueTypeF64
case wasm.ValueTypeV128:
loc.valueType = runtimeValueTypeV128Lo
hi := c.locationStack.pushRuntimeValueLocationOnStack()
hi.valueType = runtimeValueTypeV128Hi
}
}
return nil
}
// compileCallIndirect implements compiler.compileCallIndirect for the amd64 architecture.
func (c *amd64Compiler) compileCallIndirect(o *wazeroir.OperationCallIndirect) error {
offset := c.locationStack.pop()
if err := c.compileEnsureOnGeneralPurposeRegister(offset); err != nil {
return nil
}
tmp, err := c.allocateRegister(registerTypeGeneralPurpose)
if err != nil {
return err
}
c.locationStack.markRegisterUsed(tmp)
tmp2, err := c.allocateRegister(registerTypeGeneralPurpose)
if err != nil {
return err
}
c.locationStack.markRegisterUsed(tmp2)
// Load the address of the target table: tmp = &module.Tables[0]
c.assembler.CompileMemoryToRegister(amd64.MOVQ, amd64ReservedRegisterForCallEngine, callEngineModuleContextTablesElement0AddressOffset, tmp)
// tmp = &module.Tables[0] + Index*8 = &module.Tables[0] + sizeOf(*TableInstance)*index = module.Tables[o.TableIndex].
c.assembler.CompileMemoryToRegister(amd64.MOVQ, tmp, int64(o.TableIndex*8), tmp)
// Then, we need to check if the offset doesn't exceed the length of table.
c.assembler.CompileMemoryToRegister(amd64.CMPQ, tmp, tableInstanceTableLenOffset, offset.register)
notLengthExceedJump := c.assembler.CompileJump(amd64.JHI)
// If it exceeds, we return the function with nativeCallStatusCodeInvalidTableAccess.
c.compileExitFromNativeCode(nativeCallStatusCodeInvalidTableAccess)
c.assembler.SetJumpTargetOnNext(notLengthExceedJump)
// Next we check if the target's type matches the operation's one.
// In order to get the type instance's address, we have to multiply the offset
// by 8 as the offset is the "length" of table in Go's "[]uintptr{}",
// and size of uintptr equals 8 bytes == (2^3).
c.assembler.CompileConstToRegister(amd64.SHLQ, pointerSizeLog2, offset.register)
// Adds the address of wasm.Table[0] stored as callEngine.tableElement0Address to the offset.
c.assembler.CompileMemoryToRegister(amd64.ADDQ,
tmp, tableInstanceTableOffset, offset.register)
// "offset = (*offset) (== table[offset] == *code type)"
c.assembler.CompileMemoryToRegister(amd64.MOVQ, offset.register, 0, offset.register)
// At this point offset.register holds the address of *code (as uintptr) at wasm.Table[offset].
//
// Check if the value of table[offset] equals zero, meaning that the target is uninitialized.
c.assembler.CompileRegisterToConst(amd64.CMPQ, offset.register, 0)
// Jump if the target is initialized element.
jumpIfInitialized := c.assembler.CompileJump(amd64.JNE)
// If not initialized, we return the function with nativeCallStatusCodeInvalidTableAccess.
c.compileExitFromNativeCode(nativeCallStatusCodeInvalidTableAccess)
c.assembler.SetJumpTargetOnNext(jumpIfInitialized)
// Next we need to check the type matches, i.e. table[offset].source.TypeID == targetFunctionType's typeID.
//
// "tmp = table[offset].source ( == *FunctionInstance type)"
c.assembler.CompileMemoryToRegister(amd64.MOVQ, offset.register, functionSourceOffset, tmp)
// "tmp2 = [&moduleInstance.TypeIDs[0] + index * 4] (== moduleInstance.TypeIDs[index])"
c.assembler.CompileMemoryToRegister(amd64.MOVQ,
amd64ReservedRegisterForCallEngine, callEngineModuleContextTypeIDsElement0AddressOffset,
tmp2)
c.assembler.CompileMemoryToRegister(amd64.MOVQ, tmp2, int64(o.TypeIndex)*4, tmp2)
// Jump if the type matches.
c.assembler.CompileMemoryToRegister(amd64.CMPL, tmp, functionInstanceTypeIDOffset, tmp2)
jumpIfTypeMatch := c.assembler.CompileJump(amd64.JEQ)
// Otherwise, exit with type mismatch status.
c.compileExitFromNativeCode(nativeCallStatusCodeTypeMismatchOnIndirectCall)
c.assembler.SetJumpTargetOnNext(jumpIfTypeMatch)
targetFunctionType := c.ir.Types[o.TypeIndex]
if err = c.compileCallFunctionImpl(0, offset.register, targetFunctionType); err != nil {
return nil
}
// The offset register should be marked as un-used as we consumed in the function call.
c.locationStack.markRegisterUnused(offset.register, tmp, tmp2)
// We consumed the function parameters from the stack after call.
for i := 0; i < targetFunctionType.ParamNumInUint64; i++ {
c.locationStack.pop()
}
// Also, the function results were pushed by the call.
for _, t := range targetFunctionType.Results {
loc := c.locationStack.pushRuntimeValueLocationOnStack()
switch t {
case wasm.ValueTypeI32:
loc.valueType = runtimeValueTypeI32
case wasm.ValueTypeI64, wasm.ValueTypeFuncref, wasm.ValueTypeExternref:
loc.valueType = runtimeValueTypeI64
case wasm.ValueTypeF32:
loc.valueType = runtimeValueTypeF32
case wasm.ValueTypeF64:
loc.valueType = runtimeValueTypeF64
case wasm.ValueTypeV128:
loc.valueType = runtimeValueTypeV128Lo
hi := c.locationStack.pushRuntimeValueLocationOnStack()
hi.valueType = runtimeValueTypeV128Hi
}
}
return nil
}
// compileDrop implements compiler.compileDrop for the amd64 architecture.
func (c *amd64Compiler) compileDrop(o *wazeroir.OperationDrop) error {
return c.emitDropRange(o.Depth)
}
func (c *amd64Compiler) emitDropRange(r *wazeroir.InclusiveRange) error {
if r == nil {
return nil
} else if r.Start == 0 {
for i := 0; i <= r.End; i++ {
if loc := c.locationStack.pop(); loc.onRegister() {
c.locationStack.releaseRegister(loc)
}
}
return nil
}
var liveValues []*runtimeValueLocation
for i := 0; i < r.Start; i++ {
live := c.locationStack.pop()
liveValues = append(liveValues, live)
}
for i := 0; i < r.End-r.Start+1; i++ {
if loc := c.locationStack.pop(); loc.onRegister() {
c.locationStack.releaseRegister(loc)
}
}
for i := range liveValues {
live := liveValues[len(liveValues)-1-i]
// If the value is on a memory, we have to move it to a register,
// otherwise the memory location is overridden by other values
// after this drop instruction.
if err := c.compileEnsureOnGeneralPurposeRegister(live); err != nil {
return err
}
// Modify the location in the stack with new stack pointer.
c.locationStack.push(live)
}
return nil
}
// compileSelect implements compiler.compileSelect for the amd64 architecture.
//
// The emitted native code depends on whether the values are on
// the physical registers or memory stack, or maybe conditional register.
func (c *amd64Compiler) compileSelect() error {
cv := c.locationStack.pop()
if err := c.compileEnsureOnGeneralPurposeRegister(cv); err != nil {
return err
}
x2 := c.locationStack.pop()
// We do not consume x1 here, but modify the value according to
// the conditional value "c" above.
peekedX1 := c.locationStack.peek()
// Compare the conditional value with zero.
c.assembler.CompileRegisterToConst(amd64.CMPQ, cv.register, 0)
// Now we can use c.register as temporary location.
// We alias it here for readability.
tmpRegister := cv.register
// Set the jump if the top value is not zero.
jmpIfNotZero := c.assembler.CompileJump(amd64.JNE)
// If the value is zero, we must place the value of x2 onto the stack position of x1.
// First we copy the value of x2 to the temporary register if x2 is not currently on a register.
if x2.onStack() {
x2.register = tmpRegister
c.compileLoadValueOnStackToRegister(x2)
}
//
// At this point x2's value is always on a register.
//
// Then release the value in the x2's register to the x1's stack position.
if peekedX1.onRegister() {
c.assembler.CompileRegisterToRegister(amd64.MOVQ, x2.register, peekedX1.register)
} else {
peekedX1.register = x2.register
c.compileReleaseRegisterToStack(peekedX1) // Note inside we mark the register unused!
}
// Else, we don't need to adjust value, just need to jump to the next instruction.
c.assembler.SetJumpTargetOnNext(jmpIfNotZero)
// In any case, we don't need x2 and c anymore!
c.locationStack.releaseRegister(x2)
c.locationStack.releaseRegister(cv)
return nil
}
// compilePick implements compiler.compilePick for the amd64 architecture.
func (c *amd64Compiler) compilePick(o *wazeroir.OperationPick) error {
c.maybeCompileMoveTopConditionalToFreeGeneralPurposeRegister()
// TODO: if we track the type of values on the stack,
// we could optimize the instruction according to the bit size of the value.
// For now, we just move the entire register i.e. as a quad word (8 bytes).
pickTarget := c.locationStack.stack[c.locationStack.sp-1-uint64(o.Depth)]
reg, err := c.allocateRegister(pickTarget.getRegisterType())
if err != nil {
return err
}
if pickTarget.onRegister() {
if o.IsTargetVector {
c.assembler.CompileRegisterToRegister(amd64.MOVDQU, pickTarget.register, reg)
} else {
c.assembler.CompileRegisterToRegister(amd64.MOVQ, pickTarget.register, reg)
}
} else if pickTarget.onStack() {
// Copy the value from the stack.
var inst asm.Instruction
if o.IsTargetVector {
inst = amd64.MOVDQU
} else {
inst = amd64.MOVQ
}
// Note: stack pointers are ensured not to exceed 2^27 so this offset never exceeds 32-bit range.
c.assembler.CompileMemoryToRegister(inst, amd64ReservedRegisterForStackBasePointerAddress,
int64(pickTarget.stackPointer)*8, reg)
}
// Now we already placed the picked value on the register,
// so push the location onto the stack.
if o.IsTargetVector {