-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathMoveOnlyAddressCheckerUtils.cpp
4096 lines (3628 loc) · 157 KB
/
MoveOnlyAddressCheckerUtils.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
//===--- MoveOnlyAddressCheckerUtils.cpp ----------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// Move Only Checking of Addresses
/// -------------------------------
///
/// In this file, we implement move checking of addresses. This allows for the
/// compiler to perform move checking of address only lets, vars, inout args,
/// and mutating self.
///
/// Move Address Checking in Swift
/// ------------------------------
///
/// In order to not have to rewrite all of SILGen to avoid copies, Swift has
/// taken an approach where SILGen marks moveonly addresses with a special
/// marker instruction and emits copies when it attempts to access move only
/// addresses. Then this algorithm fixed up SILGen's output by analyzing the
/// memory uses of a marked memory root location recursively using AccessPath
/// based analyses and then attempting to transform those uses based off of the
/// marked kind into one of a few variants of "simple move only address form"
/// (see below for more information). If the pass is unable to reason that it
/// can safely transform the uses into said form, we emit a diagnostic stating
/// the error to the user. If we emit said diagnostic, we then bail early. If we
/// do not emit a diagnostic, we then transform the IR so that the move only
/// address uses are in said form. This then guarantees that despite SILGen
/// emitting move only types with copies, in the end, our move only types are
/// never copied. As an additional check, once the pass has run we emit an extra
/// diagnostic if we find any copies of move only types so that the user can be
/// sure that any accepted program does not copy move only types.
///
/// Simple Move Only Address Form
/// -----------------------------
///
/// We define a memory location to be in "simple move only address" form (SMOA
/// form for ease of typing) to mean that along any path from an init of the
/// address to a consume of the address, all uses are guaranteed to be semantic
/// "borrow uses" instead of semantic "copy uses". Additionally, SMOA does not
/// consider destroy_addr to be a true consuming use since it will rewrite
/// destroy_addr as necessary so the consuming uses are defined by consuming
/// uses modulo destroy_addr.
///
/// An example of a memory location in "simple move only address form" is the
/// following:
///
/// ```
/// // Memory is defined
/// %0 = alloc_stack $Type
///
/// // Initial initialization.
/// store %input to [init] %0 : $Type
///
/// // Sequence of borrow uses.
/// %1 = load_borrow %0 : $Type
/// apply %f(%1) : $@convention(thin) (@guaranteed Type) -> ()
/// end_borrow %1
/// apply %f2(%0) : $@convention(thin) (@in_guaranteed Type) -> ()
///
/// // Assign is ok since we are just consuming the value.
/// store %input2 to [assign] %0 : $*Type
///
/// // More borrow uses.
/// %3 = load_borrow %0 : $*Type
/// apply %f(%3) : $@convention(thin) (@guaranteed Type) -> ()
/// end_borrow %1
/// apply %f2(%0) : $@convention(thin) (@in_guaranteed Type) -> ()
///
/// // Final destroy
/// destroy_addr %0 : $Type
/// ```
///
/// An example of an instruction not in SMOA form is:
///
/// ```
/// // Memory is defined
/// %0 = alloc_stack $Type
///
/// // Initial initialization.
/// store %input to [init] %0 : $*Type
///
/// // Perform a load + copy of %0 to pass as an argument to %f.
/// %1 = load [copy] %0 : $*Type
/// apply %f(%1) : $@convention(thin) (@guaranteed Type) -> ()
/// destroy_value %1 : $Type
///
/// // Initialize other variable.
/// %otherVar = alloc_stack $Type
/// copy_addr %0 to [initialization] %otherVar : $*Type
/// ...
///
/// // Final destroy that is not part of the use set.
/// destroy_addr %0 : $*Type
/// ```
///
/// The variants of SMOA form can be classified by the specific
/// mark_unresolved_non_copyable_value kind put on the checker mark
/// instruction and are as follows:
///
/// 1. no_consume_or_assign. This means that the address can only be consumed by
/// destroy_addr and otherwise is only read from. This simulates guaranteed
/// semantics.
///
/// 2. consumable_and_assignable. This means that the address can be consumed
/// (e.x.: take/pass to a +1 function) or assigned to. Additionally, the value
/// is supposed to have its lifetime end along all program paths locally in the
/// function. This simulates a local var's semantics.
///
/// 3. assignable_but_not_consumable. This means that the address can be
/// assigned over, but cannot be taken from. It additionally must have a valid
/// value in it and the end of its lifetime. This simulates accesses to class
/// fields, globals, and escaping mutable captures where we want the user to be
/// able to update the value, but allowing for escapes of the value would break
/// memory safety. In all cases where this is used, the
/// mark_unresolved_non_copyable_value is used as the initial def of the value
/// lifetime. Example:
///
/// 4. initable_but_not_consumable. This means that the address can only be
/// initialized once but cannot be taken from or assigned over. It is assumed
/// that the initial def will always be the mark_unresolved_non_copyable_value
/// and that the value will be uninitialized at that point. Example:
///
/// Algorithm Stages In Detail
/// --------------------------
///
/// To implement this, our algorithm works in 4 stages: a use classification
/// stage, a dataflow stage, and then depending on success/failure one of two
/// transform stages.
///
/// Use Classification Stage
/// ~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Here we use an AccessPath based analysis to transitively visit all uses of
/// our marked address and classify a use as one of the following kinds of uses:
///
/// * init - store [init], copy_addr [init] %dest.
/// * destroy - destroy_addr.
/// * pureTake - load [take], copy_addr [take] %src.
/// * copyTransformableToTake - certain load [copy], certain copy_addr ![take]
/// %src of a temporary %dest.
/// * reinit - store [assign], copy_addr ![init] %dest
/// * borrow - load_borrow, a load [copy] without consuming uses.
/// * livenessOnly - a read only use of the address.
///
/// We classify these by adding them to several disjoint SetVectors which track
/// membership.
///
/// When we classify an instruction as copyTransformableToTake, we perform some
/// extra preprocessing to determine if we can actually transform this copy to a
/// take. This means that we:
///
/// 1. For loads, we perform object move only checking. If we find a need for
/// multiple copies, we emit an error. If we find no extra copies needed, we
/// classify the load [copy] as a take if it has any last consuming uses and a
/// borrow if it only has destroy_addr consuming uses.
///
/// 2. For copy_addr, we pattern match if a copy_addr is initializing a "simple
/// temporary" (an alloc_stack with only one use that initializes it, a
/// copy_addr [init] in the same block). In this case, if the copy_addr only has
/// destroy_addr consuming uses, we treat it as a borrow... otherwise, we treat
/// it as a take. If we find any extra initializations, we fail the visitor so
/// we emit a "I don't understand this error" so that users report this case and
/// we can extend it as appropriate.
///
/// If we fail in either case, if we emit an error, we bail early with success
/// so we can assume invariants later in the dataflow stages that make the
/// dataflow easier.
///
/// Dataflow Stage
/// ~~~~~~~~~~~~~~
///
/// To perform our dataflow, we take our classified uses and initialize field
/// sensitive pruned liveness with the data. We then use field sensitive pruned
/// liveness and our check kinds to determine if all of our copy uses that could
/// not be changed into borrows are on the liveness boundary of the memory. If
/// they are within the liveness boundary, then we know a copy is needed and we
/// emit an error to the user. Otherwise, we know that we can change them
/// semantically into a take.
///
/// Success Transformation
/// ~~~~~~~~~~~~~~~~~~~~~~
///
/// Now that we know that we can change our address into "simple move only
/// address form", we transform the IR in the following way:
///
/// 1. Any load [copy] that are classified as borrows are changed to
/// load_borrow.
/// 2. Any load [copy] that are classified as takes are changed to load [take].
/// 3. Any copy_addr [init] temporary allocation are eliminated with their
/// destroy_addr. All uses are placed on the source address.
/// 4. Any destroy_addr that is paired with a copyTransformableToTake is
/// eliminated.
///
/// Fail Transformation
/// ~~~~~~~~~~~~~~~~~~~
///
/// If we emit any diagnostics, we loop through the function one last time after
/// we are done processing and convert all load [copy]/copy_addr of move only
/// types into their explicit forms. We take a little more compile time, but we
/// are going to fail anyways at this point, so it is ok to do so since we will
/// fail before attempting to codegen into LLVM IR.
///
/// Final Black Box Checks on Success
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Finally since we want to be able to guarantee to users 100% that the
/// compiler will reject programs even if the checker gives a false success for
/// some reason due to human compiler writer error, we do a last pass over the
/// IR and emit an error diagnostic on any copies of move only types that we
/// see. The error states to the user that this is a compiler bug and to file a
/// bug report. Since it is a completely separate, simple implementation, this
/// gives the user of our implementation the confidence to know that the
/// compiler even in the face of complexity in the checker will emit correct
/// code.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-move-only-checker"
#include "swift/AST/AccessScope.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/SemanticAttrs.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Debug.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/FrozenMultiMap.h"
#include "swift/Basic/SmallBitVector.h"
#include "swift/SIL/ApplySite.h"
#include "swift/SIL/BasicBlockBits.h"
#include "swift/SIL/BasicBlockData.h"
#include "swift/SIL/BasicBlockDatastructures.h"
#include "swift/SIL/BasicBlockUtils.h"
#include "swift/SIL/Consumption.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/FieldSensitivePrunedLiveness.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/OSSALifetimeCompletion.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/PrunedLiveness.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILArgumentConvention.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/SILValue.h"
#include "swift/SILOptimizer/Analysis/ClosureScope.h"
#include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h"
#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h"
#include "swift/SILOptimizer/Analysis/NonLocalAccessBlockAnalysis.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/CanonicalizeOSSALifetime.h"
#include "swift/SILOptimizer/Utils/InstructionDeleter.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "MoveOnlyAddressCheckerUtils.h"
#include "MoveOnlyBorrowToDestructureUtils.h"
#include "MoveOnlyDiagnostics.h"
#include "MoveOnlyObjectCheckerUtils.h"
#include "MoveOnlyTypeUtils.h"
#include "MoveOnlyUtils.h"
#include <utility>
using namespace swift;
using namespace swift::siloptimizer;
llvm::cl::opt<bool> DisableMoveOnlyAddressCheckerLifetimeExtension(
"move-only-address-checker-disable-lifetime-extension",
llvm::cl::init(false),
llvm::cl::desc("Disable the lifetime extension of non-consumed fields of "
"move-only values."));
//===----------------------------------------------------------------------===//
// MARK: Utilities
//===----------------------------------------------------------------------===//
struct RAIILLVMDebug {
StringRef str;
RAIILLVMDebug(StringRef str) : str(str) {
LLVM_DEBUG(llvm::dbgs() << "===>>> Starting " << str << '\n');
}
RAIILLVMDebug(StringRef str, SILInstruction *u) : str(str) {
LLVM_DEBUG(llvm::dbgs() << "===>>> Starting " << str << ":" << *u);
}
~RAIILLVMDebug() {
LLVM_DEBUG(llvm::dbgs() << "===<<< Completed " << str << '\n');
}
};
static void insertDebugValueBefore(SILInstruction *insertPt,
DebugVarCarryingInst debugVar,
llvm::function_ref<SILValue ()> operand) {
if (!debugVar) {
return;
}
auto varInfo = debugVar.getVarInfo();
if (!varInfo) {
return;
}
SILBuilderWithScope debugInfoBuilder(insertPt);
debugInfoBuilder.setCurrentDebugScope(debugVar->getDebugScope());
debugInfoBuilder.createDebugValue(debugVar->getLoc(), operand(), *varInfo,
DontPoisonRefs, UsesMoveableValueDebugInfo);
}
static void convertMemoryReinitToInitForm(SILInstruction *memInst,
DebugVarCarryingInst debugVar) {
SILValue dest;
switch (memInst->getKind()) {
default:
llvm_unreachable("unsupported?!");
case SILInstructionKind::CopyAddrInst: {
auto *cai = cast<CopyAddrInst>(memInst);
cai->setIsInitializationOfDest(IsInitialization_t::IsInitialization);
dest = cai->getDest();
break;
}
case SILInstructionKind::StoreInst: {
auto *si = cast<StoreInst>(memInst);
si->setOwnershipQualifier(StoreOwnershipQualifier::Init);
dest = si->getDest();
break;
}
}
// Insert a new debug_value instruction after the reinitialization, so that
// the debugger knows that the variable is in a usable form again.
insertDebugValueBefore(memInst->getNextInstruction(), debugVar,
[&]{ return debugVar.getOperandForDebugValueClone(); });
}
/// Is this a reinit instruction that we know how to convert into its init form.
static bool isReinitToInitConvertibleInst(SILInstruction *memInst) {
switch (memInst->getKind()) {
default:
return false;
case SILInstructionKind::CopyAddrInst: {
auto *cai = cast<CopyAddrInst>(memInst);
return !cai->isInitializationOfDest();
}
case SILInstructionKind::StoreInst: {
auto *si = cast<StoreInst>(memInst);
return si->getOwnershipQualifier() == StoreOwnershipQualifier::Assign;
}
}
}
using ScopeRequiringFinalInit = DiagnosticEmitter::ScopeRequiringFinalInit;
/// If \p markedAddr's operand must be initialized at the end of the scope it
/// introduces, visit those scope ending ends.
///
/// Examples:
/// (1) inout function argument. Must be initialized at function exit.
///
/// sil [ossa] @f : $(inout MOV) -> ()
/// entry(%addr : $*MOV):
/// ...
/// return %t : $() // %addr must be initialized here
///
/// (2) coroutine. Must be initialized at end_apply/abort_apply.
///
/// (%addr, %token) = begin_apply ... -> @yields @inout MOV
/// bbN:
/// end_apply %token // %addr must be initialized here
/// bbM:
/// abort_apply %token // %addr must be initialized here
///
/// (3) modify access. Must be initialized at end_access.
///
/// %addr = begin_access [modify] %location
///
/// end_access %addr // %addr must be initialized here
///
/// To enforce this requirement, function exiting instructions are treated as
/// liveness uses of such addresses, ensuring that the address is initialized at
/// that point.
static bool visitScopeEndsRequiringInit(
MarkUnresolvedNonCopyableValueInst *markedAddr,
llvm::function_ref<void(SILInstruction *, ScopeRequiringFinalInit)> visit) {
SILValue operand = markedAddr->getOperand();
// TODO: This should really be a property of the marker instruction.
switch (markedAddr->getCheckKind()) {
case MarkUnresolvedNonCopyableValueInst::CheckKind::
AssignableButNotConsumable:
case MarkUnresolvedNonCopyableValueInst::CheckKind::ConsumableAndAssignable:
break;
case MarkUnresolvedNonCopyableValueInst::CheckKind::InitableButNotConsumable:
case MarkUnresolvedNonCopyableValueInst::CheckKind::NoConsumeOrAssign:
return false;
case MarkUnresolvedNonCopyableValueInst::CheckKind::Invalid:
llvm_unreachable("invalid check!?");
}
// Look through wrappers.
if (auto m = dyn_cast<CopyableToMoveOnlyWrapperAddrInst>(operand)) {
operand = m->getOperand();
}
// Check for inout types of arguments that are marked with consumable and
// assignable.
if (auto *fArg = dyn_cast<SILFunctionArgument>(operand)) {
switch (fArg->getArgumentConvention()) {
case SILArgumentConvention::Indirect_In:
case SILArgumentConvention::Indirect_Out:
case SILArgumentConvention::Indirect_In_Guaranteed:
case SILArgumentConvention::Indirect_In_CXX:
case SILArgumentConvention::Direct_Guaranteed:
case SILArgumentConvention::Direct_Owned:
case SILArgumentConvention::Direct_Unowned:
case SILArgumentConvention::Pack_Guaranteed:
case SILArgumentConvention::Pack_Owned:
case SILArgumentConvention::Pack_Out:
return false;
case SILArgumentConvention::Indirect_Inout:
case SILArgumentConvention::Indirect_InoutAliasable:
case SILArgumentConvention::Pack_Inout:
LLVM_DEBUG(llvm::dbgs() << "Found inout arg: " << *fArg);
SmallVector<SILBasicBlock *, 8> exitBlocks;
markedAddr->getFunction()->findExitingBlocks(exitBlocks);
for (auto *block : exitBlocks) {
visit(block->getTerminator(), ScopeRequiringFinalInit::InoutArgument);
}
return true;
}
}
// Check for yields from a modify coroutine.
if (auto bai =
dyn_cast_or_null<BeginApplyInst>(operand->getDefiningInstruction())) {
for (auto *use : bai->getEndApplyUses()) {
auto *inst = use->getUser();
assert(isa<EndApplyInst>(inst) || isa<AbortApplyInst>(inst) ||
isa<EndBorrowInst>(inst));
visit(inst, ScopeRequiringFinalInit::Coroutine);
}
return true;
}
// Check for modify accesses.
if (auto access = dyn_cast<BeginAccessInst>(operand)) {
if (access->getAccessKind() != SILAccessKind::Modify) {
return false;
}
for (auto *inst : access->getEndAccesses()) {
visit(inst, ScopeRequiringFinalInit::ModifyMemoryAccess);
}
return true;
}
return false;
}
static bool isCopyableValue(SILValue value) {
if (value->getType().isMoveOnly())
return false;
if (isa<MoveOnlyWrapperToCopyableAddrInst>(value))
return false;
return true;
}
//===----------------------------------------------------------------------===//
// MARK: Find Candidate Mark Must Checks
//===----------------------------------------------------------------------===//
void swift::siloptimizer::
searchForCandidateAddressMarkUnresolvedNonCopyableValueInsts(
SILFunction *fn, PostOrderAnalysis *poa,
llvm::SmallSetVector<MarkUnresolvedNonCopyableValueInst *, 32>
&moveIntroducersToProcess,
DiagnosticEmitter &diagnosticEmitter) {
auto *po = poa->get(fn);
for (auto *block : po->getPostOrder()) {
for (auto &ii : llvm::make_range(block->rbegin(), block->rend())) {
auto *mmci = dyn_cast<MarkUnresolvedNonCopyableValueInst>(&ii);
if (!mmci || !mmci->hasMoveCheckerKind() || !mmci->getType().isAddress())
continue;
moveIntroducersToProcess.insert(mmci);
}
}
}
//===----------------------------------------------------------------------===//
// MARK: Use State
//===----------------------------------------------------------------------===//
namespace {
struct UseState {
MarkUnresolvedNonCopyableValueInst *address;
DominanceInfo *const domTree;
// FIXME: [partial_consume_of_deiniting_aggregate_with_drop_deinit] Keep track
// of the projections out of which a use emerges and use that to tell
// whether a particular partial consume is allowed.
//
// For example, give the TransitiveAddressWalker's worklist a
// client-dependent context and look in that to determine whether a
// relevant drop_deinit has been seen when erroring on partial
// destructuring.
bool sawDropDeinit = false;
using InstToBitMap =
llvm::SmallMapVector<SILInstruction *, SmallBitVector, 4>;
std::optional<unsigned> cachedNumSubelements;
/// The blocks that consume fields of the value.
///
/// A map from blocks to a bit vector recording which fields were destroyed
/// in each.
llvm::SmallMapVector<SILBasicBlock *, SmallBitVector, 8> consumingBlocks;
/// A map from destroy_addr to the part of the type that it destroys.
llvm::SmallMapVector<SILInstruction *, TypeTreeLeafTypeRange, 4> destroys;
/// Maps a non-consuming use to the part of the type that it requires
/// liveness for.
InstToBitMap nonconsumingUses;
/// A map from a load [copy] or load [take] that we determined must be
/// converted to a load_borrow to the part of the type tree that it needs to
/// borrow.
///
/// NOTE: This does not include actual load_borrow which are treated
/// just as liveness uses.
///
/// NOTE: load_borrow that we actually copy, we canonicalize early to a load
/// [copy] + begin_borrow so that we do not need to convert load_borrow to a
/// normal load when rewriting.
llvm::SmallMapVector<SILInstruction *, TypeTreeLeafTypeRange, 4> borrows;
/// A copy_addr, load [copy], or load [take] that we determine is semantically
/// truly a take mapped to the part of the type tree that it needs to use.
///
/// DISCUSSION: A copy_addr [init] or load [copy] are considered actually
/// takes if they are not destroyed with a destroy_addr/destroy_value. We
/// consider them to be takes since after the transform they must be a take.
///
/// Importantly, these we know are never copied and are only consumed once.
InstToBitMap takeInsts;
/// A map from a copy_addr, load [copy], or load [take] that we determine
/// semantically are true copies to the part of the type tree they must copy.
///
/// DISCUSSION: One of these instructions being a true copy means that their
/// result or destination is used in a way that some sort of extra copy is
/// needed. Example:
///
/// %0 = load [take] %addr
/// %1 = copy_value %0
/// consume(%0)
/// consume(%1)
///
/// Notice how the load [take] above semantically requires a copy since it was
/// consumed twice even though SILGen emitted it as a load [take].
///
/// We represent these separately from \p takeInsts since:
///
/// 1.
InstToBitMap copyInsts;
/// A map from an instruction that initializes memory to the description of
/// the part of the type tree that it initializes.
InstToBitMap initInsts;
SmallFrozenMultiMap<SILInstruction *, SILValue, 8> initToValueMultiMap;
/// memInstMustReinitialize insts. Contains both insts like copy_addr/store
/// [assign] that are reinits that we will convert to inits and true reinits.
InstToBitMap reinitInsts;
SmallFrozenMultiMap<SILInstruction *, SILValue, 8> reinitToValueMultiMap;
/// The set of drop_deinits of this mark_unresolved_non_copyable_value
llvm::SmallSetVector<SILInstruction *, 2> dropDeinitInsts;
/// Instructions indicating the end of a scope at which addr must be
/// initialized.
///
/// Adding such instructions to liveness forces the value to be initialized at
/// them as required.
///
/// See visitScopeEndsRequiringInit.
llvm::MapVector<SILInstruction *, ScopeRequiringFinalInit>
scopeEndsRequiringInit;
/// We add debug_values to liveness late after we diagnose, but before we
/// hoist destroys to ensure that we do not hoist destroys out of access
/// scopes.
DebugValueInst *debugValue = nullptr;
UseState(DominanceInfo *domTree) : domTree(domTree) {}
SILFunction *getFunction() const { return address->getFunction(); }
/// The number of fields in the exploded type.
unsigned getNumSubelements() {
if (!cachedNumSubelements) {
cachedNumSubelements = TypeSubElementCount(address);
}
return *cachedNumSubelements;
}
SmallBitVector &getOrCreateAffectedBits(SILInstruction *inst,
InstToBitMap &map) {
auto iter = map.find(inst);
if (iter == map.end()) {
iter = map.insert({inst, SmallBitVector(getNumSubelements())}).first;
}
return iter->second;
}
void setAffectedBits(SILInstruction *inst, SmallBitVector const &bits,
InstToBitMap &map) {
getOrCreateAffectedBits(inst, map) |= bits;
}
void setAffectedBits(SILInstruction *inst, TypeTreeLeafTypeRange range,
InstToBitMap &map) {
range.setBits(getOrCreateAffectedBits(inst, map));
}
void recordLivenessUse(SILInstruction *inst, SmallBitVector const &bits) {
setAffectedBits(inst, bits, nonconsumingUses);
}
void recordLivenessUse(SILInstruction *inst, TypeTreeLeafTypeRange range) {
setAffectedBits(inst, range, nonconsumingUses);
}
void recordReinitUse(SILInstruction *inst, SILValue value,
TypeTreeLeafTypeRange range) {
reinitToValueMultiMap.insert(inst, value);
setAffectedBits(inst, range, reinitInsts);
}
void recordInitUse(SILInstruction *inst, SILValue value,
TypeTreeLeafTypeRange range) {
initToValueMultiMap.insert(inst, value);
setAffectedBits(inst, range, initInsts);
}
void recordTakeUse(SILInstruction *inst, TypeTreeLeafTypeRange range) {
setAffectedBits(inst, range, takeInsts);
}
void recordCopyUse(SILInstruction *inst, TypeTreeLeafTypeRange range) {
setAffectedBits(inst, range, copyInsts);
}
/// Returns true if this is an instruction that is used by the pass to ensure
/// that we reinit said argument if we consumed it in a region of code.
///
/// Example:
///
/// 1. In the case of an inout argument, this will contain the terminator
/// instruction.
/// 2. In the case of a ref_element_addr or a global, this will contain the
/// end_access.
std::optional<ScopeRequiringFinalInit>
isImplicitEndOfLifetimeLivenessUses(SILInstruction *inst) const {
auto iter = scopeEndsRequiringInit.find(inst);
if (iter == scopeEndsRequiringInit.end()) {
return std::nullopt;
}
return {iter->second};
}
/// Returns true if the given instruction is within the same block as a reinit
/// and precedes a reinit instruction in that block.
bool precedesReinitInSameBlock(SILInstruction *inst) const {
SILBasicBlock *block = inst->getParent();
llvm::SmallSetVector<SILInstruction *, 8> sameBlockReinits;
// First, search for all reinits that are within the same block.
for (auto &reinit : reinitInsts) {
if (reinit.first->getParent() != block)
continue;
sameBlockReinits.insert(reinit.first);
}
if (sameBlockReinits.empty())
return false;
// Walk down from the given instruction to see if we encounter a reinit.
for (auto ii = std::next(inst->getIterator()); ii != block->end(); ++ii) {
if (sameBlockReinits.contains(&*ii))
return true;
}
return false;
}
void clear() {
address = nullptr;
cachedNumSubelements = std::nullopt;
consumingBlocks.clear();
destroys.clear();
nonconsumingUses.clear();
borrows.clear();
copyInsts.clear();
takeInsts.clear();
initInsts.clear();
initToValueMultiMap.reset();
reinitInsts.clear();
reinitToValueMultiMap.reset();
dropDeinitInsts.clear();
scopeEndsRequiringInit.clear();
debugValue = nullptr;
}
void dump() {
llvm::dbgs() << "AddressUseState!\n";
llvm::dbgs() << "Destroys:\n";
for (auto pair : destroys) {
llvm::dbgs() << *pair.first;
}
llvm::dbgs() << "LivenessUses:\n";
for (auto pair : nonconsumingUses) {
llvm::dbgs() << *pair.first;
}
llvm::dbgs() << "Borrows:\n";
for (auto pair : borrows) {
llvm::dbgs() << *pair.first;
}
llvm::dbgs() << "Takes:\n";
for (auto pair : takeInsts) {
llvm::dbgs() << *pair.first;
}
llvm::dbgs() << "Copies:\n";
for (auto pair : copyInsts) {
llvm::dbgs() << *pair.first;
}
llvm::dbgs() << "Inits:\n";
for (auto pair : initInsts) {
llvm::dbgs() << *pair.first;
}
llvm::dbgs() << "Reinits:\n";
for (auto pair : reinitInsts) {
llvm::dbgs() << *pair.first;
}
llvm::dbgs() << "DropDeinits:\n";
for (auto *inst : dropDeinitInsts) {
llvm::dbgs() << *inst;
}
llvm::dbgs() << "Implicit End Of Lifetime Liveness Users:\n";
for (auto pair : scopeEndsRequiringInit) {
llvm::dbgs() << pair.first;
}
llvm::dbgs() << "Debug Value User:\n";
if (debugValue) {
llvm::dbgs() << *debugValue;
}
}
void freezeMultiMaps() {
initToValueMultiMap.setFrozen();
reinitToValueMultiMap.setFrozen();
}
SmallBitVector &getOrCreateConsumingBlock(SILBasicBlock *block) {
auto iter = consumingBlocks.find(block);
if (iter == consumingBlocks.end()) {
iter =
consumingBlocks.insert({block, SmallBitVector(getNumSubelements())})
.first;
}
return iter->second;
}
void recordConsumingBlock(SILBasicBlock *block, TypeTreeLeafTypeRange range) {
auto &consumingBits = getOrCreateConsumingBlock(block);
range.setBits(consumingBits);
}
void recordConsumingBlock(SILBasicBlock *block, SmallBitVector &bits) {
auto &consumingBits = getOrCreateConsumingBlock(block);
consumingBits |= bits;
}
void
initializeLiveness(FieldSensitiveMultiDefPrunedLiveRange &prunedLiveness);
void initializeImplicitEndOfLifetimeLivenessUses() {
visitScopeEndsRequiringInit(address, [&](auto *inst, auto kind) {
LLVM_DEBUG(llvm::dbgs()
<< " Adding scope end as liveness user: " << *inst);
scopeEndsRequiringInit[inst] = kind;
});
}
bool isConsume(SILInstruction *inst, SmallBitVector const &bits) const {
{
auto iter = takeInsts.find(inst);
if (iter != takeInsts.end()) {
if (bits.anyCommon(iter->second))
return true;
}
}
{
auto iter = copyInsts.find(inst);
if (iter != copyInsts.end()) {
if (bits.anyCommon(iter->second))
return true;
}
}
return false;
}
bool isCopy(SILInstruction *inst, const SmallBitVector &bv) const {
auto iter = copyInsts.find(inst);
if (iter != copyInsts.end()) {
if (bv.anyCommon(iter->second))
return true;
}
return false;
}
bool isLivenessUse(SILInstruction *inst, SmallBitVector const &bits) const {
{
auto iter = nonconsumingUses.find(inst);
if (iter != nonconsumingUses.end()) {
if (bits.anyCommon(iter->second))
return true;
}
}
{
auto iter = borrows.find(inst);
if (iter != borrows.end()) {
if (iter->second.intersects(bits))
return true;
}
}
if (!isReinitToInitConvertibleInst(inst)) {
auto iter = reinitInsts.find(inst);
if (iter != reinitInsts.end()) {
if (bits.anyCommon(iter->second))
return true;
}
}
// An "inout terminator use" is an implicit liveness use of the entire
// value. This is because we need to ensure that our inout value is
// reinitialized along exit paths.
if (scopeEndsRequiringInit.count(inst))
return true;
return false;
}
bool isInitUse(SILInstruction *inst, const SmallBitVector &requiredBits) const {
{
auto iter = initInsts.find(inst);
if (iter != initInsts.end()) {
if (requiredBits.anyCommon(iter->second))
return true;
}
}
if (isReinitToInitConvertibleInst(inst)) {
auto iter = reinitInsts.find(inst);
if (iter != reinitInsts.end()) {
if (requiredBits.anyCommon(iter->second))
return true;
}
}
return false;
}
};
} // namespace
//===----------------------------------------------------------------------===//
// MARK: Partial Apply Utilities
//===----------------------------------------------------------------------===//
static bool findNonEscapingPartialApplyUses(PartialApplyInst *pai,
TypeTreeLeafTypeRange leafRange,
UseState &useState) {
StackList<Operand *> worklist(pai->getFunction());
for (auto *use : pai->getUses())
worklist.push_back(use);
LLVM_DEBUG(llvm::dbgs() << "Searching for partial apply uses!\n");
while (!worklist.empty()) {
auto *use = worklist.pop_back_val();
if (use->isTypeDependent())
continue;
auto *user = use->getUser();
// These instructions do not cause us to escape.
if (isIncidentalUse(user) || isa<DestroyValueInst>(user))
continue;
// Look through these instructions.
if (isa<BeginBorrowInst>(user) || isa<CopyValueInst>(user) ||
isa<MoveValueInst>(user) ||
// If we capture this partial_apply in another partial_apply, then we
// know that said partial_apply must not have escaped the value since
// otherwise we could not have an inout_aliasable argument or be
// on_stack. Process it recursively so that we treat uses of that
// partial_apply and applies of that partial_apply as uses of our
// partial_apply.
//
// We have this separately from the other look through sections so that
// we can make it clearer what we are doing here.
isa<PartialApplyInst>(user) ||
// Likewise with convert_function. Any valid function conversion that
// doesn't prevent stack promotion of the closure must retain the
// invariants on its transitive uses.
isa<ConvertFunctionInst>(user)) {
for (auto *use : cast<SingleValueInstruction>(user)->getUses())
worklist.push_back(use);
continue;
}
// If we have a mark_dependence and are the value, look through the
// mark_dependence.
if (auto *mdi = dyn_cast<MarkDependenceInst>(user)) {
if (mdi->getValue() == use->get()) {
for (auto *use : mdi->getUses())
worklist.push_back(use);
continue;
}
}
if (auto apply = FullApplySite::isa(user)) {
// If we apply the function or pass the function off to an apply, then we
// need to treat the function application as a liveness use of the
// variable since if the partial_apply is invoked within the function
// application, we may access the captured variable.
useState.recordLivenessUse(user, leafRange);
if (apply.beginsCoroutineEvaluation()) {
// If we have a coroutine, we need to treat the abort_apply and
// end_apply as liveness uses since once we execute one of those
// instructions, we have returned control to the coroutine which means
// that we could then access the captured variable again.
auto *bai = cast<BeginApplyInst>(user);
SmallVector<EndApplyInst *, 4> endApplies;
SmallVector<AbortApplyInst *, 4> abortApplies;
bai->getCoroutineEndPoints(endApplies, abortApplies);
for (auto *eai : endApplies)
useState.recordLivenessUse(eai, leafRange);
for (auto *aai : abortApplies)
useState.recordLivenessUse(aai, leafRange);
}
continue;
}
LLVM_DEBUG(
llvm::dbgs()
<< "Found instruction we did not understand... returning false!\n");
LLVM_DEBUG(llvm::dbgs() << "Instruction: " << *user);
return false;
}
return true;
}
static bool
addressBeginsInitialized(MarkUnresolvedNonCopyableValueInst *address) {
// FIXME: Whether the initial use is an initialization ought to be entirely
// derivable from the CheckKind of the mark instruction.
SILValue operand = address->getOperand();
if (auto *mdi = dyn_cast<MarkDependenceInst>(operand)) {
operand = mdi->getValue();
}