-
Notifications
You must be signed in to change notification settings - Fork 851
Expand file tree
/
Copy pathwasm-validator.cpp
More file actions
4218 lines (3979 loc) · 143 KB
/
wasm-validator.cpp
File metadata and controls
4218 lines (3979 loc) · 143 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 2017 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.
*/
#include <mutex>
#include <set>
#include <sstream>
#include <unordered_set>
#include "ir/eh-utils.h"
#include "ir/features.h"
#include "ir/find_all.h"
#include "ir/gc-type-utils.h"
#include "ir/global-utils.h"
#include "ir/intrinsics.h"
#include "ir/local-graph.h"
#include "ir/local-structural-dominance.h"
#include "ir/module-utils.h"
#include "ir/stack-utils.h"
#include "ir/utils.h"
#include "support/colors.h"
#include "wasm-validator.h"
#include "wasm.h"
namespace wasm {
// Print anything that can be streamed to an ostream
template<typename T,
typename std::enable_if<!std::is_base_of<
Expression,
typename std::remove_pointer<T>::type>::value>::type* = nullptr>
inline std::ostream&
printModuleComponent(T curr, std::ostream& stream, Module& wasm) {
stream << curr << std::endl;
return stream;
}
// Extra overload for Expressions, to print their contents.
inline std::ostream&
printModuleComponent(Expression* curr, std::ostream& stream, Module& wasm) {
if (curr) {
stream << ModuleExpression(wasm, curr) << '\n';
}
return stream;
}
// For parallel validation, we have a helper struct for coordination
struct ValidationInfo {
Module& wasm;
bool validateWeb;
bool validateGlobally;
bool quiet;
bool closedWorld;
std::atomic<bool> valid;
// a stream of error test for each function. we print in the right order at
// the end, for deterministic output
// note errors are rare/unexpected, so it's ok to use a slow mutex here
std::mutex mutex;
std::unordered_map<Function*, std::unique_ptr<std::ostringstream>> outputs;
ValidationInfo(Module& wasm) : wasm(wasm) { valid.store(true); }
std::ostringstream& getStream(Function* func) {
std::unique_lock<std::mutex> lock(mutex);
auto iter = outputs.find(func);
if (iter != outputs.end()) {
return *(iter->second.get());
}
auto& ret = outputs[func] = std::make_unique<std::ostringstream>();
return *ret.get();
}
// printing and error handling support
template<typename T, typename S>
std::ostream& fail(S text, T curr, Function* func) {
valid.store(false);
auto& stream = getStream(func);
if (quiet) {
return stream;
}
auto& ret = printFailureHeader(func);
ret << text << ", on \n";
return printModuleComponent(curr, ret, wasm);
}
std::ostream& printFailureHeader(Function* func) {
auto& stream = getStream(func);
if (quiet) {
return stream;
}
Colors::red(stream);
if (func) {
stream << "[wasm-validator error in function ";
Colors::green(stream);
stream << func->name;
Colors::red(stream);
stream << "] ";
} else {
stream << "[wasm-validator error in module] ";
}
Colors::normal(stream);
return stream;
}
// Checking utilities.
// Returns whether the result was in fact true.
template<typename T>
bool shouldBeTrue(bool result,
T curr,
const char* text,
Function* func = nullptr) {
if (!result) {
fail("unexpected false: " + std::string(text), curr, func);
return false;
}
return true;
}
// Returns whether the result was in fact false.
template<typename T>
bool shouldBeFalse(bool result,
T curr,
const char* text,
Function* func = nullptr) {
if (result) {
fail("unexpected true: " + std::string(text), curr, func);
return false;
}
return true;
}
template<typename T, typename S>
bool shouldBeEqual(
S left, S right, T curr, const char* text, Function* func = nullptr) {
if (left != right) {
std::ostringstream ss;
ss << left << " != " << right << ": " << text;
fail(ss.str(), curr, func);
return false;
}
return true;
}
template<typename T, typename S>
bool shouldBeEqualOrFirstIsUnreachable(
S left, S right, T curr, const char* text, Function* func = nullptr) {
if (left != Type::unreachable && left != right) {
std::ostringstream ss;
ss << left << " != " << right << ": " << text;
fail(ss.str(), curr, func);
return false;
}
return true;
}
template<typename T, typename S>
bool shouldBeUnequal(
S left, S right, T curr, const char* text, Function* func = nullptr) {
if (left == right) {
std::ostringstream ss;
ss << left << " == " << right << ": " << text;
fail(ss.str(), curr, func);
return false;
}
return true;
}
void shouldBeIntOrUnreachable(Type ty,
Expression* curr,
const char* text,
Function* func = nullptr) {
switch (ty.getBasic()) {
case Type::i32:
case Type::i64:
case Type::unreachable: {
break;
}
default:
fail(text, curr, func);
}
}
// Type 'left' should be a subtype of 'right'.
bool shouldBeSubType(Type left,
Type right,
Expression* curr,
const char* text,
Function* func = nullptr) {
if (Type::isSubType(left, right)) {
return true;
}
fail(text, curr, func);
return false;
}
bool shouldBeSubTypeIgnoringShared(Type left,
Type right,
Expression* curr,
const char* text,
Function* func = nullptr) {
assert(right.isRef() && right.getHeapType().isBasic());
auto share = left.isRef() ? left.getHeapType().getShared() : Unshared;
auto ht = right.getHeapType();
auto matchedRight = Type(ht.getBasic(share), right.getNullability());
return shouldBeSubType(left, matchedRight, curr, text, func);
}
};
std::string getMissingFeaturesList(Module& wasm, FeatureSet feats) {
std::stringstream ss;
bool first = true;
ss << '[';
(feats - wasm.features).iterFeatures([&](FeatureSet feat) {
if (first) {
first = false;
} else {
ss << " ";
}
ss << "--enable-" << feat.toString();
});
ss << ']';
return ss.str();
}
struct FunctionValidator : public WalkerPass<PostWalker<FunctionValidator>> {
bool isFunctionParallel() override { return true; }
std::unique_ptr<Pass> create() override {
return std::make_unique<FunctionValidator>(*getModule(), &info);
}
bool modifiesBinaryenIR() override { return false; }
ValidationInfo& info;
FunctionValidator(Module& wasm, ValidationInfo* info) : info(*info) {
setModule(&wasm);
}
// Validate the entire module.
void validate(PassRunner* runner) { run(runner, getModule()); }
// Validate a specific expression.
void validate(Expression* curr) { walk(curr); }
// Validate a function.
void validate(Function* func) { walkFunction(func); }
std::unordered_map<Name, std::unordered_set<Type>> breakTypes;
std::unordered_set<Name> delegateTargetNames;
std::unordered_set<Name> rethrowTargetNames;
// Binaryen IR requires that label names must be unique - IR generators must
// ensure that
std::unordered_set<Name> labelNames;
void noteLabelName(Name name);
public:
// visitors
void validatePoppyExpression(Expression* curr);
static void visitPoppyExpression(FunctionValidator* self,
Expression** currp) {
self->validatePoppyExpression(*currp);
}
static void visitPreBlock(FunctionValidator* self, Expression** currp) {
auto* curr = (*currp)->cast<Block>();
if (curr->name.is()) {
self->breakTypes[curr->name];
}
}
void visitBlock(Block* curr);
void validateNormalBlockElements(Block* curr);
void validatePoppyBlockElements(Block* curr);
static void visitPreLoop(FunctionValidator* self, Expression** currp) {
auto* curr = (*currp)->cast<Loop>();
if (curr->name.is()) {
self->breakTypes[curr->name];
}
}
void visitLoop(Loop* curr);
void visitIf(If* curr);
static void visitPreTry(FunctionValidator* self, Expression** currp) {
auto* curr = (*currp)->cast<Try>();
if (curr->name.is()) {
self->delegateTargetNames.insert(curr->name);
}
}
// We remove try's label before proceeding to verify catch bodies because the
// following is a validation failure:
// (try $l0
// (do ... )
// (catch $e
// (try
// (do ...)
// (delegate $l0) ;; validation failure
// )
// )
// )
// Unlike branches, if delegate's target 'catch' is located above the
// delegate, it is a validation failure.
static void visitPreCatch(FunctionValidator* self, Expression** currp) {
auto* curr = (*currp)->cast<Try>();
if (curr->name.is()) {
self->delegateTargetNames.erase(curr->name);
self->rethrowTargetNames.insert(curr->name);
}
}
// override scan to add a pre and a post check task to all nodes
static void scan(FunctionValidator* self, Expression** currp) {
auto* curr = *currp;
// Treat 'Try' specially because we need to run visitPreCatch between the
// try body and catch bodies
if (curr->is<Try>()) {
self->pushTask(doVisitTry, currp);
auto& list = curr->cast<Try>()->catchBodies;
for (int i = int(list.size()) - 1; i >= 0; i--) {
self->pushTask(scan, &list[i]);
}
self->pushTask(visitPreCatch, currp);
self->pushTask(scan, &curr->cast<Try>()->body);
self->pushTask(visitPreTry, currp);
return;
}
PostWalker<FunctionValidator>::scan(self, currp);
if (curr->is<Block>()) {
self->pushTask(visitPreBlock, currp);
}
if (curr->is<Loop>()) {
self->pushTask(visitPreLoop, currp);
}
if (auto* func = self->getFunction()) {
if (func->profile == IRProfile::Poppy) {
self->pushTask(visitPoppyExpression, currp);
}
}
// Also verify that only allowed expressions end up in the situation where
// the expression has type unreachable but there is no unreachable child.
// For example a Call with no unreachable child cannot be unreachable, but a
// Break can be.
if (curr->type == Type::unreachable) {
switch (curr->_id) {
case Expression::BreakId: {
// If there is a condition, that is already validated fully in
// visitBreak(). If there isn't a condition, then this is allowed to
// be unreachable even without an unreachable child. Either way, we
// can leave.
return;
}
case Expression::SwitchId:
case Expression::ReturnId:
case Expression::UnreachableId:
case Expression::ThrowId:
case Expression::RethrowId:
case Expression::ThrowRefId: {
// These can all be unreachable without an unreachable child.
return;
}
case Expression::CallId: {
if (curr->cast<Call>()->isReturn) {
return;
}
break;
}
case Expression::CallIndirectId: {
if (curr->cast<CallIndirect>()->isReturn) {
return;
}
break;
}
case Expression::CallRefId: {
if (curr->cast<CallRef>()->isReturn) {
return;
}
break;
}
default: {
break;
}
}
// If we reach here, then we must have an unreachable child.
bool hasUnreachableChild = false;
for (auto* child : ChildIterator(curr)) {
if (child->type == Type::unreachable) {
hasUnreachableChild = true;
break;
}
}
self->shouldBeTrue(hasUnreachableChild,
curr,
"unreachable instruction must have unreachable child");
}
}
void noteBreak(Name name, Expression* value, Expression* curr);
void noteBreak(Name name, Type valueType, Expression* curr);
void visitBreak(Break* curr);
void visitSwitch(Switch* curr);
void visitCall(Call* curr);
void visitCallIndirect(CallIndirect* curr);
void visitConst(Const* curr);
void visitLocalGet(LocalGet* curr);
void visitLocalSet(LocalSet* curr);
void visitGlobalGet(GlobalGet* curr);
void visitGlobalSet(GlobalSet* curr);
void visitLoad(Load* curr);
void visitStore(Store* curr);
void visitAtomicRMW(AtomicRMW* curr);
void visitAtomicCmpxchg(AtomicCmpxchg* curr);
void visitAtomicWait(AtomicWait* curr);
void visitAtomicNotify(AtomicNotify* curr);
void visitAtomicFence(AtomicFence* curr);
void visitSIMDExtract(SIMDExtract* curr);
void visitSIMDReplace(SIMDReplace* curr);
void visitSIMDShuffle(SIMDShuffle* curr);
void visitSIMDTernary(SIMDTernary* curr);
void visitSIMDShift(SIMDShift* curr);
void visitSIMDLoad(SIMDLoad* curr);
void visitSIMDLoadStoreLane(SIMDLoadStoreLane* curr);
void visitMemoryInit(MemoryInit* curr);
void visitDataDrop(DataDrop* curr);
void visitMemoryCopy(MemoryCopy* curr);
void visitMemoryFill(MemoryFill* curr);
void visitBinary(Binary* curr);
void visitUnary(Unary* curr);
void visitSelect(Select* curr);
void visitDrop(Drop* curr);
void visitReturn(Return* curr);
void visitMemorySize(MemorySize* curr);
void visitMemoryGrow(MemoryGrow* curr);
void visitRefNull(RefNull* curr);
void visitRefIsNull(RefIsNull* curr);
void visitRefAs(RefAs* curr);
void visitRefFunc(RefFunc* curr);
void visitRefEq(RefEq* curr);
void visitTableGet(TableGet* curr);
void visitTableSet(TableSet* curr);
void visitTableSize(TableSize* curr);
void visitTableGrow(TableGrow* curr);
void visitTableFill(TableFill* curr);
void visitTableCopy(TableCopy* curr);
void visitTableInit(TableInit* curr);
void noteDelegate(Name name, Expression* curr);
void noteRethrow(Name name, Expression* curr);
void visitTry(Try* curr);
void visitTryTable(TryTable* curr);
void visitThrow(Throw* curr);
void visitRethrow(Rethrow* curr);
void visitThrowRef(ThrowRef* curr);
void visitTupleMake(TupleMake* curr);
void visitTupleExtract(TupleExtract* curr);
void visitCallRef(CallRef* curr);
void visitRefI31(RefI31* curr);
void visitI31Get(I31Get* curr);
void visitRefTest(RefTest* curr);
void visitRefCast(RefCast* curr);
void visitBrOn(BrOn* curr);
void visitStructNew(StructNew* curr);
void visitStructGet(StructGet* curr);
void visitStructSet(StructSet* curr);
void visitArrayNew(ArrayNew* curr);
template<typename ArrayNew> void visitArrayNew(ArrayNew* curr);
void visitArrayNewData(ArrayNewData* curr);
void visitArrayNewElem(ArrayNewElem* curr);
void visitArrayNewFixed(ArrayNewFixed* curr);
void visitArrayGet(ArrayGet* curr);
void visitArraySet(ArraySet* curr);
void visitArrayLen(ArrayLen* curr);
void visitArrayCopy(ArrayCopy* curr);
void visitArrayFill(ArrayFill* curr);
template<typename ArrayInit> void visitArrayInit(ArrayInit* curr);
void visitArrayInitData(ArrayInitData* curr);
void visitArrayInitElem(ArrayInitElem* curr);
void visitStringNew(StringNew* curr);
void visitStringConst(StringConst* curr);
void visitStringMeasure(StringMeasure* curr);
void visitStringEncode(StringEncode* curr);
void visitStringConcat(StringConcat* curr);
void visitStringEq(StringEq* curr);
void visitStringWTF16Get(StringWTF16Get* curr);
void visitStringSliceWTF(StringSliceWTF* curr);
void visitContBind(ContBind* curr);
void visitContNew(ContNew* curr);
void visitResume(Resume* curr);
void visitSuspend(Suspend* curr);
void visitFunction(Function* curr);
// helpers
private:
std::ostream& getStream() { return info.getStream(getFunction()); }
template<typename T>
bool shouldBeTrue(bool result, T curr, const char* text) {
return info.shouldBeTrue(result, curr, text, getFunction());
}
template<typename T>
bool shouldBeFalse(bool result, T curr, const char* text) {
return info.shouldBeFalse(result, curr, text, getFunction());
}
template<typename T, typename S>
bool shouldBeEqual(S left, S right, T curr, const char* text) {
return info.shouldBeEqual(left, right, curr, text, getFunction());
}
template<typename T, typename S>
bool
shouldBeEqualOrFirstIsUnreachable(S left, S right, T curr, const char* text) {
return info.shouldBeEqualOrFirstIsUnreachable(
left, right, curr, text, getFunction());
}
template<typename T, typename S>
bool shouldBeUnequal(S left, S right, T curr, const char* text) {
return info.shouldBeUnequal(left, right, curr, text, getFunction());
}
void shouldBeIntOrUnreachable(Type ty, Expression* curr, const char* text) {
return info.shouldBeIntOrUnreachable(ty, curr, text, getFunction());
}
bool
shouldBeSubType(Type left, Type right, Expression* curr, const char* text) {
return info.shouldBeSubType(left, right, curr, text, getFunction());
}
bool shouldBeSubTypeIgnoringShared(Type left,
Type right,
Expression* curr,
const char* text) {
return info.shouldBeSubTypeIgnoringShared(left, right, curr, text);
}
void validateOffset(Address offset, Memory* mem, Expression* curr);
void validateAlignment(
size_t align, Type type, Index bytes, bool isAtomic, Expression* curr);
void validateMemBytes(uint8_t bytes, Type type, Expression* curr);
template<typename T> void validateReturnCall(T* curr) {
shouldBeTrue(!curr->isReturn || getModule()->features.hasTailCall(),
curr,
"return_call* requires tail calls [--enable-tail-call]");
}
// |printable| is the expression to print in case of an error. That may differ
// from |curr| which we are validating.
template<typename T>
void validateCallParamsAndResult(T* curr,
HeapType sigType,
Expression* printable) {
if (!shouldBeTrue(sigType.isSignature(),
printable,
"Heap type must be a signature type")) {
return;
}
auto sig = sigType.getSignature();
if (!shouldBeTrue(curr->operands.size() == sig.params.size(),
printable,
"call* param number must match")) {
return;
}
size_t i = 0;
for (const auto& param : sig.params) {
if (!shouldBeSubType(curr->operands[i]->type,
param,
printable,
"call param types must match") &&
!info.quiet) {
getStream() << "(on argument " << i << ")\n";
}
++i;
}
if (curr->isReturn) {
shouldBeEqual(curr->type,
Type(Type::unreachable),
printable,
"return_call* should have unreachable type");
auto* func = getFunction();
if (!shouldBeTrue(!!func, curr, "function not defined")) {
return;
}
shouldBeSubType(
sig.results,
func->getResults(),
printable,
"return_call* callee return type must match caller return type");
} else {
shouldBeEqualOrFirstIsUnreachable(
curr->type,
sig.results,
printable,
"call* type must match callee return type");
}
}
// In the common case, we use |curr| as |printable|.
template<typename T>
void validateCallParamsAndResult(T* curr, HeapType sigType) {
validateCallParamsAndResult(curr, sigType, curr);
}
};
void FunctionValidator::noteLabelName(Name name) {
if (!name.is()) {
return;
}
auto [_, inserted] = labelNames.insert(name);
shouldBeTrue(
inserted,
name,
"names in Binaryen IR must be unique - IR generators must ensure that");
}
void FunctionValidator::validatePoppyExpression(Expression* curr) {
if (curr->type == Type::unreachable) {
shouldBeTrue(StackUtils::mayBeUnreachable(curr),
curr,
"Only control flow structures and unreachable polymorphic"
" instructions may be unreachable in Poppy IR");
}
if (Properties::isControlFlowStructure(curr)) {
// Check that control flow children (except If conditions) are blocks
if (auto* if_ = curr->dynCast<If>()) {
shouldBeTrue(
if_->condition->is<Pop>(), curr, "Expected condition to be a Pop");
shouldBeTrue(if_->ifTrue->is<Block>(),
curr,
"Expected control flow child to be a block");
shouldBeTrue(!if_->ifFalse || if_->ifFalse->is<Block>(),
curr,
"Expected control flow child to be a block");
} else if (!curr->is<Block>()) {
for (auto* child : ChildIterator(curr)) {
shouldBeTrue(child->is<Block>(),
curr,
"Expected control flow child to be a block");
}
}
} else {
// Check that all children are Pops
for (auto* child : ChildIterator(curr)) {
shouldBeTrue(child->is<Pop>(), curr, "Unexpected non-Pop child");
}
}
}
void FunctionValidator::visitBlock(Block* curr) {
if (!getModule()->features.hasMultivalue()) {
shouldBeTrue(
!curr->type.isTuple(),
curr,
"Multivalue block type require multivalue [--enable-multivalue]");
}
// if we are break'ed to, then the value must be right for us
if (curr->name.is()) {
noteLabelName(curr->name);
auto iter = breakTypes.find(curr->name);
assert(iter != breakTypes.end()); // we set it ourselves
for (Type breakType : iter->second) {
if (breakType == Type::none && curr->type == Type::unreachable) {
// We allow empty breaks to unreachable blocks.
continue;
}
shouldBeSubType(breakType,
curr->type,
curr,
"break type must be a subtype of the target block type");
}
breakTypes.erase(iter);
}
auto* func = getFunction();
if (!shouldBeTrue(!!func, curr, "function not defined")) {
return;
}
switch (func->profile) {
case IRProfile::Normal:
validateNormalBlockElements(curr);
break;
case IRProfile::Poppy:
validatePoppyBlockElements(curr);
break;
}
}
void FunctionValidator::validateNormalBlockElements(Block* curr) {
if (curr->list.size() > 1) {
for (Index i = 0; i < curr->list.size() - 1; i++) {
if (!shouldBeTrue(
!curr->list[i]->type.isConcrete(),
curr,
"non-final block elements returning a value must be drop()ed "
"(binaryen's autodrop option might help you)") &&
!info.quiet) {
getStream() << "(on index " << i << ":\n"
<< curr->list[i] << "\n), type: " << curr->list[i]->type
<< "\n";
}
}
}
if (curr->list.size() > 0) {
auto backType = curr->list.back()->type;
if (!curr->type.isConcrete()) {
shouldBeFalse(backType.isConcrete(),
curr,
"if block is not returning a value, final element should "
"not flow out a value");
} else {
if (backType.isConcrete()) {
shouldBeSubType(
backType,
curr->type,
curr,
"block with value and last element with value must match types");
} else {
shouldBeUnequal(
backType,
Type(Type::none),
curr,
"block with value must not have last element that is none");
}
}
}
if (curr->type.isConcrete()) {
shouldBeTrue(
curr->list.size() > 0, curr, "block with a value must not be empty");
}
}
void FunctionValidator::validatePoppyBlockElements(Block* curr) {
StackSignature blockSig;
for (size_t i = 0; i < curr->list.size(); ++i) {
Expression* expr = curr->list[i];
if (!shouldBeTrue(
!expr->is<Pop>(), expr, "Unexpected top-level pop in block")) {
return;
}
StackSignature sig(expr);
if (!shouldBeTrue(blockSig.composes(sig),
curr,
"block element has incompatible type") &&
!info.quiet) {
getStream() << "(on index " << i << ":\n"
<< expr << "\n), required: " << sig.params << ", available: ";
if (blockSig.kind == StackSignature::Polymorphic) {
getStream() << "polymorphic, ";
}
getStream() << blockSig.results << "\n";
return;
}
blockSig += sig;
}
if (curr->type == Type::unreachable) {
shouldBeTrue(blockSig.kind == StackSignature::Polymorphic,
curr,
"unreachable block should have unreachable element");
} else {
if (!shouldBeTrue(
StackSignature::isSubType(
blockSig,
StackSignature(Type::none, curr->type, StackSignature::Fixed)),
curr,
"block contents should satisfy block type") &&
!info.quiet) {
getStream() << "contents: " << blockSig.results
<< (blockSig.kind == StackSignature::Polymorphic
? " [polymorphic]"
: "")
<< "\n"
<< "expected: " << curr->type << "\n";
}
}
}
void FunctionValidator::visitLoop(Loop* curr) {
if (curr->name.is()) {
noteLabelName(curr->name);
auto iter = breakTypes.find(curr->name);
assert(iter != breakTypes.end()); // we set it ourselves
for (Type breakType : iter->second) {
shouldBeEqual(breakType,
Type(Type::none),
curr,
"breaks to a loop cannot pass a value");
}
breakTypes.erase(iter);
}
if (curr->type == Type::none) {
shouldBeFalse(curr->body->type.isConcrete(),
curr,
"bad body for a loop that has no value");
}
// When there are multiple instructions within a loop, they are wrapped in a
// Block internally, so visitBlock can take care of verification. Here we
// check cases when there is only one instruction in a Loop.
if (!curr->body->is<Block>()) {
if (!curr->type.isConcrete()) {
shouldBeFalse(curr->body->type.isConcrete(),
curr,
"if loop is not returning a value, final element should "
"not flow out a value");
} else {
shouldBeSubType(curr->body->type,
curr->type,
curr,
"loop with value and body must match types");
}
}
}
void FunctionValidator::visitIf(If* curr) {
shouldBeTrue(curr->condition->type == Type::unreachable ||
curr->condition->type == Type::i32,
curr,
"if condition must be valid");
if (!curr->ifFalse) {
shouldBeFalse(curr->ifTrue->type.isConcrete(),
curr,
"if without else must not return a value in body");
if (curr->condition->type != Type::unreachable) {
shouldBeEqual(curr->type,
Type(Type::none),
curr,
"if without else and reachable condition must be none");
}
} else {
if (curr->type != Type::unreachable) {
shouldBeSubType(curr->ifTrue->type,
curr->type,
curr,
"returning if-else's true must have right type");
shouldBeSubType(curr->ifFalse->type,
curr->type,
curr,
"returning if-else's false must have right type");
} else {
if (curr->condition->type != Type::unreachable) {
shouldBeEqual(curr->ifTrue->type,
Type(Type::unreachable),
curr,
"unreachable if-else must have unreachable true");
shouldBeEqual(curr->ifFalse->type,
Type(Type::unreachable),
curr,
"unreachable if-else must have unreachable false");
}
}
if (curr->ifTrue->type.isConcrete()) {
shouldBeSubType(curr->ifTrue->type,
curr->type,
curr,
"if type must match concrete ifTrue");
}
if (curr->ifFalse->type.isConcrete()) {
shouldBeSubType(curr->ifFalse->type,
curr->type,
curr,
"if type must match concrete ifFalse");
}
}
}
void FunctionValidator::noteBreak(Name name,
Expression* value,
Expression* curr) {
if (value) {
shouldBeUnequal(
value->type, Type(Type::none), curr, "breaks must have a valid value");
}
noteBreak(name, value ? value->type : Type::none, curr);
}
void FunctionValidator::noteBreak(Name name, Type valueType, Expression* curr) {
auto iter = breakTypes.find(name);
if (!shouldBeTrue(
iter != breakTypes.end(), curr, "all break targets must be valid")) {
return;
}
iter->second.insert(valueType);
}
void FunctionValidator::visitBreak(Break* curr) {
noteBreak(curr->name, curr->value, curr);
if (curr->value) {
shouldBeTrue(curr->value->type != Type::none,
curr,
"break value must not have none type");
}
if (curr->condition) {
shouldBeTrue(curr->condition->type == Type::unreachable ||
curr->condition->type == Type::i32,
curr,
"break condition must be i32");
}
}
void FunctionValidator::visitSwitch(Switch* curr) {
for (auto& target : curr->targets) {
noteBreak(target, curr->value, curr);
}
noteBreak(curr->default_, curr->value, curr);
shouldBeTrue(curr->condition->type == Type::unreachable ||
curr->condition->type == Type::i32,
curr,
"br_table condition must be i32");
}
void FunctionValidator::visitCall(Call* curr) {
validateReturnCall(curr);
if (!info.validateGlobally) {
return;
}
auto* target = getModule()->getFunctionOrNull(curr->target);
if (!shouldBeTrue(!!target, curr, "call target must exist")) {
return;
}
validateCallParamsAndResult(curr, target->type);
if (Intrinsics(*getModule()).isCallWithoutEffects(curr)) {
// call.without.effects has the specific form of the last argument being a
// function reference, which will be called with all the previous arguments.
// The type must be consistent with that. This, for example, is not:
//
// (call $call.without.effects
// (i32.const 1)
// (.. some function reference that expects an f64 param and not i32 ..)
// )
if (shouldBeTrue(!curr->operands.empty(),
curr,
"call.without.effects must have a target operand")) {
auto* target = curr->operands.back();
// Validate only in the case that the target is a function. If it isn't,
// it might be unreachable (which is fine, and we can ignore this), or if
// the call.without.effects import doesn't have a function as the last
// parameter, then validateImports() will handle that later (and it's
// better to emit a single error there than one per callsite here).
if (target->type.isFunction()) {
// Copy the original call and remove the reference. It must then match
// the expected signature.
struct Copy {
std::vector<Expression*> operands;
bool isReturn;
Type type;
} copy;
for (Index i = 0; i < curr->operands.size() - 1; i++) {
copy.operands.push_back(curr->operands[i]);
}
copy.isReturn = curr->isReturn;
copy.type = curr->type;
validateCallParamsAndResult(©, target->type.getHeapType(), curr);
}
}
}
}
void FunctionValidator::visitCallIndirect(CallIndirect* curr) {
validateReturnCall(curr);
if (curr->target->type != Type::unreachable) {
auto* table = getModule()->getTableOrNull(curr->table);
if (shouldBeTrue(!!table, curr, "call-indirect table must exist")) {
shouldBeEqualOrFirstIsUnreachable(
curr->target->type,
table->indexType,
curr,
"call-indirect call target must match the table index type");
shouldBeTrue(!!table, curr, "call-indirect table must exist");