-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathDIMemoryUseCollector.cpp
2168 lines (1859 loc) · 79.1 KB
/
DIMemoryUseCollector.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
//===--- DIMemoryUseCollector.cpp -----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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 "definite-init"
#include "DIMemoryUseCollector.h"
#include "swift/AST/Expr.h"
#include "swift/Basic/Assertions.h"
#include "swift/SIL/ApplySite.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SILOptimizer/Utils/DistributedActor.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
using namespace ownership;
//===----------------------------------------------------------------------===//
// Utility
//===----------------------------------------------------------------------===//
static bool isVariableOrResult(MarkUninitializedInst *MUI) {
return MUI->isVar() || MUI->isOut();
}
static void gatherDestroysOfContainer(const DIMemoryObjectInfo &memoryInfo,
DIElementUseInfo &useInfo) {
auto *uninitMemory = memoryInfo.getUninitializedValue();
// The uninitMemory must be used on an alloc_box, alloc_stack, or global_addr.
// If we have an alloc_stack or a global_addr, there is nothing further to do.
if (isa<AllocStackInst>(uninitMemory->getOperand(0)) ||
isa<GlobalAddrInst>(uninitMemory->getOperand(0)) ||
isa<SILArgument>(uninitMemory->getOperand(0)) ||
// FIXME: We only support pointer to address here to not break LLDB. It is
// important that long term we get rid of this since this is a situation
// where LLDB is breaking SILGen/DI invariants by not creating a new
// independent stack location for the pointer to address.
isa<PointerToAddressInst>(uninitMemory->getOperand(0))) {
return;
}
// Otherwise, we assume that we have an alloc_box. Treat destroys of the
// alloc_box as load+destroys of the value stored in the box.
//
// TODO: This should really be tracked separately from other destroys so that
// we distinguish the lifetime of the container from the value itself.
assert(isa<ProjectBoxInst>(uninitMemory));
auto value = uninitMemory->getOperand(0);
if (auto *bbi = dyn_cast<BeginBorrowInst>(value)) {
value = bbi->getOperand();
}
auto *mui = cast<MarkUninitializedInst>(value);
for (auto *user : mui->getUsersOfType<DestroyValueInst>()) {
useInfo.trackDestroy(user);
}
}
//===----------------------------------------------------------------------===//
// DIMemoryObjectInfo Implementation
//===----------------------------------------------------------------------===//
static unsigned getElementCountRec(TypeExpansionContext context,
SILModule &Module, SILType T,
bool IsSelfOfNonDelegatingInitializer) {
// If this is a tuple, it is always recursively flattened.
if (CanTupleType TT = T.getAs<TupleType>()) {
assert(!IsSelfOfNonDelegatingInitializer && "self never has tuple type");
unsigned NumElements = 0;
for (unsigned i = 0, e = TT->getNumElements(); i < e; ++i)
NumElements +=
getElementCountRec(context, Module, T.getTupleElementType(i), false);
return NumElements;
}
// If this is the top level of a 'self' value, we flatten structs and classes.
// Stored properties with tuple types are tracked with independent lifetimes
// for each of the tuple members.
if (IsSelfOfNonDelegatingInitializer) {
// Protocols never have a stored properties.
if (auto *NTD = T.getNominalOrBoundGenericNominal()) {
unsigned NumElements = 0;
for (auto *VD : NTD->getStoredProperties())
NumElements += getElementCountRec(
context, Module, T.getFieldType(VD, Module, context), false);
for (auto *P : NTD->getInitAccessorProperties()) {
auto *init = P->getAccessor(AccessorKind::Init);
if (init->getInitializedProperties().empty())
++NumElements;
}
return NumElements;
}
}
// Otherwise, it is a single element.
return 1;
}
static std::pair<SILType, bool>
computeMemorySILType(MarkUninitializedInst *MUI, SILValue Address) {
// Compute the type of the memory object.
SILType MemorySILType = Address->getType().getObjectType();
// If this is a let variable we're initializing, remember this so we don't
// allow reassignment.
if (!isVariableOrResult(MUI))
return {MemorySILType, false};
auto *VDecl = MUI->getLoc().getAsASTNode<VarDecl>();
if (!VDecl)
return {MemorySILType, false};
return {MemorySILType, VDecl->isLet()};
}
DIMemoryObjectInfo::DIMemoryObjectInfo(MarkUninitializedInst *MI)
: MemoryInst(MI) {
auto &Module = MI->getModule();
SILValue Address = MemoryInst;
if (auto BBI = MemoryInst->getSingleUserOfType<BeginBorrowInst>()) {
if (auto PBI = BBI->getSingleUserOfType<ProjectBoxInst>()) {
IsBox = true;
Address = PBI;
}
}
if (auto PBI = MemoryInst->getSingleUserOfType<ProjectBoxInst>()) {
IsBox = true;
Address = PBI;
}
std::tie(MemorySILType, IsLet) = computeMemorySILType(MI, Address);
// Compute the number of elements to track in this memory object.
// If this is a 'self' in a delegating initializer, we only track one bit:
// whether self.init is called or not.
if (isDelegatingInit()) {
NumElements = 1;
return;
}
// If this is a derived class init method for which stored properties are
// separately initialized, track an element for the super.init call.
if (isDerivedClassSelfOnly()) {
NumElements = 1;
return;
}
// Otherwise, we break down the initializer.
NumElements =
getElementCountRec(TypeExpansionContext(*MI->getFunction()), Module,
MemorySILType, isNonDelegatingInit());
// If this is a derived class init method, track an extra element to determine
// whether super.init has been called at each program point.
NumElements += unsigned(isDerivedClassSelf());
// Make sure we track /something/ in a cross-module struct initializer.
if (NumElements == 0 && isCrossModuleStructInitSelf()) {
NumElements = 1;
HasDummyElement = true;
}
}
SILInstruction *DIMemoryObjectInfo::getFunctionEntryPoint() const {
return &*getFunction().begin()->begin();
}
static SingleValueInstruction *
getUninitializedValue(MarkUninitializedInst *MemoryInst) {
SILValue inst = MemoryInst;
if (auto *bbi = MemoryInst->getSingleUserOfType<BeginBorrowInst>()) {
inst = bbi;
}
if (SingleValueInstruction *svi =
inst->getSingleUserOfType<ProjectBoxInst>()) {
return svi;
}
return MemoryInst;
}
SingleValueInstruction *DIMemoryObjectInfo::getUninitializedValue() const {
return ::getUninitializedValue(MemoryInst);
}
/// Given a symbolic element number, return the type of the element.
static SILType getElementTypeRec(TypeExpansionContext context,
SILModule &Module, SILType T, unsigned EltNo,
bool IsSelfOfNonDelegatingInitializer) {
// If this is a tuple type, walk into it.
if (CanTupleType TT = T.getAs<TupleType>()) {
assert(!IsSelfOfNonDelegatingInitializer && "self never has tuple type");
for (unsigned i = 0, e = TT->getNumElements(); i < e; ++i) {
auto FieldType = T.getTupleElementType(i);
unsigned NumFieldElements =
getElementCountRec(context, Module, FieldType, false);
if (EltNo < NumFieldElements)
return getElementTypeRec(context, Module, FieldType, EltNo, false);
EltNo -= NumFieldElements;
}
// This can only happen if we look at a symbolic element number of an empty
// tuple.
llvm::report_fatal_error("invalid element number");
}
// If this is the top level of a 'self' value, we flatten structs and classes.
// Stored properties with tuple types are tracked with independent lifetimes
// for each of the tuple members.
if (IsSelfOfNonDelegatingInitializer) {
if (auto *NTD = T.getNominalOrBoundGenericNominal()) {
bool HasStoredProperties = false;
for (auto *VD : NTD->getStoredProperties()) {
HasStoredProperties = true;
auto FieldType = T.getFieldType(VD, Module, context);
unsigned NumFieldElements =
getElementCountRec(context, Module, FieldType, false);
if (EltNo < NumFieldElements)
return getElementTypeRec(context, Module, FieldType, EltNo, false);
EltNo -= NumFieldElements;
}
// If we do not have any stored properties and were passed an EltNo of 0,
// just return self.
if (!HasStoredProperties && EltNo == 0) {
return T;
}
llvm::report_fatal_error("invalid element number");
}
}
// Otherwise, it is a leaf element.
assert(EltNo == 0);
return T;
}
/// getElementTypeRec - Return the swift type of the specified element.
SILType DIMemoryObjectInfo::getElementType(unsigned EltNo) const {
auto &Module = MemoryInst->getModule();
return getElementTypeRec(TypeExpansionContext(*MemoryInst->getFunction()),
Module, MemorySILType, EltNo, isNonDelegatingInit());
}
/// During tear-down of a distributed actor, we must invoke its
/// \p actorSystem.resignID method, passing in the \p id from the
/// instance. Thus, this function inspects the VarDecl about to be destroyed
/// and if it matches the \p id, the \p resignIdentity call is emitted.
///
/// NOTE (id-before-actorSystem): it is crucial that the \p id is
/// deinitialized before the \p actorSystem is deinitialized, because
/// resigning the identity requires a call into the \p actorSystem.
/// Since deinitialization consistently happens in-order, according to the
/// listing returned by \p NominalTypeDecl::getStoredProperties
/// it is important the VarDecl for the \p id is synthesized before
/// the \p actorSystem so that we get the right ordering in DI and deinits.
///
/// \param nomDecl a distributed actor decl
/// \param var a VarDecl that is a member of the \p nomDecl
static void tryToResignIdentity(SILLocation loc, SILBuilder &B,
NominalTypeDecl* nomDecl, VarDecl *var,
SILValue idRef, SILValue actorInst) {
assert(nomDecl->isDistributedActor());
if (var != nomDecl->getDistributedActorIDProperty())
return;
emitResignIdentityCall(B, loc, cast<ClassDecl>(nomDecl),
actorInst, idRef);
}
/// Given a tuple element number (in the flattened sense) return a pointer to a
/// leaf element of the specified number, so we can insert destroys for it.
SILValue DIMemoryObjectInfo::emitElementAddressForDestroy(
unsigned EltNo, SILLocation Loc, SILBuilder &B,
SmallVectorImpl<std::pair<SILValue, EndScopeKind>> &EndScopeList) const {
SILValue Ptr = getUninitializedValue();
bool IsSelf = isNonDelegatingInit();
auto &Module = MemoryInst->getModule();
auto PointeeType = MemorySILType;
while (1) {
// If we have a tuple, flatten it.
if (CanTupleType TT = PointeeType.getAs<TupleType>()) {
assert(!IsSelf && "self never has tuple type");
// Figure out which field we're walking into.
unsigned FieldNo = 0;
for (unsigned i = 0, e = TT->getNumElements(); i < e; ++i) {
auto EltTy = PointeeType.getTupleElementType(i);
unsigned NumSubElt = getElementCountRec(
TypeExpansionContext(B.getFunction()), Module, EltTy, false);
if (EltNo < NumSubElt) {
Ptr = B.createTupleElementAddr(Loc, Ptr, FieldNo);
PointeeType = EltTy;
break;
}
EltNo -= NumSubElt;
++FieldNo;
}
continue;
}
// If this is the top level of a 'self' value, we flatten structs and
// classes. Stored properties with tuple types are tracked with independent
// lifetimes for each of the tuple members.
if (IsSelf) {
if (auto *NTD = PointeeType.getNominalOrBoundGenericNominal()) {
const bool IsDistributedActor = NTD->isDistributedActor();
bool HasStoredProperties = false;
for (auto *VD : NTD->getStoredProperties()) {
if (!HasStoredProperties) {
HasStoredProperties = true;
// If we have a class, we can use a borrow directly and avoid ref
// count traffic.
if (isa<ClassDecl>(NTD) && Ptr->getType().isAddress()) {
SILValue Borrowed = Ptr = B.createLoadBorrow(Loc, Ptr);
EndScopeList.emplace_back(Borrowed, EndScopeKind::Borrow);
}
}
auto expansionContext = TypeExpansionContext(B.getFunction());
auto FieldType =
PointeeType.getFieldType(VD, Module, expansionContext);
unsigned NumFieldElements =
getElementCountRec(expansionContext, Module, FieldType, false);
if (EltNo < NumFieldElements) {
if (isa<StructDecl>(NTD)) {
Ptr = B.createStructElementAddr(Loc, Ptr, VD);
} else {
assert(isa<ClassDecl>(NTD));
SILValue Original, Borrowed;
if (Ptr->getOwnershipKind() != OwnershipKind::Guaranteed) {
Original = Ptr;
Borrowed = Ptr = B.createBeginBorrow(Loc, Ptr);
EndScopeList.emplace_back(Borrowed, EndScopeKind::Borrow);
}
SILValue Self = Ptr;
Ptr = B.createRefElementAddr(Loc, Ptr, VD);
Ptr = B.createBeginAccess(
Loc, Ptr, SILAccessKind::Deinit, SILAccessEnforcement::Static,
false /*noNestedConflict*/, false /*fromBuiltin*/);
if (IsDistributedActor)
tryToResignIdentity(Loc, B, NTD, VD, Ptr, Self);
EndScopeList.emplace_back(Ptr, EndScopeKind::Access);
}
PointeeType = FieldType;
IsSelf = false;
break;
}
EltNo -= NumFieldElements;
}
if (!HasStoredProperties) {
assert(EltNo == 0 && "Element count problem");
return Ptr;
}
continue;
}
}
// Have we gotten to our leaf element?
assert(EltNo == 0 && "Element count problem");
return Ptr;
}
}
/// Push the symbolic path name to the specified element number onto the
/// specified std::string.
static void getPathStringToElementRec(TypeExpansionContext context,
SILModule &Module, SILType T,
unsigned EltNo, std::string &Result) {
CanTupleType TT = T.getAs<TupleType>();
if (!TT) {
// Otherwise, there are no subelements.
assert(EltNo == 0 && "Element count problem");
return;
}
unsigned FieldNo = 0;
for (unsigned i = 0, e = TT->getNumElements(); i < e; ++i) {
auto Field = TT->getElement(i);
SILType FieldTy = T.getTupleElementType(i);
unsigned NumFieldElements = getElementCountRec(context, Module, FieldTy, false);
if (EltNo < NumFieldElements) {
Result += '.';
if (Field.hasName())
Result += Field.getName().str();
else
Result += llvm::utostr(FieldNo);
return getPathStringToElementRec(context, Module, FieldTy, EltNo, Result);
}
EltNo -= NumFieldElements;
++FieldNo;
}
llvm_unreachable("Element number is out of range for this type!");
}
ValueDecl *
DIMemoryObjectInfo::getPathStringToElement(unsigned Element,
std::string &Result) const {
auto &Module = MemoryInst->getModule();
if (isAnyInitSelf())
Result = "self";
else if (ValueDecl *VD =
dyn_cast_or_null<ValueDecl>(getLoc().getAsASTNode<Decl>()))
Result = VD->hasName() ? VD->getBaseIdentifier().str() : "_";
else
Result = "<unknown>";
// If this is indexing into a field of 'self', look it up.
auto expansionContext = TypeExpansionContext(*MemoryInst->getFunction());
if (isNonDelegatingInit() && !isDerivedClassSelfOnly()) {
if (auto *NTD = MemorySILType.getNominalOrBoundGenericNominal()) {
bool HasStoredProperty = false;
for (auto *VD : NTD->getStoredProperties()) {
HasStoredProperty = true;
auto FieldType =
MemorySILType.getFieldType(VD, Module, expansionContext);
unsigned NumFieldElements =
getElementCountRec(expansionContext, Module, FieldType, false);
if (Element < NumFieldElements) {
Result += '.';
auto originalProperty = VD->getOriginalWrappedProperty();
if (originalProperty) {
Result += originalProperty->getName().str();
} else {
Result += VD->getName().str();
}
getPathStringToElementRec(expansionContext, Module, FieldType,
Element, Result);
return VD;
}
Element -= NumFieldElements;
}
for (auto *property : NTD->getInitAccessorProperties()) {
auto *init = property->getAccessor(AccessorKind::Init);
if (init->getInitializedProperties().empty()) {
if (Element == 0)
return property;
--Element;
}
}
// If we do not have any stored properties, we have nothing of interest.
if (!HasStoredProperty)
return nullptr;
}
}
// Get the path through a tuple, if relevant.
getPathStringToElementRec(expansionContext, Module, MemorySILType, Element,
Result);
// If we are analyzing a variable, we can generally get the decl associated
// with it.
if (isVariableOrResult(MemoryInst))
return MemoryInst->getLoc().getAsASTNode<VarDecl>();
// Otherwise, we can't.
return nullptr;
}
/// If the specified value is a 'let' property in an initializer, return true.
bool DIMemoryObjectInfo::isElementLetProperty(unsigned Element) const {
// If we aren't representing 'self' in a non-delegating initializer, then we
// can't have 'let' properties.
if (!isNonDelegatingInit())
return IsLet;
auto NTD = MemorySILType.getNominalOrBoundGenericNominal();
if (!NTD) {
// Otherwise, we miscounted elements?
assert(Element == 0 && "Element count problem");
return false;
}
auto &Module = MemoryInst->getModule();
auto expansionContext = TypeExpansionContext(*MemoryInst->getFunction());
for (auto *VD : NTD->getStoredProperties()) {
auto FieldType = MemorySILType.getFieldType(VD, Module, expansionContext);
unsigned NumFieldElements =
getElementCountRec(expansionContext, Module, FieldType, false);
if (Element < NumFieldElements)
return VD->isLet();
Element -= NumFieldElements;
}
for (auto *property : NTD->getInitAccessorProperties()) {
auto *init = property->getAccessor(AccessorKind::Init);
if (init->getInitializedProperties().empty()) {
if (Element == 0)
return !property->getAccessor(AccessorKind::Set);
--Element;
}
}
// Otherwise, we miscounted elements?
assert(Element == 0 && "Element count problem");
return false;
}
SingleValueInstruction *DIMemoryObjectInfo::findUninitializedSelfValue() const {
// If the object is 'self', return its uninitialized value.
if (isAnyInitSelf())
return getUninitializedValue();
// Otherwise we need to scan entry block to find mark_uninitialized
// instruction that belongs to `self`.
auto *BB = getFunction().getEntryBlock();
if (!BB)
return nullptr;
for (auto &I : *BB) {
SILInstruction *Inst = &I;
if (auto *MUI = dyn_cast<MarkUninitializedInst>(Inst)) {
// If instruction is not a local variable, it could only
// be some kind of `self` (root, delegating, derived etc.)
// see \c MarkUninitializedInst::Kind for more details.
if (!isVariableOrResult(MUI))
return ::getUninitializedValue(MUI);
}
}
return nullptr;
}
ConstructorDecl *DIMemoryObjectInfo::getActorInitSelf() const {
// is it 'self'?
if (!isVariableOrResult(MemoryInst)) {
if (auto decl =
dyn_cast_or_null<ClassDecl>(getASTType()->getAnyNominal()))
// is it for an actor?
if (decl->isAnyActor())
if (auto *silFn = MemoryInst->getFunction())
// are we in a constructor?
if (auto *ctor = dyn_cast_or_null<ConstructorDecl>(
silFn->getDeclContext()->getAsDecl()))
return ctor;
}
return nullptr;
}
//===----------------------------------------------------------------------===//
// DIMemoryUse Implementation
//===----------------------------------------------------------------------===//
/// onlyTouchesTrivialElements - Return true if all of the accessed elements
/// have trivial type and the access itself is a trivial instruction.
bool DIMemoryUse::onlyTouchesTrivialElements(
const DIMemoryObjectInfo &MI) const {
// assign_by_wrapper calls functions to assign a value. This is not
// considered as trivial.
if (isa<AssignByWrapperInst>(Inst) || isa<AssignOrInitInst>(Inst))
return false;
auto *F = Inst->getFunction();
for (unsigned i = FirstElement, e = i + NumElements; i != e; ++i) {
// Skip 'super.init' bit
if (i == MI.getNumMemoryElements())
return false;
auto EltTy = MI.getElementType(i);
if (!EltTy.isTrivial(*F))
return false;
}
return true;
}
//===----------------------------------------------------------------------===//
// DIElementUseInfo Implementation
//===----------------------------------------------------------------------===//
void DIElementUseInfo::trackStoreToSelf(SILInstruction *I) {
StoresToSelf.push_back(I);
}
//===----------------------------------------------------------------------===//
// ElementUseCollector Implementation
//===----------------------------------------------------------------------===//
namespace {
/// Gathers information about a specific address and its uses to determine
/// definite initialization.
class ElementUseCollector {
public:
typedef SmallPtrSet<SILFunction *, 8> FunctionSet;
private:
SILModule &Module;
const DIMemoryObjectInfo &TheMemory;
DIElementUseInfo &UseInfo;
FunctionSet &VisitedClosures;
/// IsSelfOfNonDelegatingInitializer - This is true if we're looking at the
/// top level of a 'self' variable in a non-delegating init method.
bool IsSelfOfNonDelegatingInitializer;
/// When walking the use list, if we index into a struct element, keep track
/// of this, so that any indexes into tuple subelements don't affect the
/// element we attribute an access to.
bool InStructSubElement = false;
/// When walking the use list, if we index into an enum slice, keep track
/// of this.
bool InEnumSubElement = false;
/// If true, then encountered uses correspond to a VarDecl marked
/// as \p @_compilerInitialized
bool InCompilerInitializedField = false;
public:
ElementUseCollector(const DIMemoryObjectInfo &TheMemory,
DIElementUseInfo &UseInfo,
FunctionSet &visitedClosures)
: Module(TheMemory.getModule()), TheMemory(TheMemory), UseInfo(UseInfo),
VisitedClosures(visitedClosures)
{}
/// This is the main entry point for the use walker. It collects uses from
/// the address and the refcount result of the allocation.
void collectFrom(SILValue V, bool collectDestroysOfContainer) {
IsSelfOfNonDelegatingInitializer = TheMemory.isNonDelegatingInit();
// If this is a delegating initializer, collect uses specially.
if (IsSelfOfNonDelegatingInitializer &&
TheMemory.getASTType()->getClassOrBoundGenericClass() != nullptr) {
assert(!TheMemory.isDerivedClassSelfOnly() &&
"Should have been handled outside of here");
// If this is a class pointer, we need to look through ref_element_addrs.
collectClassSelfUses(V);
return;
}
collectUses(V, 0);
if (collectDestroysOfContainer) {
assert(V == TheMemory.getUninitializedValue() &&
"can only gather destroys of root value");
gatherDestroysOfContainer(TheMemory, UseInfo);
}
}
void trackUse(DIMemoryUse Use) { UseInfo.trackUse(Use); }
void trackDestroy(SILInstruction *Destroy) { UseInfo.trackDestroy(Destroy); }
/// Return the raw number of elements including the 'super.init' value.
unsigned getNumMemoryElements() const { return TheMemory.getNumElements(); }
private:
void collectUses(SILValue Pointer, unsigned BaseEltNo);
bool addClosureElementUses(PartialApplyInst *pai, Operand *argUse);
void collectAssignOrInitUses(AssignOrInitInst *pai, unsigned BaseEltNo = 0);
void collectClassSelfUses(SILValue ClassPointer);
void collectClassSelfUses(SILValue ClassPointer, SILType MemorySILType,
llvm::SmallDenseMap<VarDecl *, unsigned> &EN);
void addElementUses(unsigned BaseEltNo, SILType UseTy, SILInstruction *User,
DIUseKind Kind, NullablePtr<VarDecl> Field = 0);
void collectTupleElementUses(TupleElementAddrInst *TEAI, unsigned BaseEltNo);
void collectStructElementUses(StructElementAddrInst *SEAI,
unsigned BaseEltNo);
};
} // end anonymous namespace
/// addElementUses - An operation (e.g. load, store, inout usec etc) on a value
/// acts on all of the aggregate elements in that value. For example, a load
/// of $*(Int,Int) is a use of both Int elements of the tuple. This is a helper
/// to keep the Uses data structure up to date for aggregate uses.
void ElementUseCollector::addElementUses(unsigned BaseEltNo, SILType UseTy,
SILInstruction *User, DIUseKind Kind,
NullablePtr<VarDecl> Field) {
// If we're in a subelement of a struct or enum, just mark the struct, not
// things that come after it in a parent tuple.
unsigned NumElements = 1;
if (TheMemory.getNumElements() != 1 && !InStructSubElement &&
!InEnumSubElement)
NumElements =
getElementCountRec(TypeExpansionContext(*User->getFunction()), Module,
UseTy, IsSelfOfNonDelegatingInitializer);
trackUse(DIMemoryUse(User, Kind, BaseEltNo, NumElements, Field));
}
/// Given a tuple_element_addr or struct_element_addr, compute the new
/// BaseEltNo implicit in the selected member, and recursively add uses of
/// the instruction.
void ElementUseCollector::collectTupleElementUses(TupleElementAddrInst *TEAI,
unsigned BaseEltNo) {
// If we're walking into a tuple within a struct or enum, don't adjust the
// BaseElt. The uses hanging off the tuple_element_addr are going to be
// counted as uses of the struct or enum itself.
if (InStructSubElement || InEnumSubElement)
return collectUses(TEAI, BaseEltNo);
assert(!IsSelfOfNonDelegatingInitializer && "self doesn't have tuple type");
// tuple_element_addr P, 42 indexes into the current tuple element.
// Recursively process its uses with the adjusted element number.
unsigned FieldNo = TEAI->getFieldIndex();
auto T = TEAI->getOperand()->getType();
if (T.is<TupleType>()) {
for (unsigned i = 0; i != FieldNo; ++i) {
SILType EltTy = T.getTupleElementType(i);
BaseEltNo += getElementCountRec(TypeExpansionContext(*TEAI->getFunction()),
Module, EltTy, false);
}
}
collectUses(TEAI, BaseEltNo);
}
void ElementUseCollector::collectStructElementUses(StructElementAddrInst *SEAI,
unsigned BaseEltNo) {
// Generally, we set the "InStructSubElement" flag and recursively process
// the uses so that we know that we're looking at something within the
// current element.
if (!IsSelfOfNonDelegatingInitializer) {
llvm::SaveAndRestore<bool> X(InStructSubElement, true);
collectUses(SEAI, BaseEltNo);
return;
}
// If this is the top level of 'self' in an init method, we treat each
// element of the struct as an element to be analyzed independently.
llvm::SaveAndRestore<bool> X(IsSelfOfNonDelegatingInitializer, false);
for (auto *VD : SEAI->getStructDecl()->getStoredProperties()) {
if (SEAI->getField() == VD)
break;
auto expansionContext = TypeExpansionContext(*SEAI->getFunction());
auto FieldType = SEAI->getOperand()->getType().getFieldType(VD, Module, expansionContext);
BaseEltNo += getElementCountRec(expansionContext, Module, FieldType, false);
}
collectUses(SEAI, BaseEltNo);
}
/// Return the underlying accessed pointer value. This peeks through
/// begin_access patterns such as:
///
/// %mark = mark_uninitialized [rootself] %alloc : $*T
/// %access = begin_access [modify] [unknown] %mark : $*T
/// apply %f(%access) : $(@inout T) -> ()
static SILValue getAccessedPointer(SILValue Pointer) {
if (auto *Access = dyn_cast<BeginAccessInst>(Pointer))
return Access->getSource();
return Pointer;
}
static DIUseKind verifyCompilerInitialized(SILValue pointer,
SILInstruction *write,
DIUseKind origKind) {
// if the write is _not_ auto-generated, it's a bad store.
if (!write->getLoc().isAutoGenerated())
return DIUseKind::BadExplicitStore;
return origKind;
}
void ElementUseCollector::collectUses(SILValue Pointer, unsigned BaseEltNo) {
assert(Pointer->getType().isAddress() &&
"Walked through the pointer to the value?");
SILType PointeeType = Pointer->getType().getObjectType();
for (auto *Op : Pointer->getUses()) {
auto *User = Op->getUser();
// struct_element_addr P, #field indexes into the current element.
if (auto *SEAI = dyn_cast<StructElementAddrInst>(User)) {
collectStructElementUses(SEAI, BaseEltNo);
continue;
}
// Instructions that compute a subelement are handled by a helper.
if (auto *TEAI = dyn_cast<TupleElementAddrInst>(User)) {
collectTupleElementUses(TEAI, BaseEltNo);
continue;
}
// Look through begin_access.
if (isa<BeginAccessInst>(User)) {
auto begin = cast<SingleValueInstruction>(User);
collectUses(begin, BaseEltNo);
continue;
}
// Ignore end_access.
if (isa<EndAccessInst>(User)) {
continue;
}
// Look through mark_unresolved_non_copyable_value. To us, it is not
// interesting.
if (auto *mmi = dyn_cast<MarkUnresolvedNonCopyableValueInst>(User)) {
collectUses(mmi, BaseEltNo);
continue;
}
// Loads are a use of the value.
if (isa<LoadInst>(User)) {
addElementUses(BaseEltNo, PointeeType, User, DIUseKind::Load);
continue;
}
// Load borrows are similar to loads except that we do not support
// scalarizing them now.
if (isa<LoadBorrowInst>(User)) {
addElementUses(BaseEltNo, PointeeType, User, DIUseKind::Load);
continue;
}
#define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
if (isa<Load##Name##Inst>(User)) { \
trackUse(DIMemoryUse(User, DIUseKind::Load, BaseEltNo, 1)); \
continue; \
}
#include "swift/AST/ReferenceStorage.def"
// Stores *to* the allocation are writes.
if ((isa<StoreInst>(User) || isa<AssignInst>(User) ||
isa<AssignByWrapperInst>(User)) &&
Op->getOperandNumber() == 1) {
// Coming out of SILGen, we assume that raw stores are initializations,
// unless they have trivial type (which we classify as InitOrAssign).
DIUseKind Kind;
if (InStructSubElement)
Kind = DIUseKind::PartialStore;
else if (isa<AssignInst>(User) || isa<AssignByWrapperInst>(User))
Kind = DIUseKind::InitOrAssign;
else if (PointeeType.isTrivial(*User->getFunction()))
Kind = DIUseKind::InitOrAssign;
else
Kind = DIUseKind::Initialization;
// If it's a non-synthesized write to a @_compilerInitialized field,
// indicate that in the Kind.
if (LLVM_UNLIKELY(InCompilerInitializedField))
Kind = verifyCompilerInitialized(Pointer, User, Kind);
addElementUses(BaseEltNo, PointeeType, User, Kind);
continue;
}
#define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
if (auto SWI = dyn_cast<Store##Name##Inst>(User)) \
if (Op->getOperandNumber() == 1) { \
DIUseKind Kind; \
if (InStructSubElement) \
Kind = DIUseKind::PartialStore; \
else if (SWI->isInitializationOfDest()) \
Kind = DIUseKind::Initialization; \
else \
Kind = DIUseKind::InitOrAssign; \
trackUse(DIMemoryUse(User, Kind, BaseEltNo, 1)); \
continue; \
}
#include "swift/AST/ReferenceStorage.def"
if (auto *CAI = dyn_cast<CopyAddrInst>(User)) {
// If this is the source of the copy_addr, then this is a load. If it is
// the destination, then this is an unknown assignment. Note that we'll
// revisit this instruction and add it to Uses twice if it is both a load
// and store to the same aggregate.
DIUseKind Kind;
if (Op->getOperandNumber() == 0)
Kind = DIUseKind::Load;
else if (InStructSubElement)
Kind = DIUseKind::PartialStore;
else if (CAI->isInitializationOfDest())
Kind = DIUseKind::Initialization;
else
Kind = DIUseKind::InitOrAssign;
addElementUses(BaseEltNo, PointeeType, User, Kind);
continue;
}
if (auto *TACI = dyn_cast<TupleAddrConstructorInst>(User)) {
// If this is the source of the copy_addr, then this is a load. If it is
// the destination, then this is an unknown assignment. Note that we'll
// revisit this instruction and add it to Uses twice if it is both a load
// and store to the same aggregate.
DIUseKind Kind;
if (TACI->getDest() == Op->get()) {
if (InStructSubElement)
Kind = DIUseKind::PartialStore;
else if (TACI->isInitializationOfDest())
Kind = DIUseKind::Initialization;
else
Kind = DIUseKind::InitOrAssign;
} else {
Kind = DIUseKind::Load;
}
addElementUses(BaseEltNo, PointeeType, User, Kind);
continue;
}
if (isa<MarkUnresolvedMoveAddrInst>(User)) {
// If this is the source of the copy_addr, then this is a load. If it is
// the destination, then this is an unknown assignment. Note that we'll
// revisit this instruction and add it to Uses twice if it is both a load
// and store to the same aggregate.
DIUseKind Kind;
if (Op->getOperandNumber() == 0)
Kind = DIUseKind::Load;
else if (InStructSubElement)
Kind = DIUseKind::PartialStore;
else
Kind = DIUseKind::Initialization;
addElementUses(BaseEltNo, PointeeType, User, Kind);
continue;
}
// The apply instruction does not capture the pointer when it is passed
// through 'inout' arguments or for indirect returns. InOut arguments are
// treated as uses and may-store's, but an indirect return is treated as a
// full store.
//
// Note that partial_apply instructions always close over their argument.
//
auto Apply = FullApplySite::isa(User);
if (Apply) {
auto substConv = Apply.getSubstCalleeConv();
unsigned ArgumentNumber = Op->getOperandNumber() - 1;
// If this is an out-parameter, it is like a store.
unsigned NumIndirectResults = substConv.getNumIndirectSILResults() +
substConv.getNumIndirectSILErrorResults();
if (ArgumentNumber < NumIndirectResults) {
assert(!InStructSubElement && "We're initializing sub-members?");
addElementUses(BaseEltNo, PointeeType, User, DIUseKind::Initialization);
continue;
// Otherwise, adjust the argument index.
} else {
ArgumentNumber -= NumIndirectResults;
}
auto ParamConvention =
substConv.getParameters()[ArgumentNumber].getConvention();
switch (ParamConvention) {
case ParameterConvention::Direct_Owned:
case ParameterConvention::Direct_Unowned:
case ParameterConvention::Direct_Guaranteed:
case ParameterConvention::Pack_Guaranteed:
case ParameterConvention::Pack_Owned:
case ParameterConvention::Pack_Inout:
llvm_unreachable("address value passed to indirect parameter");
// If this is an in-parameter, it is like a load.
case ParameterConvention::Indirect_In_CXX:
case ParameterConvention::Indirect_In:
case ParameterConvention::Indirect_In_Guaranteed:
addElementUses(BaseEltNo, PointeeType, User, DIUseKind::IndirectIn);
continue;
// If this is an @inout parameter, it is like both a load and store.
case ParameterConvention::Indirect_InoutAliasable: {
// FIXME: The @inout_aliasable convention is used for indirect captures
// of both 'let' and 'var' variables. Using a more specific convention
// for 'let' properties like @in_guaranteed unfortunately exposes bugs
// elsewhere in the pipeline. A 'let' capture cannot really be mutated