-
Notifications
You must be signed in to change notification settings - Fork 780
/
Copy pathwasm-ir-builder.cpp
2524 lines (2238 loc) · 77.3 KB
/
wasm-ir-builder.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2023 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 <cassert>
#include "ir/child-typer.h"
#include "ir/eh-utils.h"
#include "ir/names.h"
#include "ir/properties.h"
#include "ir/utils.h"
#include "wasm-ir-builder.h"
#define IR_BUILDER_DEBUG 0
#if IR_BUILDER_DEBUG
#define DBG(statement) statement
#else
#define DBG(statement)
#endif
using namespace std::string_literals;
namespace wasm {
namespace {
Result<> validateTypeAnnotation(HeapType type, Expression* child) {
if (child->type == Type::unreachable) {
return Ok{};
}
if (!child->type.isRef() ||
!HeapType::isSubType(child->type.getHeapType(), type)) {
return Err{"invalid reference type on stack"};
}
return Ok{};
}
} // anonymous namespace
Result<Index> IRBuilder::addScratchLocal(Type type) {
if (!func) {
return Err{"scratch local required, but there is no function context"};
}
Name name = Names::getValidLocalName(*func, "scratch");
return Builder::addVar(func, name, type);
}
MaybeResult<IRBuilder::HoistedVal> IRBuilder::hoistLastValue() {
auto& stack = getScope().exprStack;
int index = stack.size() - 1;
for (; index >= 0; --index) {
if (stack[index]->type != Type::none) {
break;
}
}
if (index < 0) {
// There is no value-producing or unreachable expression.
return {};
}
if (unsigned(index) == stack.size() - 1) {
// Value-producing expression already on top of the stack.
return HoistedVal{Index(index), nullptr};
}
auto*& expr = stack[index];
auto type = expr->type;
if (type == Type::unreachable) {
// Make sure the top of the stack also has an unreachable expression.
if (stack.back()->type != Type::unreachable) {
push(builder.makeUnreachable());
}
return HoistedVal{Index(index), nullptr};
}
// Hoist with a scratch local.
auto scratchIdx = addScratchLocal(type);
CHECK_ERR(scratchIdx);
expr = builder.makeLocalSet(*scratchIdx, expr);
auto* get = builder.makeLocalGet(*scratchIdx, type);
push(get);
return HoistedVal{Index(index), get};
}
Result<> IRBuilder::packageHoistedValue(const HoistedVal& hoisted,
size_t sizeHint) {
auto& scope = getScope();
assert(!scope.exprStack.empty());
auto packageAsBlock = [&](Type type) {
// Create a block containing the producer of the hoisted value, the final
// get of the hoisted value, and everything in between. Record the fact that
// we are synthesizing a block to help us determine later whether we need to
// run the nested pop fixup.
scopeStack[0].noteSyntheticBlock();
std::vector<Expression*> exprs(scope.exprStack.begin() + hoisted.valIndex,
scope.exprStack.end());
auto* block = builder.makeBlock(exprs, type);
scope.exprStack.resize(hoisted.valIndex);
push(block);
};
auto type = scope.exprStack.back()->type;
if (type.size() == sizeHint || type.size() <= 1) {
if (hoisted.get) {
packageAsBlock(type);
}
return Ok{};
}
// We need to break up the hoisted tuple. Create and push an expression
// setting the tuple to a local and returning its first element, then push
// additional gets of each of its subsequent elements. Reuse the scratch local
// we used for hoisting, if it exists.
Index scratchIdx;
if (hoisted.get) {
// Update the get on top of the stack to just return the first element.
scope.exprStack.back() = builder.makeTupleExtract(hoisted.get, 0);
packageAsBlock(type[0]);
scratchIdx = hoisted.get->index;
} else {
auto scratch = addScratchLocal(type);
CHECK_ERR(scratch);
scope.exprStack.back() = builder.makeTupleExtract(
builder.makeLocalTee(*scratch, scope.exprStack.back(), type), 0);
scratchIdx = *scratch;
}
for (Index i = 1, size = type.size(); i < size; ++i) {
push(builder.makeTupleExtract(builder.makeLocalGet(scratchIdx, type), i));
}
return Ok{};
}
void IRBuilder::push(Expression* expr) {
auto& scope = getScope();
if (expr->type == Type::unreachable) {
scope.unreachable = true;
}
scope.exprStack.push_back(expr);
applyDebugLoc(expr);
if (binaryPos && func && lastBinaryPos != *binaryPos) {
func->expressionLocations[expr] =
BinaryLocations::Span{BinaryLocation(lastBinaryPos - codeSectionOffset),
BinaryLocation(*binaryPos - codeSectionOffset)};
lastBinaryPos = *binaryPos;
}
DBG(std::cerr << "After pushing " << ShallowExpression{expr} << ":\n");
DBG(dump());
}
Result<Expression*> IRBuilder::build() {
if (scopeStack.empty()) {
return builder.makeBlock();
}
if (scopeStack.size() > 1 || !scopeStack.back().isNone()) {
return Err{"unfinished block context"};
}
if (scopeStack.back().exprStack.size() > 1) {
return Err{"unused expressions without block context"};
}
assert(scopeStack.back().exprStack.size() == 1);
auto* expr = scopeStack.back().exprStack.back();
scopeStack.clear();
labelDepths.clear();
return expr;
}
void IRBuilder::setDebugLocation(
const std::optional<Function::DebugLocation>& loc) {
if (loc) {
DBG(std::cerr << "setting debugloc " << loc->fileIndex << ":"
<< loc->lineNumber << ":" << loc->columnNumber << "\n";);
} else {
DBG(std::cerr << "setting debugloc to none\n";);
}
if (loc) {
debugLoc = *loc;
} else {
debugLoc = NoDebug();
}
}
void IRBuilder::applyDebugLoc(Expression* expr) {
if (!std::get_if<CanReceiveDebug>(&debugLoc)) {
if (func) {
if (auto* loc = std::get_if<Function::DebugLocation>(&debugLoc)) {
DBG(std::cerr << "applying debugloc " << loc->fileIndex << ":"
<< loc->lineNumber << ":" << loc->columnNumber
<< " to expression " << ShallowExpression{expr} << "\n");
func->debugLocations[expr] = *loc;
} else {
assert(std::get_if<NoDebug>(&debugLoc));
DBG(std::cerr << "applying debugloc to expression "
<< ShallowExpression{expr} << "\n");
func->debugLocations[expr] = std::nullopt;
}
}
debugLoc = CanReceiveDebug();
}
}
void IRBuilder::dump() {
#if IR_BUILDER_DEBUG
std::cerr << "Scope stack";
if (func) {
std::cerr << " in function $" << func->name;
}
std::cerr << ":\n";
for (auto& scope : scopeStack) {
std::cerr << " scope ";
if (scope.isNone()) {
std::cerr << "none";
} else if (auto* f = scope.getFunction()) {
std::cerr << "func " << f->name;
} else if (scope.getBlock()) {
std::cerr << "block";
} else if (scope.getIf()) {
std::cerr << "if";
} else if (scope.getElse()) {
std::cerr << "else";
} else if (scope.getLoop()) {
std::cerr << "loop";
} else if (auto* tryy = scope.getTry()) {
std::cerr << "try";
if (tryy->name) {
std::cerr << " " << tryy->name;
}
} else if (auto* tryy = scope.getCatch()) {
std::cerr << "catch";
if (tryy->name) {
std::cerr << " " << tryy->name;
}
} else if (auto* tryy = scope.getCatchAll()) {
std::cerr << "catch_all";
if (tryy->name) {
std::cerr << " " << tryy->name;
}
} else {
WASM_UNREACHABLE("unexpected scope");
}
if (auto name = scope.getOriginalLabel()) {
std::cerr << " (original label: " << name << ")";
}
if (scope.label) {
std::cerr << " (label: " << scope.label << ")";
}
if (scope.branchLabel) {
std::cerr << " (branch label: " << scope.branchLabel << ")";
}
if (scope.unreachable) {
std::cerr << " (unreachable)";
}
std::cerr << ":\n";
for (auto* expr : scope.exprStack) {
std::cerr << " " << ShallowExpression{expr} << "\n";
}
}
#endif // IR_BUILDER_DEBUG
}
struct IRBuilder::ChildPopper
: UnifiedExpressionVisitor<ChildPopper, Result<>> {
struct Subtype {
Type bound;
};
struct AnyType {};
struct AnyReference {};
struct AnyTuple {
size_t arity;
};
struct AnyI8ArrayReference {};
struct AnyI16ArrayReference {};
struct Constraint : std::variant<Subtype,
AnyType,
AnyReference,
AnyTuple,
AnyI8ArrayReference,
AnyI16ArrayReference> {
std::optional<Type> getSubtype() const {
if (auto* subtype = std::get_if<Subtype>(this)) {
return subtype->bound;
}
return std::nullopt;
}
bool isAnyType() const { return std::get_if<AnyType>(this); }
bool isAnyReference() const { return std::get_if<AnyReference>(this); }
bool isAnyI8ArrayReference() const {
return std::get_if<AnyI8ArrayReference>(this);
}
bool isAnyI16ArrayReference() const {
return std::get_if<AnyI16ArrayReference>(this);
}
std::optional<size_t> getAnyTuple() const {
if (auto* tuple = std::get_if<AnyTuple>(this)) {
return tuple->arity;
}
return std::nullopt;
}
size_t size() const {
if (auto type = getSubtype()) {
return type->size();
}
if (auto arity = getAnyTuple()) {
return *arity;
}
return 1;
}
Constraint operator[](size_t i) const {
if (auto type = getSubtype()) {
return {Subtype{(*type)[i]}};
}
if (getAnyTuple()) {
return {AnyType{}};
}
return *this;
}
};
struct Child {
Expression** childp;
Constraint constraint;
};
struct ConstraintCollector : ChildTyper<ConstraintCollector> {
IRBuilder& builder;
std::vector<Child>& children;
ConstraintCollector(IRBuilder& builder, std::vector<Child>& children)
: ChildTyper(builder.wasm, builder.func), builder(builder),
children(children) {}
void noteSubtype(Expression** childp, Type type) {
children.push_back({childp, {Subtype{type}}});
}
void noteAnyType(Expression** childp) {
children.push_back({childp, {AnyType{}}});
}
void noteAnyReferenceType(Expression** childp) {
children.push_back({childp, {AnyReference{}}});
}
void noteAnyTupleType(Expression** childp, size_t arity) {
children.push_back({childp, {AnyTuple{arity}}});
}
void noteAnyI8ArrayReferenceType(Expression** childp) {
children.push_back({childp, {AnyI8ArrayReference{}}});
}
void noteAnyI16ArrayReferenceType(Expression** childp) {
children.push_back({childp, {AnyI16ArrayReference{}}});
}
Type getLabelType(Name label) {
WASM_UNREACHABLE("labels should be explicitly provided");
};
void visitIf(If* curr) {
// Skip the control flow children because we only want to pop the
// condition.
children.push_back({&curr->condition, {Subtype{Type::i32}}});
}
};
IRBuilder& builder;
ChildPopper(IRBuilder& builder) : builder(builder) {}
private:
Result<> popConstrainedChildren(std::vector<Child>& children) {
auto& scope = builder.getScope();
// Two-part indices into the stack of available expressions and the vector
// of requirements, allowing them to move independently with the granularity
// of a single tuple element.
size_t stackIndex = scope.exprStack.size();
size_t stackTupleIndex = 0;
size_t childIndex = children.size();
size_t childTupleIndex = 0;
// The index of the shallowest unreachable instruction on the stack.
std::optional<size_t> unreachableIndex;
// Whether popping the children past the unreachable would produce a type
// mismatch or try to pop from an empty stack.
bool needUnreachableFallback = false;
if (!scope.unreachable) {
// We only need to check requirements if there is an unreachable.
// Otherwise the validator will catch any problems.
goto pop;
}
// Check whether the values on the stack will be able to meet the given
// requirements.
while (true) {
// Advance to the next requirement.
if (childTupleIndex > 0) {
--childTupleIndex;
} else {
if (childIndex == 0) {
// We have examined all the requirements.
break;
}
--childIndex;
childTupleIndex = children[childIndex].constraint.size() - 1;
}
// Advance to the next available value on the stack.
while (true) {
if (stackTupleIndex > 0) {
--stackTupleIndex;
} else {
if (stackIndex == 0) {
// No more available values. This is valid iff we are reaching past
// an unreachable, but we still need the fallback behavior to ensure
// the input unreachable instruction is executed first. If we are
// not reaching past an unreachable, the error will be caught when
// we pop.
needUnreachableFallback = true;
goto pop;
}
--stackIndex;
stackTupleIndex = scope.exprStack[stackIndex]->type.size() - 1;
}
// Skip expressions that don't produce values.
if (scope.exprStack[stackIndex]->type == Type::none) {
stackTupleIndex = 0;
continue;
}
break;
}
// We have an available type and a constraint. Only check constraints if
// we are past an unreachable, since otherwise we can leave problems to be
// caught by the validator later.
auto type = scope.exprStack[stackIndex]->type[stackTupleIndex];
if (unreachableIndex) {
auto constraint = children[childIndex].constraint[childTupleIndex];
if (constraint.isAnyType()) {
// Always succeeds.
} else if (constraint.isAnyReference()) {
if (!type.isRef() && type != Type::unreachable) {
needUnreachableFallback = true;
break;
}
} else if (auto bound = constraint.getSubtype()) {
if (!Type::isSubType(type, *bound)) {
needUnreachableFallback = true;
break;
}
} else if (constraint.isAnyI8ArrayReference()) {
bool isI8Array =
type.isRef() && type.getHeapType().isArray() &&
type.getHeapType().getArray().element.packedType == Field::i8;
bool isNone =
type.isRef() && type.getHeapType().isMaybeShared(HeapType::none);
if (!isI8Array && !isNone && type != Type::unreachable) {
needUnreachableFallback = true;
break;
}
} else if (constraint.isAnyI16ArrayReference()) {
bool isI16Array =
type.isRef() && type.getHeapType().isArray() &&
type.getHeapType().getArray().element.packedType == Field::i16;
bool isNone =
type.isRef() && type.getHeapType().isMaybeShared(HeapType::none);
if (!isI16Array && !isNone && type != Type::unreachable) {
needUnreachableFallback = true;
break;
}
} else {
WASM_UNREACHABLE("unexpected constraint");
}
}
// No problems for children after this unreachable.
if (type == Type::unreachable) {
assert(!needUnreachableFallback);
unreachableIndex = stackIndex;
}
}
pop:
// We have checked all the constraints, so we are ready to pop children.
for (int i = children.size() - 1; i >= 0; --i) {
if (needUnreachableFallback &&
scope.exprStack.size() == *unreachableIndex + 1 && i > 0) {
// The next item on the stack is the unreachable instruction we must
// not pop past. We cannot insert unreachables in front of it because
// it might be a branch we actually have to execute, so this next item
// must be child 0. But we are not ready to pop child 0 yet, so
// synthesize an unreachable instead of popping. The deeper
// instructions that would otherwise have been popped will remain on
// the stack to become prior children of future expressions or to be
// implicitly dropped at the end of the scope.
*children[i].childp = builder.builder.makeUnreachable();
continue;
}
// Pop a child normally.
auto val = pop(children[i].constraint.size());
CHECK_ERR(val);
*children[i].childp = *val;
}
return Ok{};
}
Result<Expression*> pop(size_t size) {
assert(size >= 1);
auto& scope = builder.getScope();
// Find the suffix of expressions that do not produce values.
auto hoisted = builder.hoistLastValue();
CHECK_ERR(hoisted);
if (!hoisted) {
// There are no expressions that produce values.
if (scope.unreachable) {
return builder.builder.makeUnreachable();
}
return Err{"popping from empty stack"};
}
CHECK_ERR(builder.packageHoistedValue(*hoisted, size));
auto* ret = scope.exprStack.back();
// If the top value has the correct size, we can pop it and be done.
// Unreachable values satisfy any size.
if (ret->type.size() == size || ret->type == Type::unreachable) {
scope.exprStack.pop_back();
return ret;
}
// The last value-producing expression did not produce exactly the right
// number of values, so we need to construct a tuple piecewise instead.
assert(size > 1);
std::vector<Expression*> elems;
elems.resize(size);
for (int i = size - 1; i >= 0; --i) {
auto elem = pop(1);
CHECK_ERR(elem);
elems[i] = *elem;
}
return builder.builder.makeTupleMake(elems);
}
public:
Result<> visitExpression(Expression* expr) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visit(expr);
return popConstrainedChildren(children);
}
Result<> visitAtomicCmpxchg(AtomicCmpxchg* curr,
std::optional<Type> type = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitAtomicCmpxchg(curr, type);
return popConstrainedChildren(children);
}
Result<> visitStructGet(StructGet* curr,
std::optional<HeapType> ht = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitStructGet(curr, ht);
return popConstrainedChildren(children);
}
Result<> visitStructSet(StructSet* curr,
std::optional<HeapType> ht = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitStructSet(curr, ht);
return popConstrainedChildren(children);
}
Result<> visitStructRMW(StructRMW* curr,
std::optional<HeapType> ht = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitStructRMW(curr, ht);
return popConstrainedChildren(children);
}
Result<> visitStructCmpxchg(StructCmpxchg* curr,
std::optional<HeapType> ht = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitStructCmpxchg(curr, ht);
return popConstrainedChildren(children);
}
Result<> visitArrayGet(ArrayGet* curr,
std::optional<HeapType> ht = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitArrayGet(curr, ht);
return popConstrainedChildren(children);
}
Result<> visitArraySet(ArraySet* curr,
std::optional<HeapType> ht = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitArraySet(curr, ht);
return popConstrainedChildren(children);
}
Result<> visitArrayCopy(ArrayCopy* curr,
std::optional<HeapType> dest = std::nullopt,
std::optional<HeapType> src = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitArrayCopy(curr, dest, src);
return popConstrainedChildren(children);
}
Result<> visitArrayFill(ArrayFill* curr,
std::optional<HeapType> ht = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitArrayFill(curr, ht);
return popConstrainedChildren(children);
}
Result<> visitArrayInitData(ArrayInitData* curr,
std::optional<HeapType> ht = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitArrayInitData(curr, ht);
return popConstrainedChildren(children);
}
Result<> visitArrayInitElem(ArrayInitElem* curr,
std::optional<HeapType> ht = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitArrayInitElem(curr, ht);
return popConstrainedChildren(children);
}
Result<> visitStringEncode(StringEncode* curr,
std::optional<HeapType> ht = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitStringEncode(curr, ht);
return popConstrainedChildren(children);
}
Result<> visitCallRef(CallRef* curr,
std::optional<HeapType> ht = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitCallRef(curr, ht);
return popConstrainedChildren(children);
}
Result<> visitBreak(Break* curr,
std::optional<Type> labelType = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitBreak(curr, labelType);
return popConstrainedChildren(children);
}
Result<> visitSwitch(Switch* curr,
std::optional<Type> labelType = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitSwitch(curr, labelType);
return popConstrainedChildren(children);
}
Result<> visitDrop(Drop* curr, std::optional<Index> arity = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitDrop(curr, arity);
return popConstrainedChildren(children);
}
Result<> visitTupleExtract(TupleExtract* curr,
std::optional<Index> arity = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitTupleExtract(curr, arity);
return popConstrainedChildren(children);
}
Result<> visitContBind(ContBind* curr,
std::optional<HeapType> src = std::nullopt,
std::optional<HeapType> dest = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitContBind(curr, src, dest);
return popConstrainedChildren(children);
}
Result<> visitResume(Resume* curr,
std::optional<HeapType> ct = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitResume(curr, ct);
return popConstrainedChildren(children);
}
Result<> visitResumeThrow(ResumeThrow* curr,
std::optional<HeapType> ct = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitResumeThrow(curr, ct);
return popConstrainedChildren(children);
}
Result<> visitStackSwitch(StackSwitch* curr,
std::optional<HeapType> ct = std::nullopt) {
std::vector<Child> children;
ConstraintCollector{builder, children}.visitStackSwitch(curr, ct);
return popConstrainedChildren(children);
}
};
Result<> IRBuilder::visit(Expression* curr) {
// Call either `visitExpression` or an expression-specific override.
auto val = UnifiedExpressionVisitor<IRBuilder, Result<>>::visit(curr);
CHECK_ERR(val);
if (auto* block = curr->dynCast<Block>()) {
block->finalize(block->type);
} else {
// TODO: Call more efficient versions of finalize() that take the known type
// for other kinds of nodes as well, as done above.
ReFinalizeNode{}.visit(curr);
}
push(curr);
return Ok{};
}
// Handle the common case of instructions with a constant number of children
// uniformly.
Result<> IRBuilder::visitExpression(Expression* curr) {
if (Properties::isControlFlowStructure(curr) && !curr->is<If>()) {
// Control flow structures (besides `if`, handled separately) do not consume
// stack values.
return Ok{};
}
return ChildPopper{*this}.visit(curr);
}
Result<Type> IRBuilder::getLabelType(Index label) {
auto scope = getScope(label);
CHECK_ERR(scope);
return (*scope)->getLabelType();
}
Result<Type> IRBuilder::getLabelType(Name labelName) {
auto label = getLabelIndex(labelName);
CHECK_ERR(label);
return getLabelType(*label);
}
Result<> IRBuilder::visitBreakWithType(Break* curr, Type type) {
CHECK_ERR(ChildPopper{*this}.visitBreak(curr, type));
curr->finalize();
push(curr);
return Ok{};
}
Result<> IRBuilder::visitSwitchWithType(Switch* curr, Type type) {
CHECK_ERR(ChildPopper{*this}.visitSwitch(curr, type));
curr->finalize();
push(curr);
return Ok{};
}
Result<> IRBuilder::visitFunctionStart(Function* func) {
if (!scopeStack.empty()) {
return Err{"unexpected start of function"};
}
if (auto* loc = std::get_if<Function::DebugLocation>(&debugLoc)) {
func->prologLocation = *loc;
}
debugLoc = CanReceiveDebug();
scopeStack.push_back(ScopeCtx::makeFunc(func));
this->func = func;
if (binaryPos) {
lastBinaryPos = *binaryPos;
}
return Ok{};
}
Result<> IRBuilder::visitBlockStart(Block* curr, Type inputType) {
applyDebugLoc(curr);
return pushScope(ScopeCtx::makeBlock(curr, inputType));
}
Result<> IRBuilder::visitIfStart(If* iff, Name label, Type inputType) {
applyDebugLoc(iff);
CHECK_ERR(visitIf(iff));
return pushScope(ScopeCtx::makeIf(iff, label, inputType));
}
Result<> IRBuilder::visitLoopStart(Loop* loop, Type inputType) {
applyDebugLoc(loop);
return pushScope(ScopeCtx::makeLoop(loop, inputType));
}
Result<> IRBuilder::visitTryStart(Try* tryy, Name label, Type inputType) {
applyDebugLoc(tryy);
return pushScope(ScopeCtx::makeTry(tryy, label, inputType));
}
Result<>
IRBuilder::visitTryTableStart(TryTable* trytable, Name label, Type inputType) {
applyDebugLoc(trytable);
return pushScope(ScopeCtx::makeTryTable(trytable, label, inputType));
}
Result<Expression*> IRBuilder::finishScope(Block* block) {
#if IR_BUILDER_DEBUG
if (auto* loc = std::get_if<Function::DebugLocation>(&debugLoc)) {
std::cerr << "discarding debugloc " << loc->fileIndex << ":"
<< loc->lineNumber << ":" << loc->columnNumber << "\n";
}
#endif
debugLoc = CanReceiveDebug();
if (scopeStack.empty() || scopeStack.back().isNone()) {
return Err{"unexpected end of scope"};
}
auto& scope = scopeStack.back();
auto type = scope.getResultType();
if (scope.unreachable) {
// Drop everything before the last unreachable.
bool sawUnreachable = false;
for (int i = scope.exprStack.size() - 1; i >= 0; --i) {
if (sawUnreachable) {
scope.exprStack[i] = builder.dropIfConcretelyTyped(scope.exprStack[i]);
} else if (scope.exprStack[i]->type == Type::unreachable) {
sawUnreachable = true;
}
}
}
if (type.isConcrete()) {
auto hoisted = hoistLastValue();
CHECK_ERR(hoisted);
if (!hoisted) {
return Err{"popping from empty stack"};
}
if (type.isTuple()) {
auto hoistedType = scope.exprStack.back()->type;
if (hoistedType != Type::unreachable &&
hoistedType.size() != type.size()) {
// We cannot propagate the hoisted value directly because it does not
// have the correct number of elements. Repackage it.
CHECK_ERR(packageHoistedValue(*hoisted, hoistedType.size()));
CHECK_ERR(makeTupleMake(type.size()));
}
}
}
Expression* ret = nullptr;
if (scope.exprStack.size() == 0) {
// No expressions for this scope, but we need something. If we were given a
// block, we can empty it out and return it, but otherwise create a new
// empty block.
if (block) {
block->list.clear();
ret = block;
} else {
ret = builder.makeBlock();
}
} else if (scope.exprStack.size() == 1) {
// We can put our single expression directly into the surrounding scope.
if (block) {
block->list.resize(1);
block->list[0] = scope.exprStack.back();
ret = block;
} else {
ret = scope.exprStack.back();
}
} else {
// More than one expression, so we need a block. Allocate one if we weren't
// already given one.
if (block) {
block->list.set(scope.exprStack);
} else {
block = builder.makeBlock(scope.exprStack, type);
}
ret = block;
}
// If this scope had a label, remove it from the context.
if (auto label = scope.getOriginalLabel()) {
labelDepths.at(label).pop_back();
}
scopeStack.pop_back();
return ret;
}
Result<> IRBuilder::visitElse() {
auto scope = getScope();
auto* iff = scope.getIf();
if (!iff) {
return Err{"unexpected else"};
}
auto expr = finishScope();
CHECK_ERR(expr);
iff->ifTrue = *expr;
if (binaryPos && func) {
func->delimiterLocations[iff][BinaryLocations::Else] =
lastBinaryPos - codeSectionOffset;
}
return pushScope(ScopeCtx::makeElse(std::move(scope)));
}
void setCatchBody(Try* tryy, Expression* expr, Index index) {
// Indexes are managed manually to support Outlining.
// Its prepopulated try catchBodies and catchTags vectors
// cannot be appended to, as in the case of the empty try
// used during parsing.
if (tryy->catchBodies.size() < index) {
tryy->catchBodies.resize(tryy->catchBodies.size() + 1);
}
// The first time visitCatch is called: the body of the
// try is set and catchBodies is not appended to, but the tag
// for the following catch is appended. So, catchTags uses
// index as-is, but catchBodies uses index-1.
tryy->catchBodies[index - 1] = expr;
}
Result<> IRBuilder::visitCatch(Name tag) {
auto scope = getScope();
bool wasTry = true;
auto* tryy = scope.getTry();
if (!tryy) {
wasTry = false;
tryy = scope.getCatch();
}
if (!tryy) {
return Err{"unexpected catch"};
}
auto index = scope.getIndex();
auto expr = finishScope();
CHECK_ERR(expr);
if (wasTry) {
tryy->body = *expr;
} else {
setCatchBody(tryy, *expr, index);
}
if (tryy->catchTags.size() == index) {
tryy->catchTags.resize(tryy->catchTags.size() + 1);
}
tryy->catchTags[index] = tag;
if (binaryPos && func) {
auto& delimiterLocs = func->delimiterLocations[tryy];
delimiterLocs[delimiterLocs.size()] = lastBinaryPos - codeSectionOffset;
}
CHECK_ERR(pushScope(ScopeCtx::makeCatch(std::move(scope), tryy)));
// Push a pop for the exception payload if necessary.
auto params = wasm.getTag(tag)->params();
if (params != Type::none) {
// Note that we have a pop to help determine later whether we need to run
// the fixup for pops within blocks.
scopeStack[0].notePop();
push(builder.makePop(params));
}
return Ok{};
}
Result<> IRBuilder::visitCatchAll() {
auto scope = getScope();
bool wasTry = true;
auto* tryy = scope.getTry();
if (!tryy) {
wasTry = false;
tryy = scope.getCatch();
}
if (!tryy) {
return Err{"unexpected catch"};