-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathFieldSensitivePrunedLiveness.cpp
1678 lines (1483 loc) · 61.7 KB
/
FieldSensitivePrunedLiveness.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
//===--- FieldSensitivePrunedLiveness.cpp ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-move-only-checker"
#include "swift/SIL/FieldSensitivePrunedLiveness.h"
#include "swift/AST/TypeExpansionContext.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/SmallBitVector.h"
#include "swift/SIL/BasicBlockDatastructures.h"
#include "swift/SIL/BasicBlockUtils.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/ScopedAddressUtils.h"
#include "swift/SIL/Test.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"
using namespace swift;
static llvm::cl::opt<bool> EmitLogging(
"sil-move-only-checker-emit-pruned-liveness-logging");
#define PRUNED_LIVENESS_LOG(X) \
do { \
if (EmitLogging) { \
LLVM_DEBUG(X); \
} \
} while (0)
// We can only analyze components of structs whose storage is fully accessible
// from Swift.
static StructDecl *getFullyReferenceableStruct(SILType ktypeTy) {
auto structDecl = ktypeTy.getStructOrBoundGenericStruct();
if (!structDecl || structDecl->hasUnreferenceableStorage())
return nullptr;
return structDecl;
}
//===----------------------------------------------------------------------===//
// MARK: TypeSubElementCount
//===----------------------------------------------------------------------===//
TypeSubElementCount::TypeSubElementCount(SILType type, SILModule &mod,
TypeExpansionContext context)
: number(1) {
if (auto tupleType = type.getAs<TupleType>()) {
unsigned numElements = 0;
for (auto index : indices(tupleType.getElementTypes()))
numElements +=
TypeSubElementCount(type.getTupleElementType(index), mod, context);
number = numElements;
return;
}
if (auto *structDecl = getFullyReferenceableStruct(type)) {
unsigned numElements = 0;
for (auto *fieldDecl : structDecl->getStoredProperties())
numElements += TypeSubElementCount(
type.getFieldType(fieldDecl, mod, context), mod, context);
number = numElements;
// If we do not have any elements, just set our size to 1.
if (number == 0)
number = 1;
if (type.isValueTypeWithDeinit()) {
// 'self' has its own liveness represented as an additional field at the
// end of the structure.
++number;
}
return;
}
if (auto *enumDecl = type.getEnumOrBoundGenericEnum()) {
unsigned numElements = 0;
for (auto *eltDecl : enumDecl->getAllElements()) {
if (!eltDecl->hasAssociatedValues())
continue;
auto elt = type.getEnumElementType(eltDecl, mod, context);
numElements += unsigned(TypeSubElementCount(elt, mod, context));
}
number = numElements + 1;
if (type.isValueTypeWithDeinit()) {
// 'self' has its own liveness represented as an additional field at the
// end of the structure.
++number;
}
return;
}
// If this isn't a tuple, struct, or enum, it is a single element. This was
// our default value, so we can just return.
}
TypeSubElementCount::TypeSubElementCount(SILValue value) : number(1) {
auto whole = TypeSubElementCount(value->getType(), *value->getModule(),
TypeExpansionContext(*value->getFunction()));
// The value produced by a drop_deinit has one fewer subelement than that of
// its type--the deinit bit is not included.
if (isa<DropDeinitInst>(value)) {
assert(value->getType().isValueTypeWithDeinit());
whole = whole - 1;
}
number = whole;
}
//===----------------------------------------------------------------------===//
// MARK: SubElementNumber
//===----------------------------------------------------------------------===//
std::optional<SubElementOffset>
SubElementOffset::computeForAddress(SILValue projectionDerivedFromRoot,
SILValue rootAddress) {
unsigned finalSubElementOffset = 0;
SILModule &mod = *rootAddress->getModule();
LLVM_DEBUG(llvm::dbgs() << "computing element offset for root:\n";
rootAddress->print(llvm::dbgs()));
while (1) {
LLVM_DEBUG(llvm::dbgs() << "projection: ";
projectionDerivedFromRoot->print(llvm::dbgs()));
// If we got to the root, we're done.
if (rootAddress == projectionDerivedFromRoot)
return {SubElementOffset(finalSubElementOffset)};
if (auto *pbi = dyn_cast<ProjectBoxInst>(projectionDerivedFromRoot)) {
projectionDerivedFromRoot = pbi->getOperand();
continue;
}
if (auto *bai = dyn_cast<BeginAccessInst>(projectionDerivedFromRoot)) {
projectionDerivedFromRoot = bai->getSource();
continue;
}
if (auto *sbi = dyn_cast<StoreBorrowInst>(projectionDerivedFromRoot)) {
projectionDerivedFromRoot = sbi->getDest();
continue;
}
if (auto *m = dyn_cast<MoveOnlyWrapperToCopyableAddrInst>(
projectionDerivedFromRoot)) {
projectionDerivedFromRoot = m->getOperand();
continue;
}
if (auto *oea =
dyn_cast<OpenExistentialAddrInst>(projectionDerivedFromRoot)) {
projectionDerivedFromRoot = oea->getOperand();
continue;
}
if (auto *iea =
dyn_cast<InitExistentialAddrInst>(projectionDerivedFromRoot)) {
projectionDerivedFromRoot = iea->getOperand();
continue;
}
if (auto *teai =
dyn_cast<TupleElementAddrInst>(projectionDerivedFromRoot)) {
SILType tupleType = teai->getOperand()->getType();
// Keep track of what subelement is being referenced.
for (unsigned i : range(teai->getFieldIndex())) {
finalSubElementOffset += TypeSubElementCount(
tupleType.getTupleElementType(i), mod,
TypeExpansionContext(*rootAddress->getFunction()));
}
projectionDerivedFromRoot = teai->getOperand();
continue;
}
if (auto *seai =
dyn_cast<StructElementAddrInst>(projectionDerivedFromRoot)) {
SILType type = seai->getOperand()->getType();
// Keep track of what subelement is being referenced.
StructDecl *structDecl = seai->getStructDecl();
for (auto *fieldDecl : structDecl->getStoredProperties()) {
if (fieldDecl == seai->getField())
break;
auto context = TypeExpansionContext(*rootAddress->getFunction());
finalSubElementOffset += TypeSubElementCount(
type.getFieldType(fieldDecl, mod, context), mod, context);
}
projectionDerivedFromRoot = seai->getOperand();
continue;
}
if (auto *enumData = dyn_cast<UncheckedTakeEnumDataAddrInst>(
projectionDerivedFromRoot)) {
auto ty = enumData->getOperand()->getType();
auto *enumDecl = enumData->getEnumDecl();
for (auto *element : enumDecl->getAllElements()) {
if (!element->hasAssociatedValues())
continue;
if (element == enumData->getElement())
break;
auto context = TypeExpansionContext(*rootAddress->getFunction());
auto elementTy = ty.getEnumElementType(element, mod, context);
finalSubElementOffset +=
unsigned(TypeSubElementCount(elementTy, mod, context));
}
projectionDerivedFromRoot = enumData->getOperand();
continue;
}
// Init enum data addr is treated like unchecked take enum data addr.
if (auto *initData =
dyn_cast<InitEnumDataAddrInst>(projectionDerivedFromRoot)) {
projectionDerivedFromRoot = initData->getOperand();
continue;
}
// A drop_deinit consumes the "self" bit at the end of its type. The offset
// is still to the beginning.
if (auto dd = dyn_cast<DropDeinitInst>(projectionDerivedFromRoot)) {
projectionDerivedFromRoot = dd->getOperand();
continue;
}
// Look through wrappers.
if (auto c2m = dyn_cast<CopyableToMoveOnlyWrapperAddrInst>(projectionDerivedFromRoot)) {
projectionDerivedFromRoot = c2m->getOperand();
continue;
}
if (auto m2c = dyn_cast<MoveOnlyWrapperToCopyableValueInst>(projectionDerivedFromRoot)) {
projectionDerivedFromRoot = m2c->getOperand();
continue;
}
// If we do not know how to handle this case, just return None.
//
// NOTE: We use to assert here, but since this is used for diagnostics, we
// really do not want to abort. Instead, our caller can choose to abort if
// they get back a None. This ensures that we do not abort in cases where we
// just want to emit to the user a "I do not understand" error.
LLVM_DEBUG(llvm::dbgs() << "unhandled projection derived from root:\n";
projectionDerivedFromRoot->print(llvm::dbgs()));
return std::nullopt;
}
}
std::optional<SubElementOffset>
SubElementOffset::computeForValue(SILValue projectionDerivedFromRoot,
SILValue rootAddress) {
unsigned finalSubElementOffset = 0;
SILModule &mod = *rootAddress->getModule();
while (1) {
// If we got to the root, we're done.
if (rootAddress == projectionDerivedFromRoot)
return {SubElementOffset(finalSubElementOffset)};
// Look through these single operand instructions.
if (isa<BeginBorrowInst>(projectionDerivedFromRoot) ||
isa<CopyValueInst>(projectionDerivedFromRoot) ||
isa<MoveOnlyWrapperToCopyableValueInst>(projectionDerivedFromRoot)) {
projectionDerivedFromRoot =
cast<SingleValueInstruction>(projectionDerivedFromRoot)
->getOperand(0);
continue;
}
if (auto *teai = dyn_cast<TupleExtractInst>(projectionDerivedFromRoot)) {
SILType tupleType = teai->getOperand()->getType();
// Keep track of what subelement is being referenced.
for (unsigned i : range(teai->getFieldIndex())) {
finalSubElementOffset += TypeSubElementCount(
tupleType.getTupleElementType(i), mod,
TypeExpansionContext(*rootAddress->getFunction()));
}
projectionDerivedFromRoot = teai->getOperand();
continue;
}
if (auto *mvir = dyn_cast<MultipleValueInstructionResult>(
projectionDerivedFromRoot)) {
if (auto *dsi = dyn_cast<DestructureStructInst>(mvir->getParent())) {
SILType type = dsi->getOperand()->getType();
// Keep track of what subelement is being referenced.
unsigned resultIndex = mvir->getIndex();
StructDecl *structDecl = dsi->getStructDecl();
for (auto pair : llvm::enumerate(structDecl->getStoredProperties())) {
if (pair.index() == resultIndex)
break;
auto context = TypeExpansionContext(*rootAddress->getFunction());
finalSubElementOffset += TypeSubElementCount(
type.getFieldType(pair.value(), mod, context), mod, context);
}
projectionDerivedFromRoot = dsi->getOperand();
continue;
}
if (auto *dti = dyn_cast<DestructureTupleInst>(mvir->getParent())) {
SILType type = dti->getOperand()->getType();
// Keep track of what subelement is being referenced.
unsigned resultIndex = mvir->getIndex();
for (unsigned i : range(resultIndex)) {
auto context = TypeExpansionContext(*rootAddress->getFunction());
finalSubElementOffset +=
TypeSubElementCount(type.getTupleElementType(i), mod, context);
}
projectionDerivedFromRoot = dti->getOperand();
continue;
}
}
if (auto *seai = dyn_cast<StructExtractInst>(projectionDerivedFromRoot)) {
SILType type = seai->getOperand()->getType();
// Keep track of what subelement is being referenced.
StructDecl *structDecl = seai->getStructDecl();
for (auto *fieldDecl : structDecl->getStoredProperties()) {
if (fieldDecl == seai->getField())
break;
auto context = TypeExpansionContext(*rootAddress->getFunction());
finalSubElementOffset += TypeSubElementCount(
type.getFieldType(fieldDecl, mod, context), mod, context);
}
projectionDerivedFromRoot = seai->getOperand();
continue;
}
// In the case of enums, we note that our representation is:
//
// ---------|Enum| ---
// / \
// / \
// v v
// |Bits for Max Sized Payload| |Discrim Bit|
//
// So our payload is always going to start at the current field number since
// we are the left most child of our parent enum. So we just need to look
// through to our parent enum.
//
// Enum projections can happen either directly via an unchecked instruction…
if (auto *enumData =
dyn_cast<UncheckedEnumDataInst>(projectionDerivedFromRoot)) {
projectionDerivedFromRoot = enumData->getOperand();
continue;
}
// …or via the bb arg of a `switch_enum` successor.
if (auto bbArg = dyn_cast<SILArgument>(projectionDerivedFromRoot)) {
if (auto pred = bbArg->getParent()->getSinglePredecessorBlock()) {
if (auto switchEnum = dyn_cast<SwitchEnumInst>(pred->getTerminator())) {
projectionDerivedFromRoot = switchEnum->getOperand();
continue;
}
}
}
// If we do not know how to handle this case, just return None.
//
// NOTE: We use to assert here, but since this is used for diagnostics, we
// really do not want to abort. Instead, our caller can choose to abort if
// they get back a None. This ensures that we do not abort in cases where we
// just want to emit to the user a "I do not understand" error.
return std::nullopt;
}
}
//===----------------------------------------------------------------------===//
// MARK: TypeTreeLeafTypeRange
//===----------------------------------------------------------------------===//
/// Whether \p targetInst is dominated by one of the provided switch_enum_addr's
/// destination blocks whose corresponding enum element has no associated values
/// which need to be destroyed (i.e. either it has no associated values or they
/// are trivial).
static bool isDominatedByPayloadlessSwitchEnumAddrDests(
SILInstruction *targetInst, ArrayRef<SwitchEnumAddrInst *> seais,
DominanceInfo *domTree) {
if (seais.empty())
return false;
auto *target = targetInst->getParent();
for (auto *seai : seais) {
if (!domTree->dominates(seai, targetInst)) {
continue;
}
auto size = seai->getNumCases();
auto ty = seai->getOperand()->getType();
for (unsigned index = 0; index < size; ++index) {
auto pair = seai->getCase(index);
auto *eltDecl = pair.first;
if (eltDecl->hasAssociatedValues()) {
auto eltTy = ty.getEnumElementType(eltDecl, seai->getFunction());
if (!eltTy.isTrivial(*seai->getFunction())) {
continue;
}
}
auto *block = pair.second;
if (domTree->dominates(block, target))
return true;
}
}
return false;
}
void TypeTreeLeafTypeRange::constructFilteredProjections(
SILValue value, SILInstruction *insertPt, SmallBitVector &filterBitVector,
DominanceInfo *domTree,
llvm::function_ref<bool(SILValue, TypeTreeLeafTypeRange, NeedsDestroy_t)>
callback) {
auto *fn = insertPt->getFunction();
SILType type = value->getType();
auto loc =
(insertPt->getLoc().getKind() != SILLocation::ArtificialUnreachableKind)
? insertPt->getLoc()
: RegularLocation::getAutoGeneratedLocation();
PRUNED_LIVENESS_LOG(llvm::dbgs() << "ConstructFilteredProjection. Bv: "
<< filterBitVector << '\n');
SILBuilderWithScope builder(insertPt);
auto noneSet = [](SmallBitVector &bv, unsigned start, unsigned end) {
return llvm::none_of(range(start, end),
[&](unsigned index) { return bv[index]; });
};
auto allSet = [](SmallBitVector &bv, unsigned start, unsigned end) {
return llvm::all_of(range(start, end),
[&](unsigned index) { return bv[index]; });
};
if (auto *structDecl = type.getStructOrBoundGenericStruct()) {
unsigned start = startEltOffset;
for (auto *varDecl : structDecl->getStoredProperties()) {
auto nextType = type.getFieldType(varDecl, fn);
unsigned next = start + TypeSubElementCount(nextType, fn);
// If we do not have any set bits, do not create the struct element addr
// for this entry.
if (noneSet(filterBitVector, start, next)) {
start = next;
continue;
}
auto newValue = builder.createStructElementAddr(loc, value, varDecl);
callback(newValue, TypeTreeLeafTypeRange(start, next), NeedsDestroy);
start = next;
}
if (start == 0) {
++start;
}
if (type.isValueTypeWithDeinit()) {
// 'self' has its own liveness
++start;
}
assert(start == endEltOffset);
return;
}
if (auto *enumDecl = type.getEnumOrBoundGenericEnum()) {
struct ElementRecord {
EnumElementDecl *element;
unsigned start;
unsigned next;
};
SmallVector<ElementRecord, 2> projectedElements;
unsigned runningStart = startEltOffset;
for (auto *eltDecl : enumDecl->getAllElements()) {
if (!eltDecl->hasAssociatedValues())
continue;
auto eltTy = type.getEnumElementType(eltDecl, fn);
unsigned next = runningStart + TypeSubElementCount(eltTy, fn);
if (noneSet(filterBitVector, runningStart, next)) {
runningStart = next;
continue;
}
projectedElements.push_back({eltDecl, runningStart, next});
runningStart = next;
}
assert((runningStart + 1 + (type.isValueTypeWithDeinit() ? 1 : 0)) ==
endEltOffset);
if (!allSet(filterBitVector, startEltOffset, endEltOffset)) {
TinyPtrVector<SwitchEnumAddrInst *> seais;
for (auto record : projectedElements) {
// Find a preexisting unchecked_take_enum_data_addr that dominates
// insertPt.
bool foundProjection = false;
StackList<SILValue> worklist(value->getFunction());
worklist.push_back(value);
while (!worklist.empty()) {
auto v = worklist.pop_back_val();
for (auto *user : v->getUsers()) {
if (auto *ddi = dyn_cast<DropDeinitInst>(user)) {
worklist.push_back(ddi);
continue;
}
if (auto *seai = dyn_cast<SwitchEnumAddrInst>(user)) {
seais.push_back(seai);
}
auto *utedai = dyn_cast<UncheckedTakeEnumDataAddrInst>(user);
if (!utedai) {
continue;
}
if (utedai->getElement() != record.element) {
continue;
}
if (!domTree->dominates(utedai, insertPt)) {
continue;
}
callback(utedai, TypeTreeLeafTypeRange(record.start, record.next),
NeedsDestroy);
foundProjection = true;
}
}
(void)foundProjection;
assert(foundProjection ||
llvm::count_if(
enumDecl->getAllElements(),
[](auto *elt) { return elt->hasAssociatedValues(); }) == 1 ||
isDominatedByPayloadlessSwitchEnumAddrDests(insertPt, seais,
domTree));
}
return;
}
// Then just pass back our enum base value as the pointer.
callback(value, TypeTreeLeafTypeRange(startEltOffset, endEltOffset),
NeedsDestroy);
return;
}
if (auto tupleType = type.getAs<TupleType>()) {
unsigned start = startEltOffset;
for (unsigned index : indices(tupleType.getElementTypes())) {
auto nextType = type.getTupleElementType(index);
unsigned next = start + TypeSubElementCount(nextType, fn);
if (noneSet(filterBitVector, start, next)) {
start = next;
continue;
}
auto newValue = builder.createTupleElementAddr(loc, value, index);
callback(newValue, TypeTreeLeafTypeRange(start, next), NeedsDestroy);
start = next;
}
assert(start == endEltOffset);
return;
}
llvm_unreachable("Not understand subtype");
}
void TypeTreeLeafTypeRange::get(
Operand *op, SILValue rootValue,
SmallVectorImpl<TypeTreeLeafTypeRange> &ranges) {
auto projectedValue = op->get();
auto startEltOffset = SubElementOffset::compute(projectedValue, rootValue);
if (!startEltOffset)
return;
// A drop_deinit only consumes the deinit bit of its operand.
if (isa<DropDeinitInst>(op->getUser())) {
auto upperBound = *startEltOffset + TypeSubElementCount(projectedValue);
ranges.push_back({upperBound - 1, upperBound});
return;
}
// An `inject_enum_addr` only initializes the enum tag.
if (isa<InjectEnumAddrInst>(op->getUser())) {
// Subtract the deinit bit, if any: the discriminator bit is before it:
//
// [ case1 bits ..., case2 bits, ..., discriminator bit, deinit bit ]
auto deinitBits = projectedValue->getType().isValueTypeWithDeinit() ? 1 : 0;
auto upperBound =
*startEltOffset + TypeSubElementCount(projectedValue) - deinitBits;
ranges.push_back({upperBound - 1, upperBound});
return;
}
if (auto *utedai = dyn_cast<UncheckedTakeEnumDataAddrInst>(op->getUser())) {
auto *selected = utedai->getElement();
auto *enumDecl = utedai->getEnumDecl();
unsigned numAtoms = 0;
for (auto *element : enumDecl->getAllElements()) {
if (!element->hasAssociatedValues()) {
continue;
}
auto elementTy = projectedValue->getType().getEnumElementType(
element, op->getFunction());
auto elementAtoms =
unsigned(TypeSubElementCount(elementTy, op->getFunction()));
if (element != selected) {
ranges.push_back({*startEltOffset + numAtoms,
*startEltOffset + numAtoms + elementAtoms});
}
numAtoms += elementAtoms;
}
// The discriminator bit is consumed.
ranges.push_back(
{*startEltOffset + numAtoms, *startEltOffset + numAtoms + 1});
// The deinit bit is _not_ consumed. A drop_deinit is required to
// consumingly switch an enum with a deinit.
return;
}
// Uses that borrow a value do not involve the deinit bit.
//
// FIXME: This shouldn't be limited to applies.
unsigned deinitBitOffset = 0;
if (op->get()->getType().isValueTypeWithDeinit() &&
op->getOperandOwnership() == OperandOwnership::Borrow &&
ApplySite::isa(op->getUser())) {
deinitBitOffset = 1;
}
ranges.push_back({*startEltOffset, *startEltOffset +
TypeSubElementCount(projectedValue) -
deinitBitOffset});
}
void TypeTreeLeafTypeRange::constructProjectionsForNeededElements(
SILValue rootValue, SILInstruction *insertPt, DominanceInfo *domTree,
SmallBitVector &neededElements,
SmallVectorImpl<std::tuple<SILValue, TypeTreeLeafTypeRange, NeedsDestroy_t>>
&resultingProjections) {
TypeTreeLeafTypeRange rootRange(rootValue);
(void)rootRange;
assert(rootRange.size() == neededElements.size());
StackList<std::tuple<SILValue, TypeTreeLeafTypeRange, NeedsDestroy_t>>
worklist(insertPt->getFunction());
worklist.push_back({rootValue, rootRange, NeedsDestroy});
// Temporary vector we use for our computation.
SmallBitVector tmp(neededElements.size());
auto allInRange = [](const SmallBitVector &bv, TypeTreeLeafTypeRange span) {
return llvm::all_of(span.getRange(),
[&bv](unsigned index) { return bv[index]; });
};
while (!worklist.empty()) {
auto pair = worklist.pop_back_val();
SILValue value;
TypeTreeLeafTypeRange range;
NeedsDestroy_t needsDestroy;
std::tie(value, range, needsDestroy) = pair;
tmp.reset();
tmp.set(range.startEltOffset, range.endEltOffset);
tmp &= neededElements;
// If we do not have any unpaired bits in this range, just continue... we do
// not have any further work to do.
if (tmp.none()) {
continue;
}
// Otherwise, we had some sort of overlap. First lets see if we have
// everything set in the range. In that case, we just add this range to the
// result and continue.
if (allInRange(tmp, range)) {
resultingProjections.emplace_back(value, range, needsDestroy);
continue;
}
// Otherwise, we have a partial range. We need to split our range and then
// recursively process those ranges looking for subranges that have
// completely set bits.
range.constructFilteredProjections(
value, insertPt, neededElements, domTree,
[&](SILValue subType, TypeTreeLeafTypeRange range,
NeedsDestroy_t needsDestroy) -> bool {
worklist.push_back({subType, range, needsDestroy});
return true;
});
}
}
void TypeTreeLeafTypeRange::visitContiguousRanges(
SmallBitVector const &bits,
llvm::function_ref<void(TypeTreeLeafTypeRange)> callback) {
if (bits.size() == 0)
return;
std::optional<unsigned> current = std::nullopt;
for (unsigned bit = 0, size = bits.size(); bit < size; ++bit) {
auto isSet = bits.test(bit);
if (current) {
if (!isSet) {
callback(TypeTreeLeafTypeRange(*current, bit));
current = std::nullopt;
}
} else if (isSet) {
current = bit;
}
}
if (current) {
callback(TypeTreeLeafTypeRange(*current, bits.size()));
}
}
//===----------------------------------------------------------------------===//
// MARK: FieldSensitivePrunedLiveBlocks
//===----------------------------------------------------------------------===//
void FieldSensitivePrunedLiveBlocks::computeScalarUseBlockLiveness(
SILBasicBlock *userBB, unsigned bitNo) {
// If, we are visiting this block, then it is not already LiveOut. Mark it
// LiveWithin to indicate a liveness boundary within the block.
markBlockLive(userBB, bitNo, LiveWithin);
BasicBlockWorklist worklist(userBB->getFunction());
worklist.push(userBB);
while (auto *block = worklist.pop()) {
// The popped `bb` is live; now mark all its predecessors LiveOut.
//
// Traversal terminates at any previously visited block, including the
// blocks initialized as definition blocks.
for (auto *predBlock : block->getPredecessorBlocks()) {
switch (getBlockLiveness(predBlock, bitNo)) {
case Dead:
worklist.pushIfNotVisited(predBlock);
LLVM_FALLTHROUGH;
case LiveWithin:
markBlockLive(predBlock, bitNo, LiveOut);
break;
case DeadToLiveEdge:
case LiveOut:
break;
}
}
}
}
/// Update the current def's liveness based on one specific use instruction.
///
/// Return the updated liveness of the \p use block (LiveOut or LiveWithin).
///
/// Terminators are not live out of the block.
void FieldSensitivePrunedLiveBlocks::updateForUse(
SILInstruction *user, unsigned startBitNo, unsigned endBitNo,
SmallBitVector const &useBeforeDefBits,
SmallVectorImpl<IsLive> &resultingLivenessInfo) {
assert(isInitialized());
resultingLivenessInfo.clear();
SWIFT_ASSERT_ONLY(seenUse = true);
auto *bb = user->getParent();
getBlockLiveness(bb, startBitNo, endBitNo, resultingLivenessInfo);
assert(resultingLivenessInfo.size() == (endBitNo - startBitNo));
for (unsigned index : indices(resultingLivenessInfo)) {
unsigned specificBitNo = startBitNo + index;
auto isUseBeforeDef = useBeforeDefBits.test(specificBitNo);
switch (resultingLivenessInfo[index]) {
case LiveOut:
case LiveWithin:
if (!isUseBeforeDef) {
continue;
} else {
LLVM_FALLTHROUGH;
}
case DeadToLiveEdge:
case Dead: {
// This use block has not yet been marked live. Mark it and its
// predecessor blocks live.
computeScalarUseBlockLiveness(bb, specificBitNo);
resultingLivenessInfo[index] = getBlockLiveness(bb, specificBitNo);
continue;
}
}
llvm_unreachable("covered switch");
}
}
llvm::StringRef
FieldSensitivePrunedLiveBlocks::getStringRef(IsLive isLive) const {
switch (isLive) {
case Dead:
return "Dead";
case LiveWithin:
return "LiveWithin";
case DeadToLiveEdge:
return "DeadToLiveEdge";
case LiveOut:
return "LiveOut";
}
llvm_unreachable("Covered switch?!");
}
void FieldSensitivePrunedLiveBlocks::print(llvm::raw_ostream &OS) const {
if (!discoveredBlocks) {
OS << "No deterministic live block list\n";
return;
}
SmallVector<IsLive, 8> isLive;
for (auto *block : *discoveredBlocks) {
block->printAsOperand(OS);
OS << ": ";
for (unsigned i : range(getNumBitsToTrack()))
OS << getStringRef(this->getBlockLiveness(block, i)) << ", ";
OS << "\n";
}
}
void FieldSensitivePrunedLiveBlocks::dump() const { print(llvm::dbgs()); }
//===----------------------------------------------------------------------===//
// FieldSensitivePrunedLivenessBoundary
//===----------------------------------------------------------------------===//
void FieldSensitivePrunedLivenessBoundary::print(llvm::raw_ostream &OS) const {
for (auto pair : lastUsers) {
auto *user = pair.first;
auto bits = pair.second;
OS << "last user: " << *user
<< "\tat " << bits << "\n";
}
for (auto pair : boundaryEdges) {
auto *block = pair.first;
auto bits = pair.second;
OS << "boundary edge: ";
block->printAsOperand(OS);
OS << "\n" << "\tat " << bits << "\n";
}
if (!deadDefs.empty()) {
for (auto pair : deadDefs) {
auto *deadDef = pair.first;
auto bits = pair.second;
OS << "dead def: " << *deadDef
<< "\tat " << bits << "\n";
}
}
}
void FieldSensitivePrunedLivenessBoundary::dump() const {
print(llvm::dbgs());
}
//===----------------------------------------------------------------------===//
// MARK: FieldSensitiveLiveness
//===----------------------------------------------------------------------===//
void FieldSensitivePrunedLiveness::updateForUse(
SILInstruction *user, TypeTreeLeafTypeRange range, bool lifetimeEnding,
SmallBitVector const &useBeforeDefBits) {
SmallVector<FieldSensitivePrunedLiveBlocks::IsLive, 8> resultingLiveness;
liveBlocks.updateForUse(user, range.startEltOffset, range.endEltOffset,
useBeforeDefBits, resultingLiveness);
addInterestingUser(user, range, lifetimeEnding);
}
void FieldSensitivePrunedLiveness::updateForUse(
SILInstruction *user, SmallBitVector const &bits, bool lifetimeEnding,
SmallBitVector const &useBeforeDefBits) {
for (auto bit : bits.set_bits()) {
liveBlocks.updateForUse(user, bit, useBeforeDefBits.test(bit));
}
addInterestingUser(user, bits, lifetimeEnding);
}
void FieldSensitivePrunedLiveness::extendToNonUse(
SILInstruction *user, TypeTreeLeafTypeRange range,
SmallBitVector const &useBeforeDefBits) {
SmallVector<FieldSensitivePrunedLiveBlocks::IsLive, 8> resultingLiveness;
liveBlocks.updateForUse(user, range.startEltOffset, range.endEltOffset,
useBeforeDefBits, resultingLiveness);
extendToNonUse(user, range);
}
void FieldSensitivePrunedLiveness::extendToNonUse(
SILInstruction *user, SmallBitVector const &bits,
SmallBitVector const &useBeforeDefBits) {
for (auto bit : bits.set_bits()) {
liveBlocks.updateForUse(user, bit, useBeforeDefBits.test(bit));
}
extendToNonUse(user, bits);
}
void FieldSensitivePrunedLiveness::print(llvm::raw_ostream &os) const {
liveBlocks.print(os);
for (auto &userAndInterest : users) {
for (size_t bit = 0, size = userAndInterest.second.liveBits.size();
bit < size; ++bit) {
auto isLive = userAndInterest.second.liveBits.test(bit);
auto isConsuming = userAndInterest.second.consumingBits.test(bit);
if (!isLive && !isConsuming) {
continue;
} else if (!isLive && isConsuming) {
os << "non-user: ";
} else if (isLive && isConsuming) {
os << "lifetime-ending user: ";
} else if (isLive && !isConsuming) {
os << "regular user: ";
}
os << *userAndInterest.first << "\tat " << bit << "\n";
}
}
}
namespace swift::test {
// Arguments:
// - SILValue: def whose pruned liveness will be calculated
// - the string "uses:"
// - variadic list of live-range user instructions
// Dumps:
// -
static FunctionTest FieldSensitiveSSAUseLivenessTest(
"fs_ssa_use_liveness", [](auto &function, auto &arguments, auto &test) {
auto value = arguments.takeValue();
auto begin = (unsigned)arguments.takeUInt();
auto end = (unsigned)arguments.takeUInt();
SmallVector<SILBasicBlock *, 8> discoveredBlocks;
FieldSensitiveSSAPrunedLiveRange liveness(&function, &discoveredBlocks);
liveness.init(value);
liveness.initializeDef(value, TypeTreeLeafTypeRange(begin, end));
auto argument = arguments.takeArgument();
if (cast<StringArgument>(argument).getValue() != "uses:") {
llvm::report_fatal_error(
"test specification expects the 'uses:' label\n");
}
while (arguments.hasUntaken()) {
auto *inst = arguments.takeInstruction();
auto kindString = arguments.takeString();
enum Kind {
NonUse,
Ending,
NonEnding,
};
auto kind = llvm::StringSwitch<std::optional<Kind>>(kindString)
.Case("non-use", Kind::NonUse)
.Case("ending", Kind::Ending)
.Case("non-ending", Kind::NonEnding)
.Default(std::nullopt);
if (!kind.has_value()) {
llvm::errs() << "Unknown kind: " << kindString << "\n";
llvm::report_fatal_error("Bad user kind. Value must be one of "
"'non-use', 'ending', 'non-ending'");
}
auto begin = (unsigned)arguments.takeUInt();
auto end = (unsigned)arguments.takeUInt();
switch (kind.value()) {
case Kind::NonUse:
liveness.extendToNonUse(inst, TypeTreeLeafTypeRange(begin, end));
break;
case Kind::Ending:
liveness.updateForUse(inst, TypeTreeLeafTypeRange(begin, end),
/*lifetimeEnding*/ true);
break;
case Kind::NonEnding:
liveness.updateForUse(inst, TypeTreeLeafTypeRange(begin, end),
/*lifetimeEnding*/ false);
break;
}
}
liveness.print(llvm::outs());
FieldSensitivePrunedLivenessBoundary boundary(1);
liveness.computeBoundary(boundary);
boundary.print(llvm::outs());
});
} // end namespace swift::test
//===----------------------------------------------------------------------===//
// MARK: FieldSensitivePrunedLiveRange
//===----------------------------------------------------------------------===//