-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathRegionAnalysis.cpp
4295 lines (3679 loc) · 163 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 "send-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;
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));
//===----------------------------------------------------------------------===//
// MARK: Utilities
//===----------------------------------------------------------------------===//
namespace {
using OperandRefRangeTransform = std::function<Operand *(Operand &)>;
using OperandRefRange =
iterator_range<llvm::mapped_iterator<MutableArrayRef<Operand>::iterator,
OperandRefRangeTransform>>;
} // anonymous namespace
static OperandRefRange makeOperandRefRange(MutableArrayRef<Operand> input) {
auto toOperand = [](Operand &operand) { return &operand; };
auto baseRange = llvm::make_range(input.begin(), input.end());
return llvm::map_range(baseRange, OperandRefRangeTransform(toOperand));
}
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 {
/// A visitor that walks from uses -> def attempting to determine an object or
/// address base for the passed in address.
///
/// It also is used to determine if we are assigning into a part of an aggregate
/// or are assigning over an entire value.
///
/// RULES:
///
/// 1. We allow for sendable types to be rooted in non-Sendable types. We allow
/// for our caller to reason about this by placing in our metadata if the entire
/// search path was just sendable types. If any are non-Sendable except for our
/// base, we need to be more conservative.
///
/// 2. We stop when we find a non-Sendable type rooted in a Sendable type. In
/// such a case, we want to process the non-Sendable type as if it is rooted in
/// the Sendable type.
struct AddressBaseComputingVisitor
: public AccessUseDefChainVisitor<AddressBaseComputingVisitor, SILValue> {
bool isProjectedFromAggregate = false;
SILValue value;
SILValue visitAll(SILValue sourceAddr) {
// If our initial value is Sendable, then it is our "value".
if (SILIsolationInfo::isSendableType(sourceAddr))
value = 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 if we are projecting out
// of an aggregate that will require us to merge.
isProjectedFromAggregate |= castType != AccessStorageCast::Identity;
return sourceAddr->get();
}
SILValue visitAccessProjection(SingleValueInstruction *projInst,
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(projInst)) {
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>(projInst)->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.
isProjectedFromAggregate = true;
break;
case ProjectionKind::Enum: {
auto op = cast<UncheckedTakeEnumDataAddrInst>(projInst)->getOperand();
bool isOperandSendable = !SILIsolationInfo::isNonSendableType(
op->getType(), op->getFunction());
// If our operand is Sendable and our field is non-Sendable and we have
// not stashed a value yet, stash value.
if (!value && isOperandSendable &&
SILIsolationInfo::isNonSendableType(projInst->getType(),
projInst->getFunction())) {
value = projInst;
}
break;
}
case ProjectionKind::Tuple: {
// These are merges if we have multiple fields.
auto op = cast<TupleElementAddrInst>(projInst)->getOperand();
bool isOperandSendable = !SILIsolationInfo::isNonSendableType(
op->getType(), op->getFunction());
// If our operand is Sendable and our field is non-Sendable, we need to
// bail since we want to root the non-Sendable type in the Sendable
// type.
if (!value && isOperandSendable &&
SILIsolationInfo::isNonSendableType(projInst->getType(),
projInst->getFunction()))
value = projInst;
isProjectedFromAggregate |= op->getType().getNumTupleElements() > 1;
break;
}
case ProjectionKind::Struct:
auto op = cast<StructElementAddrInst>(projInst)->getOperand();
bool isOperandSendable = !SILIsolationInfo::isNonSendableType(
op->getType(), op->getFunction());
// If our operand is Sendable and our field is non-Sendable, we need to
// bail since we want to root the non-Sendable type in the Sendable
// type.
if (!value && isOperandSendable &&
SILIsolationInfo::isNonSendableType(projInst->getType(),
projInst->getFunction()))
value = projInst;
// These are merges if we have multiple fields.
isProjectedFromAggregate |= 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:
case SILInstructionKind::UncheckedEnumDataInst:
case SILInstructionKind::StructElementAddrInst:
case SILInstructionKind::TupleElementAddrInst:
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 isLookThroughIfOperandAndResultNonSendable(SILInstruction *inst) {
switch (inst->getKind()) {
default:
return false;
case SILInstructionKind::UncheckedTrivialBitCastInst:
case SILInstructionKind::UncheckedBitwiseCastInst:
case SILInstructionKind::UncheckedValueCastInst:
case SILInstructionKind::ConvertEscapeToNoEscapeInst:
case SILInstructionKind::ConvertFunctionInst:
case SILInstructionKind::RefToRawPointerInst:
case SILInstructionKind::RawPointerToRefInst:
return true;
}
}
namespace {
struct TermArgSources {
SmallFrozenMultiMap<SILValue, Operand *, 8> argSources;
template <typename ValueRangeTy = ArrayRef<Operand *>>
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(makeOperandRefRange(bi->getAllOperands()), bi->getDestBB());
}
void init(CondBranchInst *cbi) {
addValues(makeOperandRefRange(cbi->getTrueOperands()), cbi->getTrueBB());
addValues(makeOperandRefRange(cbi->getFalseOperands()), cbi->getFalseBB());
}
void init(DynamicMethodBranchInst *dmBranchInst) {
addValues({&dmBranchInst->getAllOperands()[0]},
dmBranchInst->getHasMethodBB());
}
void init(CheckedCastBranchInst *ccbi) {
addValues({&ccbi->getAllOperands()[0]}, ccbi->getSuccessBB());
}
};
} // namespace
static bool isProjectedFromAggregate(SILValue value) {
assert(value->getType().isAddress());
AddressBaseComputingVisitor visitor;
visitor.visitAll(value);
return visitor.isProjectedFromAggregate;
}
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 sent in the
/// body of our function.
static bool canFunctionArgumentBeSent(SILFunctionArgument *arg) {
// Indirect out parameters can never be sent.
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 sent.
//
// 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 sent 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 sending parameters and be
// non-Sendable.
if (arg->isClosureCapture() &&
arg->getFunction()->getLoweredFunctionType()->isSendable())
return true;
// Otherwise, we only allow for the argument to be sent if it is explicitly
// marked as a 'sending' parameter.
return arg->isSending();
}
//===----------------------------------------------------------------------===//
// MARK: RegionAnalysisValueMap
//===----------------------------------------------------------------------===//
SILInstruction *RegionAnalysisValueMap::maybeGetActorIntroducingInst(
Element trackableValueID) const {
if (auto value = getValueForId(trackableValueID)) {
auto rep = value->getRepresentative();
if (rep.hasRegionIntroducingInst())
return rep.getActorRegionIntroducingInst();
}
return nullptr;
}
std::optional<TrackableValue>
RegionAnalysisValueMap::getValueForId(Element id) const {
auto iter = stateIndexToEquivalenceClass.find(id);
if (iter == stateIndexToEquivalenceClass.end())
return {};
auto iter2 = equivalenceClassValuesToState.find(iter->second);
if (iter2 == equivalenceClassValuesToState.end())
return {};
return {{iter2->first, iter2->second}};
}
SILValue
RegionAnalysisValueMap::getRepresentative(Element trackableValueID) const {
return getValueForId(trackableValueID)->getRepresentative().getValue();
}
SILValue
RegionAnalysisValueMap::maybeGetRepresentative(Element trackableValueID) const {
return getValueForId(trackableValueID)->getRepresentative().maybeGetValue();
}
RepresentativeValue
RegionAnalysisValueMap::getRepresentativeValue(Element trackableValueID) const {
return getValueForId(trackableValueID)->getRepresentative();
}
SILIsolationInfo
RegionAnalysisValueMap::getIsolationRegion(Element trackableValueID) const {
auto iter = getValueForId(trackableValueID);
if (!iter)
return {};
return iter->getValueState().getIsolationRegionInfo();
}
SILIsolationInfo
RegionAnalysisValueMap::getIsolationRegion(SILValue value) const {
auto iter = equivalenceClassValuesToState.find(RepresentativeValue(value));
if (iter == equivalenceClassValuesToState.end())
return {};
return iter->getSecond().getIsolationRegionInfo();
}
std::pair<TrackableValue, bool>
RegionAnalysisValueMap::initializeTrackableValue(
SILValue value, SILIsolationInfo newInfo) const {
auto info = getUnderlyingTrackedValue(value);
value = info.value;
auto *self = const_cast<RegionAnalysisValueMap *>(this);
auto iter = self->equivalenceClassValuesToState.try_emplace(
value, TrackableValueState(equivalenceClassValuesToState.size()));
// If we did not insert, just return the already stored value.
if (!iter.second) {
return {{iter.first->first, iter.first->second}, false};
}
// If we did not insert, just return the already stored value.
self->stateIndexToEquivalenceClass[iter.first->second.getID()] = value;
// Before we do anything, see if we have a Sendable value.
if (!SILIsolationInfo::isNonSendableType(value->getType(), fn)) {
iter.first->getSecond().addFlag(TrackableValueFlag::isSendable);
return {{iter.first->first, iter.first->second}, true};
}
// Otherwise, we have a non-Sendable type... so wire up the isolation.
iter.first->getSecond().setIsolationRegionInfo(newInfo);
return {{iter.first->first, iter.first->second}, true};
}
TrackableValue RegionAnalysisValueMap::getTrackableValueHelper(
SILValue value, bool isAddressCapturedByPartialApply) const {
auto *self = const_cast<RegionAnalysisValueMap *>(this);
auto iter = self->equivalenceClassValuesToState.try_emplace(
value, TrackableValueState(equivalenceClassValuesToState.size()));
// If we did not insert, just return the already stored value.
if (!iter.second) {
return {iter.first->first, iter.first->second};
}
// If we did not insert, just return the already stored value.
self->stateIndexToEquivalenceClass[iter.first->second.getID()] = value;
// Otherwise, we need to compute our flags.
// Treat function ref and class method as either actor isolated or
// sendable. Formally they are non-Sendable, so we do the check before we
// check the oracle.
if (isa<FunctionRefInst, ClassMethodInst>(value)) {
if (auto isolation = SILIsolationInfo::get(value)) {
iter.first->getSecond().setIsolationRegionInfo(isolation);
return {iter.first->first, iter.first->second};
}
iter.first->getSecond().addFlag(TrackableValueFlag::isSendable);
return {iter.first->first, iter.first->second};
}
// Then check our oracle to see if the value is actually sendable. If we have
// a Sendable value, just return early.
if (!SILIsolationInfo::isNonSendableType(value->getType(), fn)) {
iter.first->getSecond().addFlag(TrackableValueFlag::isSendable);
return {iter.first->first, iter.first->second};
}
// Ok, at this point we have a non-Sendable value. First process addresses.
if (value->getType().isAddress()) {
auto storage = AccessStorageWithBase::compute(value);
if (storage.storage) {
// Check if we have a uniquely identified address that was not captured
// by a partial apply... in such a case, we treat it as no-alias.
if (storage.storage.isUniquelyIdentified() &&
!isAddressCapturedByPartialApply) {
iter.first->getSecond().removeFlag(TrackableValueFlag::isMayAlias);
}
if (auto isolation = SILIsolationInfo::get(storage.base)) {
iter.first->getSecond().setIsolationRegionInfo(isolation);
}
}
}
// Check if we have a load or load_borrow from an address. In that case, we
// want to look through the load and find a better root from the address we
// loaded from.
if (isa<LoadInst, LoadBorrowInst>(iter.first->first.getValue())) {
auto *svi = cast<SingleValueInstruction>(iter.first->first.getValue());
auto storage = AccessStorageWithBase::compute(svi->getOperand(0));
if (storage.storage) {
if (auto isolation = SILIsolationInfo::get(storage.base)) {
iter.first->getSecond().setIsolationRegionInfo(isolation);
}
}
return {iter.first->first, iter.first->second};
}
// Ok, we have a non-Sendable type, see if we do not have any isolation
// yet. If we don't, attempt to infer its isolation.
if (!iter.first->getSecond().hasIsolationRegionInfo()) {
if (auto isolation = SILIsolationInfo::get(iter.first->first.getValue())) {
iter.first->getSecond().setIsolationRegionInfo(isolation);
return {iter.first->first, iter.first->second};
}
}
return {iter.first->first, iter.first->second};
}
/// If \p isAddressCapturedByPartialApply is set to true, then this value is
/// an address that is captured by a partial_apply and we want to treat it as
/// may alias.
TrackableValueLookupResult RegionAnalysisValueMap::getTrackableValue(
SILValue inputValue, bool isAddressCapturedByPartialApply) const {
auto info = getUnderlyingTrackedValue(inputValue);
SILValue value = info.value;
SILValue base = info.base;
auto trackedValue =
getTrackableValueHelper(value, isAddressCapturedByPartialApply);
std::optional<TrackableValue> trackedBase;
if (base)
trackedBase =
getTrackableValueHelper(base, isAddressCapturedByPartialApply);
return {trackedValue, trackedBase};
}
std::optional<TrackableValue>
RegionAnalysisValueMap::getTrackableValueForActorIntroducingInst(
SILInstruction *inst) const {
auto *self = const_cast<RegionAnalysisValueMap *>(this);
auto iter = self->equivalenceClassValuesToState.find(inst);
if (iter == self->equivalenceClassValuesToState.end())
return {};
// Otherwise, we need to compute our flags.
return {{iter->first, iter->second}};
}
std::optional<TrackableValueLookupResult>
RegionAnalysisValueMap::tryToTrackValue(SILValue value) const {
auto state = getTrackableValue(value);
if (state.value.isNonSendable() ||
(state.base && state.base->isNonSendable()))
return state;
return {};
}
TrackableValue RegionAnalysisValueMap::getActorIntroducingRepresentative(
SILInstruction *introducingInst, SILIsolationInfo actorIsolation) const {
auto *self = const_cast<RegionAnalysisValueMap *>(this);
auto iter = self->equivalenceClassValuesToState.try_emplace(
introducingInst,
TrackableValueState(equivalenceClassValuesToState.size()));
// If we did not insert, just return the already stored value.
if (!iter.second) {
return {iter.first->first, iter.first->second};
}
// Otherwise, wire up the value.
self->stateIndexToEquivalenceClass[iter.first->second.getID()] =
introducingInst;
iter.first->getSecond().setIsolationRegionInfo(actorIsolation);
return {iter.first->first, iter.first->second};
}
bool RegionAnalysisValueMap::valueHasID(SILValue value, bool dumpIfHasNoID) {
assert(getTrackableValue(value).value.isNonSendable() &&
"Can only accept non-Sendable values");
bool hasID = equivalenceClassValuesToState.count(value);
if (!hasID && dumpIfHasNoID) {
llvm::errs() << "FAILURE: valueHasID of ";
value->print(llvm::errs());
llvm::report_fatal_error("standard compiler error");
}
return hasID;
}
Element RegionAnalysisValueMap::lookupValueID(SILValue value) {
auto state = getTrackableValue(value).value;
assert(state.isNonSendable() &&
"only non-Sendable values should be entered in the map");
return state.getID();
}
void RegionAnalysisValueMap::print(llvm::raw_ostream &os) const {
#ifndef NDEBUG
// Since this is just used for debug output, be inefficient to make nicer
// output.
std::vector<std::pair<unsigned, RepresentativeValue>> temp;
for (auto p : stateIndexToEquivalenceClass) {
temp.emplace_back(p.first, p.second);
}
std::sort(temp.begin(), temp.end());
for (auto p : temp) {
os << "%%" << p.first << ": ";
auto value = getValueForId(Element(p.first));
value->print(os);
}
#endif
}
namespace {
/// Walk from use->def looking through instructions. We have two goals here:
/// determining the actual equivilance class representative for the passed in
/// value and looking more aggressively up through uses (even Sendable ones) to
/// see if we are potentially accessing a base address value as a result of our
/// value being loaded. We explain these two below in more detail.
///
/// # Determining the equivalence class representative for our initial value
///
/// We want to determine the actual underlying object that is meant to be used
/// as the underlying object for our initial value. This value must either be
/// Sendable (in case which we take the first one). Or if it is non-Sendable, we
/// need to walk back through instructions that we consider look through until
/// we hit a Sendable value. We want to view the non-Sendable value as rooted in
/// the Sendable value since that Sendable value will likely be global actor
/// isolated or unchecked Sendable and we want SILIsolationInfo to infer
/// isolation from that instruction.
///
/// # Determining the "base" for our initial value
///
/// While the above process would be enough if we lived just in a world of
/// objects, we have to consider additionally the possibility that our object
/// value was loaded from a var, a non-copyable let that was captured, or an
/// address only type. In that case, even though generally the frontend performs
/// all transformations before loading:
///
/// ```sil
/// %0 = alloc_stack $Type
/// %1 = struct_element_addr %0, $Type, #Type.field
/// %2 = load [copy] %1 : $FieldType
/// ```
///
/// To truly be complete, we need to be able to handle cases where the frontend
/// has instead emitted the projection on the object:
///
/// ```sil
/// %0 = alloc_stack $Type
/// %1 = load_borrow %1 : $Type
/// %2 = struct_extract %1 : $Type, #Type.field
/// ```
///
/// To ensure that we can always find that base, we need to do some work like we
/// do in the AddressBaseComputingVisitor: namely we look through sendable
/// object projections (and object projections in general) until we find what I
/// term an object base (e.x.: a function argument, an apply result, a cast from
/// a RawPointer) or a load instruction. If we find a load instruction, then our
/// caller can know to run AddressBaseComputingVisitor to determine if we are
/// loading from a box in order to grab the value.
///
/// NOTE: The author has only seen this happen so far with unchecked_enum_data,
/// but relying on the frontend to emit code in a specific manner rather than
/// coming up with a model that works completely in SIL no matter what the
/// frontend does is the only way to have a coherent, non-brittle
/// model. Otherwise, there is an implicit contract in between the frontend and
/// the optimizer where both are following each other making it easy for the two
/// to get out of sync.
struct UnderlyingTrackedObjectValueVisitor {
SILValue value;
private:
/// Visit \p sourceValue returning a load base if we find one. The actual
/// underlying object is value.
SILValue visit(SILValue sourceValue) {
auto *fn = sourceValue->getFunction();
// If our result is ever Sendable, we record that as our value if we do
// not have a value yet. We always want to take the first one.
if (SILIsolationInfo::isSendableType(sourceValue->getType(), fn)) {
if (!value) {
value = sourceValue;
}
}
if (auto *svi = dyn_cast<SingleValueInstruction>(sourceValue)) {
if (isStaticallyLookThroughInst(svi)) {
if (!value && SILIsolationInfo::isSendableType(svi->getOperand(0)) &&
SILIsolationInfo::isNonSendableType(svi)) {
value = svi;
}
return 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)) {
return svi->getOperand(0);
}
if (!value && SILIsolationInfo::isSendableType(svi->getOperand(0)) &&
SILIsolationInfo::isNonSendableType(svi)) {
value = svi;
}
}
}
if (auto *inst = sourceValue->getDefiningInstruction()) {
if (isStaticallyLookThroughInst(inst)) {
if (!value && SILIsolationInfo::isSendableType(inst->getOperand(0)) &&
SILIsolationInfo::isNonSendableType(sourceValue)) {
value = sourceValue;
}
return inst->getOperand(0);
}
}
return SILValue();
}
public:
SILValue visitAll(SILValue sourceValue) {
// Before we do anything,
if (SILIsolationInfo::isSendableType(sourceValue))
value = sourceValue;
SILValue result = visit(sourceValue);
if (!result)
return sourceValue;
while (SILValue nextValue = visit(result))
result = nextValue;
return result;
}
};
} // namespace
RegionAnalysisValueMap::UnderlyingTrackedValueInfo
RegionAnalysisValueMap::getUnderlyingTrackedValueHelperObject(
SILValue value) const {
// Look through all look through values stopping at any Sendable values.
UnderlyingTrackedObjectValueVisitor visitor;
SILValue baseValue = visitor.visitAll(value);
assert(baseValue->getType().isObject());
if (!visitor.value) {
return UnderlyingTrackedValueInfo(baseValue);
}
assert(visitor.value->getType().isObject());
if (visitor.value == baseValue)
return UnderlyingTrackedValueInfo(visitor.value);
return UnderlyingTrackedValueInfo(visitor.value, baseValue);
}
RegionAnalysisValueMap::UnderlyingTrackedValueInfo
RegionAnalysisValueMap::getUnderlyingTrackedValueHelperAddress(
SILValue value) const {
AddressBaseComputingVisitor visitor;
SILValue base = visitor.visitAll(value);
assert(base);
// If we have an object base...
if (base->getType().isObject()) {
// Recurse.
//
// NOTE: We purposely recurse into getUnderlyingTrackedValueHelper instead
// of getUnderlyingTrackedValue since we could cause an invalidation to
// occur in the underlying DenseMap that backs getUnderlyingTrackedValue()
// if we insert another entry into the DenseMap.
if (!visitor.value)
return UnderlyingTrackedValueInfo(
getUnderlyingTrackedValueHelperObject(base));
// TODO: Should we us the base or value from
// getUnderlyingTrackedValueHelperObject as our base?
return UnderlyingTrackedValueInfo(
visitor.value, getUnderlyingTrackedValueHelperObject(base).value);
}
// Otherwise, we return the actorIsolation that our visitor found.
if (!visitor.value)
return UnderlyingTrackedValueInfo(base);
return UnderlyingTrackedValueInfo(visitor.value, base);