-
Notifications
You must be signed in to change notification settings - Fork 851
Expand file tree
/
Copy pathpossible-contents.cpp
More file actions
1679 lines (1496 loc) · 61.2 KB
/
possible-contents.cpp
File metadata and controls
1679 lines (1496 loc) · 61.2 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 2022 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 <optional>
#include <variant>
#include "ir/branch-utils.h"
#include "ir/eh-utils.h"
#include "ir/module-utils.h"
#include "ir/possible-contents.h"
#include "wasm.h"
#ifdef POSSIBLE_CONTENTS_INSERT_ORDERED
// Use an insert-ordered set for easier debugging with deterministic queue
// ordering.
#include "support/insert_ordered.h"
#endif
namespace std {
std::ostream& operator<<(std::ostream& stream,
const wasm::PossibleContents& contents) {
contents.dump(stream);
return stream;
}
} // namespace std
namespace wasm {
void PossibleContents::combine(const PossibleContents& other) {
// First handle the trivial cases of them being equal, or one of them is
// None or Many.
if (*this == other) {
return;
}
if (other.isNone()) {
return;
}
if (isNone()) {
value = other.value;
return;
}
if (isMany()) {
return;
}
if (other.isMany()) {
value = Many();
return;
}
auto type = getType();
auto otherType = other.getType();
if (!type.isRef() || !otherType.isRef()) {
// At least one is not a reference. The only possibility left for a useful
// combination here is if they have the same type (since we've already ruled
// out the case of them being equal). If they have the same type then
// neither is a reference and we can emit an exact type (since subtyping is
// not relevant for non-references.
if (type == otherType) {
value = ExactType(type);
} else {
value = Many();
}
return;
}
// Special handling for references from here.
// Nulls are always equal to each other, even if their types differ.
if (isNull() || other.isNull()) {
// If only one is a null, but the other's type is known exactly, then the
// combination is to add nullability (if the type is *not* known exactly,
// like for a global, then we cannot do anything useful here).
if (!isNull() && hasExactType()) {
value = ExactType(Type(type.getHeapType(), Nullable));
return;
} else if (!other.isNull() && other.hasExactType()) {
value = ExactType(Type(otherType.getHeapType(), Nullable));
return;
} else if (isNull() && other.isNull()) {
// Both are null. The result is a null, of the LUB.
auto lub = HeapType::getLeastUpperBound(type.getHeapType(),
otherType.getHeapType());
value = Literal::makeNull(lub);
return;
}
}
if (hasExactType() && other.hasExactType() &&
type.getHeapType() == otherType.getHeapType()) {
// We know the types here exactly, and even the heap types match, but
// there is some other difference that prevents them from being 100%
// identical (for example, one might be an ExactType and the other a
// Literal; or both might be ExactTypes and only one might be nullable).
// In these cases we can emit a proper ExactType here, adding nullability
// if we need to.
value = ExactType(Type(
type.getHeapType(),
type.isNullable() || otherType.isNullable() ? Nullable : NonNullable));
return;
}
// Nothing else possible combines in an interesting way; emit a Many.
value = Many();
}
namespace {
// We are going to do a very large flow operation, potentially, as we create
// a Location for every interesting part in the entire wasm, and some of those
// places will have lots of links (like a struct field may link out to every
// single struct.get of that type), so we must make the data structures here
// as efficient as possible. Towards that goal, we work with location
// *indexes* where possible, which are small (32 bits) and do not require any
// complex hashing when we use them in sets or maps.
//
// Note that we do not use indexes everywhere, since the initial analysis is
// done in parallel, and we do not have a fixed indexing of locations yet. When
// we merge the parallel data we create that indexing, and use indexes from then
// on.
using LocationIndex = uint32_t;
#ifndef NDEBUG
// Assert on not having duplicates in a vector.
template<typename T> void disallowDuplicates(const T& targets) {
#if defined(POSSIBLE_CONTENTS_DEBUG) && POSSIBLE_CONTENTS_DEBUG >= 2
std::unordered_set<LocationIndex> uniqueTargets;
for (const auto& target : targets) {
uniqueTargets.insert(target);
}
assert(uniqueTargets.size() == targets.size());
#endif
}
#endif
// A link indicates a flow of content from one location to another. For
// example, if we do a local.get and return that value from a function, then
// we have a link from a LocalLocation to a ResultLocation.
template<typename T> struct Link {
T from;
T to;
bool operator==(const Link<T>& other) const {
return from == other.from && to == other.to;
}
};
using LocationLink = Link<Location>;
using IndexLink = Link<LocationIndex>;
} // anonymous namespace
} // namespace wasm
namespace std {
template<> struct hash<wasm::LocationLink> {
size_t operator()(const wasm::LocationLink& loc) const {
return std::hash<std::pair<wasm::Location, wasm::Location>>{}(
{loc.from, loc.to});
}
};
template<> struct hash<wasm::IndexLink> {
size_t operator()(const wasm::IndexLink& loc) const {
return std::hash<std::pair<wasm::LocationIndex, wasm::LocationIndex>>{}(
{loc.from, loc.to});
}
};
} // namespace std
namespace wasm {
namespace {
// The data we gather from each function, as we process them in parallel. Later
// this will be merged into a single big graph.
struct CollectedFuncInfo {
// All the links we found in this function. Rarely are there duplicates
// in this list (say when writing to the same global location from another
// global location), and we do not try to deduplicate here, just store them in
// a plain array for now, which is faster (later, when we merge all the info
// from the functions, we need to deduplicate anyhow).
std::vector<LocationLink> links;
// All the roots of the graph, that is, places that begin by containing some
// particular content. That includes i32.const, ref.func, struct.new, etc. All
// possible contents in the rest of the graph flow from such places.
//
// The vector here is of the location of the root and then its contents.
std::vector<std::pair<Location, PossibleContents>> roots;
// In some cases we need to know the parent of the expression. Consider this:
//
// (struct.set $A k
// (local.get $ref)
// (local.get $value)
// )
//
// Imagine that the first local.get, for $ref, receives a new value. That can
// affect where the struct.set sends values: if previously that local.get had
// no possible contents, and now it does, then we have DataLocations to
// update. Likewise, when the second local.get is updated we must do the same,
// but again which DataLocations we update depends on the ref passed to the
// struct.set. To handle such things, we set add a childParent link, and then
// when we update the child we can find the parent and handle any special
// behavior we need there.
std::unordered_map<Expression*, Expression*> childParents;
};
// Walk the wasm and find all the links we need to care about, and the locations
// and roots related to them. This builds up a CollectedFuncInfo data structure.
// After all InfoCollectors run, those data structures will be merged and the
// main flow will begin.
struct InfoCollector
: public PostWalker<InfoCollector, OverriddenVisitor<InfoCollector>> {
CollectedFuncInfo& info;
InfoCollector(CollectedFuncInfo& info) : info(info) {}
// Check if a type is relevant for us. If not, we can ignore it entirely.
bool isRelevant(Type type) {
if (type == Type::unreachable || type == Type::none) {
return false;
}
if (type.isTuple()) {
for (auto t : type) {
if (isRelevant(t)) {
return true;
}
}
}
if (type.isRef() && getTypeSystem() != TypeSystem::Nominal &&
getTypeSystem() != TypeSystem::Isorecursive) {
// We need explicit supers in the SubTyping helper class. Without that,
// cannot handle refs, and consider them irrelevant.
return false;
}
return true;
}
bool isRelevant(Signature sig) {
return isRelevant(sig.params) || isRelevant(sig.results);
}
bool isRelevant(Expression* curr) { return curr && isRelevant(curr->type); }
template<typename T> bool isRelevant(const T& vec) {
for (auto* expr : vec) {
if (isRelevant(expr->type)) {
return true;
}
}
return false;
}
// Each visit*() call is responsible for connecting the children of a node to
// that node. Responsibility for connecting the node's output to anywhere
// else (another expression or the function itself, if we are at the top
// level) is the responsibility of the outside.
void visitBlock(Block* curr) {
if (curr->list.empty()) {
return;
}
// Values sent to breaks to this block must be received here.
handleBreakTarget(curr);
// The final item in the block can flow a value to here as well.
receiveChildValue(curr->list.back(), curr);
}
void visitIf(If* curr) {
// Each arm may flow out a value.
receiveChildValue(curr->ifTrue, curr);
receiveChildValue(curr->ifFalse, curr);
}
void visitLoop(Loop* curr) { receiveChildValue(curr->body, curr); }
void visitBreak(Break* curr) {
// Connect the value (if present) to the break target.
handleBreakValue(curr);
// The value may also flow through in a br_if (the type will indicate that,
// which receiveChildValue will notice).
receiveChildValue(curr->value, curr);
}
void visitSwitch(Switch* curr) { handleBreakValue(curr); }
void visitLoad(Load* curr) {
// We could infer the exact type here, but as no subtyping is possible, it
// would have no benefit, so just add a generic root (which will be "Many").
// See the comment on the ContentOracle class.
addRoot(curr);
}
void visitStore(Store* curr) {}
void visitAtomicRMW(AtomicRMW* curr) { addRoot(curr); }
void visitAtomicCmpxchg(AtomicCmpxchg* curr) { addRoot(curr); }
void visitAtomicWait(AtomicWait* curr) { addRoot(curr); }
void visitAtomicNotify(AtomicNotify* curr) { addRoot(curr); }
void visitAtomicFence(AtomicFence* curr) {}
void visitSIMDExtract(SIMDExtract* curr) { addRoot(curr); }
void visitSIMDReplace(SIMDReplace* curr) { addRoot(curr); }
void visitSIMDShuffle(SIMDShuffle* curr) { addRoot(curr); }
void visitSIMDTernary(SIMDTernary* curr) { addRoot(curr); }
void visitSIMDShift(SIMDShift* curr) { addRoot(curr); }
void visitSIMDLoad(SIMDLoad* curr) { addRoot(curr); }
void visitSIMDLoadStoreLane(SIMDLoadStoreLane* curr) { addRoot(curr); }
void visitMemoryInit(MemoryInit* curr) {}
void visitDataDrop(DataDrop* curr) {}
void visitMemoryCopy(MemoryCopy* curr) {}
void visitMemoryFill(MemoryFill* curr) {}
void visitConst(Const* curr) {
addRoot(curr, PossibleContents::literal(curr->value));
}
void visitUnary(Unary* curr) {
// TODO: Optimize cases like this using interpreter integration: if the
// input is a Literal, we could interpret the Literal result.
addRoot(curr);
}
void visitBinary(Binary* curr) { addRoot(curr); }
void visitSelect(Select* curr) {
// TODO: We could use the fact that both sides are executed unconditionally
// while optimizing (if one arm must trap, then the Select will trap,
// which is not the same as with an If).
receiveChildValue(curr->ifTrue, curr);
receiveChildValue(curr->ifFalse, curr);
}
void visitDrop(Drop* curr) {}
void visitMemorySize(MemorySize* curr) { addRoot(curr); }
void visitMemoryGrow(MemoryGrow* curr) { addRoot(curr); }
void visitRefNull(RefNull* curr) {
addRoot(
curr,
PossibleContents::literal(Literal::makeNull(curr->type.getHeapType())));
}
void visitRefIs(RefIs* curr) {
// TODO: optimize when possible
addRoot(curr);
}
void visitRefFunc(RefFunc* curr) {
addRoot(curr, PossibleContents::literal(Literal(curr->func, curr->type)));
}
void visitRefEq(RefEq* curr) {
// TODO: optimize when possible (e.g. when both sides must contain the same
// global)
addRoot(curr);
}
void visitTableGet(TableGet* curr) {
// TODO: optimize when possible
addRoot(curr);
}
void visitTableSet(TableSet* curr) {}
void visitTableSize(TableSize* curr) { addRoot(curr); }
void visitTableGrow(TableGrow* curr) { addRoot(curr); }
void visitNop(Nop* curr) {}
void visitUnreachable(Unreachable* curr) {}
#ifndef NDEBUG
// For now we only handle pops in a catch body, see visitTry(). To check for
// errors, use counter of the pops we handled and all the pops; those sums
// must agree at the end, or else we've seen something we can't handle.
Index totalPops = 0;
Index handledPops = 0;
#endif
void visitPop(Pop* curr) {
#ifndef NDEBUG
totalPops++;
#endif
}
void visitI31New(I31New* curr) {
// TODO: optimize like struct references
addRoot(curr);
}
void visitI31Get(I31Get* curr) {
// TODO: optimize like struct references
addRoot(curr);
}
void visitRefTest(RefTest* curr) {
// TODO: optimize when possible
addRoot(curr);
}
void visitRefCast(RefCast* curr) {
// We will handle this in a special way later during the flow, as ref.cast
// only allows valid values to flow through.
addChildParentLink(curr->ref, curr);
}
void visitBrOn(BrOn* curr) {
// TODO: optimize when possible
handleBreakValue(curr);
receiveChildValue(curr->ref, curr);
}
void visitRttCanon(RttCanon* curr) { addRoot(curr); }
void visitRttSub(RttSub* curr) { addRoot(curr); }
void visitRefAs(RefAs* curr) {
// TODO: optimize when possible: like RefCast, not all values flow through.
receiveChildValue(curr->value, curr);
}
// Locals read and write to their index.
// TODO: we could use a LocalGraph for SSA-like precision
void visitLocalGet(LocalGet* curr) {
if (isRelevant(curr->type)) {
for (Index i = 0; i < curr->type.size(); i++) {
info.links.push_back({LocalLocation{getFunction(), curr->index, i},
ExpressionLocation{curr, i}});
}
}
}
void visitLocalSet(LocalSet* curr) {
if (!isRelevant(curr->value->type)) {
return;
}
for (Index i = 0; i < curr->value->type.size(); i++) {
info.links.push_back({ExpressionLocation{curr->value, i},
LocalLocation{getFunction(), curr->index, i}});
}
// Tees also flow out the value (receiveChildValue will see if this is a tee
// based on the type, automatically).
receiveChildValue(curr->value, curr);
}
// Globals read and write from their location.
void visitGlobalGet(GlobalGet* curr) {
if (isRelevant(curr->type)) {
// FIXME: we allow tuples in globals, so GlobalLocation needs a tupleIndex
// and we should loop here.
assert(!curr->type.isTuple());
info.links.push_back(
{GlobalLocation{curr->name}, ExpressionLocation{curr, 0}});
}
}
void visitGlobalSet(GlobalSet* curr) {
if (isRelevant(curr->value->type)) {
info.links.push_back(
{ExpressionLocation{curr->value, 0}, GlobalLocation{curr->name}});
}
}
// Iterates over a list of children and adds links to parameters and results
// as needed. The param/result functions receive the index and create the
// proper location for it.
template<typename T>
void handleCall(T* curr,
std::function<Location(Index)> makeParamLocation,
std::function<Location(Index)> makeResultLocation) {
Index i = 0;
for (auto* operand : curr->operands) {
if (isRelevant(operand->type)) {
info.links.push_back(
{ExpressionLocation{operand, 0}, makeParamLocation(i)});
}
i++;
}
// Add results, if anything flows out.
for (Index i = 0; i < curr->type.size(); i++) {
if (isRelevant(curr->type[i])) {
info.links.push_back(
{makeResultLocation(i), ExpressionLocation{curr, i}});
}
}
// If this is a return call then send the result to the function return as
// well.
if (curr->isReturn) {
auto results = getFunction()->getResults();
for (Index i = 0; i < results.size(); i++) {
auto result = results[i];
if (isRelevant(result)) {
info.links.push_back(
{makeResultLocation(i), ResultLocation{getFunction(), i}});
}
}
}
}
// Calls send values to params in their possible targets, and receive
// results.
void visitCall(Call* curr) {
auto* target = getModule()->getFunction(curr->target);
handleCall(
curr,
[&](Index i) {
return LocalLocation{target, i, 0};
},
[&](Index i) {
return ResultLocation{target, i};
});
}
void visitCallIndirect(CallIndirect* curr) {
// TODO: the table identity could also be used here
auto targetType = curr->heapType;
handleCall(
curr,
[&](Index i) {
return SignatureParamLocation{targetType, i};
},
[&](Index i) {
return SignatureResultLocation{targetType, i};
});
}
void visitCallRef(CallRef* curr) {
auto targetType = curr->target->type;
if (targetType != Type::unreachable) {
auto heapType = targetType.getHeapType();
handleCall(
curr,
[&](Index i) {
return SignatureParamLocation{heapType, i};
},
[&](Index i) {
return SignatureResultLocation{heapType, i};
});
}
}
// Creates a location for a null of a particular type and adds a root for it.
// Such roots are where the default value of an i32 local comes from, or the
// value in a ref.null.
Location getNullLocation(Type type) {
auto location = NullLocation{type};
addRoot(location, PossibleContents::literal(Literal::makeZero(type)));
return location;
}
// Iterates over a list of children and adds links from them. The target of
// those link is created using a function that is passed in, which receives
// the index of the child.
void linkChildList(ExpressionList& operands,
std::function<Location(Index)> makeTarget) {
Index i = 0;
for (auto* operand : operands) {
// This helper is not used from places that allow a tuple (hence we can
// hardcode the index 0 a few lines down).
assert(!operand->type.isTuple());
if (isRelevant(operand->type)) {
info.links.push_back({ExpressionLocation{operand, 0}, makeTarget(i)});
}
i++;
}
}
void visitStructNew(StructNew* curr) {
if (curr->type == Type::unreachable) {
return;
}
auto type = curr->type.getHeapType();
if (curr->isWithDefault()) {
// Link the default values to the struct's fields.
auto& fields = type.getStruct().fields;
for (Index i = 0; i < fields.size(); i++) {
info.links.push_back(
{getNullLocation(fields[i].type), DataLocation{type, i}});
}
} else {
// Link the operands to the struct's fields.
linkChildList(curr->operands, [&](Index i) {
return DataLocation{type, i};
});
}
addRoot(curr, PossibleContents::exactType(curr->type));
}
void visitArrayNew(ArrayNew* curr) {
if (curr->type == Type::unreachable) {
return;
}
auto type = curr->type.getHeapType();
if (curr->init) {
info.links.push_back(
{ExpressionLocation{curr->init, 0}, DataLocation{type, 0}});
} else {
info.links.push_back(
{getNullLocation(type.getArray().element.type), DataLocation{type, 0}});
}
addRoot(curr, PossibleContents::exactType(curr->type));
}
void visitArrayInit(ArrayInit* curr) {
if (curr->type == Type::unreachable) {
return;
}
if (!curr->values.empty()) {
auto type = curr->type.getHeapType();
linkChildList(curr->values, [&](Index i) {
// The index i is ignored, as we do not track indexes in Arrays -
// everything is modeled as if at index 0.
return DataLocation{type, 0};
});
}
addRoot(curr, PossibleContents::exactType(curr->type));
}
// Struct operations access the struct fields' locations.
void visitStructGet(StructGet* curr) {
if (!isRelevant(curr->ref)) {
// If references are irrelevant then we will ignore them, and we won't
// have information about this struct.get's reference, which means we
// won't have information to compute relevant values for this struct.get.
// Instead, just mark this as an unknown value (root).
addRoot(curr);
return;
}
// The struct.get will receive different values depending on the contents
// in the reference, so mark us as the parent of the ref, and we will
// handle all of this in a special way during the flow. Note that we do
// not even create a DataLocation here; anything that we need will be
// added during the flow.
addChildParentLink(curr->ref, curr);
}
void visitStructSet(StructSet* curr) {
if (curr->ref->type == Type::unreachable) {
return;
}
// See comment on visitStructGet. Here we also connect the value.
addChildParentLink(curr->ref, curr);
addChildParentLink(curr->value, curr);
}
// Array operations access the array's location, parallel to how structs work.
void visitArrayGet(ArrayGet* curr) {
if (!isRelevant(curr->ref)) {
addRoot(curr);
return;
}
addChildParentLink(curr->ref, curr);
}
void visitArraySet(ArraySet* curr) {
if (curr->ref->type == Type::unreachable) {
return;
}
addChildParentLink(curr->ref, curr);
addChildParentLink(curr->value, curr);
}
void visitArrayLen(ArrayLen* curr) {
// TODO: optimize when possible (perhaps we can infer a Literal for the
// length)
addRoot(curr);
}
void visitArrayCopy(ArrayCopy* curr) {
if (curr->type == Type::unreachable) {
return;
}
// Our flow handling of GC data is not simple: we have special code for each
// read and write instruction. Therefore, to avoid adding special code for
// ArrayCopy, model it as a combination of an ArrayRead and ArrayWrite, by
// just emitting fake expressions for those. The fake expressions are not
// part of the main IR, which is potentially confusing during debugging,
// however, which is a downside.
Builder builder(*getModule());
auto* get = builder.makeArrayGet(curr->srcRef, curr->srcIndex);
visitArrayGet(get);
auto* set = builder.makeArraySet(curr->destRef, curr->destIndex, get);
visitArraySet(set);
}
void visitStringNew(StringNew* curr) {
if (curr->type == Type::unreachable) {
return;
}
addRoot(curr, PossibleContents::exactType(curr->type));
}
void visitStringConst(StringConst* curr) {
addRoot(curr, PossibleContents::exactType(curr->type));
}
void visitStringMeasure(StringMeasure* curr) {
// TODO: optimize when possible
addRoot(curr);
}
void visitStringEncode(StringEncode* curr) {
// TODO: optimize when possible
addRoot(curr);
}
void visitStringConcat(StringConcat* curr) {
// TODO: optimize when possible
addRoot(curr);
}
// TODO: Model which throws can go to which catches. For now, anything thrown
// is sent to the location of that tag, and any catch of that tag can
// read them.
void visitTry(Try* curr) {
receiveChildValue(curr->body, curr);
for (auto* catchBody : curr->catchBodies) {
receiveChildValue(catchBody, curr);
}
auto numTags = curr->catchTags.size();
for (Index tagIndex = 0; tagIndex < numTags; tagIndex++) {
auto tag = curr->catchTags[tagIndex];
auto* body = curr->catchBodies[tagIndex];
auto params = getModule()->getTag(tag)->sig.params;
if (params.size() == 0) {
continue;
}
// Find the pop of the tag's contents. The body must start with such a
// pop, which might be of a tuple.
auto* pop = EHUtils::findPop(body);
// There must be a pop since we checked earlier if it was an empty tag,
// and would not reach here.
assert(pop);
assert(pop->type.size() == params.size());
for (Index i = 0; i < params.size(); i++) {
if (isRelevant(params[i])) {
info.links.push_back(
{TagLocation{tag, i}, ExpressionLocation{pop, i}});
}
}
#ifndef NDEBUG
// This pop was in the position we can handle, note that (see visitPop
// for details).
handledPops++;
#endif
}
}
void visitThrow(Throw* curr) {
auto& operands = curr->operands;
if (!isRelevant(operands)) {
return;
}
auto tag = curr->tag;
for (Index i = 0; i < curr->operands.size(); i++) {
info.links.push_back(
{ExpressionLocation{operands[i], 0}, TagLocation{tag, i}});
}
}
void visitRethrow(Rethrow* curr) {}
void visitTupleMake(TupleMake* curr) {
if (isRelevant(curr->type)) {
for (Index i = 0; i < curr->operands.size(); i++) {
info.links.push_back({ExpressionLocation{curr->operands[i], 0},
ExpressionLocation{curr, i}});
}
}
}
void visitTupleExtract(TupleExtract* curr) {
if (isRelevant(curr->type)) {
info.links.push_back({ExpressionLocation{curr->tuple, curr->index},
ExpressionLocation{curr, 0}});
}
}
// Adds a result to the current function, such as from a return or the value
// that flows out.
void addResult(Expression* value) {
if (value && isRelevant(value->type)) {
for (Index i = 0; i < value->type.size(); i++) {
info.links.push_back(
{ExpressionLocation{value, i}, ResultLocation{getFunction(), i}});
}
}
}
void visitReturn(Return* curr) { addResult(curr->value); }
void visitFunction(Function* curr) {
// Vars have an initial value.
for (Index i = 0; i < curr->getNumLocals(); i++) {
if (curr->isVar(i)) {
Index j = 0;
for (auto t : curr->getLocalType(i)) {
if (t.isDefaultable()) {
info.links.push_back(
{getNullLocation(t), LocalLocation{curr, i, j}});
}
j++;
}
}
}
// Functions with a result can flow a value out from their body.
addResult(curr->body);
// See visitPop().
assert(handledPops == totalPops);
}
// Helpers
// Handles the value sent in a break instruction. Does not handle anything
// else like the condition etc.
void handleBreakValue(Expression* curr) {
BranchUtils::operateOnScopeNameUsesAndSentValues(
curr, [&](Name target, Expression* value) {
if (value && isRelevant(value->type)) {
for (Index i = 0; i < value->type.size(); i++) {
// Breaks send the contents of the break value to the branch target
// that the break goes to.
info.links.push_back(
{ExpressionLocation{value, i},
BreakTargetLocation{getFunction(), target, i}});
}
}
});
}
// Handles receiving values from breaks at the target (as in a block).
void handleBreakTarget(Expression* curr) {
if (isRelevant(curr->type)) {
BranchUtils::operateOnScopeNameDefs(curr, [&](Name target) {
for (Index i = 0; i < curr->type.size(); i++) {
info.links.push_back({BreakTargetLocation{getFunction(), target, i},
ExpressionLocation{curr, i}});
}
});
}
}
// Connect a child's value to the parent, that is, all content in the child is
// now considered possible in the parent as well.
void receiveChildValue(Expression* child, Expression* parent) {
if (isRelevant(parent) && isRelevant(child)) {
// The tuple sizes must match (or, if not a tuple, the size should be 1 in
// both cases).
assert(child->type.size() == parent->type.size());
for (Index i = 0; i < child->type.size(); i++) {
info.links.push_back(
{ExpressionLocation{child, i}, ExpressionLocation{parent, i}});
}
}
}
// See the comment on CollectedFuncInfo::childParents.
void addChildParentLink(Expression* child, Expression* parent) {
if (isRelevant(child->type)) {
info.childParents[child] = parent;
}
}
// Adds a root, if the expression is relevant. If the value is not specified,
// mark the root as containing Many (which is the common case, so avoid
// verbose code).
void addRoot(Expression* curr,
PossibleContents contents = PossibleContents::many()) {
if (isRelevant(curr)) {
addRoot(ExpressionLocation{curr, 0}, contents);
}
}
// As above, but given an arbitrary location and not just an expression.
void addRoot(Location loc,
PossibleContents contents = PossibleContents::many()) {
info.roots.emplace_back(loc, contents);
}
};
// Main logic for building data for the flow analysis and then performing that
// analysis.
struct Flower {
Module& wasm;
Flower(Module& wasm);
// Each LocationIndex will have one LocationInfo that contains the relevant
// information we need for each location.
struct LocationInfo {
// The location at this index.
Location location;
// The possible contents in that location.
PossibleContents contents;
// A list of the target locations to which this location sends content.
// TODO: benchmark SmallVector<1> here, as commonly there may be a single
// target (an expression has one parent)
std::vector<LocationIndex> targets;
LocationInfo(Location location) : location(location) {}
};
// Maps location indexes to the info stored there, as just described above.
std::vector<LocationInfo> locations;
// Reverse mapping of locations to their indexes.
std::unordered_map<Location, LocationIndex> locationIndexes;
const Location& getLocation(LocationIndex index) {
assert(index < locations.size());
return locations[index].location;
}
PossibleContents& getContents(LocationIndex index) {
assert(index < locations.size());
return locations[index].contents;
}
private:
std::vector<LocationIndex>& getTargets(LocationIndex index) {
assert(index < locations.size());
return locations[index].targets;
}
// Convert the data into the efficient LocationIndex form we will use during
// the flow analysis. This method returns the index of a location, allocating
// one if this is the first time we see it.
LocationIndex getIndex(const Location& location) {
auto iter = locationIndexes.find(location);
if (iter != locationIndexes.end()) {
return iter->second;
}
// Allocate a new index here.
size_t index = locations.size();
#if defined(POSSIBLE_CONTENTS_DEBUG) && POSSIBLE_CONTENTS_DEBUG >= 2
std::cout << " new index " << index << " for ";
dump(location);
#endif
if (index >= std::numeric_limits<LocationIndex>::max()) {
// 32 bits should be enough since each location takes at least one byte
// in the binary, and we don't have 4GB wasm binaries yet... do we?
Fatal() << "Too many locations for 32 bits";
}
locations.emplace_back(location);
locationIndexes[location] = index;
return index;
}
bool hasIndex(const Location& location) {
return locationIndexes.find(location) != locationIndexes.end();
}
IndexLink getIndexes(const LocationLink& link) {
return {getIndex(link.from), getIndex(link.to)};
}
// See the comment on CollectedFuncInfo::childParents. This is the merged info
// from all the functions and the global scope.
std::unordered_map<LocationIndex, LocationIndex> childParents;
// The work remaining to do during the flow: locations that we need to flow
// content from, after new content reached them.
//
// Using a set here is efficient as multiple updates may arrive to a location
// before we get to processing it.
//
// The items here could be {location, newContents}, but it is more efficient
// to have already written the new contents to the main data structure. That
// avoids larger data here, and also, updating the contents as early as
// possible is helpful as anything reading them meanwhile (before we get to
// their work item in the queue) will see the newer value, possibly avoiding
// flowing an old value that would later be overwritten.
#ifdef POSSIBLE_CONTENTS_INSERT_ORDERED
InsertOrderedSet<LocationIndex> workQueue;
#else
std::unordered_set<LocationIndex> workQueue;
#endif
// All existing links in the graph. We keep this to know when a link we want
// to add is new or not.
std::unordered_set<IndexLink> links;
// Update a location with new contents that are added to everything already
// present there. If the update changes the contents at that location (if
// there was anything new) then we also need to flow from there, which we will
// do by adding the location to the work queue, and eventually flowAfterUpdate
// will be called on this location.
//
// Returns whether it is worth sending new contents to this location in the
// future. If we return false, the sending location never needs to do that
// ever again.
bool updateContents(LocationIndex locationIndex,
PossibleContents newContents);
// Slow helper that converts a Location to a LocationIndex. This should be
// avoided. TODO: remove the remaining uses of this.
bool updateContents(const Location& location,
const PossibleContents& newContents) {
return updateContents(getIndex(location), newContents);
}
// Flow contents from a location where a change occurred. This sends the new
// contents to all the normal targets of this location (using
// flowToTargetsAfterUpdate), and also handles special cases of flow after.
void flowAfterUpdate(LocationIndex locationIndex);
// Internal part of flowAfterUpdate that handles sending new values to the