forked from WebAssembly/binaryen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasm2wasm.h
3274 lines (3128 loc) · 117 KB
/
asm2wasm.h
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 2015 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// asm.js-to-WebAssembly translator. Uses the Emscripten optimizer
// infrastructure.
//
#ifndef wasm_asm2wasm_h
#define wasm_asm2wasm_h
#include "abi/js.h"
#include "asm_v_wasm.h"
#include "asmjs/shared-constants.h"
#include "emscripten-optimizer/optimizer.h"
#include "ir/bits.h"
#include "ir/branch-utils.h"
#include "ir/function-type-utils.h"
#include "ir/literal-utils.h"
#include "ir/module-utils.h"
#include "ir/trapping.h"
#include "ir/utils.h"
#include "mixed_arena.h"
#include "parsing.h"
#include "pass.h"
#include "passes/passes.h"
#include "shared-constants.h"
#include "wasm-builder.h"
#include "wasm-emscripten.h"
#include "wasm-module-building.h"
#include "wasm.h"
namespace wasm {
using namespace cashew;
// Names
Name I32_CTTZ("i32_cttz");
Name I32_CTPOP("i32_ctpop");
Name I32_BC2F("i32_bc2f");
Name I32_BC2I("i32_bc2i");
Name I64("i64");
Name I64_CONST("i64_const");
Name I64_ADD("i64_add");
Name I64_SUB("i64_sub");
Name I64_MUL("i64_mul");
Name I64_UDIV("i64_udiv");
Name I64_SDIV("i64_sdiv");
Name I64_UREM("i64_urem");
Name I64_SREM("i64_srem");
Name I64_AND("i64_and");
Name I64_OR("i64_or");
Name I64_XOR("i64_xor");
Name I64_SHL("i64_shl");
Name I64_ASHR("i64_ashr");
Name I64_LSHR("i64_lshr");
Name I64_EQ("i64_eq");
Name I64_NE("i64_ne");
Name I64_ULE("i64_ule");
Name I64_SLE("i64_sle");
Name I64_UGE("i64_uge");
Name I64_SGE("i64_sge");
Name I64_ULT("i64_ult");
Name I64_SLT("i64_slt");
Name I64_UGT("i64_ugt");
Name I64_SGT("i64_sgt");
Name I64_TRUNC("i64_trunc");
Name I64_SEXT("i64_sext");
Name I64_ZEXT("i64_zext");
Name I64_S2F("i64_s2f");
Name I64_S2D("i64_s2d");
Name I64_U2F("i64_u2f");
Name I64_U2D("i64_u2d");
Name I64_F2S("i64_f2s");
Name I64_D2S("i64_d2s");
Name I64_F2U("i64_f2u");
Name I64_D2U("i64_d2u");
Name I64_BC2D("i64_bc2d");
Name I64_BC2I("i64_bc2i");
Name I64_CTTZ("i64_cttz");
Name I64_CTLZ("i64_ctlz");
Name I64_CTPOP("i64_ctpop");
Name F32_COPYSIGN("f32_copysign");
Name F64_COPYSIGN("f64_copysign");
Name LOAD1("load1");
Name LOAD2("load2");
Name LOAD4("load4");
Name LOAD8("load8");
Name LOADF("loadf");
Name LOADD("loadd");
Name STORE1("store1");
Name STORE2("store2");
Name STORE4("store4");
Name STORE8("store8");
Name STOREF("storef");
Name STORED("stored");
Name FTCALL("ftCall_");
Name MFTCALL("mftCall_");
Name MAX_("max");
Name MIN_("min");
Name ATOMICS("Atomics");
Name ATOMICS_LOAD("load");
Name ATOMICS_STORE("store");
Name ATOMICS_EXCHANGE("exchange");
Name ATOMICS_COMPARE_EXCHANGE("compareExchange");
Name ATOMICS_ADD("add");
Name ATOMICS_SUB("sub");
Name ATOMICS_AND("and");
Name ATOMICS_OR("or");
Name ATOMICS_XOR("xor");
Name I64_ATOMICS_LOAD("i64_atomics_load");
Name I64_ATOMICS_STORE("i64_atomics_store");
Name I64_ATOMICS_AND("i64_atomics_and");
Name I64_ATOMICS_OR("i64_atomics_or");
Name I64_ATOMICS_XOR("i64_atomics_xor");
Name I64_ATOMICS_ADD("i64_atomics_add");
Name I64_ATOMICS_SUB("i64_atomics_sub");
Name I64_ATOMICS_EXCHANGE("i64_atomics_exchange");
Name I64_ATOMICS_COMPAREEXCHANGE("i64_atomics_compareExchange");
Name TEMP_DOUBLE_PTR("tempDoublePtr");
Name EMSCRIPTEN_DEBUGINFO("emscripten_debuginfo");
// Utilities
static void abort_on(std::string why, Ref element) {
std::cerr << why << ' ';
element->stringify(std::cerr);
std::cerr << '\n';
abort();
}
static void abort_on(std::string why, IString element) {
std::cerr << why << ' ' << element.str << '\n';
abort();
}
Index indexOr(Index x, Index y) { return x ? x : y; }
// useful when we need to see our parent, in an asm.js expression stack
struct AstStackHelper {
static std::vector<Ref> astStack;
AstStackHelper(Ref curr) { astStack.push_back(curr); }
~AstStackHelper() { astStack.pop_back(); }
Ref getParent() {
if (astStack.size() >= 2) {
return astStack[astStack.size() - 2];
} else {
return Ref();
}
}
};
std::vector<Ref> AstStackHelper::astStack;
static bool startsWith(const char* string, const char* prefix) {
while (1) {
if (*prefix == 0) {
return true;
}
if (*string == 0) {
return false;
}
if (*string++ != *prefix++) {
return false;
}
}
};
//
// Asm2WasmPreProcessor - does some initial parsing/processing
// of asm.js code.
//
struct Asm2WasmPreProcessor {
bool memoryGrowth = false;
bool debugInfo = false;
std::vector<std::string> debugInfoFileNames;
std::unordered_map<std::string, Index> debugInfoFileIndices;
char* allocatedCopy = nullptr;
~Asm2WasmPreProcessor() {
if (allocatedCopy) {
free(allocatedCopy);
}
}
char* process(char* input) {
// emcc --separate-asm modules can look like
//
// Module["asm"] = (function(global, env, buffer) {
// ..
// });
//
// we need to clean that up.
if (*input == 'M') {
size_t num = strlen(input);
while (*input != 'f') {
input++;
num--;
}
char* end = input + num - 1;
while (*end != '}') {
*end = 0;
end--;
}
}
// asm.js memory growth uses a quite elaborate pattern. Instead of parsing
// and matching it, we do a simpler detection on emscripten's asm.js output
// format
const char* START_FUNCS = "// EMSCRIPTEN_START_FUNCS";
char* marker = strstr(input, START_FUNCS);
if (marker) {
// look for memory growth code just up to here, as an optimization
*marker = 0;
}
// this can only show up in growth code, as normal asm.js lacks "true"
char* growthSign = strstr(input, "return true;");
if (growthSign) {
memoryGrowth = true;
// clean out this function, we don't need it. first where it starts
char* growthFuncStart = growthSign;
while (*growthFuncStart != '{') {
growthFuncStart--; // skip body
}
while (*growthFuncStart != '(') {
growthFuncStart--; // skip params
}
while (*growthFuncStart != ' ') {
growthFuncStart--; // skip function name
}
while (*growthFuncStart != 'f') {
growthFuncStart--; // skip 'function'
}
assert(strstr(growthFuncStart, "function ") == growthFuncStart);
char* growthFuncEnd = strchr(growthSign, '}');
assert(growthFuncEnd > growthFuncStart + 5);
growthFuncStart[0] = '/';
growthFuncStart[1] = '*';
growthFuncEnd--;
growthFuncEnd[0] = '*';
growthFuncEnd[1] = '/';
}
if (marker) {
*marker = START_FUNCS[0];
}
// handle debug info, if this build wants that.
if (debugInfo) {
// asm.js debug info comments look like
// ..command..; //@line 4 "tests/hello_world.c"
// we convert those into emscripten_debuginfo(file, line)
// calls, where the params are indices into a mapping. then
// the compiler and optimizer can operate on them. after
// that, we can apply the debug info to the wasm node right
// before it - this is guaranteed to be correct without opts,
// and is usually decently accurate with them.
// an upper bound on how much more space we need as a multiple of the
// original
const auto SCALE_FACTOR = 1.25;
// an upper bound on how much we write for each debug info element itself
const auto ADD_FACTOR = 100;
auto size = strlen(input);
auto upperBound = Index(size * SCALE_FACTOR) + ADD_FACTOR;
char* copy = allocatedCopy = (char*)malloc(upperBound);
char* end = copy + upperBound;
char* out = copy;
std::string DEBUGINFO_INTRINSIC = EMSCRIPTEN_DEBUGINFO.str;
auto DEBUGINFO_INTRINSIC_SIZE = DEBUGINFO_INTRINSIC.size();
const char* UNKNOWN_FILE = "(unknown)";
bool seenUseAsm = false;
while (input[0]) {
if (out + ADD_FACTOR >= end) {
Fatal() << "error in handling debug info";
}
if (startsWith(input, "//@line")) {
char* linePos = input + 8;
char* lineEnd = strpbrk(input + 8, " \n");
if (!lineEnd) {
// comment goes to end of input
break;
}
input = lineEnd + 1;
std::string file;
if (*lineEnd == ' ') {
// we have a file
char* filePos = strpbrk(input, "\"\n");
if (!filePos) {
// goes to end of input
break;
}
if (*filePos == '"') {
char* fileEnd = strpbrk(filePos + 1, "\"\n");
input = fileEnd + 1;
*fileEnd = 0;
file = filePos + 1;
} else {
file = UNKNOWN_FILE;
input = filePos + 1;
}
} else {
// no file, we found \n
file = UNKNOWN_FILE;
}
*lineEnd = 0;
std::string line = linePos;
auto iter = debugInfoFileIndices.find(file);
if (iter == debugInfoFileIndices.end()) {
Index index = debugInfoFileNames.size();
debugInfoFileNames.push_back(file);
debugInfoFileIndices[file] = index;
}
std::string fileIndex = std::to_string(debugInfoFileIndices[file]);
// write out the intrinsic
strcpy(out, DEBUGINFO_INTRINSIC.c_str());
out += DEBUGINFO_INTRINSIC_SIZE;
*out++ = '(';
strcpy(out, fileIndex.c_str());
out += fileIndex.size();
*out++ = ',';
strcpy(out, line.c_str());
out += line.size();
*out++ = ')';
*out++ = ';';
} else if (!seenUseAsm &&
(startsWith(input, "asm'") || startsWith(input, "asm\""))) {
// end of "use asm" or "almost asm"
// skip the end of "use asm"; (5 chars, a,s,m," or ',;)
const auto SKIP = 5;
seenUseAsm = true;
memcpy(out, input, SKIP);
out += SKIP;
input += SKIP;
// add a fake import for the intrinsic, so the module validates
std::string import =
"\n var emscripten_debuginfo = env.emscripten_debuginfo;";
strcpy(out, import.c_str());
out += import.size();
} else {
*out++ = *input++;
}
}
if (out >= end) {
Fatal() << "error in handling debug info";
}
*out = 0;
input = copy;
}
return input;
}
};
static Call* checkDebugInfo(Expression* curr) {
if (auto* call = curr->dynCast<Call>()) {
if (call->target == EMSCRIPTEN_DEBUGINFO) {
return call;
}
}
return nullptr;
}
// Debug info appears in the ast as calls to the debug intrinsic. These are
// usually after the relevant node. We adjust them to a position that is not
// dce-able, so that they are not trivially removed when optimizing.
struct AdjustDebugInfo
: public WalkerPass<PostWalker<AdjustDebugInfo, Visitor<AdjustDebugInfo>>> {
bool isFunctionParallel() override { return true; }
Pass* create() override { return new AdjustDebugInfo(); }
AdjustDebugInfo() { name = "adjust-debug-info"; }
void visitBlock(Block* curr) {
// look for a debug info call that is unreachable
if (curr->list.size() == 0) {
return;
}
auto* back = curr->list.back();
for (Index i = 1; i < curr->list.size(); i++) {
if (checkDebugInfo(curr->list[i]) && !checkDebugInfo(curr->list[i - 1])) {
// swap them
std::swap(curr->list[i - 1], curr->list[i]);
}
}
if (curr->list.back() != back) {
// we changed the last element, update the type
curr->finalize();
}
}
};
//
// Asm2WasmBuilder - converts an asm.js module into WebAssembly
//
class Asm2WasmBuilder {
public:
Module& wasm;
MixedArena& allocator;
Builder builder;
std::unique_ptr<OptimizingIncrementalModuleBuilder> optimizingBuilder;
// globals
struct MappedGlobal {
Type type;
// if true, this is an import - we should read the value, not just set a
// zero
bool import;
IString module, base;
MappedGlobal() : type(none), import(false) {}
MappedGlobal(Type type) : type(type), import(false) {}
MappedGlobal(Type type, bool import, IString module, IString base)
: type(type), import(import), module(module), base(base) {}
};
// function table
// each asm function table gets a range in the one wasm table, starting at a
// location
std::map<IString, int> functionTableStarts;
Asm2WasmPreProcessor& preprocessor;
bool debug;
TrapMode trapMode;
TrappingFunctionContainer trappingFunctions;
PassOptions passOptions;
bool legalizeJavaScriptFFI;
bool runOptimizationPasses;
bool wasmOnly;
public:
std::map<IString, MappedGlobal> mappedGlobals;
private:
void allocateGlobal(IString name, Type type, Literal value = Literal()) {
assert(mappedGlobals.find(name) == mappedGlobals.end());
if (value.type == none) {
value = Literal::makeZero(type);
}
mappedGlobals.emplace(name, MappedGlobal(type));
wasm.addGlobal(builder.makeGlobal(
name, type, builder.makeConst(value), Builder::Mutable));
}
struct View {
unsigned bytes;
bool integer, signed_;
AsmType type;
View() : bytes(0) {}
View(unsigned bytes, bool integer, bool signed_, AsmType type)
: bytes(bytes), integer(integer), signed_(signed_), type(type) {}
};
std::map<IString, View> views; // name (e.g. HEAP8) => view info
// Imported names of Math.*
IString Math_imul;
IString Math_clz32;
IString Math_fround;
IString Math_abs;
IString Math_floor;
IString Math_ceil;
IString Math_sqrt;
IString Math_max;
IString Math_min;
// Imported names of Atomics.*
IString Atomics_load;
IString Atomics_store;
IString Atomics_exchange;
IString Atomics_compareExchange;
IString Atomics_add;
IString Atomics_sub;
IString Atomics_and;
IString Atomics_or;
IString Atomics_xor;
IString llvm_cttz_i32;
IString tempDoublePtr; // imported name of tempDoublePtr
// possibly-minified names, detected via their exports
IString udivmoddi4;
IString getTempRet0;
// function types. we fill in this information as we see
// uses, in the first pass
std::map<IString, std::unique_ptr<FunctionType>> importedFunctionTypes;
void noteImportedFunctionCall(Ref ast, Type resultType, Call* call) {
assert(ast[0] == CALL && ast[1]->isString());
IString importName = ast[1]->getIString();
auto type = make_unique<FunctionType>();
type->name = IString((std::string("type$") + importName.str).c_str(),
false); // TODO: make a list of such types
type->result = resultType;
for (auto* operand : call->operands) {
type->params.push_back(operand->type);
}
// if we already saw this signature, verify it's the same (or else handle
// that)
if (importedFunctionTypes.find(importName) != importedFunctionTypes.end()) {
FunctionType* previous = importedFunctionTypes[importName].get();
if (*type != *previous) {
// merge it in. we'll add on extra 0 parameters for ones not actually
// used, and upgrade types to double where there is a conflict (which is
// ok since in JS, double can contain everything i32 and f32 can).
for (size_t i = 0; i < type->params.size(); i++) {
if (previous->params.size() > i) {
if (previous->params[i] == none) {
previous->params[i] = type->params[i]; // use a more concrete type
} else if (previous->params[i] != type->params[i]) {
previous->params[i] = f64; // overloaded type, make it a double
}
} else {
previous->params.push_back(type->params[i]); // add a new param
}
}
// we accept none and a concrete type, but two concrete types mean we
// need to use an f64 to contain anything
if (previous->result == none) {
previous->result = type->result; // use a more concrete type
} else if (previous->result != type->result && type->result != none) {
previous->result = f64; // overloaded return type, make it a double
}
}
} else {
importedFunctionTypes[importName].swap(type);
}
}
Type getResultTypeOfCallUsingParent(Ref parent, AsmData* data) {
auto result = none;
if (!!parent) {
// if the parent is a seq, we cannot be the last element in it (we would
// have a coercion, which would be the parent), so we must be (us,
// somethingElse), and so our return is void
if (parent[0] != SEQ) {
result = detectWasmType(parent, data);
}
}
return result;
}
FunctionType*
getFunctionType(Ref parent, ExpressionList& operands, AsmData* data) {
Type result = getResultTypeOfCallUsingParent(parent, data);
return ensureFunctionType(getSig(result, operands), &wasm);
}
public:
Asm2WasmBuilder(Module& wasm,
Asm2WasmPreProcessor& preprocessor,
bool debug,
TrapMode trapMode,
PassOptions passOptions,
bool legalizeJavaScriptFFI,
bool runOptimizationPasses,
bool wasmOnly)
: wasm(wasm), allocator(wasm.allocator), builder(wasm),
preprocessor(preprocessor), debug(debug), trapMode(trapMode),
trappingFunctions(trapMode, wasm, /* immediate = */ true),
passOptions(passOptions), legalizeJavaScriptFFI(legalizeJavaScriptFFI),
runOptimizationPasses(runOptimizationPasses), wasmOnly(wasmOnly) {}
void processAsm(Ref ast);
private:
AsmType detectAsmType(Ref ast, AsmData* data) {
if (ast->isString()) {
IString name = ast->getIString();
if (!data->isLocal(name)) {
// must be global
assert(mappedGlobals.find(name) != mappedGlobals.end());
return wasmToAsmType(mappedGlobals[name].type);
}
} else if (ast->isArray(SUB) && ast[1]->isString()) {
// could be a heap access, use view info
auto view = views.find(ast[1]->getIString());
if (view != views.end()) {
return view->second.type;
}
}
return detectType(ast, data, false, Math_fround, wasmOnly);
}
Type detectWasmType(Ref ast, AsmData* data) {
return asmToWasmType(detectAsmType(ast, data));
}
bool isUnsignedCoercion(Ref ast) {
return detectSign(ast, Math_fround) == ASM_UNSIGNED;
}
bool isParentUnsignedCoercion(Ref parent) {
// parent may not exist, or may be a non-relevant node
if (!!parent && parent->isArray() && parent[0] == BINARY &&
isUnsignedCoercion(parent)) {
return true;
}
return false;
}
BinaryOp parseAsmBinaryOp(IString op,
Ref left,
Ref right,
Expression* leftWasm,
Expression* rightWasm) {
Type leftType = leftWasm->type;
bool isInteger = leftType == Type::i32;
if (op == PLUS) {
return isInteger ? BinaryOp::AddInt32
: (leftType == f32 ? BinaryOp::AddFloat32
: BinaryOp::AddFloat64);
}
if (op == MINUS) {
return isInteger ? BinaryOp::SubInt32
: (leftType == f32 ? BinaryOp::SubFloat32
: BinaryOp::SubFloat64);
}
if (op == MUL) {
return isInteger ? BinaryOp::MulInt32
: (leftType == f32 ? BinaryOp::MulFloat32
: BinaryOp::MulFloat64);
}
if (op == AND) {
return BinaryOp::AndInt32;
}
if (op == OR) {
return BinaryOp::OrInt32;
}
if (op == XOR) {
return BinaryOp::XorInt32;
}
if (op == LSHIFT) {
return BinaryOp::ShlInt32;
}
if (op == RSHIFT) {
return BinaryOp::ShrSInt32;
}
if (op == TRSHIFT) {
return BinaryOp::ShrUInt32;
}
if (op == EQ) {
return isInteger
? BinaryOp::EqInt32
: (leftType == f32 ? BinaryOp::EqFloat32 : BinaryOp::EqFloat64);
}
if (op == NE) {
return isInteger
? BinaryOp::NeInt32
: (leftType == f32 ? BinaryOp::NeFloat32 : BinaryOp::NeFloat64);
}
bool isUnsigned = isUnsignedCoercion(left) || isUnsignedCoercion(right);
if (op == DIV) {
if (isInteger) {
return isUnsigned ? BinaryOp::DivUInt32 : BinaryOp::DivSInt32;
}
return leftType == f32 ? BinaryOp::DivFloat32 : BinaryOp::DivFloat64;
}
if (op == MOD) {
if (isInteger) {
return isUnsigned ? BinaryOp::RemUInt32 : BinaryOp::RemSInt32;
}
return BinaryOp::RemSInt32; // XXX no floating-point remainder op, this
// must be handled by the caller
}
if (op == GE) {
if (isInteger) {
return isUnsigned ? BinaryOp::GeUInt32 : BinaryOp::GeSInt32;
}
return leftType == f32 ? BinaryOp::GeFloat32 : BinaryOp::GeFloat64;
}
if (op == GT) {
if (isInteger) {
return isUnsigned ? BinaryOp::GtUInt32 : BinaryOp::GtSInt32;
}
return leftType == f32 ? BinaryOp::GtFloat32 : BinaryOp::GtFloat64;
}
if (op == LE) {
if (isInteger) {
return isUnsigned ? BinaryOp::LeUInt32 : BinaryOp::LeSInt32;
}
return leftType == f32 ? BinaryOp::LeFloat32 : BinaryOp::LeFloat64;
}
if (op == LT) {
if (isInteger) {
return isUnsigned ? BinaryOp::LtUInt32 : BinaryOp::LtSInt32;
}
return leftType == f32 ? BinaryOp::LtFloat32 : BinaryOp::LtFloat64;
}
abort_on("bad wasm binary op", op);
abort(); // avoid warning
}
int32_t bytesToShift(unsigned bytes) {
switch (bytes) {
case 1:
return 0;
case 2:
return 1;
case 4:
return 2;
case 8:
return 3;
default: {}
}
abort();
return -1; // avoid warning
}
std::map<unsigned, Ref> tempNums;
Literal checkLiteral(Ref ast, bool rawIsInteger = true) {
if (ast->isNumber()) {
if (rawIsInteger) {
return Literal((int32_t)ast->getInteger());
} else {
return Literal(ast->getNumber());
}
} else if (ast->isArray(UNARY_PREFIX)) {
if (ast[1] == PLUS && ast[2]->isNumber()) {
return Literal((double)ast[2]->getNumber());
}
if (ast[1] == MINUS && ast[2]->isNumber()) {
double num = -ast[2]->getNumber();
if (isSInteger32(num)) {
return Literal((int32_t)num);
}
if (isUInteger32(num)) {
return Literal((uint32_t)num);
}
assert(false && "expected signed or unsigned int32");
}
if (ast[1] == PLUS && ast[2]->isArray(UNARY_PREFIX) &&
ast[2][1] == MINUS && ast[2][2]->isNumber()) {
return Literal((double)-ast[2][2]->getNumber());
}
if (ast[1] == MINUS && ast[2]->isArray(UNARY_PREFIX) &&
ast[2][1] == PLUS && ast[2][2]->isNumber()) {
return Literal((double)-ast[2][2]->getNumber());
}
} else if (wasmOnly && ast->isArray(CALL) && ast[1]->isString() &&
ast[1] == I64_CONST) {
uint64_t low = ast[2][0]->getNumber();
uint64_t high = ast[2][1]->getNumber();
return Literal(uint64_t(low + (high << 32)));
}
return Literal();
}
Literal getLiteral(Ref ast) {
Literal ret = checkLiteral(ast);
assert(ret.type != none);
return ret;
}
void fixCallType(Expression* call, Type type) {
if (call->is<Call>()) {
call->cast<Call>()->type = type;
} else if (call->is<CallIndirect>()) {
call->cast<CallIndirect>()->type = type;
}
}
FunctionType* getBuiltinFunctionType(Name module,
Name base,
ExpressionList* operands = nullptr) {
if (module == GLOBAL_MATH) {
if (base == ABS) {
assert(operands && operands->size() == 1);
Type type = (*operands)[0]->type;
if (type == i32) {
return ensureFunctionType("ii", &wasm);
}
if (type == f32) {
return ensureFunctionType("ff", &wasm);
}
if (type == f64) {
return ensureFunctionType("dd", &wasm);
}
}
}
return nullptr;
}
// ensure a nameless block
Block* blockify(Expression* expression) {
if (expression->is<Block>() && !expression->cast<Block>()->name.is()) {
return expression->dynCast<Block>();
}
auto ret = allocator.alloc<Block>();
ret->list.push_back(expression);
ret->finalize();
return ret;
}
Expression* ensureDouble(Expression* expr) {
return wasm::ensureDouble(expr, allocator);
}
Expression* truncateToInt32(Expression* value) {
if (value->type == i64) {
return builder.makeUnary(UnaryOp::WrapInt64, value);
}
// either i32, or a call_import whose type we don't know yet (but would be
// legalized to i32 anyhow)
return value;
}
Function* processFunction(Ref ast);
};
void Asm2WasmBuilder::processAsm(Ref ast) {
assert(ast[0] == TOPLEVEL);
if (ast[1]->size() == 0) {
Fatal() << "empty input";
}
Ref asmFunction = ast[1][0];
assert(asmFunction[0] == DEFUN);
Ref body = asmFunction[3];
assert(body[0][0] == STRING &&
(body[0][1]->getIString() == IString("use asm") ||
body[0][1]->getIString() == IString("almost asm")));
// extra functions that we add, that are not from the compiled code. we need
// to make sure to optimize them normally (OptimizingIncrementalModuleBuilder
// does that on the fly for compiled code)
std::vector<Function*> extraSupportFunctions;
// first, add the memory elements. we do this before the main compile+optimize
// since the optimizer should see the memory
// apply memory growth, if relevant
if (preprocessor.memoryGrowth) {
EmscriptenGlueGenerator generator(wasm);
auto* func = generator.generateMemoryGrowthFunction();
extraSupportFunctions.push_back(func);
wasm.memory.max = Memory::kUnlimitedSize;
}
// import memory
wasm.memory.name = MEMORY;
wasm.memory.module = ENV;
wasm.memory.base = MEMORY;
wasm.memory.exists = true;
// import table
wasm.table.name = TABLE;
wasm.table.module = ENV;
wasm.table.base = TABLE;
wasm.table.exists = true;
// Import memory offset, if not already there
{
auto* import = new Global;
import->name = MEMORY_BASE;
import->module = "env";
import->base = MEMORY_BASE;
import->type = i32;
wasm.addGlobal(import);
}
// Import table offset, if not already there
{
auto* import = new Global;
import->name = TABLE_BASE;
import->module = "env";
import->base = TABLE_BASE;
import->type = i32;
wasm.addGlobal(import);
}
auto addImport = [&](IString name, Ref imported, Type type) {
assert(imported[0] == DOT);
Ref module = imported[1];
IString moduleName;
if (module->isArray(DOT)) {
// we can have (global.Math).floor; skip the 'Math'
assert(module[1]->isString());
if (module[2] == MATH) {
if (imported[2] == IMUL) {
assert(Math_imul.isNull());
Math_imul = name;
return;
} else if (imported[2] == CLZ32) {
assert(Math_clz32.isNull());
Math_clz32 = name;
return;
} else if (imported[2] == FROUND) {
assert(Math_fround.isNull());
Math_fround = name;
return;
} else if (imported[2] == ABS) {
assert(Math_abs.isNull());
Math_abs = name;
return;
} else if (imported[2] == FLOOR) {
assert(Math_floor.isNull());
Math_floor = name;
return;
} else if (imported[2] == CEIL) {
assert(Math_ceil.isNull());
Math_ceil = name;
return;
} else if (imported[2] == SQRT) {
assert(Math_sqrt.isNull());
Math_sqrt = name;
return;
} else if (imported[2] == MAX_) {
assert(Math_max.isNull());
Math_max = name;
return;
} else if (imported[2] == MIN_) {
assert(Math_min.isNull());
Math_min = name;
return;
}
} else if (module[2] == ATOMICS) {
if (imported[2] == ATOMICS_LOAD) {
assert(Atomics_load.isNull());
Atomics_load = name;
return;
} else if (imported[2] == ATOMICS_STORE) {
assert(Atomics_store.isNull());
Atomics_store = name;
return;
} else if (imported[2] == ATOMICS_EXCHANGE) {
assert(Atomics_exchange.isNull());
Atomics_exchange = name;
return;
} else if (imported[2] == ATOMICS_COMPARE_EXCHANGE) {
assert(Atomics_compareExchange.isNull());
Atomics_compareExchange = name;
return;
} else if (imported[2] == ATOMICS_ADD) {
assert(Atomics_add.isNull());
Atomics_add = name;
return;
} else if (imported[2] == ATOMICS_SUB) {
assert(Atomics_sub.isNull());
Atomics_sub = name;
return;
} else if (imported[2] == ATOMICS_AND) {
assert(Atomics_and.isNull());
Atomics_and = name;
return;
} else if (imported[2] == ATOMICS_OR) {
assert(Atomics_or.isNull());
Atomics_or = name;
return;
} else if (imported[2] == ATOMICS_XOR) {
assert(Atomics_xor.isNull());
Atomics_xor = name;
return;
}
}
std::string fullName = module[1]->getCString();
fullName += '.';
fullName += +module[2]->getCString();
moduleName = IString(fullName.c_str(), false);
} else {
assert(module->isString());
moduleName = module->getIString();
if (moduleName == ENV) {
auto base = imported[2]->getIString();
if (base == TEMP_DOUBLE_PTR) {
assert(tempDoublePtr.isNull());
tempDoublePtr = name;
// we don't return here, as we can only optimize out some uses of tDP.
// So it remains imported
} else if (base == LLVM_CTTZ_I32) {
assert(llvm_cttz_i32.isNull());
llvm_cttz_i32 = name;
return;
}