-
Notifications
You must be signed in to change notification settings - Fork 849
Expand file tree
/
Copy pathheap-types.cpp
More file actions
1419 lines (1307 loc) · 47.8 KB
/
heap-types.cpp
File metadata and controls
1419 lines (1307 loc) · 47.8 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 2021 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 <variant>
#include "ir/gc-type-utils.h"
#include "ir/subtypes.h"
#include "tools/fuzzing.h"
#include "tools/fuzzing/heap-types.h"
namespace wasm {
namespace {
struct HeapTypeGeneratorImpl {
HeapTypeGenerator result;
TypeBuilder& builder;
std::vector<std::vector<Index>>& subtypeIndices;
std::vector<std::optional<Index>> supertypeIndices;
std::vector<std::optional<Index>>& descriptorIndices;
std::vector<std::optional<Index>> describedIndices;
std::vector<size_t> descriptorChainLengths;
Random& rand;
FeatureSet features;
// Map the HeapTypes we are building to their indices in the builder.
std::unordered_map<HeapType, Index> typeIndices;
// Top-level kinds, chosen before the types are actually constructed. This
// allows us to choose HeapTypes that we know will be subtypes of data or func
// before we actually generate the types.
struct SignatureKind {};
struct StructKind {};
struct ArrayKind {};
struct ContinuationKind {};
using HeapTypeKind =
std::variant<SignatureKind, StructKind, ArrayKind, ContinuationKind>;
std::vector<HeapTypeKind> typeKinds;
// For each type, the index one past the end of its recursion group, used to
// determine what types could be valid children. Alternatively, the cumulative
// size of the current and prior rec groups at each type index.
std::vector<Index> recGroupEnds;
// The index of the type we are currently generating.
Index index = 0;
FuzzParams params;
HeapTypeGeneratorImpl(Random& rand, FeatureSet features, size_t n)
: result{TypeBuilder(n),
std::vector<std::vector<Index>>(n),
std::vector<std::optional<Index>>(n)},
builder(result.builder), subtypeIndices(result.subtypeIndices),
supertypeIndices(n), descriptorIndices(result.descriptorIndices),
describedIndices(n), descriptorChainLengths(n), rand(rand),
features(features) {
// Set up the subtype relationships. Start with some number of root types,
// then after that start creating subtypes of existing types. Determine the
// top-level kind and shareability of each type in advance so that we can
// appropriately use types we haven't constructed yet.
typeKinds.reserve(builder.size());
supertypeIndices.reserve(builder.size());
recGroupEnds.reserve(builder.size());
// The number of root types to generate before we start adding subtypes.
size_t numRoots = 1 + rand.upTo(builder.size());
// The mean expected size of the recursion groups.
size_t expectedGroupSize = 1 + rand.upTo(builder.size());
size_t i = 0;
while (i < builder.size()) {
i += planGroup(i, numRoots, expectedGroupSize);
}
assert(recGroupEnds.size() == builder.size());
populateTypes();
}
size_t planGroup(size_t start, size_t numRoots, size_t expectedGroupSize) {
size_t maxSize = builder.size() - start;
size_t size = 1;
// Generate the group size according to a geometric distribution.
for (; size < maxSize; ++size) {
if (rand.oneIn(expectedGroupSize)) {
break;
}
}
assert(start + size <= builder.size());
builder.createRecGroup(start, size);
// The indices of types that need descriptors and the total number of
// remaining descriptors we have committed to create in this group.
std::vector<Index> describees;
size_t numPlannedDescriptors = 0;
size_t end = start + size;
for (size_t i = start; i < end; ++i) {
recGroupEnds.push_back(end);
planType(i, numRoots, end - i, describees, numPlannedDescriptors);
}
return size;
}
// We can only emit continuations after emitting a valid signature for them,
// as the signature must appear first.
bool canEmitContinuation = false;
void planType(size_t i,
size_t numRoots,
size_t remaining,
std::vector<Index>& describees,
size_t& numPlannedDescriptors) {
assert(remaining >= numPlannedDescriptors);
typeIndices.insert({builder[i], i});
// Everything is a subtype of itself.
subtypeIndices[i].push_back(i);
// We may pick a supertype. If we have a described type that itself has a
// supertype, then we must choose that supertype's descriptor as our
// supertype.
std::optional<Index> super;
// Pick a type to describe, or choose not to describe a type by
// picking the one-past-the-end index. If all of the remaining types must be
// descriptors, then we must choose a describee.
Index describee =
rand.upTo(describees.size() + (remaining != numPlannedDescriptors));
bool isDescriptor = false;
if (describee != describees.size()) {
isDescriptor = true;
--numPlannedDescriptors;
// If the intended described type has a supertype with a descriptor, then
// that descriptor must be the supertype of the type we intend to
// generate. However, we may not have generated that descriptor yet,
// meaning it is unavailable to be the supertype of the current type.
// Detect that situation and plan to generate the missing supertype
// instead.
Index described;
while (true) {
assert(describee < describees.size());
described = describees[describee];
auto describedSuper = supertypeIndices[described];
if (!describedSuper) {
// The described type has no supertype, so there is no problem.
break;
}
if (descriptorChainLengths[*describedSuper] == 0) {
// The supertype of the described type will not have a descriptor,
// so there is no problem.
break;
}
if ((super = descriptorIndices[*describedSuper])) {
// The descriptor of the described type's supertype, which must become
// the current type's supertype, has already been generated. There is
// no problem.
break;
}
// The necessary supertype does not yet exist. Find its described type
// so we can try to generate the missing supertype instead.
for (describee = 0; describee < describees.size(); ++describee) {
if (describees[describee] == *describedSuper) {
break;
}
}
// Go back and check whether the new intended type can be generated.
continue;
}
// We have locked in the type we will describe.
std::swap(describees[describee], describees.back());
describees.pop_back();
descriptorIndices[described] = i;
describedIndices[i] = described;
builder[described].descriptor(builder[i]);
builder[i].describes(builder[described]);
// The length of the descriptor chain from this type is determined by the
// planned length of the chain from its described type.
descriptorChainLengths[i] = descriptorChainLengths[described] - 1;
}
--remaining;
assert(remaining >= numPlannedDescriptors);
size_t remainingUncommitted = remaining - numPlannedDescriptors;
// Possibly choose a supertype. If the current type is a descriptor type,
// then either we already determined its supertype based on its described
// type, or there is no valid supertype to give it. A valid supertype would
// have to describe the supertype of the current described type, but if the
// supertype chain had such an entry, we would already have found it above.
if (!super && !isDescriptor && i >= numRoots && rand.oneIn(2)) {
// Try to pick a supertype. The supertype must not be a descriptor type,
// and we must have space left in the rec group to mirror the supertype's
// descriptor chain, if it has one.
std::vector<Index> candidates;
candidates.reserve(i);
for (Index candidate = 0; candidate < i; ++candidate) {
if (describedIndices[candidate]) {
continue;
}
if (descriptorChainLengths[candidate] <= remainingUncommitted) {
candidates.push_back(candidate);
}
}
if (!candidates.empty()) {
super = rand.pick(candidates);
}
}
// Set up the builder entry and type kind for this type.
if (super) {
typeKinds.push_back(typeKinds[*super]);
builder[i].subTypeOf(builder[*super]);
builder[i].setShared(HeapType(builder[*super]).getShared());
supertypeIndices[i] = *super;
subtypeIndices[*super].push_back(i);
} else if (isDescriptor) {
// Descriptor types must be structs and their sharedness must match their
// described types.
typeKinds.push_back(StructKind{});
builder[i].setShared(HeapType(builder[*describedIndices[i]]).getShared());
} else {
// This is a root type with no supertype. Choose a kind for this type.
auto kind = generateHeapTypeKind();
if (std::get_if<ContinuationKind>(&kind) && !canEmitContinuation) {
// No signature for a continuation. Emit a signature so we can emit one
// later.
kind = SignatureKind{};
}
typeKinds.emplace_back(kind);
// Continuations cannot be shared, but other things can.
auto shared = Unshared;
if (features.hasSharedEverything() &&
!std::get_if<ContinuationKind>(&kind) && rand.oneIn(2)) {
shared = Shared;
}
builder[i].setShared(shared);
// Once we emit a non-shared signature, continuations are possible.
if (std::get_if<SignatureKind>(&kind) && shared == Unshared) {
canEmitContinuation = true;
}
}
// Plan this descriptor chain for this type if it is not already determined
// by a described type. Only structs may have descriptor chains.
if (!isDescriptor && std::get_if<StructKind>(&typeKinds.back()) &&
remainingUncommitted && features.hasCustomDescriptors()) {
if (super) {
// If we have a supertype, our descriptor chain must be at least as
// long as the supertype's descriptor chain.
size_t length = descriptorChainLengths[*super];
if (rand.oneIn(2)) {
length += rand.upToSquared(remainingUncommitted - length);
}
descriptorChainLengths[i] = length;
numPlannedDescriptors += length;
} else {
// We can choose to start a brand new chain at this type.
if (rand.oneIn(2)) {
size_t length = rand.upToSquared(remainingUncommitted);
descriptorChainLengths[i] = length;
numPlannedDescriptors += length;
}
}
}
// If this type has a descriptor chain, then we need to be able to
// choose to generate the next type in the chain in the future.
if (descriptorChainLengths[i]) {
describees.push_back(i);
}
}
void populateTypes() {
// Create the heap types.
for (; index < builder.size(); ++index) {
// Types without nontrivial subtypes may be marked final.
builder[index].setOpen(subtypeIndices[index].size() > 1 || rand.oneIn(2));
auto kind = typeKinds[index];
auto share = HeapType(builder[index]).getShared();
bool isDesc = describedIndices[index].has_value();
if (!supertypeIndices[index]) {
// No nontrivial supertype, so create a root type.
if (std::get_if<SignatureKind>(&kind)) {
builder[index] = generateSignature();
} else if (std::get_if<StructKind>(&kind)) {
builder[index] = generateStruct(share, isDesc);
} else if (std::get_if<ArrayKind>(&kind)) {
builder[index] = generateArray(share);
} else if (std::get_if<ContinuationKind>(&kind)) {
builder[index] = generateContinuation(share);
} else {
WASM_UNREACHABLE("unexpected kind");
}
} else {
// We have a supertype, so create a subtype.
HeapType supertype = builder[*supertypeIndices[index]];
switch (supertype.getKind()) {
case wasm::HeapTypeKind::Func:
builder[index] = generateSubSignature(supertype.getSignature());
break;
case wasm::HeapTypeKind::Struct:
builder[index] = generateSubStruct(supertype.getStruct(), share);
break;
case wasm::HeapTypeKind::Array:
builder[index] = generateSubArray(supertype.getArray());
break;
case wasm::HeapTypeKind::Cont:
builder[index] =
generateSubContinuation(supertype.getContinuation());
break;
case wasm::HeapTypeKind::Basic:
WASM_UNREACHABLE("unexpected kind");
}
}
}
}
HeapType::BasicHeapType generateBasicHeapType(Shareability share) {
// Choose bottom types more rarely.
// TODO: string types
if (rand.oneIn(16)) {
std::vector<HeapType> bottoms{
HeapType::noext, HeapType::nofunc, HeapType::none};
// Continuations cannot be shared.
if (features.hasStackSwitching() && share == Unshared) {
bottoms.push_back(HeapType::nocont);
}
return rand.pick(bottoms).getBasic(share);
}
// Sometimes emit shared in unshared contexts.
if (share == Unshared && features.hasSharedEverything() && rand.oneIn(4)) {
share = Shared;
}
std::vector<HeapType> options{HeapType::func,
HeapType::ext,
HeapType::any,
HeapType::eq,
HeapType::i31,
HeapType::struct_,
HeapType::array};
if (features.hasStackSwitching() && share == Unshared) {
options.push_back(HeapType::cont);
}
// Avoid shared exn, which we cannot generate.
if (features.hasExceptionHandling() && share == Unshared) {
options.push_back(HeapType::exn);
}
auto ht = rand.pick(options);
return ht.getBasic(share);
}
Type::BasicType generateBasicType() {
return rand.pick(
Random::FeatureOptions<Type::BasicType>{}
.add(FeatureSet::MVP, Type::i32, Type::i64, Type::f32, Type::f64)
.add(FeatureSet::SIMD, Type::v128));
}
HeapType generateHeapType(Shareability share) {
if (rand.oneIn(4)) {
return generateBasicHeapType(share);
}
if (share == Shared) {
// We can only reference other shared types.
std::vector<Index> eligible;
for (Index i = 0, n = recGroupEnds[index]; i < n; ++i) {
if (HeapType(builder[i]).getShared() == Shared) {
eligible.push_back(i);
}
}
if (eligible.empty()) {
return generateBasicHeapType(share);
}
return builder[rand.pick(eligible)];
}
// Any heap type can be referenced in an unshared context.
return builder[rand.upTo(recGroupEnds[index])];
}
Type generateRefType(Shareability share) {
auto heapType = generateHeapType(share);
Nullability nullability;
if (heapType.isMaybeShared(HeapType::exn)) {
// Do not generate non-nullable exnrefs for now, as we cannot generate
// them in global positions (they cannot be created in wasm, nor imported
// from JS).
nullability = Nullable;
} else {
nullability = rand.oneIn(2) ? Nullable : NonNullable;
}
return builder.getTempRefType(heapType, nullability);
}
Type generateSingleType(Shareability share) {
switch (rand.upTo(2)) {
case 0:
return generateBasicType();
case 1:
return generateRefType(share);
}
WASM_UNREACHABLE("unexpected");
}
Type generateTupleType(Shareability share) {
std::vector<Type> types(2 + rand.upTo(params.MAX_TUPLE_SIZE - 1));
for (auto& type : types) {
type = generateSingleType(share);
}
return builder.getTempTupleType(Tuple(types));
}
Type generateReturnType() {
if (rand.oneIn(6)) {
return Type::none;
} else if (features.hasMultivalue() && rand.oneIn(5)) {
return generateTupleType(Unshared);
} else {
return generateSingleType(Unshared);
}
}
Signature generateSignature() {
std::vector<Type> types(rand.upToSquared(params.MAX_PARAMS));
for (auto& type : types) {
type = generateSingleType(Unshared);
}
auto params = builder.getTempTupleType(types);
return {params, generateReturnType()};
}
Field generateField(Shareability share, bool isPrototypeField = false) {
// If this field could configure a prototype, then we want to give it a type
// that lets it do so a significant portion of the time.
if (isPrototypeField && share == Unshared && rand.oneIn(2)) {
auto nullability = rand.oneIn(2) ? NonNullable : Nullable;
return {Type(HeapType::ext, nullability), Immutable};
}
auto mutability = rand.oneIn(2) ? Mutable : Immutable;
if (rand.oneIn(6)) {
return {rand.oneIn(2) ? Field::i8 : Field::i16, mutability};
} else {
return {generateSingleType(share), mutability};
}
}
Struct generateStruct(Shareability share, bool isDesc) {
std::vector<Field> fields(rand.upTo(params.MAX_STRUCT_SIZE + 1));
// Prototypes are configured on the first field of descriptors types.
bool isPrototypeField = isDesc;
for (auto& field : fields) {
field = generateField(share, isPrototypeField);
isPrototypeField = false;
}
return {fields};
}
Array generateArray(Shareability share) { return {generateField(share)}; }
Continuation generateContinuation(Shareability share) {
auto type = pickKind<SignatureKind>(share);
// There must be signatures to pick from.
assert(type);
return Continuation(*type);
}
Continuation generateSubContinuation(Continuation super) {
auto subType = pickSubHeapType(super.type);
if (subType.isBasic()) {
// We cannot use a bottom type here.
subType = super.type;
}
return Continuation(subType);
}
template<typename Kind>
std::vector<HeapType> getKindCandidates(Shareability share) {
std::vector<HeapType> candidates;
// Iterate through the top level kinds, finding matches for `Kind`. Since we
// are constructing a child, we can only look through the end of the current
// recursion group.
for (Index i = 0, end = recGroupEnds[index]; i < end; ++i) {
if (std::get_if<Kind>(&typeKinds[i]) &&
share == HeapType(builder[i]).getShared()) {
candidates.push_back(builder[i]);
}
}
return candidates;
}
template<typename Kind> std::optional<HeapType> pickKind(Shareability share) {
auto candidates = getKindCandidates<Kind>(share);
if (candidates.size()) {
return rand.pick(candidates);
} else {
return std::nullopt;
}
}
HeapType pickSubFunc(Shareability share) {
auto choice = rand.upTo(8);
switch (choice) {
case 0:
return HeapTypes::func.getBasic(share);
case 1:
return HeapTypes::nofunc.getBasic(share);
default: {
if (auto type = pickKind<SignatureKind>(share)) {
return *type;
}
HeapType ht = (choice % 2) ? HeapType::func : HeapType::nofunc;
return ht.getBasic(share);
}
}
}
HeapType pickSubStruct(Shareability share) {
auto choice = rand.upTo(8);
switch (choice) {
case 0:
return HeapTypes::struct_.getBasic(share);
case 1:
return HeapTypes::none.getBasic(share);
default: {
if (auto type = pickKind<StructKind>(share)) {
return *type;
}
HeapType ht = (choice % 2) ? HeapType::struct_ : HeapType::none;
return ht.getBasic(share);
}
}
}
HeapType pickSubArray(Shareability share) {
auto choice = rand.upTo(8);
switch (choice) {
case 0:
return HeapTypes::array.getBasic(share);
case 1:
return HeapTypes::none.getBasic(share);
default: {
if (auto type = pickKind<ArrayKind>(share)) {
return *type;
}
HeapType ht = (choice % 2) ? HeapType::array : HeapType::none;
return ht.getBasic(share);
}
}
}
HeapType pickSubCont(Shareability share) {
auto choice = rand.upTo(8);
switch (choice) {
case 0:
return HeapTypes::cont.getBasic(share);
case 1:
return HeapTypes::nocont.getBasic(share);
default: {
if (auto type = pickKind<ContinuationKind>(share)) {
return *type;
}
HeapType ht = (choice % 2) ? HeapType::cont : HeapType::nocont;
return ht.getBasic(share);
}
}
}
HeapType pickSubEq(Shareability share) {
auto choice = rand.upTo(16);
switch (choice) {
case 0:
return HeapTypes::eq.getBasic(share);
case 1:
return HeapTypes::array.getBasic(share);
case 2:
return HeapTypes::struct_.getBasic(share);
case 3:
return HeapTypes::none.getBasic(share);
default: {
auto candidates = getKindCandidates<StructKind>(share);
auto arrayCandidates = getKindCandidates<ArrayKind>(share);
candidates.insert(
candidates.end(), arrayCandidates.begin(), arrayCandidates.end());
if (candidates.size()) {
return rand.pick(candidates);
}
switch (choice >> 2) {
case 0:
return HeapTypes::eq.getBasic(share);
case 1:
return HeapTypes::array.getBasic(share);
case 2:
return HeapTypes::struct_.getBasic(share);
case 3:
return HeapTypes::none.getBasic(share);
default:
WASM_UNREACHABLE("unexpected index");
}
}
}
}
HeapType pickSubAny(Shareability share) {
switch (rand.upTo(8)) {
case 0:
return HeapTypes::any.getBasic(share);
case 1:
return HeapTypes::none.getBasic(share);
default:
return pickSubEq(share);
}
WASM_UNREACHABLE("unexpected index");
}
HeapType pickSubHeapType(HeapType type) {
auto share = type.getShared();
auto it = typeIndices.find(type);
if (it != typeIndices.end()) {
// This is a constructed type, so we know where its subtypes are, but we
// can only choose those defined before the end of the current recursion
// group.
std::vector<HeapType> candidates;
for (auto i : subtypeIndices[it->second]) {
if (i < recGroupEnds[index]) {
candidates.push_back(builder[i]);
}
}
// Very rarely choose the relevant bottom type instead. We can't just use
// `type.getBottom()` because `type` may not have been initialized yet in
// the builder.
if (rand.oneIn(candidates.size() * 8)) {
auto* kind = &typeKinds[it->second];
if (std::get_if<SignatureKind>(kind)) {
return HeapTypes::nofunc.getBasic(share);
} else if (std::get_if<ContinuationKind>(kind)) {
return HeapTypes::nocont.getBasic(share);
} else {
return HeapTypes::none.getBasic(share);
}
}
// If we had no candidates then the oneIn() above us should have returned
// true, since oneIn(0) => true.
assert(!candidates.empty());
return rand.pick(candidates);
} else {
// This is not a constructed type, so it must be a basic type.
assert(type.isBasic());
if (rand.oneIn(8)) {
return type.getBottom();
}
switch (type.getBasic(Unshared)) {
case HeapType::func:
return pickSubFunc(share);
case HeapType::cont:
return pickSubCont(share);
case HeapType::any:
return pickSubAny(share);
case HeapType::eq:
return pickSubEq(share);
case HeapType::i31:
return HeapTypes::i31.getBasic(share);
case HeapType::struct_:
return pickSubStruct(share);
case HeapType::array:
return pickSubArray(share);
case HeapType::ext:
case HeapType::exn:
case HeapType::string:
case HeapType::none:
case HeapType::noext:
case HeapType::nofunc:
case HeapType::nocont:
case HeapType::noexn:
return type;
}
WASM_UNREACHABLE("unexpected type");
}
}
HeapType pickSuperHeapType(HeapType type) {
auto share = type.getShared();
std::vector<HeapType> candidates;
auto it = typeIndices.find(type);
if (it != typeIndices.end()) {
// This is a constructed type, so we know its supertypes. Collect the
// supertype chain as well as basic supertypes. We can't inspect `type`
// directly because it may not have been initialized yet in the builder.
for (std::optional<Index> curr = it->second; curr;
curr = supertypeIndices[*curr]) {
candidates.push_back(builder[*curr]);
}
auto* kind = &typeKinds[it->second];
if (std::get_if<StructKind>(kind)) {
candidates.push_back(HeapTypes::struct_.getBasic(share));
candidates.push_back(HeapTypes::eq.getBasic(share));
candidates.push_back(HeapTypes::any.getBasic(share));
return rand.pick(candidates);
} else if (std::get_if<ArrayKind>(kind)) {
candidates.push_back(HeapTypes::array.getBasic(share));
candidates.push_back(HeapTypes::eq.getBasic(share));
candidates.push_back(HeapTypes::any.getBasic(share));
return rand.pick(candidates);
} else if (std::get_if<SignatureKind>(kind)) {
candidates.push_back(HeapTypes::func.getBasic(share));
return rand.pick(candidates);
} else if (std::get_if<ContinuationKind>(kind)) {
candidates.push_back(HeapTypes::cont.getBasic(share));
return rand.pick(candidates);
} else {
WASM_UNREACHABLE("unexpected kind");
}
}
// This is not a constructed type, so it must be a basic type.
assert(type.isBasic());
candidates.push_back(type);
switch (type.getBasic(Unshared)) {
case HeapType::ext:
case HeapType::func:
case HeapType::exn:
case HeapType::cont:
case HeapType::any:
break;
case HeapType::eq:
candidates.push_back(HeapTypes::any.getBasic(share));
break;
case HeapType::i31:
case HeapType::struct_:
case HeapType::array:
candidates.push_back(HeapTypes::eq.getBasic(share));
candidates.push_back(HeapTypes::any.getBasic(share));
break;
case HeapType::string:
candidates.push_back(HeapTypes::ext.getBasic(share));
break;
case HeapType::none:
return pickSubAny(share);
case HeapType::nofunc:
return pickSubFunc(share);
case HeapType::nocont:
return pickSubCont(share);
case HeapType::noext:
candidates.push_back(HeapTypes::ext.getBasic(share));
break;
case HeapType::noexn:
candidates.push_back(HeapTypes::exn.getBasic(share));
break;
}
assert(!candidates.empty());
return rand.pick(candidates);
}
// TODO: Make this part of the wasm-type.h API
struct Ref {
HeapType type;
Nullability nullability;
};
Ref generateSubRef(Ref super) {
if (super.type.isMaybeShared(HeapType::exn)) {
// Do not generate non-nullable exnrefs for now, as we cannot generate
// them in global positions (they cannot be created in wasm, nor imported
// from JS). There are also no subtypes to consider, so just return.
return super;
}
auto nullability = super.nullability == NonNullable ? NonNullable
: rand.oneIn(2) ? Nullable
: NonNullable;
return {pickSubHeapType(super.type), nullability};
}
Ref generateSuperRef(Ref sub) {
auto nullability = sub.nullability == Nullable ? Nullable
: rand.oneIn(2) ? Nullable
: NonNullable;
return {pickSuperHeapType(sub.type), nullability};
}
Type generateSubtype(Type type) {
if (type.isTuple()) {
std::vector<Type> types;
types.reserve(type.size());
for (auto t : type) {
types.push_back(generateSubtype(t));
}
return builder.getTempTupleType(types);
} else if (type.isRef()) {
auto ref = generateSubRef({type.getHeapType(), type.getNullability()});
return builder.getTempRefType(ref.type, ref.nullability);
} else if (type.isBasic()) {
// Non-reference basic types do not have subtypes.
return type;
} else {
WASM_UNREACHABLE("unexpected type kind");
}
}
Type generateSupertype(Type type) {
if (type.isTuple()) {
std::vector<Type> types;
types.reserve(type.size());
for (auto t : type) {
types.push_back(generateSupertype(t));
}
return builder.getTempTupleType(types);
} else if (type.isRef()) {
auto ref = generateSuperRef({type.getHeapType(), type.getNullability()});
return builder.getTempRefType(ref.type, ref.nullability);
} else if (type.isBasic()) {
// Non-reference basic types do not have supertypes.
return type;
} else {
WASM_UNREACHABLE("unexpected type kind");
}
}
Signature generateSubSignature(Signature super) {
auto params = generateSupertype(super.params);
auto results = generateSubtype(super.results);
return Signature(params, results);
}
Field generateSubField(Field super) {
if (super.mutable_ == Mutable) {
// Only immutable fields support subtyping.
return super;
}
if (super.isPacked()) {
// No other subtypes of i8 or i16.
return super;
}
return {generateSubtype(super.type), Immutable};
}
Struct generateSubStruct(const Struct& super, Shareability share) {
std::vector<Field> fields;
// Depth subtyping
for (auto field : super.fields) {
fields.push_back(generateSubField(field));
}
// Width subtyping
Index extra = rand.upTo(params.MAX_STRUCT_SIZE + 1 - fields.size());
for (Index i = 0; i < extra; ++i) {
fields.push_back(generateField(share));
}
return {fields};
}
Array generateSubArray(Array super) {
return {generateSubField(super.element)};
}
HeapTypeKind generateHeapTypeKind() {
// Emit continuations less frequently, as we need fewer of them to get
// interesting results.
uint32_t numKinds = features.hasStackSwitching() ? 7 : 6;
switch (rand.upTo(numKinds)) {
case 0:
case 1:
return SignatureKind{};
case 2:
case 3:
return StructKind{};
case 4:
case 5:
return ArrayKind{};
case 6:
return ContinuationKind{};
}
WASM_UNREACHABLE("unexpected index");
}
};
} // anonymous namespace
HeapTypeGenerator
HeapTypeGenerator::create(Random& rand, FeatureSet features, size_t n) {
return HeapTypeGeneratorImpl(rand, features, n).result;
}
namespace {
// `makeInhabitable` implementation.
//
// There are two root causes of uninhabitability: First, a non-nullable
// reference to a bottom type is always uninhabitable. Second, a cycle in the
// type graph formed from non-nullable references makes all the types involved
// in that cycle uninhabitable because there is no way to construct the types
// one at at time. All types that reference uninhabitable types via non-nullable
// references are also themselves uninhabitable, but these transitively
// uninhabitable types will become inhabitable once we fix the root causes, so
// we don't worry about them.
//
// To modify uninhabitable types to make them habitable, it suffices to make all
// non-nullable references to bottom types nullable and to break all cycles of
// non-nullable references by making one of the references nullable. To preserve
// valid subtyping, the newly nullable fields must also be made nullable in any
// supertypes in which they appear.
struct Inhabitator {
// Uniquely identify fields as an index into a type.
using FieldPos = std::pair<HeapType, Index>;
// When we make a reference nullable, we typically need to make the same
// reference in other types nullable to maintain valid subtyping. Which types
// we need to update depends on the variance of the reference, which is
// determined by how it is used in its enclosing heap type.
//
// An invariant field of a heaptype must have the same type in subtypes of
// that heaptype. A covariant field of a heaptype must be typed with a subtype
// of its original type in subtypes of the heaptype.
enum Variance { Invariant, Covariant };
// The input types.
const std::vector<HeapType>& types;
// The fields we will make nullable.
std::unordered_set<FieldPos> nullables;
SubTypes subtypes;
Inhabitator(const std::vector<HeapType>& types)
: types(types), subtypes(types) {}
Variance getVariance(FieldPos fieldPos);
void markNullable(FieldPos field);
void markBottomRefsNullable();
void markExternRefsNullable();
void breakNonNullableCycles();
std::vector<HeapType> build();
};
Inhabitator::Variance Inhabitator::getVariance(FieldPos fieldPos) {
auto [type, idx] = fieldPos;
assert(!type.isBasic() && !type.isSignature() && !type.isContinuation());
auto field = GCTypeUtils::getField(type, idx);
assert(field);
if (field->mutable_ == Mutable) {
return Invariant;
} else {
return Covariant;
}
}
void Inhabitator::markNullable(FieldPos field) {
// Mark the given field nullable in the original type and in other types
// necessary to keep subtyping valid.
nullables.insert(field);
auto [curr, idx] = field;
switch (getVariance(field)) {
case Covariant:
// Mark the field null in all supertypes. If the supertype field is
// already nullable, that's ok and this will have no effect.
while (auto super = curr.getDeclaredSuperType()) {
if (super->isStruct() && idx >= super->getStruct().fields.size()) {
// Do not mark fields that don't exist as nullable; this index may be
// used by a descriptor.
break;
}
nullables.insert({*super, idx});
curr = *super;
}
break;
case Invariant:
// Find the top type for which this field exists and mark the field
// nullable in all of its subtypes.
if (curr.isArray()) {
while (auto super = curr.getDeclaredSuperType()) {
curr = *super;
}
} else {
assert(curr.isStruct());
while (auto super = curr.getDeclaredSuperType()) {
if (super->getStruct().fields.size() <= idx) {
break;
}
curr = *super;
}
}
// Mark the field nullable in all subtypes. If the subtype field is
// already nullable, that's ok and this will have no effect. TODO: Remove
// this extra `index` variable once we have C++20. It's a workaround for