forked from AssemblyScript/assemblyscript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompiler.ts
10509 lines (9858 loc) · 378 KB
/
compiler.ts
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
/**
* @fileoverview The AssemblyScript compiler.
* @license Apache-2.0
*/
// helper globals used by mangleImportName
let mangleImportName_moduleName: string = "";
let mangleImportName_elementName: string = "";
import {
BuiltinNames,
BuiltinFunctionContext,
BuiltinVariableContext,
builtinFunctions,
builtinVariables_onAccess,
builtinVariables_onCompile,
compileVisitGlobals,
compileVisitMembers,
compileRTTI
} from "./builtins";
import {
Range,
DiagnosticCode,
DiagnosticEmitter
} from "./diagnostics";
import {
Module,
MemorySegment,
ExpressionRef,
UnaryOp,
BinaryOp,
TypeRef,
FunctionRef,
ExpressionId,
GlobalRef,
FeatureFlags,
Index,
getExpressionId,
getExpressionType,
getConstValueI32,
getConstValueI64Low,
getConstValueI64High,
getConstValueF32,
getConstValueF64,
getConstValueV128,
getBlockChildCount,
getBlockChildAt,
getBlockName,
getLocalSetValue,
getGlobalGetName,
isGlobalMutable,
getSideEffects,
SideEffects,
SwitchBuilder,
ExpressionRunnerFlags,
isConstZero,
isConstNegZero,
isConstExpressionNaN,
ensureType,
createType
} from "./module";
import {
CommonFlags,
STATIC_DELIMITER,
INDEX_SUFFIX,
CommonNames,
Feature,
Target,
Runtime
} from "./common";
import {
Program,
ClassPrototype,
Class,
Element,
ElementKind,
DeclaredElement,
Enum,
FunctionPrototype,
Function,
Global,
Local,
EnumValue,
Property,
VariableLikeElement,
ConstantValueKind,
OperatorKind,
DecoratorFlags,
PropertyPrototype,
IndexSignature,
File,
mangleInternalName,
TypeDefinition
} from "./program";
import {
FlowFlags,
Flow,
LocalFlags,
FieldFlags,
ConditionKind
} from "./flow";
import {
Resolver,
ReportMode
} from "./resolver";
import {
Token,
operatorTokenToString
} from "./tokenizer";
import {
Node,
NodeKind,
DecoratorKind,
AssertionKind,
SourceKind,
FunctionTypeNode,
DecoratorNode,
Statement,
BlockStatement,
BreakStatement,
ClassDeclaration,
ContinueStatement,
DeclarationStatement,
DoStatement,
EmptyStatement,
EnumDeclaration,
ExportDefaultStatement,
ExportStatement,
ExpressionStatement,
FieldDeclaration,
ForStatement,
ForOfStatement,
FunctionDeclaration,
IfStatement,
ImportStatement,
InstanceOfExpression,
NamespaceDeclaration,
ReturnStatement,
SwitchStatement,
ThrowStatement,
TryStatement,
VariableStatement,
VoidStatement,
WhileStatement,
Expression,
AssertionExpression,
BinaryExpression,
CallExpression,
CommaExpression,
ElementAccessExpression,
FloatLiteralExpression,
FunctionExpression,
IdentifierExpression,
IntegerLiteralExpression,
LiteralExpression,
LiteralKind,
NewExpression,
ObjectLiteralExpression,
ParenthesizedExpression,
PropertyAccessExpression,
TernaryExpression,
ArrayLiteralExpression,
StringLiteralExpression,
TemplateLiteralExpression,
UnaryPostfixExpression,
UnaryPrefixExpression,
CompiledExpression,
TypeNode,
NamedTypeNode,
findDecorator,
isTypeOmitted,
Source,
TypeDeclaration
} from "./ast";
import {
Type,
TypeKind,
TypeFlags,
Signature,
typesToRefs
} from "./types";
import {
writeI8,
writeI16,
writeI32,
writeI64,
writeF32,
writeF64,
writeV128,
cloneMap,
isPowerOf2,
readI32,
isIdentifier,
accuratePow64,
v128_zero,
v128_ones,
} from "./util";
import {
RtraceMemory
} from "./passes/rtrace";
import {
ShadowStackPass
} from "./passes/shadowstack";
import {
liftRequiresExportRuntime,
lowerRequiresExportRuntime
} from "./bindings/js";
/** Features enabled by default. */
export const defaultFeatures = Feature.MutableGlobals
| Feature.SignExtension
| Feature.NontrappingF2I
| Feature.BulkMemory;
/** Compiler options. */
export class Options {
constructor() { /* as internref */ }
/** WebAssembly target. Defaults to {@link Target.Wasm32}. */
target: Target = Target.Wasm32;
/** Runtime type. Defaults to Incremental GC. */
runtime: Runtime = Runtime.Incremental;
/** If true, indicates that debug information will be emitted by Binaryen. */
debugInfo: bool = false;
/** If true, replaces assertions with nops. */
noAssert: bool = false;
/** It true, exports the memory to the embedder. */
exportMemory: bool = true;
/** If true, imports the memory provided by the embedder. */
importMemory: bool = false;
/** Initial memory size, in pages. */
initialMemory: u32 = 0;
/** Maximum memory size, in pages. */
maximumMemory: u32 = 0;
/** If true, memory is declared as shared. */
sharedMemory: bool = false;
/** If true, imported memory is zero filled. */
zeroFilledMemory: bool = false;
/** If true, imports the function table provided by the embedder. */
importTable: bool = false;
/** If true, exports the function table. */
exportTable: bool = false;
/** If true, generates information necessary for source maps. */
sourceMap: bool = false;
/** Unchecked behavior. Defaults to only using unchecked operations inside unchecked(). */
uncheckedBehavior: UncheckedBehavior = UncheckedBehavior.Default;
/** If given, exports the start function instead of calling it implicitly. */
exportStart: string | null = null;
/** Static memory start offset. */
memoryBase: u32 = 0;
/** Static table start offset. */
tableBase: u32 = 0;
/** Global aliases, mapping alias names as the key to internal names to be aliased as the value. */
globalAliases: Map<string,string> | null = null;
/** Features to activate by default. */
features: Feature = defaultFeatures;
/** If true, disallows unsafe features in user code. */
noUnsafe: bool = false;
/** If true, enables pedantic diagnostics. */
pedantic: bool = false;
/** Indicates a very low (<64k) memory limit. */
lowMemoryLimit: u32 = 0;
/** If true, exports the runtime helpers. */
exportRuntime: bool = false;
/** Stack size in bytes, if using a stack. */
stackSize: i32 = 0;
/** Semantic major bundle version from root package.json */
bundleMajorVersion: i32 = 0;
/** Semantic minor bundle version from root package.json */
bundleMinorVersion: i32 = 0;
/** Semantic patch bundle version from root package.json */
bundlePatchVersion: i32 = 0;
/** Hinted optimize level. Not applied by the compiler itself. */
optimizeLevelHint: i32 = 0;
/** Hinted shrink level. Not applied by the compiler itself. */
shrinkLevelHint: i32 = 0;
/** Hinted basename. */
basenameHint: string = "output";
/** Hinted bindings generation. */
bindingsHint: bool = false;
/** Tests if the target is WASM64 or, otherwise, WASM32. */
get isWasm64(): bool {
return this.target == Target.Wasm64;
}
/** Gets the unsigned size type matching the target. */
get usizeType(): Type {
return this.target == Target.Wasm64 ? Type.usize64 : Type.usize32;
}
/** Gets the signed size type matching the target. */
get isizeType(): Type {
return this.target == Target.Wasm64 ? Type.isize64 : Type.isize32;
}
/** Gets the size type reference matching the target. */
get sizeTypeRef(): TypeRef {
return this.target == Target.Wasm64 ? TypeRef.I64 : TypeRef.I32;
}
/** Gets if any optimizations will be performed. */
get willOptimize(): bool {
return this.optimizeLevelHint > 0 || this.shrinkLevelHint > 0;
}
/** Sets whether a feature is enabled. */
setFeature(feature: Feature, on: bool = true): void {
if (on) {
// Enabling Stringref also enables GC
if (feature & Feature.Stringref) feature |= Feature.GC;
// Enabling GC also enables Reference Types
if (feature & Feature.GC) feature |= Feature.ReferenceTypes;
// Enabling Relaxed SIMD also enables SIMD
if (feature & Feature.RelaxedSimd) feature |= Feature.Simd;
this.features |= feature;
} else {
// Disabling Reference Types also disables GC
if (feature & Feature.ReferenceTypes) feature |= Feature.GC;
// Disabling GC also disables Stringref
if (feature & Feature.GC) feature |= Feature.Stringref;
// Disabling SIMD also disables Relaxed SIMD
if (feature & Feature.Simd) feature |= Feature.RelaxedSimd;
this.features &= ~feature;
}
}
/** Tests if a specific feature is activated. */
hasFeature(feature: Feature): bool {
return (this.features & feature) != 0;
}
}
/** Behaviors regarding unchecked operations. */
export const enum UncheckedBehavior {
/** Only use unchecked operations inside unchecked(). */
Default = 0,
/** Never use unchecked operations. */
Never = 1,
/** Always use unchecked operations if possible. */
Always = 2
}
/** Various constraints in expression compilation. */
export const enum Constraints {
None = 0,
/** Must implicitly convert to the target type. */
ConvImplicit = 1 << 0,
/** Must explicitly convert to the target type. */
ConvExplicit = 1 << 1,
/** Must wrap small integer values to match the target type. */
MustWrap = 1 << 2,
/** Indicates that the value will be dropped immediately. */
WillDrop = 1 << 3,
/** Indicates that static data is preferred. */
PreferStatic = 1 << 4,
/** Indicates that the value will become `this` of a property access or instance call. */
IsThis = 1 << 5
}
/** Runtime features to be activated by the compiler. */
export const enum RuntimeFeatures {
None = 0,
/** Requires data setup. */
Data = 1 << 0,
/** Requires a stack. */
Stack = 1 << 1,
/** Requires heap setup. */
Heap = 1 << 2,
/** Requires runtime type information setup. */
Rtti = 1 << 3,
/** Requires the built-in globals visitor. */
visitGlobals = 1 << 4,
/** Requires the built-in members visitor. */
visitMembers = 1 << 5,
/** Requires the setArgumentsLength export. */
setArgumentsLength = 1 << 6
}
/** Imported default names of compiler-generated elements. */
export namespace ImportNames {
/** Name of the default namespace */
export const DefaultNamespace = "env";
/** Name of the memory instance, if imported. */
export const Memory = "memory";
/** Name of the table instance, if imported. */
export const Table = "table";
}
/** Exported names of compiler-generated elements. */
export namespace ExportNames {
/** Name of the memory instance, if exported. */
export const Memory = "memory";
/** Name of the table instance, if exported. */
export const Table = "table";
/** Name of the argumentsLength varargs helper global. */
export const argumentsLength = "__argumentsLength";
/** Name of the alternative argumentsLength setter function. */
export const setArgumentsLength = "__setArgumentsLength";
}
/** Functions to export if `--exportRuntime` is set. */
export const runtimeFunctions = [ "__new", "__pin", "__unpin", "__collect" ];
/** Globals to export if `--exportRuntime` is set. */
export const runtimeGlobals = [ "__rtti_base" ];
/** Compiler interface. */
export class Compiler extends DiagnosticEmitter {
/** Program reference. */
program: Program;
/** Module instance being compiled. */
get module(): Module { return this.program.module; }
/** Provided options. */
get options(): Options { return this.program.options; }
/** Resolver reference. */
get resolver(): Resolver { return this.program.resolver; }
/** Current control flow. */
currentFlow: Flow;
/** Current parent element if not a function, i.e. an enum or namespace. */
currentParent: Element | null = null;
/** Current type in compilation. */
currentType: Type = Type.void;
/** Start function statements. */
currentBody: ExpressionRef[];
/** Counting memory offset. */
memoryOffset: i64;
/** Memory segments being compiled. */
memorySegments: MemorySegment[] = [];
/** Map of already compiled static string segments. */
stringSegments: Map<string,MemorySegment> = new Map();
/** Function table being compiled. First elem is blank. */
functionTable: Function[] = [];
/** Arguments length helper global. */
builtinArgumentsLength: GlobalRef = 0;
/** Requires runtime features. */
runtimeFeatures: RuntimeFeatures = RuntimeFeatures.None;
/** Current inline functions stack. */
inlineStack: Function[] = [];
/** Lazily compiled functions. */
lazyFunctions: Set<Function> = new Set();
/** Pending instanceof helpers and their names. */
pendingInstanceOf: Map<DeclaredElement, string> = new Map();
/** Stubs to defer calls to overridden methods. */
overrideStubs: Set<Function> = new Set();
/** Elements currently undergoing compilation. */
pendingElements: Set<Element> = new Set();
/** Elements, that are module exports, already processed */
doneModuleExports: Set<Element> = new Set();
/** Shadow stack reference. */
shadowStack!: ShadowStackPass;
/** Whether the module has custom function exports. */
hasCustomFunctionExports: bool = false;
/** Whether the module would use the exported runtime to lift/lower. */
desiresExportRuntime: bool = false;
/** Compiles a {@link Program} to a {@link Module} using the specified options. */
static compile(program: Program): Module {
return new Compiler(program).compile();
}
/** Constructs a new compiler for a {@link Program} using the specified options. */
constructor(program: Program) {
super(program.diagnostics);
this.program = program;
let module = program.module;
let options = program.options;
if (options.memoryBase) {
this.memoryOffset = i64_new(options.memoryBase);
module.setLowMemoryUnused(false);
} else {
if (!options.lowMemoryLimit && options.optimizeLevelHint >= 2) {
this.memoryOffset = i64_new(1024);
module.setLowMemoryUnused(true);
} else {
this.memoryOffset = i64_new(8);
module.setLowMemoryUnused(false);
}
}
let featureFlags: FeatureFlags = 0;
if (options.hasFeature(Feature.SignExtension)) featureFlags |= FeatureFlags.SignExt;
if (options.hasFeature(Feature.MutableGlobals)) featureFlags |= FeatureFlags.MutableGlobals;
if (options.hasFeature(Feature.NontrappingF2I)) featureFlags |= FeatureFlags.TruncSat;
if (options.hasFeature(Feature.BulkMemory)) featureFlags |= FeatureFlags.BulkMemory;
if (options.hasFeature(Feature.Simd)) featureFlags |= FeatureFlags.SIMD;
if (options.hasFeature(Feature.Threads)) featureFlags |= FeatureFlags.Atomics;
if (options.hasFeature(Feature.ExceptionHandling)) featureFlags |= FeatureFlags.ExceptionHandling;
if (options.hasFeature(Feature.TailCalls)) featureFlags |= FeatureFlags.TailCall;
if (options.hasFeature(Feature.ReferenceTypes)) featureFlags |= FeatureFlags.ReferenceTypes;
if (options.hasFeature(Feature.MultiValue)) featureFlags |= FeatureFlags.MultiValue;
if (options.hasFeature(Feature.GC)) featureFlags |= FeatureFlags.GC;
if (options.hasFeature(Feature.Memory64)) featureFlags |= FeatureFlags.Memory64;
if (options.hasFeature(Feature.RelaxedSimd)) featureFlags |= FeatureFlags.RelaxedSIMD;
if (options.hasFeature(Feature.ExtendedConst)) featureFlags |= FeatureFlags.ExtendedConst;
if (options.hasFeature(Feature.Stringref)) featureFlags |= FeatureFlags.Stringref;
module.setFeatures(featureFlags);
// set up the main start function
let startFunctionInstance = program.makeNativeFunction(BuiltinNames.start, Signature.create(program, [], Type.void));
startFunctionInstance.internalName = BuiltinNames.start;
this.currentFlow = startFunctionInstance.flow;
this.currentBody = new Array<ExpressionRef>();
this.shadowStack = new ShadowStackPass(this);
}
/** Performs compilation of the underlying {@link Program} to a {@link Module}. */
compile(): Module {
let options = this.options;
let module = this.module;
let program = this.program;
let resolver = this.resolver;
let hasShadowStack = options.stackSize > 0; // implies runtime=incremental
// initialize lookup maps, built-ins, imports, exports, etc.
this.program.initialize();
// obtain the main start function
let startFunctionInstance = this.currentFlow.targetFunction;
assert(startFunctionInstance.internalName == BuiltinNames.start);
let startFunctionBody = this.currentBody;
assert(startFunctionBody.length == 0);
// compile entry file(s) while traversing reachable elements
let files = program.filesByName;
// TODO: for (let file of files.values()) {
for (let _values = Map_values(files), i = 0, k = _values.length; i < k; ++i) {
let file = unchecked(_values[i]);
if (file.source.sourceKind == SourceKind.UserEntry) {
this.compileFile(file);
this.compileModuleExports(file);
}
}
// compile and export runtime if requested or necessary
if (this.options.exportRuntime || (this.options.bindingsHint && this.desiresExportRuntime)) {
for (let i = 0, k = runtimeFunctions.length; i < k; ++i) {
let name = runtimeFunctions[i];
let instance = program.requireFunction(name);
if (this.compileFunction(instance) && !module.hasExport(name)) {
module.addFunctionExport(instance.internalName, name);
}
}
for (let i = 0, k = runtimeGlobals.length; i < k; ++i) {
let name = runtimeGlobals[i];
let instance = program.requireGlobal(name);
if (this.compileGlobal(instance) && !module.hasExport(name)) {
module.addGlobalExport(instance.internalName, name);
}
}
}
// compile lazy functions
let lazyFunctions = this.lazyFunctions;
do {
let functionsToCompile = new Array<Function>();
// TODO: for (let instance of lazyLibraryFunctions) {
for (let _values = Set_values(lazyFunctions), i = 0, k = _values.length; i < k; ++i) {
let instance = unchecked(_values[i]);
functionsToCompile.push(instance);
}
lazyFunctions.clear();
for (let i = 0, k = functionsToCompile.length; i < k; ++i) {
this.compileFunction(unchecked(functionsToCompile[i]), true);
}
} while (lazyFunctions.size);
// set up override stubs
let functionTable = this.functionTable;
let overrideStubs = this.overrideStubs;
for (let i = 0, k = functionTable.length; i < k; ++i) {
let instance = functionTable[i];
if (instance.is(CommonFlags.Overridden)) {
assert(instance.is(CommonFlags.Instance));
functionTable[i] = this.ensureOverrideStub(instance); // includes varargs stub
} else if (instance.signature.requiredParameters < instance.signature.parameterTypes.length) {
functionTable[i] = this.ensureVarargsStub(instance);
}
}
let overrideStubsSeen = new Set<Function>();
do {
// override stubs and overrides have cross-dependencies on each other, in that compiling
// either may discover the respective other. do this in a loop until no more are found.
resolver.discoveredOverride = false;
for (let _values = Set_values(overrideStubs), i = 0, k = _values.length; i < k; ++i) {
let instance = unchecked(_values[i]);
let overrideInstances = resolver.resolveOverrides(instance);
if (overrideInstances) {
for (let i = 0, k = overrideInstances.length; i < k; ++i) {
this.compileFunction(overrideInstances[i]);
}
}
overrideStubsSeen.add(instance);
}
} while (overrideStubs.size > overrideStubsSeen.size || resolver.discoveredOverride);
overrideStubsSeen.clear();
for (let _values = Set_values(overrideStubs), i = 0, k = _values.length; i < k; ++i) {
this.finalizeOverrideStub(_values[i]);
}
// compile pending instanceof helpers
for (let _keys = Map_keys(this.pendingInstanceOf), i = 0, k = _keys.length; i < k; ++i) {
let elem = _keys[i];
let name = assert(this.pendingInstanceOf.get(elem));
switch (elem.kind) {
case ElementKind.Class:
case ElementKind.Interface: {
this.finalizeInstanceOf(<Class>elem, name);
break;
}
case ElementKind.ClassPrototype:
case ElementKind.InterfacePrototype: {
this.finalizeAnyInstanceOf(<ClassPrototype>elem, name);
break;
}
default: assert(false);
}
}
// finalize runtime features
module.removeGlobal(BuiltinNames.rtti_base);
if (this.runtimeFeatures & RuntimeFeatures.Rtti) compileRTTI(this);
if (this.runtimeFeatures & RuntimeFeatures.visitGlobals) compileVisitGlobals(this);
if (this.runtimeFeatures & RuntimeFeatures.visitMembers) compileVisitMembers(this);
let memoryOffset = i64_align(this.memoryOffset, options.usizeType.byteSize);
// finalize data
module.removeGlobal(BuiltinNames.data_end);
if ((this.runtimeFeatures & RuntimeFeatures.Data) != 0 || hasShadowStack) {
if (options.isWasm64) {
module.addGlobal(BuiltinNames.data_end, TypeRef.I64, false,
module.i64(i64_low(memoryOffset), i64_high(memoryOffset))
);
} else {
module.addGlobal(BuiltinNames.data_end, TypeRef.I32, false,
module.i32(i64_low(memoryOffset))
);
}
}
// finalize stack (grows down from __heap_base to __data_end)
module.removeGlobal(BuiltinNames.stack_pointer);
if ((this.runtimeFeatures & RuntimeFeatures.Stack) != 0 || hasShadowStack) {
memoryOffset = i64_align(
i64_add(memoryOffset, i64_new(options.stackSize)),
options.usizeType.byteSize
);
if (options.isWasm64) {
module.addGlobal(BuiltinNames.stack_pointer, TypeRef.I64, true,
module.i64(i64_low(memoryOffset), i64_high(memoryOffset))
);
} else {
module.addGlobal(BuiltinNames.stack_pointer, TypeRef.I32, true,
module.i32(i64_low(memoryOffset))
);
}
}
// finalize heap
module.removeGlobal(BuiltinNames.heap_base);
if ((this.runtimeFeatures & RuntimeFeatures.Heap) != 0 || hasShadowStack) {
if (options.isWasm64) {
module.addGlobal(BuiltinNames.heap_base, TypeRef.I64, false,
module.i64(i64_low(memoryOffset), i64_high(memoryOffset))
);
} else {
module.addGlobal(BuiltinNames.heap_base, TypeRef.I32, false,
module.i32(i64_low(memoryOffset))
);
}
}
// setup default memory & table
this.initDefaultMemory(memoryOffset);
this.initDefaultTable();
// expose the arguments length helper if there are varargs exports
if (this.runtimeFeatures & RuntimeFeatures.setArgumentsLength) {
module.addFunction(BuiltinNames.setArgumentsLength, TypeRef.I32, TypeRef.None, null,
module.global_set(this.ensureArgumentsLength(), module.local_get(0, TypeRef.I32))
);
module.addFunctionExport(BuiltinNames.setArgumentsLength, ExportNames.setArgumentsLength);
}
// NOTE: no more element compiles from here. may go to the start function!
// compile the start function if not empty or if explicitly requested
let startIsEmpty = !startFunctionBody.length;
let exportStart = options.exportStart;
if (!startIsEmpty || exportStart != null) {
let signature = startFunctionInstance.signature;
if (!startIsEmpty && exportStart != null) {
module.addGlobal(BuiltinNames.started, TypeRef.I32, true, module.i32(0));
startFunctionBody.unshift(
module.global_set(BuiltinNames.started, module.i32(1))
);
startFunctionBody.unshift(
module.if(
module.global_get(BuiltinNames.started, TypeRef.I32),
module.return()
)
);
}
let funcRef = module.addFunction(
startFunctionInstance.internalName,
signature.paramRefs,
signature.resultRefs,
typesToRefs(startFunctionInstance.getNonParameterLocalTypes()),
module.flatten(startFunctionBody)
);
startFunctionInstance.finalize(module, funcRef);
if (exportStart == null) module.setStart(funcRef);
else {
if (!isIdentifier(exportStart) || module.hasExport(exportStart)) {
this.error(
DiagnosticCode.Start_function_name_0_is_invalid_or_conflicts_with_another_export,
Source.native.range, exportStart
);
} else {
module.addFunctionExport(startFunctionInstance.internalName, exportStart);
}
}
}
// Run custom passes
if (hasShadowStack) {
this.shadowStack.walkModule();
}
if (program.lookup("ASC_RTRACE") != null) {
new RtraceMemory(this).walkModule();
}
return module;
}
private initDefaultMemory(memoryOffset: i64): void {
this.memoryOffset = memoryOffset;
let options = this.options;
let module = this.module;
let memorySegments = this.memorySegments;
let initialPages: u32 = 0;
let maximumPages = Module.UNLIMITED_MEMORY;
let isSharedMemory = false;
if (options.memoryBase /* is specified */ || memorySegments.length) {
initialPages = u32(i64_low(i64_shr_u(i64_align(memoryOffset, 0x10000), i64_new(16))));
}
if (options.initialMemory) {
if (options.initialMemory < initialPages) {
this.error(
DiagnosticCode.Module_requires_at_least_0_pages_of_initial_memory,
null,
initialPages.toString()
);
} else {
initialPages = options.initialMemory;
}
}
if (options.maximumMemory) {
if (options.maximumMemory < initialPages) {
this.error(
DiagnosticCode.Module_requires_at_least_0_pages_of_maximum_memory,
null,
initialPages.toString()
);
} else {
maximumPages = options.maximumMemory;
}
}
if (options.sharedMemory) {
isSharedMemory = true;
if (!options.maximumMemory) {
this.error(
DiagnosticCode.Shared_memory_requires_maximum_memory_to_be_defined,
null
);
isSharedMemory = false;
}
if (!options.hasFeature(Feature.Threads)) {
this.error(
DiagnosticCode.Shared_memory_requires_feature_threads_to_be_enabled,
null
);
isSharedMemory = false;
}
}
// check that we didn't exceed lowMemoryLimit already
let lowMemoryLimit32 = options.lowMemoryLimit;
if (lowMemoryLimit32) {
let lowMemoryLimit = i64_new(lowMemoryLimit32 & ~15);
if (i64_gt(memoryOffset, lowMemoryLimit)) {
this.error(
DiagnosticCode.Low_memory_limit_exceeded_by_static_data_0_1,
null, i64_to_string(memoryOffset), i64_to_string(lowMemoryLimit)
);
}
}
// Setup internal memory with default name "0"
module.setMemory(
initialPages,
maximumPages,
memorySegments,
options.target,
options.exportMemory ? ExportNames.Memory : null,
CommonNames.DefaultMemory,
isSharedMemory
);
// import memory if requested (default memory is named '0' by Binaryen)
if (options.importMemory) {
module.addMemoryImport(
CommonNames.DefaultMemory,
ImportNames.DefaultNamespace,
ImportNames.Memory,
isSharedMemory
);
}
}
private initDefaultTable(): void {
let options = this.options;
let module = this.module;
// import and/or export table if requested (default table is named '0' by Binaryen)
if (options.importTable) {
module.addTableImport(
CommonNames.DefaultTable,
ImportNames.DefaultNamespace,
ImportNames.Table
);
if (options.pedantic && options.willOptimize) {
this.pedantic(
DiagnosticCode.Importing_the_table_disables_some_indirect_call_optimizations,
null
);
}
}
if (options.exportTable) {
module.addTableExport(CommonNames.DefaultTable, ExportNames.Table);
if (options.pedantic && options.willOptimize) {
this.pedantic(
DiagnosticCode.Exporting_the_table_disables_some_indirect_call_optimizations,
null
);
}
}
// set up function table (first elem is blank)
let tableBase = options.tableBase;
if (!tableBase) tableBase = 1; // leave first elem blank
let functionTable = this.functionTable;
let functionTableNames = new Array<string>(functionTable.length);
for (let i = 0, k = functionTable.length; i < k; ++i) {
functionTableNames[i] = functionTable[i].internalName;
}
let initialTableSize = <Index>tableBase + functionTable.length;
let maximumTableSize = Module.UNLIMITED_TABLE;
if (!(options.importTable || options.exportTable)) {
// use fixed size for non-imported and non-exported tables
maximumTableSize = initialTableSize;
if (options.willOptimize) {
// Hint for directize pass which indicate table's content will not change
// and can be better optimized
module.setPassArgument("directize-initial-contents-immutable", "true");
}
}
module.addFunctionTable(
CommonNames.DefaultTable,
initialTableSize,
maximumTableSize,
functionTableNames,
module.i32(tableBase)
);
}
// === Exports ==================================================================================
/** Compiles the respective module exports for the specified entry file. */
private compileModuleExports(file: File): void {
let exports = file.exports;
if (exports) {
// TODO: for (let [elementName, element] of exports) {
for (let _keys = Map_keys(exports), i = 0, k = _keys.length; i < k; ++i) {
let elementName = unchecked(_keys[i]);
let element = assert(exports.get(elementName));
this.compileModuleExport(elementName, element);
}
}
let exportsStar = file.exportsStar;
if (exportsStar) {
for (let i = 0, k = exportsStar.length; i < k; ++i) {
this.compileModuleExports(exportsStar[i]);
}
}
}
/** Compiles the respective module export(s) for the specified element. */
private compileModuleExport(name: string, element: DeclaredElement, prefix: string = ""): void {
let module = this.module;
switch (element.kind) {
case ElementKind.FunctionPrototype: {
// obtain the default instance
let functionPrototype = <FunctionPrototype>element;
if (!functionPrototype.is(CommonFlags.Generic)) {
let functionInstance = this.resolver.resolveFunction(functionPrototype, null);
if (functionInstance) {
this.compileModuleExport(name, functionInstance, prefix);
}
return;
}
break;
}
case ElementKind.Function: {
let functionInstance = <Function>element;
if (!functionInstance.hasDecorator(DecoratorFlags.Builtin)) {
let signature = functionInstance.signature;
if (signature.requiredParameters < signature.parameterTypes.length) {
// utilize varargs stub to fill in omitted arguments
functionInstance = this.ensureVarargsStub(functionInstance);
this.runtimeFeatures |= RuntimeFeatures.setArgumentsLength;
}
this.compileFunction(functionInstance);
if (functionInstance.is(CommonFlags.Compiled)) {
let exportName = prefix + name;
if (!module.hasExport(exportName)) {
module.addFunctionExport(functionInstance.internalName, exportName);
this.hasCustomFunctionExports = true;
let hasManagedOperands = signature.hasManagedOperands;
if (hasManagedOperands) {
this.shadowStack.noteExport(exportName, signature.getManagedOperandIndices());
}
if (!this.desiresExportRuntime) {
let thisType = signature.thisType;
if (
thisType && lowerRequiresExportRuntime(thisType) ||
liftRequiresExportRuntime(signature.returnType)
) {
this.desiresExportRuntime = true;
} else {
let parameterTypes = signature.parameterTypes;
for (let i = 0, k = parameterTypes.length; i < k; ++i) {
if (lowerRequiresExportRuntime(parameterTypes[i])) {
this.desiresExportRuntime = true;
break;
}
}
}
}
}
return;
}
}
break;
}
case ElementKind.Global: {
let global = <Global>element;
let isConst = global.is(CommonFlags.Const) || global.is(CommonFlags.Static | CommonFlags.Readonly);
if (!isConst && !this.options.hasFeature(Feature.MutableGlobals)) {
this.warning(
DiagnosticCode.Feature_0_is_not_enabled,
global.identifierNode.range, "mutable-globals"
);
return;
}
this.compileGlobal(global);
if (global.is(CommonFlags.Compiled)) {
let exportName = prefix + name;
if (!module.hasExport(exportName)) {
module.addGlobalExport(element.internalName, exportName);
if (!this.desiresExportRuntime) {