-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathWasmByteCodeGenerator.cpp
1745 lines (1553 loc) · 56.3 KB
/
WasmByteCodeGenerator.cpp
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 (C) Microsoft Corporation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "WasmReaderPch.h"
#ifdef ENABLE_WASM
#include "Language/WebAssemblySource.h"
#include "ByteCode/WasmByteCodeWriter.h"
#include "EmptyWasmByteCodeWriter.h"
#if DBG_DUMP
#define DebugPrintOp(op) if (DO_WASM_TRACE_BYTECODE) { PrintOpBegin(op); }
#define DebugPrintOpEnd() if (DO_WASM_TRACE_BYTECODE) { PrintOpEnd(); }
#else
#define DebugPrintOp(op)
#define DebugPrintOpEnd()
#endif
namespace Wasm
{
#define WASM_SIGNATURE(id, nTypes, ...) const WasmTypes::WasmType WasmOpCodeSignatures::id[] = {__VA_ARGS__};
#include "WasmBinaryOpCodes.h"
template<typename WriteFn>
void WasmBytecodeGenerator::WriteTypeStack(WriteFn writefn) const
{
writefn(_u("["));
int i = 0;
while (m_evalStack.Peek(i).type != WasmTypes::Limit)
{
++i;
}
--i;
bool isFirst = true;
while (i >= 0)
{
EmitInfo info = m_evalStack.Peek(i--);
if (!isFirst)
{
writefn(_u(", "));
}
isFirst = false;
writefn(GetTypeName(info.type));
}
writefn(_u("]"));
}
uint32 WasmBytecodeGenerator::WriteTypeStackToString(_Out_writes_(maxlen) char16* out, uint32 maxlen) const
{
AssertOrFailFast(out != nullptr);
uint32 numwritten = 0;
WriteTypeStack([&] (const char16* msg)
{
numwritten += _snwprintf_s(out + numwritten, maxlen - numwritten, _TRUNCATE, msg);
});
if (numwritten >= maxlen - 5)
{
// null out the last 5 characters so we can properly end it
for (int i = 1; i <= 5; i++)
{
*(out + maxlen - i) = 0;
}
numwritten -= 5;
numwritten += _snwprintf_s(out + numwritten, maxlen - numwritten, _TRUNCATE, _u("...]"));
}
return numwritten;
}
#if DBG_DUMP
void WasmBytecodeGenerator::PrintTypeStack() const
{
WriteTypeStack([](const char16* msg) { Output::Print(msg); });
}
void WasmBytecodeGenerator::PrintOpBegin(WasmOp op)
{
if (lastOpId == opId) Output::Print(_u("\r\n"));
lastOpId = ++opId;
const int depth = m_blockInfos.Count() - 1;
if (depth > 0)
{
Output::SkipToColumn(depth);
}
switch (op)
{
#define WASM_OPCODE(opname, opcode, sig, nyi) \
case wb##opname: \
Output::Print(_u(#opname)); \
break;
#include "WasmBinaryOpCodes.h"
}
switch (op)
{
case wbIf:
case wbLoop:
case wbBlock: Output::Print(_u(" () -> %s"), GetTypeName(GetReader()->m_currentNode.block.sig)); break;
case wbBr:
case wbBrIf: Output::Print(_u(" depth: %u"), GetReader()->m_currentNode.br.depth); break;
case wbBrTable: Output::Print(_u(" %u cases, default: %u"), GetReader()->m_currentNode.brTable.numTargets, GetReader()->m_currentNode.brTable.defaultTarget); break;
case wbCall:
case wbCallIndirect:
{
uint id = GetReader()->m_currentNode.call.num;
if (id < m_module->GetWasmFunctionCount())
{
FunctionIndexTypes::Type funcType = GetReader()->m_currentNode.call.funcType;
switch (funcType)
{
case Wasm::FunctionIndexTypes::Invalid: Output::Print(_u(" (invalid) ")); break;
case Wasm::FunctionIndexTypes::ImportThunk: Output::Print(_u(" (thunk) ")); break;
case Wasm::FunctionIndexTypes::Function: Output::Print(_u(" (func) ")); break;
case Wasm::FunctionIndexTypes::Import: Output::Print(_u(" (import) ")); break;
default: Output::Print(_u(" (unknown)")); break;
}
auto func = this->m_module->GetWasmFunctionInfo(id);
func->GetBody()->DumpFullFunctionName();
}
else
{
Output::Print(_u(" invalid id"));
}
break;
}
case wbSetLocal:
case wbGetLocal:
case wbTeeLocal:
case wbGetGlobal:
case wbSetGlobal: Output::Print(_u(" (%d)"), GetReader()->m_currentNode.var.num); break;
case wbI32Const: Output::Print(_u(" (%d, 0x%x)"), GetReader()->m_currentNode.cnst.i32, GetReader()->m_currentNode.cnst.i32); break;
case wbI64Const: Output::Print(_u(" (%lld, 0x%llx)"), GetReader()->m_currentNode.cnst.i64, GetReader()->m_currentNode.cnst.i64); break;
case wbF32Const: Output::Print(_u(" (%.4f)"), GetReader()->m_currentNode.cnst.f32); break;
case wbF64Const: Output::Print(_u(" (%.4f)"), GetReader()->m_currentNode.cnst.f64); break;
#define WASM_MEM_OPCODE(opname, opcode, sig, nyi) case wb##opname: // FallThrough
#include "WasmBinaryOpCodes.h"
{
const uint8 alignment = GetReader()->m_currentNode.mem.alignment;
const uint32 offset = GetReader()->m_currentNode.mem.offset;
switch (((!!alignment) << 1) | (!!offset))
{
case 0: // no alignment, no offset
Output::Print(_u(" [i]")); break;
case 1: // no alignment, offset
Output::Print(_u(" [i + %u (0x%x)]"), offset, offset); break;
case 2: // alignment, no offset
Output::Print(_u(" [i & ~0x%x]"), (1 << alignment) - 1); break;
case 3: // alignment, offset
Output::Print(_u(" [i + %u (0x%x) & ~0x%x]"), offset, offset, (1 << alignment) - 1); break;
}
break;
}
}
Output::SkipToColumn(40);
PrintTypeStack();
}
void WasmBytecodeGenerator::PrintOpEnd()
{
if (lastOpId == opId)
{
++opId;
Output::Print(_u(" -> "));
PrintTypeStack();
Output::Print(_u("\r\n"));
}
}
#endif
/* static */
Js::AsmJsRetType WasmToAsmJs::GetAsmJsReturnType(WasmTypes::WasmType wasmType)
{
switch (wasmType)
{
case WasmTypes::I32: return Js::AsmJsRetType::Signed;
case WasmTypes::I64: return Js::AsmJsRetType::Int64;
case WasmTypes::F32: return Js::AsmJsRetType::Float;
case WasmTypes::F64: return Js::AsmJsRetType::Double;
case WasmTypes::Void: return Js::AsmJsRetType::Void;
default:
throw WasmCompilationException(_u("Unknown return type %u"), wasmType);
}
}
/* static */
Js::AsmJsVarType WasmToAsmJs::GetAsmJsVarType(WasmTypes::WasmType wasmType)
{
Js::AsmJsVarType asmType = Js::AsmJsVarType::Int;
switch (wasmType)
{
case WasmTypes::I32: return Js::AsmJsVarType::Int;
case WasmTypes::I64: return Js::AsmJsVarType::Int64;
case WasmTypes::F32: return Js::AsmJsVarType::Float;
case WasmTypes::F64: return Js::AsmJsVarType::Double;
default:
throw WasmCompilationException(_u("Unknown var type %u"), wasmType);
}
}
typedef bool(*SectionProcessFunc)(WasmModuleGenerator*);
typedef void(*AfterSectionCallback)(WasmModuleGenerator*);
WasmModuleGenerator::WasmModuleGenerator(Js::ScriptContext* scriptContext, Js::WebAssemblySource* src) :
m_sourceInfo(src->GetSourceInfo()),
m_scriptContext(scriptContext),
m_recycler(scriptContext->GetRecycler())
{
m_module = RecyclerNewFinalized(m_recycler, Js::WebAssemblyModule, scriptContext, src->GetBuffer(), src->GetBufferLength(), scriptContext->GetLibrary()->GetWebAssemblyModuleType());
m_sourceInfo->EnsureInitialized(0);
m_sourceInfo->GetSrcInfo()->sourceContextInfo->EnsureInitialized();
}
Js::WebAssemblyModule* WasmModuleGenerator::GenerateModule()
{
m_module->GetReader()->InitializeReader();
BVStatic<bSectLimit + 1> visitedSections;
SectionCode nextExpectedSection = bSectCustom;
while (true)
{
SectionHeader sectionHeader = GetReader()->ReadNextSection();
SectionCode sectionCode = sectionHeader.code;
if (sectionCode == bSectLimit)
{
TRACE_WASM_SECTION(_u("Done reading module's sections"));
break;
}
// Make sure dependency for this section has been seen
SectionCode precedent = SectionInfo::All[sectionCode].precedent;
if (precedent != bSectLimit && !visitedSections.Test(precedent))
{
throw WasmCompilationException(_u("%s section missing before %s"),
SectionInfo::All[precedent].name,
sectionHeader.name);
}
visitedSections.Set(sectionCode);
// Custom section are allowed in any order
if (sectionCode != bSectCustom)
{
if (sectionCode < nextExpectedSection)
{
throw WasmCompilationException(_u("Invalid Section %s"), sectionHeader.name);
}
nextExpectedSection = SectionCode(sectionCode + 1);
}
if (!GetReader()->ProcessCurrentSection())
{
throw WasmCompilationException(_u("Error while reading section %s"), sectionHeader.name);
}
}
uint32 funcCount = m_module->GetWasmFunctionCount();
SourceContextInfo * sourceContextInfo = m_sourceInfo->GetSrcInfo()->sourceContextInfo;
m_sourceInfo->EnsureInitialized(funcCount);
sourceContextInfo->nextLocalFunctionId += funcCount;
sourceContextInfo->EnsureInitialized();
for (uint32 i = 0; i < funcCount; ++i)
{
GenerateFunctionHeader(i);
}
#if ENABLE_DEBUG_CONFIG_OPTIONS
WasmFunctionInfo* firstThunk = nullptr, *lastThunk = nullptr;
for (uint32 i = 0; i < funcCount; ++i)
{
WasmFunctionInfo* info = m_module->GetWasmFunctionInfo(i);
Assert(info->GetBody());
if (PHASE_TRACE(Js::WasmInOutPhase, info->GetBody()))
{
uint32 index = m_module->GetWasmFunctionCount();
WasmFunctionInfo* newInfo = m_module->AddWasmFunctionInfo(info->GetSignature());
if (!firstThunk)
{
firstThunk = newInfo;
}
lastThunk = newInfo;
GenerateFunctionHeader(index);
m_module->SwapWasmFunctionInfo(i, index);
m_module->AttachCustomInOutTracingReader(newInfo, index);
}
}
if (firstThunk)
{
int sourceId = (int)firstThunk->GetBody()->GetSourceContextId();
char16 range[64];
swprintf_s(range, 64, _u("%d.%d-%d.%d"),
sourceId, firstThunk->GetBody()->GetLocalFunctionId(),
sourceId, lastThunk->GetBody()->GetLocalFunctionId());
char16 offFullJit[128];
swprintf_s(offFullJit, 128, _u("-off:fulljit:%s"), range);
char16 offSimpleJit[128];
swprintf_s(offSimpleJit, 128, _u("-off:simplejit:%s"), range);
char16 offLoopJit[128];
swprintf_s(offLoopJit, 128, _u("-off:jitloopbody:%s"), range);
char16* argv[] = { nullptr, offFullJit, offSimpleJit, offLoopJit };
CmdLineArgsParser parser(nullptr);
parser.Parse(ARRAYSIZE(argv), argv);
}
#endif
#if DBG_DUMP
if (PHASE_TRACE1(Js::WasmReaderPhase))
{
GetReader()->PrintOps();
}
#endif
// If we see a FunctionSignatures section we need to see a FunctionBodies section
if (visitedSections.Test(bSectFunction) && !visitedSections.Test(bSectFunctionBodies))
{
throw WasmCompilationException(_u("Missing required section: %s"), SectionInfo::All[bSectFunctionBodies].name);
}
return m_module;
}
WasmBinaryReader* WasmModuleGenerator::GetReader() const
{
return m_module->GetReader();
}
void WasmModuleGenerator::GenerateFunctionHeader(uint32 index)
{
WasmFunctionInfo* wasmInfo = m_module->GetWasmFunctionInfo(index);
if (!wasmInfo)
{
throw WasmCompilationException(_u("Invalid function index %u"), index);
}
const char16* functionName = nullptr;
int nameLength = 0;
if (wasmInfo->GetNameLength() > 0)
{
functionName = wasmInfo->GetName();
nameLength = wasmInfo->GetNameLength();
}
else
{
for (uint32 iExport = 0; iExport < m_module->GetExportCount(); ++iExport)
{
Wasm::WasmExport* wasmExport = m_module->GetExport(iExport);
if (wasmExport &&
wasmExport->kind == ExternalKinds::Function &&
wasmExport->nameLength > 0 &&
m_module->GetFunctionIndexType(wasmExport->index) == FunctionIndexTypes::Function &&
wasmExport->index == wasmInfo->GetNumber())
{
nameLength = wasmExport->nameLength + 16;
char16 * autoName = RecyclerNewArrayLeafZ(m_recycler, char16, nameLength);
nameLength = swprintf_s(autoName, nameLength, _u("%s[%u]"), wasmExport->name, wasmInfo->GetNumber());
functionName = autoName;
break;
}
}
}
if (!functionName)
{
char16* autoName = RecyclerNewArrayLeafZ(m_recycler, char16, 32);
nameLength = swprintf_s(autoName, 32, _u("wasm-function[%u]"), wasmInfo->GetNumber());
functionName = autoName;
}
Js::FunctionBody* body = Js::FunctionBody::NewFromRecycler(
m_scriptContext,
functionName,
nameLength,
0,
0,
m_sourceInfo,
m_sourceInfo->GetSrcInfo()->sourceContextInfo->sourceContextId,
wasmInfo->GetNumber(),
nullptr,
Js::FunctionInfo::Attributes::ErrorOnNew,
Js::FunctionBody::Flags_None
#ifdef PERF_COUNTERS
, false /* is function from deferred deserialized proxy */
#endif
);
wasmInfo->SetBody(body);
// TODO (michhol): numbering
body->SetSourceInfo(0);
body->AllocateAsmJsFunctionInfo();
body->SetIsAsmJsFunction(true);
body->SetIsAsmjsMode(true);
body->SetIsWasmFunction(true);
WasmReaderInfo* readerInfo = RecyclerNew(m_recycler, WasmReaderInfo);
readerInfo->m_funcInfo = wasmInfo;
readerInfo->m_module = m_module;
Js::AsmJsFunctionInfo* info = body->GetAsmJsFunctionInfo();
info->SetWasmReaderInfo(readerInfo);
info->SetWebAssemblyModule(m_module);
Js::ArgSlot paramCount = wasmInfo->GetParamCount();
info->SetArgCount(paramCount);
info->SetWasmSignature(wasmInfo->GetSignature());
Js::ArgSlot argSizeLength = max(paramCount, 3ui16);
info->SetArgSizeArrayLength(argSizeLength);
uint32* argSizeArray = RecyclerNewArrayLeafZ(m_recycler, uint32, argSizeLength);
info->SetArgsSizesArray(argSizeArray);
if (paramCount > 0)
{
// +1 here because asm.js includes the this pointer
body->SetInParamsCount(paramCount + 1);
body->SetReportedInParamsCount(paramCount + 1);
info->SetArgTypeArray(RecyclerNewArrayLeaf(m_recycler, Js::AsmJsVarType::Which, paramCount));
}
else
{
// overwrite default value in this case
body->SetHasImplicitArgIns(false);
}
for (Js::ArgSlot i = 0; i < paramCount; ++i)
{
WasmTypes::WasmType type = wasmInfo->GetSignature()->GetParam(i);
info->SetArgType(WasmToAsmJs::GetAsmJsVarType(type), i);
argSizeArray[i] = wasmInfo->GetSignature()->GetParamSize(i);
}
info->SetArgByteSize(wasmInfo->GetSignature()->GetParamsSize());
info->SetReturnType(WasmToAsmJs::GetAsmJsReturnType(wasmInfo->GetResultType()));
}
WAsmJs::RegisterSpace* AllocateRegisterSpace(ArenaAllocator* alloc, WAsmJs::Types)
{
return Anew(alloc, WAsmJs::RegisterSpace, 1);
}
void WasmBytecodeGenerator::GenerateFunctionBytecode(Js::ScriptContext* scriptContext, WasmReaderInfo* readerinfo, bool validateOnly /*= false*/)
{
WasmBytecodeGenerator generator(scriptContext, readerinfo, validateOnly);
generator.GenerateFunction();
if (!generator.GetReader()->IsCurrentFunctionCompleted())
{
throw WasmCompilationException(_u("Invalid function format"));
}
}
void WasmBytecodeGenerator::ValidateFunction(Js::ScriptContext* scriptContext, WasmReaderInfo* readerinfo)
{
GenerateFunctionBytecode(scriptContext, readerinfo, true);
}
WasmBytecodeGenerator::WasmBytecodeGenerator(Js::ScriptContext* scriptContext, WasmReaderInfo* readerInfo, bool validateOnly) :
m_scriptContext(scriptContext),
m_alloc(_u("WasmBytecodeGen"), scriptContext->GetThreadContext()->GetPageAllocator(), Js::Throw::OutOfMemory),
m_evalStack(&m_alloc),
mTypedRegisterAllocator(&m_alloc, AllocateRegisterSpace, 1 << WAsmJs::SIMD),
m_blockInfos(&m_alloc),
currentProfileId(0),
isUnreachable(false)
{
m_emptyWriter = Anew(&m_alloc, Js::EmptyWasmByteCodeWriter);
m_writer = m_originalWriter = validateOnly ? m_emptyWriter : Anew(&m_alloc, Js::WasmByteCodeWriter);
m_writer->Create();
m_funcInfo = readerInfo->m_funcInfo;
m_module = readerInfo->m_module;
// Init reader to current func offset
GetReader()->SeekToFunctionBody(m_funcInfo);
// Use binary size to estimate bytecode size
const uint32 astSize = readerInfo->m_funcInfo->m_readerInfo.size;
m_writer->InitData(&m_alloc, astSize);
}
void WasmBytecodeGenerator::GenerateFunction()
{
#ifdef ENABLE_DEBUG_CONFIG_OPTIONS
if (DO_WASM_TRACE_BYTECODE)
{
Output::Print(_u("Generate WebAssembly Bytecode: "));
GetFunctionBody()->DumpFullFunctionName();
Output::Print(_u("\n"));
}
#endif
if (PHASE_OFF(Js::WasmBytecodePhase, GetFunctionBody()))
{
throw WasmCompilationException(_u("Compilation skipped"));
}
Js::AutoProfilingPhase functionProfiler(m_scriptContext, Js::WasmBytecodePhase);
Unused(functionProfiler);
m_maxArgOutDepth = 0;
m_writer->Begin(GetFunctionBody(), &m_alloc);
try
{
Js::ByteCodeLabel exitLabel = m_writer->DefineLabel();
m_funcInfo->SetExitLabel(exitLabel);
EnregisterLocals();
EnterEvalStackScope();
// The function's yield type is the return type
GetReader()->m_currentNode.block.sig = m_funcInfo->GetResultType();
EmitInfo lastInfo = EmitBlock();
if (lastInfo.type != WasmTypes::Void || m_funcInfo->GetResultType() == WasmTypes::Void)
{
EmitReturnExpr(&lastInfo);
}
DebugPrintOpEnd();
ExitEvalStackScope();
SetUnreachableState(false);
m_writer->MarkAsmJsLabel(exitLabel);
m_writer->EmptyAsm(Js::OpCodeAsmJs::Ret);
m_writer->SetCallSiteCount(this->currentProfileId);
m_writer->End();
GetReader()->FunctionEnd();
}
catch (...)
{
TRACE_WASM_BYTECODE(_u("\nHad Compilation error!"));
GetReader()->FunctionEnd();
m_originalWriter->Reset();
throw;
}
// Make sure we don't have any unforeseen exceptions as we finalize the body
AutoDisableInterrupt autoDisableInterrupt(m_scriptContext->GetThreadContext(), true);
#if DBG_DUMP
if (PHASE_DUMP(Js::ByteCodePhase, GetFunctionBody()) && !IsValidating())
{
Js::AsmJsByteCodeDumper::Dump(GetFunctionBody(), &mTypedRegisterAllocator, nullptr);
}
#endif
Js::AsmJsFunctionInfo* info = GetFunctionBody()->GetAsmJsFunctionInfo();
mTypedRegisterAllocator.CommitToFunctionBody(GetFunctionBody());
mTypedRegisterAllocator.CommitToFunctionInfo(info, GetFunctionBody());
GetFunctionBody()->CheckAndSetOutParamMaxDepth(m_maxArgOutDepth);
autoDisableInterrupt.Completed();
}
void WasmBytecodeGenerator::EnregisterLocals()
{
uint32 nLocals = m_funcInfo->GetLocalCount();
m_locals = AnewArray(&m_alloc, WasmLocal, nLocals);
m_funcInfo->GetBody()->SetFirstTmpReg(nLocals);
for (uint32 i = 0; i < nLocals; ++i)
{
WasmTypes::WasmType type = m_funcInfo->GetLocal(i);
WasmRegisterSpace* regSpace = GetRegisterSpace(type);
if (regSpace == nullptr)
{
throw WasmCompilationException(_u("Unable to find local register space"));
}
m_locals[i] = WasmLocal(regSpace->AcquireRegister(), type);
// Zero only the locals not corresponding to formal parameters.
if (i >= m_funcInfo->GetParamCount()) {
switch (type)
{
case WasmTypes::F32:
m_writer->AsmFloat1Const1(Js::OpCodeAsmJs::Ld_FltConst, m_locals[i].location, 0.0f);
break;
case WasmTypes::F64:
m_writer->AsmDouble1Const1(Js::OpCodeAsmJs::Ld_DbConst, m_locals[i].location, 0.0);
break;
case WasmTypes::I32:
m_writer->AsmInt1Const1(Js::OpCodeAsmJs::Ld_IntConst, m_locals[i].location, 0);
break;
case WasmTypes::I64:
m_writer->AsmLong1Const1(Js::OpCodeAsmJs::Ld_LongConst, m_locals[i].location, 0);
break;
default:
Assume(UNREACHED);
}
}
}
}
void WasmBytecodeGenerator::EmitExpr(WasmOp op)
{
DebugPrintOp(op);
switch (op)
{
#define WASM_OPCODE(opname, opcode, sig, nyi) \
case opcode: \
if (nyi) throw WasmCompilationException(_u("Operator %s NYI"), _u(#opname)); break;
#include "WasmBinaryOpCodes.h"
default:
break;
}
EmitInfo info;
switch (op)
{
case wbGetGlobal:
info = EmitGetGlobal();
break;
case wbSetGlobal:
info = EmitSetGlobal();
break;
case wbGetLocal:
info = EmitGetLocal();
break;
case wbSetLocal:
info = EmitSetLocal(false);
break;
case wbTeeLocal:
info = EmitSetLocal(true);
break;
case wbReturn:
EmitReturnExpr();
info.type = WasmTypes::Any;
break;
case wbF32Const:
info = EmitConst(WasmTypes::F32, GetReader()->m_currentNode.cnst);
break;
case wbF64Const:
info = EmitConst(WasmTypes::F64, GetReader()->m_currentNode.cnst);
break;
case wbI32Const:
info = EmitConst(WasmTypes::I32, GetReader()->m_currentNode.cnst);
break;
case wbI64Const:
info = EmitConst(WasmTypes::I64, GetReader()->m_currentNode.cnst);
break;
case wbBlock:
info = EmitBlock();
break;
case wbLoop:
info = EmitLoop();
break;
case wbCall:
info = EmitCall<wbCall>();
break;
case wbCallIndirect:
info = EmitCall<wbCallIndirect>();
break;
case wbIf:
info = EmitIfElseExpr();
break;
case wbElse:
throw WasmCompilationException(_u("Unexpected else opcode"));
case wbEnd:
throw WasmCompilationException(_u("Unexpected end opcode"));
case wbBr:
EmitBr();
info.type = WasmTypes::Any;
break;
case wbBrIf:
info = EmitBrIf();
break;
case wbSelect:
info = EmitSelect();
break;
case wbBrTable:
EmitBrTable();
info.type = WasmTypes::Any;
break;
case wbDrop:
info = EmitDrop();
break;
case wbNop:
return;
case wbCurrentMemory:
{
SetUsesMemory(0);
Js::RegSlot tempReg = GetRegisterSpace(WasmTypes::I32)->AcquireTmpRegister();
info = EmitInfo(tempReg, WasmTypes::I32);
m_writer->AsmReg1(Js::OpCodeAsmJs::CurrentMemory_Int, tempReg);
break;
}
case wbGrowMemory:
{
info = EmitGrowMemory();
break;
}
case wbUnreachable:
m_writer->EmptyAsm(Js::OpCodeAsmJs::Unreachable_Void);
SetUnreachableState(true);
info.type = WasmTypes::Any;
break;
#define WASM_MEMREAD_OPCODE(opname, opcode, sig, nyi, viewtype) \
case wb##opname: \
Assert(WasmOpCodeSignatures::n##sig > 0);\
info = EmitMemAccess(wb##opname, WasmOpCodeSignatures::sig, viewtype, false); \
break;
#define WASM_MEMSTORE_OPCODE(opname, opcode, sig, nyi, viewtype) \
case wb##opname: \
Assert(WasmOpCodeSignatures::n##sig > 0);\
info = EmitMemAccess(wb##opname, WasmOpCodeSignatures::sig, viewtype, true); \
break;
#define WASM_BINARY_OPCODE(opname, opcode, sig, asmjsop, nyi) \
case wb##opname: \
Assert(WasmOpCodeSignatures::n##sig == 3);\
info = EmitBinExpr(Js::OpCodeAsmJs::##asmjsop, WasmOpCodeSignatures::sig); \
break;
#define WASM_UNARY__OPCODE(opname, opcode, sig, asmjsop, nyi) \
case wb##opname: \
Assert(WasmOpCodeSignatures::n##sig == 2);\
info = EmitUnaryExpr(Js::OpCodeAsmJs::##asmjsop, WasmOpCodeSignatures::sig); \
break;
#define WASM_EMPTY__OPCODE(opname, opcode, asmjsop, nyi) \
case wb##opname: \
m_writer->EmptyAsm(Js::OpCodeAsmJs::##asmjsop);\
break;
#include "WasmBinaryOpCodes.h"
default:
throw WasmCompilationException(_u("Unknown expression's op 0x%X"), op);
}
if (info.type != WasmTypes::Void)
{
PushEvalStack(info);
}
DebugPrintOpEnd();
}
EmitInfo WasmBytecodeGenerator::EmitGetGlobal()
{
uint32 globalIndex = GetReader()->m_currentNode.var.num;
WasmGlobal* global = m_module->GetGlobal(globalIndex);
WasmTypes::WasmType type = global->GetType();
Js::RegSlot slot = m_module->GetOffsetForGlobal(global);
CompileAssert(WasmTypes::I32 == 1);
CompileAssert(WasmTypes::I64 == 2);
CompileAssert(WasmTypes::F32 == 3);
CompileAssert(WasmTypes::F64 == 4);
static const Js::OpCodeAsmJs globalOpcodes[] = {
Js::OpCodeAsmJs::LdSlot_Int,
Js::OpCodeAsmJs::LdSlot_Long,
Js::OpCodeAsmJs::LdSlot_Flt,
Js::OpCodeAsmJs::LdSlot_Db
};
WasmRegisterSpace* regSpace = GetRegisterSpace(type);
Js::RegSlot tmpReg = regSpace->AcquireTmpRegister();
EmitInfo info(tmpReg, type);
m_writer->AsmSlot(globalOpcodes[type - 1], tmpReg, WasmBytecodeGenerator::ModuleEnvRegister, slot);
return info;
}
EmitInfo WasmBytecodeGenerator::EmitSetGlobal()
{
uint32 globalIndex = GetReader()->m_currentNode.var.num;
WasmGlobal* global = m_module->GetGlobal(globalIndex);
Js::RegSlot slot = m_module->GetOffsetForGlobal(global);
WasmTypes::WasmType type = global->GetType();
EmitInfo info = PopEvalStack(type);
CompileAssert(WasmTypes::I32 == 1);
CompileAssert(WasmTypes::I64 == 2);
CompileAssert(WasmTypes::F32 == 3);
CompileAssert(WasmTypes::F64 == 4);
static const Js::OpCodeAsmJs globalOpcodes[] = {
Js::OpCodeAsmJs::StSlot_Int,
Js::OpCodeAsmJs::StSlot_Long,
Js::OpCodeAsmJs::StSlot_Flt,
Js::OpCodeAsmJs::StSlot_Db
};
m_writer->AsmSlot(globalOpcodes[type - 1], info.location, WasmBytecodeGenerator::ModuleEnvRegister, slot);
ReleaseLocation(&info);
return EmitInfo();
}
EmitInfo WasmBytecodeGenerator::EmitGetLocal()
{
uint32 localIndex = GetReader()->m_currentNode.var.num;
if (m_funcInfo->GetLocalCount() <= localIndex)
{
throw WasmCompilationException(_u("%u is not a valid local"), localIndex);
}
WasmLocal local = m_locals[localIndex];
Js::OpCodeAsmJs op = GetLoadOp(local.type);
WasmRegisterSpace* regSpace = GetRegisterSpace(local.type);
Js::RegSlot tmpReg = regSpace->AcquireTmpRegister();
m_writer->AsmReg2(op, tmpReg, local.location);
return EmitInfo(tmpReg, local.type);
}
EmitInfo WasmBytecodeGenerator::EmitSetLocal(bool tee)
{
uint32 localNum = GetReader()->m_currentNode.var.num;
if (localNum >= m_funcInfo->GetLocalCount())
{
throw WasmCompilationException(_u("%u is not a valid local"), localNum);
}
WasmLocal local = m_locals[localNum];
EmitInfo info = PopEvalStack(local.type);
m_writer->AsmReg2(GetLoadOp(local.type), local.location, info.location);
if (tee)
{
if (info.type == WasmTypes::Any)
{
throw WasmCompilationException(_u("Can't tee_local unreachable values"));
}
return info;
}
else
{
ReleaseLocation(&info);
return EmitInfo();
}
}
EmitInfo WasmBytecodeGenerator::EmitConst(WasmTypes::WasmType type, WasmConstLitNode cnst)
{
Js::RegSlot tmpReg = GetRegisterSpace(type)->AcquireTmpRegister();
EmitInfo dst(tmpReg, type);
EmitLoadConst(dst, cnst);
return dst;
}
void WasmBytecodeGenerator::EmitLoadConst(EmitInfo dst, WasmConstLitNode cnst)
{
switch (dst.type)
{
case WasmTypes::F32:
m_writer->AsmFloat1Const1(Js::OpCodeAsmJs::Ld_FltConst, dst.location, cnst.f32);
break;
case WasmTypes::F64:
m_writer->AsmDouble1Const1(Js::OpCodeAsmJs::Ld_DbConst, dst.location, cnst.f64);
break;
case WasmTypes::I32:
m_writer->AsmInt1Const1(Js::OpCodeAsmJs::Ld_IntConst, dst.location, cnst.i32);
break;
case WasmTypes::I64:
m_writer->AsmLong1Const1(Js::OpCodeAsmJs::Ld_LongConst, dst.location, cnst.i64);
break;
default:
throw WasmCompilationException(_u("Unknown type %u"), dst.type);
}
}
WasmConstLitNode WasmBytecodeGenerator::GetZeroCnst()
{
WasmConstLitNode cnst = {0};
return cnst;
}
void WasmBytecodeGenerator::EnsureStackAvailable()
{
if (!ThreadContext::IsCurrentStackAvailable(Js::Constants::MinStackCompile))
{
throw WasmCompilationException(_u("Maximum supported nested blocks reached"));
}
}
void WasmBytecodeGenerator::EmitBlockCommon(BlockInfo* blockInfo, bool* endOnElse /*= nullptr*/)
{
EnsureStackAvailable();
bool canResetUnreachable = !IsUnreachable();
WasmOp op;
EnterEvalStackScope();
if(endOnElse) *endOnElse = false;
do {
op = GetReader()->ReadExpr();
if (op == wbEnd)
{
break;
}
if (endOnElse && op == wbElse)
{
*endOnElse = true;
break;
}
EmitExpr(op);
} while (true);
DebugPrintOp(op);
if (blockInfo && blockInfo->HasYield())
{
EmitInfo info = PopEvalStack();
YieldToBlock(*blockInfo, info);
ReleaseLocation(&info);
}
ExitEvalStackScope();
if (canResetUnreachable)
{
SetUnreachableState(false);
}
}
EmitInfo WasmBytecodeGenerator::EmitBlock()
{
Js::ByteCodeLabel blockLabel = m_writer->DefineLabel();
BlockInfo blockInfo = PushLabel(blockLabel);
EmitBlockCommon(&blockInfo);
m_writer->MarkAsmJsLabel(blockLabel);
EmitInfo yieldInfo = PopLabel(blockLabel);
// block yields last value
return yieldInfo;
}
EmitInfo WasmBytecodeGenerator::EmitLoop()
{
Js::ByteCodeLabel loopTailLabel = m_writer->DefineLabel();
Js::ByteCodeLabel loopHeadLabel = m_writer->DefineLabel();
Js::ByteCodeLabel loopLandingPadLabel = m_writer->DefineLabel();
uint32 loopId = m_writer->EnterLoop(loopHeadLabel);
// Internally we create a block for loop to exit, but semantically, they don't exist so pop it
BlockInfo implicitBlockInfo = PushLabel(loopTailLabel);
m_blockInfos.Pop();
// We don't want nested block to jump directly to the loop header
// instead, jump to the landing pad and let it jump back to the loop header
PushLabel(loopLandingPadLabel, false);
EmitBlockCommon(&implicitBlockInfo);
PopLabel(loopLandingPadLabel);
// By default we don't loop, jump over the landing pad
m_writer->AsmBr(loopTailLabel);
m_writer->MarkAsmJsLabel(loopLandingPadLabel);
m_writer->AsmBr(loopHeadLabel);
// Put the implicit block back on the stack and yield the last expression to it
m_blockInfos.Push(implicitBlockInfo);
m_writer->MarkAsmJsLabel(loopTailLabel);
// Pop the implicit block to resolve the yield correctly
EmitInfo loopInfo = PopLabel(loopTailLabel);
m_writer->ExitLoop(loopId);
return loopInfo;
}
template<WasmOp wasmOp>
EmitInfo WasmBytecodeGenerator::EmitCall()
{
uint32 funcNum = Js::Constants::UninitializedValue;
uint32 signatureId = Js::Constants::UninitializedValue;
WasmSignature* calleeSignature = nullptr;
Js::ProfileId profileId = Js::Constants::NoProfileId;
EmitInfo indirectIndexInfo;
const bool isImportCall = GetReader()->m_currentNode.call.funcType == FunctionIndexTypes::Import;
Assert(isImportCall || GetReader()->m_currentNode.call.funcType == FunctionIndexTypes::Function || GetReader()->m_currentNode.call.funcType == FunctionIndexTypes::ImportThunk);
switch (wasmOp)
{
case wbCall:
{
funcNum = GetReader()->m_currentNode.call.num;
WasmFunctionInfo* calleeInfo = m_module->GetWasmFunctionInfo(funcNum);
calleeSignature = calleeInfo->GetSignature();
if (!isImportCall)
{
profileId = GetNextProfileId();
}
break;
}
case wbCallIndirect:
indirectIndexInfo = PopEvalStack(WasmTypes::I32, _u("Indirect call index must be int type"));
signatureId = GetReader()->m_currentNode.call.num;
calleeSignature = m_module->GetSignature(signatureId);
break;
default:
Assume(UNREACHED);
}
const auto argOverflow = []
{
throw WasmCompilationException(_u("Argument size too big"));
};
// emit start call
Js::ArgSlot argSize;
Js::OpCodeAsmJs startCallOp;
if (isImportCall)
{
argSize = ArgSlotMath::Mul(calleeSignature->GetParamCount(), sizeof(Js::Var), argOverflow);
startCallOp = Js::OpCodeAsmJs::StartCall;
}
else
{
startCallOp = Js::OpCodeAsmJs::I_StartCall;
argSize = calleeSignature->GetParamsSize();
}
// Add return value
argSize = ArgSlotMath::Add(argSize, sizeof(Js::Var), argOverflow);