forked from WebAssembly/binaryen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwasm-interpreter.h
More file actions
5482 lines (5127 loc) · 187 KB
/
wasm-interpreter.h
File metadata and controls
5482 lines (5127 loc) · 187 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 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.
*/
//
// Simple WebAssembly interpreter. This operates directly (in-place) on our IR,
// and our IR is a structured form of Wasm, so this is similar to an AST
// interpreter. Operating directly on our IR makes us efficient in the
// Precompute pass, which tries to execute every bit of code.
//
// As a side benefit, interpreting the IR directly makes the code an easy way to
// understand WebAssembly semantics (see e.g. visitLoop(), which is basically
// just a simple loop).
//
#ifndef wasm_wasm_interpreter_h
#define wasm_wasm_interpreter_h
#include <cmath>
#include <iomanip>
#include <limits.h>
#include <sstream>
#include <variant>
#include "fp16.h"
#include "ir/import-utils.h"
#include "ir/intrinsics.h"
#include "ir/iteration.h"
#include "ir/memory-utils.h"
#include "ir/module-utils.h"
#include "ir/properties.h"
#include "ir/runtime-global.h"
#include "ir/runtime-table.h"
#include "ir/table-utils.h"
#include "support/bits.h"
#include "support/safe_integer.h"
#include "support/stdckdint.h"
#include "support/string.h"
#include "wasm-builder.h"
#include "wasm-limits.h"
#include "wasm-traversal.h"
#include "wasm.h"
#if __has_feature(leak_sanitizer) || __has_feature(address_sanitizer)
#include <sanitizer/lsan_interface.h>
#endif
namespace wasm {
struct WasmException {
Literal exn;
};
// An exception thrown when we try to execute non-constant code, that is, code
// that we cannot properly evaluate at compile time (e.g. if it refers to an
// import, or we are optimizing and it uses relaxed SIMD).
// TODO: use a flow with a special name, as this is likely very slow
struct NonconstantException {};
// Utilities
extern Name RETURN_FLOW, RETURN_CALL_FLOW, NONCONSTANT_FLOW, SUSPEND_FLOW;
// Stuff that flows around during executing expressions: a literal, or a change
// in control flow.
class Flow {
public:
Flow() : values() {}
Flow(Literal value) : values{value} { assert(value.type.isConcrete()); }
Flow(Literals& values) : values(values) {}
Flow(Literals&& values) : values(std::move(values)) {}
Flow(Name breakTo) : values(), breakTo(breakTo) {}
Flow(Name breakTo, Literal value) : values{value}, breakTo(breakTo) {}
Flow(Name breakTo, Literals&& values)
: values(std::move(values)), breakTo(breakTo) {}
Flow(Name breakTo, Tag* suspendTag, Literals&& values)
: values(std::move(values)), breakTo(breakTo), suspendTag(suspendTag) {
assert(breakTo == SUSPEND_FLOW);
}
Literals values;
Name breakTo; // if non-null, a break is going on
Tag* suspendTag = nullptr; // if non-null, breakTo must be SUSPEND_FLOW, and
// this is the tag being suspended
// A helper function for the common case where there is only one value
const Literal& getSingleValue() {
assert(values.size() == 1);
return values[0];
}
Type getType() { return values.getType(); }
Expression* getConstExpression(Module& module) {
assert(values.size() > 0);
Builder builder(module);
return builder.makeConstantExpression(values);
}
// Returns true if we are breaking out of normal execution. This can be
// because of a break/continue, or a continuation.
bool breaking() const { return breakTo.is(); }
void clearIf(Name target) {
if (breakTo == target) {
breakTo = Name{};
}
}
friend std::ostream& operator<<(std::ostream& o, const Flow& flow) {
o << "(flow " << (flow.breakTo.is() ? flow.breakTo.str : "-") << " : {";
for (size_t i = 0; i < flow.values.size(); ++i) {
if (i > 0) {
o << ", ";
}
o << flow.values[i];
}
if (flow.suspendTag) {
o << " [suspend:" << flow.suspendTag->name << ']';
}
o << "})";
return o;
}
};
struct FuncData {
// Name of the function in the instance that defines it, if available, or
// otherwise the internal name of a function import.
Name name;
// The interpreter instance this function closes over, if any. (There might
// not be an interpreter instance if this is a host function or an import from
// an unknown source.) This is only used for equality comparisons, as two
// functions are equal iff they have the same name and are defined by the same
// instance (in particular, we do *not* compare the |call| field below, which
// is an execution detail).
void* self;
// A way to execute this function. We use this when it is called.
using Call = std::function<Flow(const Literals&)>;
Call call;
FuncData(Name name, void* self = nullptr, Call call = {})
: name(name), self(self), call(call) {}
bool operator==(const FuncData& other) const {
return name == other.name && self == other.self;
}
Flow doCall(const Literals& arguments) {
assert(call);
return call(arguments);
}
};
// The data of a (ref exn) literal.
struct ExnData {
const Tag* tag;
Literals payload;
ExnData(const Tag* tag, Literals payload) : tag(tag), payload(payload) {}
};
// Suspend/resume support.
//
// As we operate directly on our structured IR, we do not have a program counter
// (bytecode offset to execute, or such), nor can we use continuation-passing
// style. Instead, we implement suspending and resuming code in a parallel way
// to how Asyncify does so, see src/passes/Asyncify.cpp (as well as
// https://kripken.github.io/blog/wasm/2019/07/16/asyncify.html). That
// transformation modifies wasm, while we are an interpreter that executes wasm,
// but the shared idea is that to resume code we simply need to get to where we
// were when we suspended, so we have a "resuming" mode in which we walk the IR
// but do not execute normally. While resuming we basically re-wind the stack,
// using data we stashed on the side while unwinding.
//
// The key idea in this approach to suspending and resuming is that to suspend
// you want to unwind the stack - you "jump" back to some outer scope - and to
// resume, we want to rewind the stack - to get everything back exactly the way
// it was, so we can pick things back up. And, to achieve that, we really just
// need two things:
// * To rewind the call stack. If we called foo() and then bar(), we want to
// have foo and bar on the stack, so that when bar finishes, we return to
// foo, etc., as if we never suspended/resumed.
// * To have the same values as before. If we are an i32.add, and we
// suspended in the second arm, we need to have the same value for the
// first arm as before the suspend.
//
// Implementing these is conceptually simple:
// * For control flow, each structure handles itself. For example, if we
// unwind an If instruction then we note which arm of the If we unwound
// from, and then when we re-wind we enter that proper arm. For a Block,
// we can note the index we had executed up to, etc.
// * For values, we just save them automatically (specific visitFoo methods
// do not need to do anything themselves), see below on |valueStack|. (Note
// that we do an optimization for speed that avoids using that stack unless
// actually necessary.)
//
// Once we have those two things handled, pretty much everything else "just
// works," and 99% of instructions need no special handling at all. Even some
// instructions you might think would need custom code do not, like CallRef:
// while that instruction does a call and changes the call stack, it calls the
// value of its last child, so if we restore that child's value while resuming,
// the normal code is exactly what we want (calling that child rewinds the stack
// in exactly the right way). That is, once control flow structures know what to
// do (which is unique to each one, but trivial), and once we have values
// restored, the interpreter "wants" to return to the exact place we suspended
// at, and we just let it do that. (And when it reaches the place we suspended
// from, we do a special operation to stop resuming, and to proceed with normal
// execution, as if we never suspended.)
//
// This is not the most efficient way to pause and resume execution (a program
// counter/goto would be much faster!) but this is very simple to implement in
// our interpreter, and in a way that does not make the interpreter slower when
// not pausing/resuming. As with Asyncify, the assumption is that pauses/resumes
// are rare, and it is acceptable for them to be less efficient.
//
// Key parts of this support:
// * |ContData| is the key data structure that represents continuations. Each
// continuation Literal has a reference to one of these.
// * |ContinuationStore| is state about the execution of continuations that is
// shared between instances of the core interpreter
// (ExpressionRunner/ModuleInstance):
// * |continuations| is the stack of active continuations.
// * |resuming| is set when we are in the special "resuming" mode mentioned
// above.
// * Inside the interpreter (ExpressionRunner/ModuleInstance):
// * When we suspend, everything on the stack will save the necessary info
// to recreate itself later during resume. That is done by calling
// |pushResumeEntry|, which saves info on the continuation, and which is
// read during resume using |popResumeEntry|.
// * |valueStack| preserves values on the stack, so that we can save them
// later if we suspend.
// * When we resume, the old |valuesStack| is converted into
// |restoredValuesMap|. When a visit() sees that we have a value to
// restore, it simply returns it.
// * The main suspend/resume logic is in |visit|. That handles everything
// except for control flow structure-specific handling, which is done in
// |visitIf| etc. (each such structure handles itself).
struct ContData {
// The function we should execute to run this continuation.
Literal func;
// The continuation type.
HeapType type;
// The expression to resume execution at, which is where we suspended. Or, if
// we are just starting to execute this continuation, this is nullptr (and we
// will resume at the very start).
Expression* resumeExpr = nullptr;
// Information about how to resume execution, a list of instruction and data
// that we "replay" into the value and call stacks. For convenience we split
// this into separate entries, each one a Literals. Typically an instruction
// will emit a single Literals for itself, or possibly a few bundles.
std::vector<Literals> resumeInfo;
// The arguments sent when resuming (on first execution these appear as
// parameters to the function; on later resumes, they are returned from the
// suspend).
Literals resumeArguments;
// If set, this is the tag for an exception to be thrown at the resume point
// (from resume_throw).
Tag* exceptionTag = nullptr;
// If set, this is the exception ref to be thrown at the resume point (from
// resume_throw_ref).
Literal exception;
// Whether we executed. Continuations are one-shot, so they may not be
// executed a second time.
bool executed = false;
ContData() {}
ContData(Literal func, HeapType type) : func(func), type(type) {}
};
// Shared execution state of a set of instantiated modules.
struct ContinuationStore {
// The current continuations, in a stack. At the top of the stack is the
// current continuation, i.e., the one either executing right now, or in the
// process of unwinding or rewinding the stack.
//
// We must share this between all interpreter instances, because which
// continuation is current does not depend on which instance we happen to be
// inside (we could call an imported function from another module, and that
// should not alter what happens when we suspend/resume).
std::vector<std::shared_ptr<ContData>> continuations;
// Set when we are resuming execution, that is, re-winding the stack.
bool resuming = false;
};
// Execute an expression
template<typename SubType>
class ExpressionRunner : public OverriddenVisitor<SubType, Flow> {
SubType* self() { return static_cast<SubType*>(this); }
protected:
// Optional module context to search for globals and called functions. NULL if
// we are not interested in any context.
Module* module = nullptr;
// Maximum depth before giving up.
Index maxDepth;
Index depth = 0;
// Maximum iterations before giving up on a loop.
Index maxLoopIterations;
// Helper for visiting: Visit and handle breaking.
#define VISIT(flow, expr) \
Flow flow = self()->visit(expr); \
if (flow.breaking()) { \
return flow; \
}
// As above, but reuse an existing |flow|.
#define VISIT_REUSE(flow, expr) \
flow = self()->visit(expr); \
if (flow.breaking()) { \
return flow; \
}
Flow generateArguments(const ExpressionList& operands, Literals& arguments) {
arguments.reserve(operands.size());
for (auto expression : operands) {
VISIT(flow, expression)
arguments.push_back(flow.getSingleValue());
}
return Flow();
}
// As above, but for generateArguments.
#define VISIT_ARGUMENTS(flow, operands, arguments) \
Flow flow = self()->generateArguments(operands, arguments); \
if (flow.breaking()) { \
return flow; \
}
// This small function is mainly useful to put all GCData allocations in a
// single place. We need that because LSan reports leaks on cycles in this
// data, as we don't have a cycle collector. Those leaks are not a serious
// problem as Binaryen is not really used in long-running tasks, so we ignore
// this function in LSan.
//
// This consumes the input |data| entirely.
Literal makeGCData(Literals&& data,
Type type,
Literal desc = Literal::makeNull(HeapType::none)) {
auto allocation = std::make_shared<GCData>(std::move(data), desc);
#if __has_feature(leak_sanitizer) || __has_feature(address_sanitizer)
// GC data with cycles will leak, since shared_ptrs do not handle cycles.
// Binaryen is generally not used in long-running programs so we just ignore
// such leaks for now.
// TODO: Add a cycle collector?
__lsan_ignore_object(allocation.get());
#endif
return Literal(allocation, type.getHeapType());
}
// Same as makeGCData but for ExnData.
Literal makeExnData(Tag* tag, const Literals& payload) {
auto allocation = std::make_shared<ExnData>(tag, payload);
#if __has_feature(leak_sanitizer) || __has_feature(address_sanitizer)
__lsan_ignore_object(allocation.get());
#endif
return Literal(allocation);
}
template<typename T>
void writeBytes(T value, int numBytes, size_t index, Literals& values) {
if constexpr (std::is_same_v<T, std::array<uint8_t, 16>>) {
for (int i = 0; i < numBytes; ++i) {
values[index + i] = Literal(static_cast<int32_t>(value[i]));
}
} else {
for (int i = 0; i < numBytes; ++i) {
values[index + i] =
Literal(static_cast<int32_t>((value >> (i * 8)) & 0xff));
}
}
}
public:
// Indicates no limit of maxDepth or maxLoopIterations.
static const Index NO_LIMIT = 0;
enum RelaxedBehavior {
// Consider relaxed SIMD instructions non-constant. This is suitable for
// optimizations, as we bake the results of optimizations into the output,
// but relaxed operations must behave according to the host semantics, not
// ours, so we do not want to optimize such expressions.
NonConstant,
// Execute relaxed SIMD instructions.
Execute,
};
Literal makeFuncData(Name name, Type type) {
// Identify the interpreter, but do not provide a way to actually call the
// function.
auto allocation = std::make_shared<FuncData>(name, this);
#if __has_feature(leak_sanitizer) || __has_feature(address_sanitizer)
__lsan_ignore_object(allocation.get());
#endif
return Literal(allocation, type);
}
protected:
RelaxedBehavior relaxedBehavior = RelaxedBehavior::NonConstant;
#if WASM_INTERPRETER_DEBUG
std::string indent() {
std::string id;
if (auto* module = getModule()) {
id = module->name.toString();
}
if (id.empty()) {
id = std::to_string(reinterpret_cast<size_t>(this));
}
auto ret = '[' + id + "] ";
for (Index i = 0; i < depth; i++) {
ret += ' ';
}
return ret;
}
#endif
// Suspend/resume support.
// We save the value stack, so that we can stash it if we suspend. Normally,
// each instruction just calls visit() on its children, so the values are
// saved in those local stack frames in an efficient manner, but also we
// cannot scan those stack frames efficiently. Saving those values in
// this location (in addition to the normal place) does not add significant
// overhead (and we skip it entirely when not in a coroutine), and it is
// trivial to use when suspending.
//
// Each entry here is for an instruction in the stack of executing
// expressions, and contains all the values from its children that we have
// seen thus far. In other words, the invariant we preserve is this: when an
// instruction executes, the top of the stack contains the values of its
// children, e.g.,
//
// (i32.add (A) (B))
//
// After executing A and getting its value, valueStack looks like this:
//
// [[..], ..scopes for parents of the add.., [..], [value of A]]
// ^^^^^^^^^^^^
// scope for the
// add, with one
// child so far
//
// Imagine that B then suspends. Then using the top of valueStack, we know the
// value of A, and can stash it. When we resume, we just apply that value, and
// proceed to execute B.
std::vector<std::vector<Literals>> valueStack;
// RAII helper for |valueStack|: Adds a scope for an instruction, where the
// values of its children will be saved, and cleans it up later.
struct StackValueNoter {
ExpressionRunner* parent;
StackValueNoter(ExpressionRunner* parent) : parent(parent) {
parent->valueStack.emplace_back();
}
~StackValueNoter() {
assert(!parent->valueStack.empty());
parent->valueStack.pop_back();
}
};
// When we resume, we will apply the saved values from |valueStack| to this
// map, so we can "replay" them. Whenever visit() is asked to execute an
// expression that is in this map, then it will just return that value.
std::unordered_map<Expression*, Literals> restoredValuesMap;
// Shared execution state for continuations. This can be null if the
// instance does not want to ever suspend/resume.
std::shared_ptr<ContinuationStore> continuationStore;
std::shared_ptr<ContData> getCurrContinuationOrNull() {
if (!continuationStore || continuationStore->continuations.empty()) {
return {};
}
return continuationStore->continuations.back();
}
std::shared_ptr<ContData> getCurrContinuation() {
auto cont = getCurrContinuationOrNull();
assert(cont);
return cont;
}
void pushCurrContinuation(std::shared_ptr<ContData> cont) {
#if WASM_INTERPRETER_DEBUG
std::cout << indent() << "push continuation\n";
#endif
assert(continuationStore);
return continuationStore->continuations.push_back(cont);
}
std::shared_ptr<ContData> popCurrContinuation() {
#if WASM_INTERPRETER_DEBUG
std::cout << indent() << "pop continuation\n";
#endif
assert(continuationStore);
assert(!continuationStore->continuations.empty());
auto cont = continuationStore->continuations.back();
continuationStore->continuations.pop_back();
return cont;
}
public:
// Clear the execution state of continuations. This is done when we trap, for
// example, as that means all continuations are lost, and later calls to the
// module should start from a blank slate.
void clearContinuationStore() {
if (continuationStore) {
#if WASM_INTERPRETER_DEBUG
std::cout << indent() << "clear continuations\n";
#endif
continuationStore = std::make_shared<ContinuationStore>();
}
}
protected:
bool isResuming() { return continuationStore && continuationStore->resuming; }
// Add an entry to help us resume this continuation later. Instructions call
// this as we unwind.
void pushResumeEntry(const Literals& entry, const char* what) {
auto currContinuation = getCurrContinuationOrNull();
if (!currContinuation) {
// We are suspending outside of a continuation. This will trap as an
// unhandled suspension when we reach the host, so we don't need to save
// any resume entries (it would be simpler to just trap when we suspend in
// such a situation, but spec tests want to differentiate traps from
// suspends).
return;
}
#if WASM_INTERPRETER_DEBUG
std::cout << indent() << "push resume entry [" << what << "]: " << entry
<< "\n";
#endif
currContinuation->resumeInfo.push_back(entry);
}
// Fetch an entry as we resume. Instructions call this as we rewind.
Literals popResumeEntry(const char* what) {
#if WASM_INTERPRETER_DEBUG
std::cout << indent() << "pop resume entry [" << what << "]:\n";
#endif
auto currContinuation = getCurrContinuation();
assert(!currContinuation->resumeInfo.empty());
auto entry = currContinuation->resumeInfo.back();
currContinuation->resumeInfo.pop_back();
#if WASM_INTERPRETER_DEBUG
std::cout << indent() << " => " << entry << "\n";
#endif
return entry;
}
public:
ExpressionRunner(Module* module = nullptr,
Index maxDepth = NO_LIMIT,
Index maxLoopIterations = NO_LIMIT)
: module(module), maxDepth(maxDepth), maxLoopIterations(maxLoopIterations) {
}
virtual ~ExpressionRunner() = default;
void setRelaxedBehavior(RelaxedBehavior value) { relaxedBehavior = value; }
Flow visit(Expression* curr) {
#if WASM_INTERPRETER_DEBUG
std::cout << indent() << "visit(" << getExpressionName(curr) << ")\n";
#endif
depth++;
if (maxDepth != NO_LIMIT && depth > maxDepth) {
hostLimit("interpreter recursion limit");
}
// Execute the instruction.
Flow ret;
if (!getCurrContinuationOrNull()) {
// We are not in a continuation, so we cannot suspend/resume. Just execute
// normally.
ret = OverriddenVisitor<SubType, Flow>::visit(curr);
} else {
// We may suspend/resume.
bool hasValue = false;
if (isResuming()) {
// Perhaps we have a known value to just apply here, without executing
// the instruction.
auto iter = restoredValuesMap.find(curr);
if (iter != restoredValuesMap.end()) {
ret = iter->second;
#if WASM_INTERPRETER_DEBUG
std::cout << indent() << "consume restored value: " << ret.values
<< '\n';
#endif
restoredValuesMap.erase(iter);
hasValue = true;
}
}
if (!hasValue) {
// We must execute this instruction. Set up the logic to note the values
// of children. TODO: as an optimization, we could avoid this for
// control flow structures, at the cost of more complexity
StackValueNoter noter(this);
if (Properties::isControlFlowStructure(curr)) {
// Control flow structures have their own logic for suspend/resume.
ret = OverriddenVisitor<SubType, Flow>::visit(curr);
} else {
// A general non-control-flow instruction, with generic suspend/
// resume support implemented here.
if (isResuming()) {
// Some children may have executed, and we have values stashed for
// them (see below where we suspend). Get those values, and populate
// |restoredValuesMap| so that when visit() is called on them, we
// can return those values rather than run them.
auto numEntry = popResumeEntry("num executed children");
assert(numEntry.size() == 1);
auto num = numEntry[0].geti32();
for (auto* child : ChildIterator(curr)) {
if (num == 0) {
// We have restored all the children that executed (any others
// were not suspended, and we have no values for them).
break;
}
--num;
auto value = popResumeEntry("child value");
restoredValuesMap[child] = value;
#if WASM_INTERPRETER_DEBUG
std::cout << indent() << "prepare restored value: " << value
<< '\n';
#endif
}
}
// We are ready to return the right values for the children, and
// can visit this instruction.
ret = OverriddenVisitor<SubType, Flow>::visit(curr);
if (ret.suspendTag) {
// We are suspending a continuation. All we need to do for a
// general instruction is stash the values of executed children
// from the value stack, and their number (as we may have
// suspended after executing only some).
assert(!valueStack.empty());
auto& values = valueStack.back();
auto num = values.size();
while (!values.empty()) {
// TODO: std::move, &elsewhere?
pushResumeEntry(values.back(), "child value");
values.pop_back();
}
pushResumeEntry({Literal(int32_t(num))}, "num executed children");
}
}
}
// Outside the scope of StackValueNoter, the scope of our own child values
// has been removed (we don't need those values any more). What is now on
// the top of |valueStack| is the list of child values of our parent,
// which is the place our own value can go, if we have one (we only save
// values on the stack, not values sent on a break/suspend; suspending is
// handled above).
if (!ret.breaking() && ret.getType().isConcrete()) {
// The value stack may be empty, if we lack a parent that needs our
// value. That is the case when we are the toplevel expression, etc.
if (!valueStack.empty()) {
auto& values = valueStack.back();
values.push_back(ret.values);
#if WASM_INTERPRETER_DEBUG
std::cout << indent() << "added to valueStack: " << ret.values
<< '\n';
#endif
}
}
}
#ifndef NDEBUG
if (!ret.breaking()) {
Type type = ret.getType();
if (type.isConcrete() || curr->type.isConcrete()) {
if (!Type::isSubType(type, curr->type)) {
Fatal() << "expected " << ModuleType(*module, curr->type)
<< ", seeing " << ModuleType(*module, type) << " from\n"
<< ModuleExpression(*module, curr) << '\n';
}
}
}
#endif
depth--;
#if WASM_INTERPRETER_DEBUG
std::cout << indent() << "=> returning: " << ret << '\n';
#endif
return ret;
}
// Gets the module this runner is operating on.
Module* getModule() { return module; }
Flow visitBlock(Block* curr) {
// special-case Block, because Block nesting (in their first element) can be
// incredibly deep
std::vector<Block*> stack;
stack.push_back(curr);
while (curr->list.size() > 0 && curr->list[0]->is<Block>()) {
curr = curr->list[0]->cast<Block>();
stack.push_back(curr);
}
// Suspend/resume support.
auto suspend = [&](Index blockIndex) {
Literals entry;
// To return to the same place when we resume, we add an entry with two
// pieces of information: the index in the stack of blocks, and the index
// in the block.
entry.push_back(Literal(uint32_t(stack.size())));
entry.push_back(Literal(uint32_t(blockIndex)));
pushResumeEntry(entry, "block");
};
Index blockIndex = 0;
if (isResuming()) {
auto entry = popResumeEntry("block");
assert(entry.size() == 2);
Index stackIndex = entry[0].geti32();
blockIndex = entry[1].geti32();
assert(stack.size() > stackIndex);
stack.resize(stackIndex + 1);
}
Flow flow;
auto* top = stack.back();
while (stack.size() > 0) {
curr = stack.back();
stack.pop_back();
if (flow.breaking()) {
flow.clearIf(curr->name);
continue;
}
auto& list = curr->list;
for (size_t i = blockIndex; i < list.size(); i++) {
if (curr != top && i == 0) {
// one of the block recursions we already handled
continue;
}
flow = visit(list[i]);
if (flow.suspendTag) {
suspend(i);
return flow;
}
if (flow.breaking()) {
flow.clearIf(curr->name);
break;
}
}
// If there was a value here, we only need it for the top iteration.
blockIndex = 0;
}
return flow;
}
Flow visitIf(If* curr) {
// Suspend/resume support.
auto suspend = [&](Index resumeIndex) {
// To return to the same place when we resume, we stash an index:
// 0 - suspended in the condition
// 1 - suspended in the ifTrue arm
// 2 - suspended in the ifFalse arm
pushResumeEntry({Literal(int32_t(resumeIndex))}, "if");
};
Index resumeIndex = -1;
if (isResuming()) {
auto entry = popResumeEntry("if");
assert(entry.size() == 1);
resumeIndex = entry[0].geti32();
}
Flow flow;
// The value of the if's condition (whether to take the ifTrue arm or not).
Index condition;
if (isResuming() && resumeIndex > 0) {
// We are resuming into one of the arms. Just set the right condition.
condition = (resumeIndex == 1);
} else {
// We are executing normally, or we are resuming into the condition.
// Either way, enter the condition.
flow = visit(curr->condition);
if (flow.suspendTag) {
suspend(0);
return flow;
}
if (flow.breaking()) {
return flow;
}
condition = flow.getSingleValue().geti32();
}
if (condition) {
flow = visit(curr->ifTrue);
} else {
if (curr->ifFalse) {
flow = visit(curr->ifFalse);
} else {
flow = Flow();
}
}
if (flow.suspendTag) {
suspend(condition ? 1 : 2);
return flow;
}
return flow;
}
Flow visitLoop(Loop* curr) {
// NB: No special support is need for suspend/resume.
Index loopCount = 0;
while (1) {
Flow flow = visit(curr->body);
if (flow.breaking()) {
if (flow.breakTo == curr->name) {
if (maxLoopIterations != NO_LIMIT &&
++loopCount >= maxLoopIterations) {
return Flow(NONCONSTANT_FLOW);
}
continue; // lol
}
}
// loop does not loop automatically, only continue achieves that
return flow;
}
}
Flow visitBreak(Break* curr) {
bool condition = true;
Flow flow;
if (curr->value) {
VISIT_REUSE(flow, curr->value);
}
if (curr->condition) {
VISIT(conditionFlow, curr->condition)
condition = conditionFlow.getSingleValue().getInteger() != 0;
if (!condition) {
return flow;
}
}
flow.breakTo = curr->name;
return flow;
}
Flow visitSwitch(Switch* curr) {
Flow flow;
Literals values;
if (curr->value) {
VISIT_REUSE(flow, curr->value);
values = flow.values;
}
VISIT_REUSE(flow, curr->condition);
int64_t index = flow.getSingleValue().getInteger();
Name target = curr->default_;
if (index >= 0 && (size_t)index < curr->targets.size()) {
target = curr->targets[(size_t)index];
}
flow.breakTo = target;
flow.values = values;
return flow;
}
Flow visitConst(Const* curr) {
return Flow(curr->value); // heh
}
// Unary and Binary nodes, the core math computations. We mostly just
// delegate to the Literal::* methods, except we handle traps here.
Flow visitUnary(Unary* curr) {
VISIT(flow, curr->value)
Literal value = flow.getSingleValue();
switch (curr->op) {
case ClzInt32:
case ClzInt64:
return value.countLeadingZeroes();
case CtzInt32:
case CtzInt64:
return value.countTrailingZeroes();
case PopcntInt32:
case PopcntInt64:
return value.popCount();
case EqZInt32:
case EqZInt64:
return value.eqz();
case ReinterpretInt32:
return value.castToF32();
case ReinterpretInt64:
return value.castToF64();
case ExtendSInt32:
return value.extendToSI64();
case ExtendUInt32:
return value.extendToUI64();
case WrapInt64:
return value.wrapToI32();
case ConvertUInt32ToFloat32:
case ConvertUInt64ToFloat32:
return value.convertUIToF32();
case ConvertUInt32ToFloat64:
case ConvertUInt64ToFloat64:
return value.convertUIToF64();
case ConvertSInt32ToFloat32:
case ConvertSInt64ToFloat32:
return value.convertSIToF32();
case ConvertSInt32ToFloat64:
case ConvertSInt64ToFloat64:
return value.convertSIToF64();
case ExtendS8Int32:
case ExtendS8Int64:
return value.extendS8();
case ExtendS16Int32:
case ExtendS16Int64:
return value.extendS16();
case ExtendS32Int64:
return value.extendS32();
case NegFloat32:
case NegFloat64:
return value.neg();
case AbsFloat32:
case AbsFloat64:
return value.abs();
case CeilFloat32:
case CeilFloat64:
return value.ceil();
case FloorFloat32:
case FloorFloat64:
return value.floor();
case TruncFloat32:
case TruncFloat64:
return value.trunc();
case NearestFloat32:
case NearestFloat64:
return value.nearbyint();
case SqrtFloat32:
case SqrtFloat64:
return value.sqrt();
case TruncSFloat32ToInt32:
case TruncSFloat64ToInt32:
case TruncSFloat32ToInt64:
case TruncSFloat64ToInt64:
return truncSFloat(curr, value);
case TruncUFloat32ToInt32:
case TruncUFloat64ToInt32:
case TruncUFloat32ToInt64:
case TruncUFloat64ToInt64:
return truncUFloat(curr, value);
case TruncSatSFloat32ToInt32:
case TruncSatSFloat64ToInt32:
return value.truncSatToSI32();
case TruncSatSFloat32ToInt64:
case TruncSatSFloat64ToInt64:
return value.truncSatToSI64();
case TruncSatUFloat32ToInt32:
case TruncSatUFloat64ToInt32:
return value.truncSatToUI32();
case TruncSatUFloat32ToInt64:
case TruncSatUFloat64ToInt64:
return value.truncSatToUI64();
case ReinterpretFloat32:
return value.castToI32();
case PromoteFloat32:
return value.extendToF64();
case ReinterpretFloat64:
return value.castToI64();
case DemoteFloat64:
return value.demote();
case SplatVecI8x16:
return value.splatI8x16();
case SplatVecI16x8:
return value.splatI16x8();
case SplatVecI32x4:
return value.splatI32x4();
case SplatVecI64x2:
return value.splatI64x2();
case SplatVecF16x8:
return value.splatF16x8();