-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathRegionAnalysis.cpp
3701 lines (3160 loc) · 139 KB
/
RegionAnalysis.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
//===--- RegionAnalysis.cpp -----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 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 "transfer-non-sendable"
#include "swift/SILOptimizer/Analysis/RegionAnalysis.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Type.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/FrozenMultiMap.h"
#include "swift/Basic/ImmutablePointerSet.h"
#include "swift/Basic/SmallBitVector.h"
#include "swift/SIL/BasicBlockData.h"
#include "swift/SIL/BasicBlockDatastructures.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/NodeDatastructures.h"
#include "swift/SIL/OperandDatastructures.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/PatternMatch.h"
#include "swift/SIL/PrunedLiveness.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/Test.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "swift/SILOptimizer/Utils/PartitionUtils.h"
#include "swift/SILOptimizer/Utils/VariableNameUtils.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/Debug.h"
using namespace swift;
using namespace swift::PartitionPrimitives;
using namespace swift::PatternMatch;
using namespace swift::regionanalysisimpl;
#ifndef NDEBUG
bool swift::regionanalysisimpl::AbortOnUnknownPatternMatchError = false;
static llvm::cl::opt<bool, true> AbortOnUnknownPatternMatchErrorCmdLine(
"sil-region-isolation-assert-on-unknown-pattern",
llvm::cl::desc("Abort if SIL region isolation detects an unknown pattern. "
"Intended only to be used when debugging the compiler!"),
llvm::cl::Hidden,
llvm::cl::location(
swift::regionanalysisimpl::AbortOnUnknownPatternMatchError));
#endif
//===----------------------------------------------------------------------===//
// MARK: Utilities
//===----------------------------------------------------------------------===//
std::optional<ApplyIsolationCrossing>
regionanalysisimpl::getApplyIsolationCrossing(SILInstruction *inst) {
if (ApplyExpr *apply = inst->getLoc().getAsASTNode<ApplyExpr>())
if (auto crossing = apply->getIsolationCrossing())
return crossing;
if (auto fas = FullApplySite::isa(inst)) {
if (auto crossing = fas.getIsolationCrossing())
return crossing;
}
return {};
}
namespace {
struct UnderlyingTrackedValueInfo {
SILValue value;
/// Only used for addresses.
std::optional<ActorIsolation> actorIsolation;
explicit UnderlyingTrackedValueInfo(SILValue value) : value(value) {}
UnderlyingTrackedValueInfo(SILValue value,
std::optional<ActorIsolation> actorIsolation)
: value(value), actorIsolation(actorIsolation) {}
};
struct UseDefChainVisitor
: public AccessUseDefChainVisitor<UseDefChainVisitor, SILValue> {
bool isMerge = false;
/// The actor isolation that we found while walking from use->def. Always set
/// to the first one encountered.
std::optional<ActorIsolation> actorIsolation;
SILValue visitAll(SILValue sourceAddr) {
SILValue result = visit(sourceAddr);
if (!result)
return sourceAddr;
while (SILValue nextAddr = visit(result))
result = nextAddr;
return result;
}
SILValue visitBase(SILValue base, AccessStorage::Kind kind) {
// If we are passed a project_box, we want to return the box itself. The
// reason for this is that the project_box is considered to be non-aliasing
// memory. We want to treat it as part of the box which is
// aliasing... meaning that we need to merge.
if (kind == AccessStorage::Box)
return cast<ProjectBoxInst>(base)->getOperand();
return SILValue();
}
SILValue visitNonAccess(SILValue) { return SILValue(); }
SILValue visitPhi(SILPhiArgument *phi) {
llvm_unreachable("Should never hit this");
}
// Override AccessUseDefChainVisitor to ignore access markers and find the
// outer access base.
SILValue visitNestedAccess(BeginAccessInst *access) {
return visitAll(access->getSource());
}
SILValue visitStorageCast(SingleValueInstruction *cast, Operand *sourceAddr,
AccessStorageCast castType) {
// If this is a type case, see if the result of the cast is sendable. In
// such a case, we do not want to look through this cast.
if (castType == AccessStorageCast::Type &&
!SILIsolationInfo::isNonSendableType(cast->getType(),
cast->getFunction()))
return SILValue();
// Do not look through begin_borrow [var_decl]. They are start new semantic
// values.
//
// This only comes up if a codegen pattern occurs where the debug
// information is place on a debug_value instead of the alloc_box.
if (auto *bbi = dyn_cast<BeginBorrowInst>(cast)) {
if (bbi->isFromVarDecl())
return SILValue();
}
// If we do not have an identity cast, mark this as a merge.
isMerge |= castType != AccessStorageCast::Identity;
return sourceAddr->get();
}
SILValue visitAccessProjection(SingleValueInstruction *inst,
Operand *sourceAddr) {
// See if this access projection is into a single element value. If so, we
// do not want to treat this as a merge.
if (auto p = Projection(inst)) {
switch (p.getKind()) {
// Currently if we load and then project_box from a memory location,
// we treat that as a projection. This follows the semantics/notes in
// getAccessProjectionOperand.
case ProjectionKind::Box:
return cast<ProjectBoxInst>(inst)->getOperand();
case ProjectionKind::Upcast:
case ProjectionKind::RefCast:
case ProjectionKind::BlockStorageCast:
case ProjectionKind::BitwiseCast:
case ProjectionKind::Class:
case ProjectionKind::TailElems:
llvm_unreachable("Shouldn't see this here");
case ProjectionKind::Index:
// Index is always a merge.
isMerge = true;
break;
case ProjectionKind::Enum: {
auto op = cast<UncheckedTakeEnumDataAddrInst>(inst)->getOperand();
// See if our operand type is a sendable type. In such a case, we do not
// want to look through our operand.
if (!SILIsolationInfo::isNonSendableType(op->getType(),
op->getFunction()))
return SILValue();
break;
}
case ProjectionKind::Tuple: {
// These are merges if we have multiple fields.
auto op = cast<TupleElementAddrInst>(inst)->getOperand();
if (!SILIsolationInfo::isNonSendableType(op->getType(),
op->getFunction()))
return SILValue();
isMerge |= op->getType().getNumTupleElements() > 1;
break;
}
case ProjectionKind::Struct:
auto op = cast<StructElementAddrInst>(inst)->getOperand();
// See if our result type is a sendable type. In such a case, we do not
// want to look through the struct_element_addr since we do not want to
// identify the sendable type with the non-sendable operand. These we
// are always going to ignore anyways since a sendable let/var field of
// a struct can always be used.
if (!SILIsolationInfo::isNonSendableType(op->getType(),
op->getFunction()))
return SILValue();
// These are merges if we have multiple fields.
isMerge |= op->getType().getNumNominalFields() > 1;
break;
}
}
return sourceAddr->get();
}
};
} // namespace
/// Classify an instructions as look through when we are looking through
/// values. We assert that all instructions that are CONSTANT_TRANSLATION
/// LookThrough to make sure they stay in sync.
static bool isStaticallyLookThroughInst(SILInstruction *inst) {
switch (inst->getKind()) {
default:
return false;
case SILInstructionKind::BeginAccessInst:
case SILInstructionKind::BeginCOWMutationInst:
case SILInstructionKind::BeginDeallocRefInst:
case SILInstructionKind::BridgeObjectToRefInst:
case SILInstructionKind::CopyValueInst:
case SILInstructionKind::CopyableToMoveOnlyWrapperAddrInst:
case SILInstructionKind::CopyableToMoveOnlyWrapperValueInst:
case SILInstructionKind::DestructureStructInst:
case SILInstructionKind::DestructureTupleInst:
case SILInstructionKind::DifferentiableFunctionExtractInst:
case SILInstructionKind::DropDeinitInst:
case SILInstructionKind::EndCOWMutationInst:
case SILInstructionKind::EndInitLetRefInst:
case SILInstructionKind::ExplicitCopyValueInst:
case SILInstructionKind::InitEnumDataAddrInst:
case SILInstructionKind::LinearFunctionExtractInst:
case SILInstructionKind::MarkDependenceInst:
case SILInstructionKind::MarkUninitializedInst:
case SILInstructionKind::MarkUnresolvedNonCopyableValueInst:
case SILInstructionKind::MarkUnresolvedReferenceBindingInst:
case SILInstructionKind::MoveOnlyWrapperToCopyableAddrInst:
case SILInstructionKind::MoveOnlyWrapperToCopyableBoxInst:
case SILInstructionKind::MoveOnlyWrapperToCopyableValueInst:
case SILInstructionKind::OpenExistentialAddrInst:
case SILInstructionKind::OpenExistentialValueInst:
case SILInstructionKind::ProjectBlockStorageInst:
case SILInstructionKind::ProjectBoxInst:
case SILInstructionKind::RefToBridgeObjectInst:
case SILInstructionKind::RefToUnownedInst:
case SILInstructionKind::UncheckedRefCastInst:
case SILInstructionKind::UncheckedTakeEnumDataAddrInst:
case SILInstructionKind::UnownedCopyValueInst:
case SILInstructionKind::UnownedToRefInst:
case SILInstructionKind::UpcastInst:
case SILInstructionKind::ValueToBridgeObjectInst:
case SILInstructionKind::WeakCopyValueInst:
case SILInstructionKind::StrongCopyWeakValueInst:
case SILInstructionKind::StrongCopyUnmanagedValueInst:
case SILInstructionKind::RefToUnmanagedInst:
case SILInstructionKind::UnmanagedToRefInst:
case SILInstructionKind::InitExistentialValueInst:
return true;
case SILInstructionKind::MoveValueInst:
// Look through if it isn't from a var decl.
return !cast<MoveValueInst>(inst)->isFromVarDecl();
case SILInstructionKind::BeginBorrowInst:
// Look through if it isn't from a var decl.
return !cast<BeginBorrowInst>(inst)->isFromVarDecl();
case SILInstructionKind::UnconditionalCheckedCastInst: {
auto cast = SILDynamicCastInst::getAs(inst);
assert(cast);
if (cast.isRCIdentityPreserving())
return true;
return false;
}
}
}
static bool isLookThroughIfResultNonSendable(SILInstruction *inst) {
switch (inst->getKind()) {
default:
return false;
case SILInstructionKind::RawPointerToRefInst:
return true;
}
}
static bool isLookThroughIfOperandNonSendable(SILInstruction *inst) {
switch (inst->getKind()) {
default:
return false;
case SILInstructionKind::RefToRawPointerInst:
return true;
}
}
static bool isLookThroughIfOperandAndResultNonSendable(SILInstruction *inst) {
switch (inst->getKind()) {
default:
return false;
case SILInstructionKind::UncheckedTrivialBitCastInst:
case SILInstructionKind::UncheckedBitwiseCastInst:
case SILInstructionKind::UncheckedValueCastInst:
case SILInstructionKind::StructElementAddrInst:
case SILInstructionKind::TupleElementAddrInst:
case SILInstructionKind::UncheckedTakeEnumDataAddrInst:
return true;
}
}
static SILValue getUnderlyingTrackedObjectValue(SILValue value) {
auto *fn = value->getFunction();
SILValue result = value;
while (true) {
SILValue temp = result;
if (auto *svi = dyn_cast<SingleValueInstruction>(temp)) {
if (isStaticallyLookThroughInst(svi)) {
temp = svi->getOperand(0);
}
// If we have a cast and our operand and result are non-Sendable, treat it
// as a look through.
if (isLookThroughIfOperandAndResultNonSendable(svi)) {
if (SILIsolationInfo::isNonSendableType(svi->getType(), fn) &&
SILIsolationInfo::isNonSendableType(svi->getOperand(0)->getType(),
fn)) {
temp = svi->getOperand(0);
}
}
if (isLookThroughIfResultNonSendable(svi)) {
if (SILIsolationInfo::isNonSendableType(svi->getType(), fn)) {
temp = svi->getOperand(0);
}
}
if (isLookThroughIfOperandNonSendable(svi)) {
// If our operand is a non-Sendable type, look through this instruction.
if (SILIsolationInfo::isNonSendableType(svi->getOperand(0)->getType(),
fn)) {
temp = svi->getOperand(0);
}
}
}
if (auto *inst = temp->getDefiningInstruction()) {
if (isStaticallyLookThroughInst(inst)) {
temp = inst->getOperand(0);
}
}
if (temp != result) {
result = temp;
continue;
}
return result;
}
}
static UnderlyingTrackedValueInfo getUnderlyingTrackedValue(SILValue value) {
// Look through a project_box, so that we process it like its operand object.
if (auto *pbi = dyn_cast<ProjectBoxInst>(value)) {
value = pbi->getOperand();
}
if (!value->getType().isAddress()) {
SILValue underlyingValue = getUnderlyingTrackedObjectValue(value);
if (!isa<LoadInst, LoadBorrowInst>(underlyingValue)) {
return UnderlyingTrackedValueInfo(underlyingValue);
}
// If we got an address, lets see if we can do even better by looking at the
// address.
value = cast<SingleValueInstruction>(underlyingValue)->getOperand(0);
}
assert(value->getType().isAddress());
UseDefChainVisitor visitor;
SILValue base = visitor.visitAll(value);
assert(base);
if (base->getType().isObject())
return {getUnderlyingTrackedValue(base).value, visitor.actorIsolation};
return {base, visitor.actorIsolation};
}
SILValue RegionAnalysisFunctionInfo::getUnderlyingTrackedValue(SILValue value) {
return ::getUnderlyingTrackedValue(value).value;
}
namespace {
struct TermArgSources {
SmallFrozenMultiMap<SILValue, SILValue, 8> argSources;
template <typename ValueRangeTy = ArrayRef<SILValue>>
void addValues(ValueRangeTy valueRange, SILBasicBlock *destBlock) {
for (auto pair : llvm::enumerate(valueRange))
argSources.insert(destBlock->getArgument(pair.index()), pair.value());
}
TermArgSources() {}
void init(SILInstruction *inst) {
switch (cast<TermInst>(inst)->getTermKind()) {
case TermKind::UnreachableInst:
case TermKind::ReturnInst:
case TermKind::ThrowInst:
case TermKind::ThrowAddrInst:
case TermKind::YieldInst:
case TermKind::UnwindInst:
case TermKind::TryApplyInst:
case TermKind::SwitchValueInst:
case TermKind::SwitchEnumInst:
case TermKind::SwitchEnumAddrInst:
case TermKind::AwaitAsyncContinuationInst:
case TermKind::CheckedCastAddrBranchInst:
llvm_unreachable("Unsupported?!");
case TermKind::BranchInst:
return init(cast<BranchInst>(inst));
case TermKind::CondBranchInst:
return init(cast<CondBranchInst>(inst));
case TermKind::DynamicMethodBranchInst:
return init(cast<DynamicMethodBranchInst>(inst));
case TermKind::CheckedCastBranchInst:
return init(cast<CheckedCastBranchInst>(inst));
}
llvm_unreachable("Covered switch isn't covered?!");
}
private:
void init(BranchInst *bi) { addValues(bi->getArgs(), bi->getDestBB()); }
void init(CondBranchInst *cbi) {
addValues(cbi->getTrueArgs(), cbi->getTrueBB());
addValues(cbi->getFalseArgs(), cbi->getFalseBB());
}
void init(DynamicMethodBranchInst *dmBranchInst) {
addValues({dmBranchInst->getOperand()}, dmBranchInst->getHasMethodBB());
}
void init(CheckedCastBranchInst *ccbi) {
addValues({ccbi->getOperand()}, ccbi->getSuccessBB());
}
};
} // namespace
static bool isProjectedFromAggregate(SILValue value) {
assert(value->getType().isAddress());
UseDefChainVisitor visitor;
visitor.visitAll(value);
return visitor.isMerge;
}
namespace {
using AsyncLetSourceValue =
llvm::PointerUnion<PartialApplyInst *, ThinToThickFunctionInst *>;
} // namespace
static std::optional<AsyncLetSourceValue>
findAsyncLetPartialApplyFromStart(SILValue value) {
// If our operand is Sendable then we want to return nullptr. We only want to
// return a value if we are not
auto fType = value->getType().castTo<SILFunctionType>();
if (fType->isSendable())
return {};
SILValue temp = value;
while (true) {
if (isa<ConvertEscapeToNoEscapeInst>(temp) ||
isa<ConvertFunctionInst>(temp)) {
temp = cast<SingleValueInstruction>(temp)->getOperand(0);
}
if (temp == value)
break;
value = temp;
}
// We can also get a thin_to_thick_function here if we do not capture
// anything. In such a case, we just do not process the partial apply get
if (auto *ttfi = dyn_cast<ThinToThickFunctionInst>(value))
return {{ttfi}};
// Ok, we could still have a reabstraction thunk. In such a case, we want the
// partial_apply that we process to be the original partial_apply (or
// thin_to_thick)... so in that case process recursively.
auto *pai = cast<PartialApplyInst>(value);
if (auto *calleeFunction = pai->getCalleeFunction()) {
if (calleeFunction->isThunk() == IsReabstractionThunk) {
return findAsyncLetPartialApplyFromStart(pai->getArgument(0));
}
}
// Otherwise, this is the right partial_apply... apply it!
return {{pai}};
}
/// This recurses through reabstraction thunks.
static std::optional<AsyncLetSourceValue>
findAsyncLetPartialApplyFromStart(BuiltinInst *bi) {
return findAsyncLetPartialApplyFromStart(bi->getOperand(1));
}
/// This recurses through reabstraction thunks.
static std::optional<AsyncLetSourceValue>
findAsyncLetPartialApplyFromGet(ApplyInst *ai) {
auto *bi = cast<BuiltinInst>(FullApplySite(ai).getArgument(0));
assert(*bi->getBuiltinKind() ==
BuiltinValueKind::StartAsyncLetWithLocalBuffer);
return findAsyncLetPartialApplyFromStart(bi);
}
static bool isAsyncLetBeginPartialApply(PartialApplyInst *pai) {
if (auto *fas = pai->getCalleeFunction())
if (fas->isThunk())
return false;
// Look through reabstraction thunks.
SILValue result = pai;
while (true) {
SILValue iter = result;
if (auto *use = iter->getSingleUse()) {
if (auto *maybeThunk = dyn_cast<PartialApplyInst>(use->getUser())) {
if (auto *fas = maybeThunk->getCalleeFunction()) {
if (fas->isThunk()) {
iter = maybeThunk;
}
}
}
}
if (auto *cfi = iter->getSingleUserOfType<ConvertFunctionInst>())
iter = cfi;
if (auto *cvt = iter->getSingleUserOfType<ConvertEscapeToNoEscapeInst>())
iter = cvt;
if (iter == result)
break;
result = iter;
}
auto *bi = result->getSingleUserOfType<BuiltinInst>();
if (!bi)
return false;
auto kind = bi->getBuiltinKind();
if (!kind)
return false;
return *kind == BuiltinValueKind::StartAsyncLetWithLocalBuffer;
}
/// Returns true if this is a function argument that is able to be transferred
/// in the body of our function.
static bool isTransferrableFunctionArgument(SILFunctionArgument *arg) {
// Indirect out parameters cannot be an input transferring parameter.
if (arg->isIndirectResult() || arg->isIndirectErrorResult())
return false;
// If we have a function argument that is closure captured by a Sendable
// closure, allow for the argument to be transferred.
//
// DISCUSSION: The reason that we do this is that in the case of us
// having an actual Sendable closure there are two cases we can see:
//
// 1. If we have an actual Sendable closure, the AST will emit an
// earlier error saying that we are capturing a non-Sendable value in a
// Sendable closure. So we want to squelch the error that we would emit
// otherwise. This only occurs when we are not in swift-6 mode since in
// swift-6 mode we will error on the earlier error... but in the case of
// us not being in swift 6 mode lets not emit extra errors.
//
// 2. If we have an async-let based Sendable closure, we want to allow
// for the argument to be transferred in the async let's statement and
// not emit an error.
//
// TODO: Once the async let refactoring change this will no longer be needed
// since closure captures will have transferring parameters and be
// non-Sendable.
if (arg->isClosureCapture() &&
arg->getFunction()->getLoweredFunctionType()->isSendable())
return true;
// Otherwise, we only allow for the argument to be transferred if it is
// explicitly marked as a strong transferring parameter.
return arg->isSending();
}
//===----------------------------------------------------------------------===//
// MARK: TrackableValue
//===----------------------------------------------------------------------===//
bool TrackableValue::isSendingParameter() const {
// First get our alloc_stack.
//
// TODO: We should just put a flag on the alloc_stack, so we /know/ 100% that
// it is from a consuming parameter. We don't have that so we pattern match.
auto *asi =
dyn_cast_or_null<AllocStackInst>(representativeValue.maybeGetValue());
if (!asi)
return false;
if (asi->getParent() != asi->getFunction()->getEntryBlock())
return false;
// See if we are initialized from a transferring parameter and are the only
// use of the parameter.
OperandWorklist worklist(asi->getFunction());
worklist.pushResultOperandsIfNotVisited(asi);
while (auto *use = worklist.pop()) {
auto *user = use->getUser();
// Look through instructions that we don't care about.
if (isa<MarkUnresolvedNonCopyableValueInst,
MoveOnlyWrapperToCopyableAddrInst>(user)) {
worklist.pushResultOperandsIfNotVisited(user);
}
if (auto *si = dyn_cast<StoreInst>(user)) {
// Check if our store inst is from a function argument that is
// transferring and for which the store is the only use of the function
// argument.
auto *fArg = dyn_cast<SILFunctionArgument>(si->getSrc());
if (!fArg || !fArg->isSending())
return false;
return fArg->getSingleUse();
}
if (auto *copyAddr = dyn_cast<CopyAddrInst>(user)) {
// Check if our copy_addr is from a function argument that is transferring
// and for which the copy_addr is the only use of the function argument.
auto *fArg = dyn_cast<SILFunctionArgument>(copyAddr->getSrc());
if (!fArg || !fArg->isSending())
return false;
return fArg->getSingleUse();
}
}
// Otherwise, this isn't a consuming parameter.
return false;
}
//===----------------------------------------------------------------------===//
// MARK: Partial Apply Reachability
//===----------------------------------------------------------------------===//
namespace {
/// We need to be able to know if instructions that extract sendable fields from
/// non-sendable addresses are reachable from a partial_apply that captures the
/// non-sendable value or its underlying object by reference. In such a case, we
/// need to require the value to not be transferred when the extraction happens
/// since we could race on extracting the value.
///
/// The reason why we use a dataflow to do this is that:
///
/// 1. We do not want to recompute this for each individual instruction that
/// might be reachable from the partial apply.
///
/// 2. Just computing reachability early is a very easy way to do this.
struct PartialApplyReachabilityDataflow {
PostOrderFunctionInfo *pofi;
llvm::DenseMap<SILValue, unsigned> valueToBit;
std::vector<std::pair<SILValue, SILInstruction *>> valueToGenInsts;
struct BlockState {
SmallBitVector entry;
SmallBitVector exit;
SmallBitVector gen;
bool needsUpdate = true;
};
BasicBlockData<BlockState> blockData;
bool propagatedReachability = false;
PartialApplyReachabilityDataflow(SILFunction *fn, PostOrderFunctionInfo *pofi)
: pofi(pofi), blockData(fn) {}
/// Begin tracking an operand of a partial apply.
void add(Operand *op);
/// Once we have finished adding data to the data, propagate reachability.
void propagateReachability();
bool isReachable(SILValue value, SILInstruction *user) const;
bool isReachable(Operand *op) const {
return isReachable(op->get(), op->getUser());
}
bool isGenInstruction(SILValue value, SILInstruction *inst) const {
assert(propagatedReachability && "Only valid once propagated reachability");
auto iter =
std::lower_bound(valueToGenInsts.begin(), valueToGenInsts.end(),
std::make_pair(value, nullptr),
[](const std::pair<SILValue, SILInstruction *> &p1,
const std::pair<SILValue, SILInstruction *> &p2) {
return p1 < p2;
});
return iter != valueToGenInsts.end() && iter->first == value &&
iter->second == inst;
}
void print(llvm::raw_ostream &os) const;
SWIFT_DEBUG_DUMP { print(llvm::dbgs()); }
private:
SILValue getRootValue(SILValue value) const {
return getUnderlyingTrackedValue(value).value;
}
unsigned getBitForValue(SILValue value) const {
unsigned size = valueToBit.size();
auto &self = const_cast<PartialApplyReachabilityDataflow &>(*this);
auto iter = self.valueToBit.try_emplace(value, size);
return iter.first->second;
}
};
} // namespace
void PartialApplyReachabilityDataflow::add(Operand *op) {
assert(!propagatedReachability &&
"Cannot add more operands once reachability is computed");
SILValue underlyingValue = getRootValue(op->get());
LLVM_DEBUG(llvm::dbgs() << "PartialApplyReachability::add.\nValue: "
<< underlyingValue << "User: " << *op->getUser());
unsigned bit = getBitForValue(underlyingValue);
auto &state = blockData[op->getParentBlock()];
state.gen.resize(bit + 1);
state.gen.set(bit);
valueToGenInsts.emplace_back(underlyingValue, op->getUser());
}
bool PartialApplyReachabilityDataflow::isReachable(SILValue value,
SILInstruction *user) const {
assert(
propagatedReachability &&
"Can only check for reachability once reachability has been propagated");
SILValue baseValue = getRootValue(value);
auto iter = valueToBit.find(baseValue);
// If we aren't tracking this value... just bail.
if (iter == valueToBit.end())
return false;
unsigned bitNum = iter->second;
auto &state = blockData[user->getParent()];
// If we are reachable at entry, then we are done.
if (state.entry.test(bitNum)) {
return true;
}
// Otherwise, check if we are reachable at exit. If we are not, then we are
// not reachable.
if (!state.exit.test(bitNum)) {
return false;
}
// We were not reachable at entry but are at our exit... walk the block and
// see if our user is before a gen instruction.
auto genStart = std::lower_bound(
valueToGenInsts.begin(), valueToGenInsts.end(),
std::make_pair(baseValue, nullptr),
[](const std::pair<SILValue, SILInstruction *> &p1,
const std::pair<SILValue, SILInstruction *> &p2) { return p1 < p2; });
if (genStart == valueToGenInsts.end() || genStart->first != baseValue)
return false;
auto genEnd = genStart;
while (genEnd != valueToGenInsts.end() && genEnd->first == baseValue)
++genEnd;
// Walk forward from the beginning of the block to user. If we do not find a
// gen instruction, then we know the gen occurs after the op.
return llvm::any_of(
user->getParent()->getRangeEndingAtInst(user), [&](SILInstruction &inst) {
auto iter = std::lower_bound(
genStart, genEnd, std::make_pair(baseValue, &inst),
[](const std::pair<SILValue, SILInstruction *> &p1,
const std::pair<SILValue, SILInstruction *> &p2) {
return p1 < p2;
});
return iter != valueToGenInsts.end() && iter->first == baseValue &&
iter->second == &inst;
});
}
void PartialApplyReachabilityDataflow::propagateReachability() {
assert(!propagatedReachability && "Cannot propagate reachability twice");
propagatedReachability = true;
// Now that we have finished initializing, resize all of our bitVectors to the
// final number of bits.
unsigned numBits = valueToBit.size();
// If numBits is none, we have nothing to process.
if (numBits == 0)
return;
for (auto iter : blockData) {
iter.data.entry.resize(numBits);
iter.data.exit.resize(numBits);
iter.data.gen.resize(numBits);
iter.data.needsUpdate = true;
}
// Freeze our value to gen insts map so we can perform in block checks.
sortUnique(valueToGenInsts);
// We perform a simple gen-kill dataflow with union. Since we are just
// propagating reachability, there isn't any kill.
bool anyNeedUpdate = true;
SmallBitVector temp(numBits);
blockData[&*blockData.getFunction()->begin()].needsUpdate = true;
while (anyNeedUpdate) {
anyNeedUpdate = false;
for (auto *block : pofi->getReversePostOrder()) {
auto &state = blockData[block];
if (!state.needsUpdate) {
continue;
}
state.needsUpdate = false;
temp.reset();
for (auto *predBlock : block->getPredecessorBlocks()) {
auto &predState = blockData[predBlock];
temp |= predState.exit;
}
state.entry = temp;
temp |= state.gen;
if (temp != state.exit) {
state.exit = temp;
for (auto *succBlock : block->getSuccessorBlocks()) {
anyNeedUpdate = true;
blockData[succBlock].needsUpdate = true;
}
}
}
}
LLVM_DEBUG(llvm::dbgs() << "Propagating Captures Result!\n";
print(llvm::dbgs()));
}
void PartialApplyReachabilityDataflow::print(llvm::raw_ostream &os) const {
// This is only invoked for debugging purposes, so make nicer output.
std::vector<std::pair<unsigned, SILValue>> data;
for (auto [value, bitNo] : valueToBit) {
data.emplace_back(bitNo, value);
}
std::sort(data.begin(), data.end());
os << "(BitNo, Value):\n";
for (auto [bitNo, value] : data) {
os << " " << bitNo << ": " << value;
}
os << "(Block,GenBits):\n";
for (auto [block, state] : blockData) {
os << " bb" << block.getDebugID() << ".\n"
<< " Entry: " << state.entry << '\n'
<< " Gen: " << state.gen << '\n'
<< " Exit: " << state.exit << '\n';
}
}
//===----------------------------------------------------------------------===//
// MARK: Expr/Type Inference for Diagnostics
//===----------------------------------------------------------------------===//
namespace {
struct InferredCallerArgumentTypeInfo {
Type baseInferredType;
SmallVector<std::pair<Type, std::optional<ApplyIsolationCrossing>>, 4>
applyUses;
void init(const Operand *op);
/// Init for an apply that does not have an associated apply expr.
///
/// This should only occur when writing SIL test cases today. In the future,
/// we may represent all of the actor isolation information at the SIL level,
/// but we are not there yet today.
void initForApply(ApplyIsolationCrossing isolationCrossing);
void initForApply(const Operand *op, ApplyExpr *expr);
void initForAutoclosure(const Operand *op, AutoClosureExpr *expr);
Expr *getFoundExprForSelf(ApplyExpr *sourceApply) {
if (auto callExpr = dyn_cast<CallExpr>(sourceApply))
if (auto calledExpr =
dyn_cast<DotSyntaxCallExpr>(callExpr->getDirectCallee()))
return calledExpr->getBase();
return nullptr;
}
Expr *getFoundExprForParam(ApplyExpr *sourceApply, unsigned argNum) {
auto *expr = sourceApply->getArgs()->getExpr(argNum);
// If we have an erasure expression, lets use the original type. We do
// this since we are not saying the specific parameter that is the
// issue and we are using the type to explain it to the user.
if (auto *erasureExpr = dyn_cast<ErasureExpr>(expr))
expr = erasureExpr->getSubExpr();
return expr;
}
};
} // namespace
void InferredCallerArgumentTypeInfo::initForApply(
ApplyIsolationCrossing isolationCrossing) {
applyUses.emplace_back(baseInferredType, isolationCrossing);
}
void InferredCallerArgumentTypeInfo::initForApply(const Operand *op,
ApplyExpr *sourceApply) {
auto isolationCrossing = sourceApply->getIsolationCrossing();
assert(isolationCrossing && "Should have valid isolation crossing?!");
// Grab out full apply site and see if we can find a better expr.
SILInstruction *i = const_cast<SILInstruction *>(op->getUser());
auto fai = FullApplySite::isa(i);
Expr *foundExpr = nullptr;
// If we have self, then infer it.
if (fai.hasSelfArgument() && op == &fai.getSelfArgumentOperand()) {
foundExpr = getFoundExprForSelf(sourceApply);
} else {
// Otherwise, try to infer using the operand of the ApplyExpr.
unsigned argNum = [&]() -> unsigned {
if (fai.isCalleeOperand(*op))
return op->getOperandNumber();
return fai.getAppliedArgIndexWithoutIndirectResults(*op);
}();
// If something funny happened and we get an arg num that is larger than our
// num args... just return nullptr so we emit an error using our initial
// foundExpr.
//
// TODO: We should emit a "I don't understand error" so this gets reported
// to us.
if (argNum < sourceApply->getArgs()->size()) {
foundExpr = getFoundExprForParam(sourceApply, argNum);
}
}
auto inferredArgType =
foundExpr ? foundExpr->findOriginalType() : baseInferredType;
applyUses.emplace_back(inferredArgType, isolationCrossing);
}
namespace {
struct Walker : ASTWalker {
InferredCallerArgumentTypeInfo &foundTypeInfo;
ValueDecl *targetDecl;
SmallPtrSet<Expr *, 8> visitedCallExprDeclRefExprs;
Walker(InferredCallerArgumentTypeInfo &foundTypeInfo, ValueDecl *targetDecl)