-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathOwnershipOptUtils.cpp
2020 lines (1773 loc) · 79 KB
/
OwnershipOptUtils.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
//===--- OwnershipOptUtils.cpp --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// Ownership Utilities that rely on SILOptimizer functionality.
///
//===----------------------------------------------------------------------===//
#include "swift/SILOptimizer/Utils/OwnershipOptUtils.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/SIL/BasicBlockUtils.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/LinearLifetimeChecker.h"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/ScopedAddressUtils.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SILOptimizer/OptimizerBridging.h"
#include "swift/SILOptimizer/Utils/CFGOptUtils.h"
#include "swift/SILOptimizer/Utils/InstructionDeleter.h"
#include "swift/SILOptimizer/Utils/ValueLifetime.h"
using namespace swift;
//===----------------------------------------------------------------------===//
// Basic scope and lifetime extension API
//===----------------------------------------------------------------------===//
void swift::extendOwnedLifetime(SILValue ownedValue,
PrunedLivenessBoundary &lifetimeBoundary,
InstructionDeleter &deleter) {
// Gather the current set of destroy_values, which may die.
llvm::SmallSetVector<Operand *, 4> extraConsumes;
SmallPtrSet<SILInstruction *, 4> extraConsumers;
for (Operand *use : ownedValue->getUses()) {
if (use->isConsuming()) {
extraConsumes.insert(use);
extraConsumers.insert(use->getUser());
}
}
// Insert or reuse a destroy_value at all last users.
auto createDestroy = [&](SILBuilder &builder) {
auto loc = RegularLocation::getAutoGeneratedLocation(
builder.getInsertionPointLoc());
auto *destroy = builder.createDestroyValue(loc, ownedValue);
deleter.getCallbacks().createdNewInst(destroy);
};
for (SILInstruction *lastUser : lifetimeBoundary.lastUsers) {
if (extraConsumers.erase(lastUser))
continue;
SILBuilderWithScope::insertAfter(lastUser, createDestroy);
}
// Insert a destroy_value at all boundary edges.
for (SILBasicBlock *edge : lifetimeBoundary.boundaryEdges) {
SILBuilderWithScope builder(edge->begin());
createDestroy(builder);
}
// Delete or copy extra consumes.
for (auto *consume : extraConsumes) {
auto *consumer = consume->getUser();
if (!extraConsumers.count(consumer))
continue;
if (isa<DestroyValueInst>(consumer)) {
deleter.forceDelete(consumer);
continue;
}
auto loc = RegularLocation::getAutoGeneratedLocation(consumer->getLoc());
auto *copy = SILBuilderWithScope(consumer).createCopyValue(loc, ownedValue);
consume->set(copy);
deleter.getCallbacks().createdNewInst(copy);
}
}
void swift::extendLocalBorrow(BeginBorrowInst *beginBorrow,
PrunedLivenessBoundary &guaranteedBoundary,
InstructionDeleter &deleter) {
// Gather the current set of end_borrows, which may die.
SmallVector<EndBorrowInst *, 4> endBorrows;
SmallPtrSet<EndBorrowInst *, 4> deadEndBorrows;
for (Operand *use : beginBorrow->getUses()) {
if (auto *endBorrow = dyn_cast<EndBorrowInst>(use->getUser())) {
endBorrows.push_back(endBorrow);
deadEndBorrows.insert(endBorrow);
continue;
}
assert(use->getOperandOwnership() != OperandOwnership::EndBorrow
&& use->getOperandOwnership() != OperandOwnership::Reborrow
&& "expecting a purely local borrow scope");
}
// Insert or reuse an end_borrow at all last users.
auto createEndBorrow = [&](SILBuilder &builder) {
auto loc = RegularLocation::getAutoGeneratedLocation(
builder.getInsertionPointLoc());
auto *endBorrow = builder.createEndBorrow(loc, beginBorrow);
deleter.getCallbacks().createdNewInst(endBorrow);
};
for (SILInstruction *lastUser : guaranteedBoundary.lastUsers) {
if (auto *endBorrow = dyn_cast<EndBorrowInst>(lastUser)) {
if (deadEndBorrows.erase(endBorrow))
continue;
}
SILBuilderWithScope::insertAfter(lastUser, createEndBorrow);
}
// Insert an end_borrow at all boundary edges.
for (SILBasicBlock *edge : guaranteedBoundary.boundaryEdges) {
SILBuilderWithScope builder(edge->begin());
createEndBorrow(builder);
}
// Delete dead end_borrows.
for (auto *endBorrow : endBorrows) {
if (deadEndBorrows.count(endBorrow))
deleter.forceDelete(endBorrow);
}
}
bool swift::computeGuaranteedBoundary(SILValue value,
PrunedLivenessBoundary &boundary) {
assert(value->getOwnershipKind() == OwnershipKind::Guaranteed);
// Place end_borrows that cover the load_borrow uses. It is not necessary to
// cover the outer borrow scope of the extract's operand. If a lexical
// borrow scope exists for the outer value, which is now in memory, then
// its alloc_stack will be marked lexical, and the in-memory values will be
// kept alive until the end of the outer scope.
SmallVector<Operand *, 4> usePoints;
bool noEscape = findInnerTransitiveGuaranteedUses(value, &usePoints);
SmallVector<SILBasicBlock *, 4> discoveredBlocks;
SSAPrunedLiveness liveness(value->getFunction(), &discoveredBlocks);
liveness.initializeDef(value);
for (auto *use : usePoints) {
assert(!use->isLifetimeEnding());
liveness.updateForUse(use->getUser(), /*lifetimeEnding*/ false);
}
liveness.computeBoundary(boundary);
return noEscape;
}
//===----------------------------------------------------------------------===//
// GuaranteedOwnershipExtension
//===----------------------------------------------------------------------===//
// Can the OSSA ownership of the \p parentAddress cover all uses of the \p
// childAddress?
GuaranteedOwnershipExtension::Status
GuaranteedOwnershipExtension::checkAddressOwnership(SILValue parentAddress,
SILValue childAddress) {
AddressOwnership addressOwnership(parentAddress);
if (!addressOwnership) {
return Invalid;
}
if (!addressOwnership.hasLocalOwnershipLifetime()) {
// Indirect Arg, Stack, Global, Unidentified, Yield
// (these have no reference lifetime to extend).
return Valid;
}
SmallVector<Operand *, 8> childUses;
if (findTransitiveUsesForAddress(childAddress, &childUses)
!= AddressUseKind::NonEscaping) {
return Invalid; // pointer escape, so we don't know required lifetime
}
SILValue referenceRoot = addressOwnership.getOwnershipReferenceRoot();
assert(referenceRoot && "expect to find a reference to Box/Class/Tail");
if (referenceRoot->getOwnershipKind() != OwnershipKind::Guaranteed) {
// Note: Addresses are normally guarded by a borrow scope. But eventually,
// an address base can be considered an implicit borrow. This current
// handles project_box, which is not in a borrow scope (it is sadly modeled
// as a PointerEscape). But we can treat project_box like an implicit borrow
// in this context.
return checkLifetimeExtension(referenceRoot, childUses);
}
BorrowedValue parentBorrow(referenceRoot);
if (!parentBorrow)
return Invalid; // unexpected borrow introducer
return checkBorrowExtension(parentBorrow, childUses);
}
// Can the OSSA scope of \p borrow cover all \p newUses?
GuaranteedOwnershipExtension::Status
GuaranteedOwnershipExtension::checkBorrowExtension(
BorrowedValue borrow, ArrayRef<Operand *> newUses) {
if (!borrow.isLocalScope())
return Valid; // arguments have whole-function ownership
assert(guaranteedLiveness.empty());
borrow.computeTransitiveLiveness(guaranteedLiveness);
if (guaranteedLiveness.areUsesWithinBoundary(newUses, &deBlocks))
return Valid; // reuse the borrow scope as-is
beginBorrow = dyn_cast<BeginBorrowInst>(borrow.value);
if (!beginBorrow)
return Invalid; // cannot extend load_borrow without memory lifetime
// Extend liveness to the new uses before returning any status that leads to
// transformation.
for (Operand *use : newUses) {
guaranteedLiveness.updateForUse(use->getUser(), /*lifetimeEnding*/ false);
}
// It is unusual to have a borrow scope that (a) dominates the new uses, (b)
// does not already cover the new uses, but (c) already has a reborrow for
// some other reason.
if (borrow.hasReborrow())
return Invalid; // Can only extend a local scope up to dominated uses
auto status = checkLifetimeExtension(beginBorrow->getOperand(), newUses);
if (status == Valid) {
// The owned lifetime is adequate, but the borrow scope must be extended.
return ExtendBorrow;
}
return status;
}
GuaranteedOwnershipExtension::Status
GuaranteedOwnershipExtension::checkLifetimeExtension(
SILValue ownedValue, ArrayRef<Operand *> newUses) {
assert(ownedLifetime.empty());
auto ownershipKind = ownedValue->getOwnershipKind();
if (ownershipKind == OwnershipKind::None)
return Valid;
// If the ownedValue is not owned, give up for simplicity. We expect nested
// borrows to be removed.
if (ownershipKind != OwnershipKind::Owned)
return Invalid;
ownedLifetime.initializeDef(ownedValue);
for (Operand *use : ownedValue->getUses()) {
auto *user = use->getUser();
if (use->isConsuming()) {
ownedLifetime.updateForUse(user, true);
ownedConsumeBlocks.push_back(user->getParent());
}
}
if (ownedLifetime.areUsesWithinBoundary(newUses, &deBlocks))
return Valid;
return ExtendLifetime; // Can't cover newUses without destroy sinking.
}
void GuaranteedOwnershipExtension::transform(Status status) {
switch (status) {
case Invalid:
case Valid:
return;
case ExtendBorrow: {
PrunedLivenessBoundary guaranteedBoundary;
guaranteedLiveness.computeBoundary(guaranteedBoundary, ownedConsumeBlocks);
extendLocalBorrow(beginBorrow, guaranteedBoundary, deleter);
break;
}
case ExtendLifetime: {
ownedLifetime.extendAcrossLiveness(guaranteedLiveness);
PrunedLivenessBoundary ownedBoundary;
ownedLifetime.computeBoundary(ownedBoundary, ownedConsumeBlocks);
extendOwnedLifetime(beginBorrow->getOperand(), ownedBoundary, deleter);
PrunedLivenessBoundary guaranteedBoundary;
guaranteedLiveness.computeBoundary(guaranteedBoundary, ownedConsumeBlocks);
extendLocalBorrow(beginBorrow, guaranteedBoundary, deleter);
break;
}
}
}
//===----------------------------------------------------------------------===//
// Utility Helper Functions
//===----------------------------------------------------------------------===//
static void cleanupOperandsBeforeDeletion(SILInstruction *oldValue,
InstModCallbacks &callbacks) {
SILBuilderWithScope builder(oldValue);
for (auto &op : oldValue->getAllOperands()) {
if (!op.isLifetimeEnding()) {
continue;
}
switch (op.get()->getOwnershipKind()) {
case OwnershipKind::Any:
llvm_unreachable("Invalid ownership for value");
case OwnershipKind::Owned: {
auto *dvi = builder.createDestroyValue(oldValue->getLoc(), op.get());
callbacks.createdNewInst(dvi);
continue;
}
case OwnershipKind::Guaranteed: {
// Should only happen once we model destructures as true reborrows.
auto *ebi = builder.createEndBorrow(oldValue->getLoc(), op.get());
callbacks.createdNewInst(ebi);
continue;
}
case OwnershipKind::None:
continue;
case OwnershipKind::Unowned:
llvm_unreachable("Unowned object can never be consumed?!");
}
llvm_unreachable("Covered switch isn't covered");
}
}
//===----------------------------------------------------------------------===//
// Ownership RAUW Helper Functions
//===----------------------------------------------------------------------===//
// Determine whether it is valid to replace \p oldValue with \p newValue by
// directly checking ownership requirements. This does not determine whether the
// scope of the newValue can be fully extended.
bool OwnershipRAUWHelper::hasValidRAUWOwnership(SILValue oldValue,
SILValue newValue,
ArrayRef<Operand *> oldUses) {
auto newOwnershipKind = newValue->getOwnershipKind();
// If the either value is lexical, replacing its uses may result in
// shortening or lengthening its lifetime in ways that don't respect lexical
// scope and deinit barriers.
//
// Specifically, we have the following cases:
//
// +--------+--------+
// |oldValue|newValue|
// +--------+--------+
// | not | not | legal
// +--------+--------+
// |lexical | not | illegal
// +--------+--------+
// | * |lexical | legal so long as it doesn't extend newValue's lifetime
// +--------+--------+
if ((oldValue->isLexical() && !newValue->isLexical()) ||
(newValue->isLexical() &&
!areUsesWithinLexicalValueLifetime(newValue, oldUses)))
return false;
// If our new kind is ValueOwnershipKind::None, then we are fine. We
// trivially support that. This check also ensures that we can always
// replace any value with a ValueOwnershipKind::None value.
if (newOwnershipKind == OwnershipKind::None)
return true;
// If our old ownership kind is ValueOwnershipKind::None and our new kind is
// not, we may need to do more work that has not been implemented yet. So
// bail.
//
// Due to our requirement that types line up, this can only occur given a
// non-trivial typed value with None ownership. This can only happen when
// oldValue is a trivial payloaded or no-payload non-trivially typed
// enum. That doesn't occur that often so we just bail on it today until we
// implement this functionality.
if (oldValue->getOwnershipKind() == OwnershipKind::None)
return false;
// First check if oldValue is SILUndef. If it is, then we know that:
//
// 1. SILUndef (and thus oldValue) must have OwnershipKind::None.
// 2. newValue is not OwnershipKind::None due to our check above.
//
// Thus we know that we would be replacing a value with OwnershipKind::None
// with a value with non-None ownership. This is a case we don't support, so
// we can bail now.
if (isa<SILUndef>(oldValue))
return false;
// Ok, we now know that we do not have SILUndef implying that we must be able
// to get a module from our value since we must have an argument or an
// instruction.
auto *m = oldValue->getModule();
assert(m);
// If we are in Raw SIL, just bail at this point. We do not support
// ownership fixups.
if (m->getStage() == SILStage::Raw)
return false;
// OSSA rauw can create copies. Bail out if we have move only values.
if (newValue->getType().isMoveOnly()) {
return false;
}
return true;
}
// Determine whether it is valid to replace \p oldValue with \p newValue and
// extend the lifetime of \p oldValue to cover the new uses.
static bool canFixUpOwnershipForRAUW(SILValue oldValue, SILValue newValue,
OwnershipFixupContext &context) {
switch (oldValue->getOwnershipKind()) {
case OwnershipKind::Guaranteed: {
// Check that the old lifetime can be extended and record the necessary
// book-keeping in the OwnershipFixupContext.
context.clear();
// Check that no transitive uses have a PointerEscape, and record the leaf
// uses for liveness extension.
//
// FIXME: Use findExtendedTransitiveGuaranteedUses and switch the
// implementation of borrowCopyOverGuaranteedUses to
// GuaranteedOwnershipExtension. Utils then, reborrows are considered
// pointer escapes, causing findTransitiveGuaranteedUses to return false. So
// they can be ignored.
auto visitReborrow = [&](Operand *reborrow) {};
if (!findTransitiveGuaranteedUses(oldValue, context.guaranteedUsePoints,
visitReborrow)) {
return false;
}
return OwnershipRAUWHelper::hasValidRAUWOwnership(
oldValue, newValue, context.guaranteedUsePoints);
}
default: {
SmallVector<Operand *, 8> ownedUsePoints;
// If newValue is lexical, find the uses of oldValue so that it can be
// determined whether the replacement would illegally extend the lifetime
// of newValue.
if (newValue->isLexical() &&
!findUsesOfSimpleValue(oldValue, &ownedUsePoints))
return false;
return OwnershipRAUWHelper::hasValidRAUWOwnership(oldValue, newValue,
ownedUsePoints);
}
}
}
bool OwnershipRAUWHelper::mayIntroduceUnoptimizableCopies() {
if (oldValue->getOwnershipKind() != OwnershipKind::Guaranteed) {
return false;
}
if (areUsesWithinValueLifetime(newValue, ctx->guaranteedUsePoints,
&ctx->deBlocks)) {
return false;
}
return true;
}
bool swift::areUsesWithinLexicalValueLifetime(SILValue value,
ArrayRef<Operand *> uses) {
assert(value->isLexical());
// The lexical lifetime of a function argument is the whole body of the
// function.
if (isa<SILFunctionArgument>(value))
return true;
if (auto borrowedValue = BorrowedValue(value)) {
auto *function = value->getFunction();
MultiDefPrunedLiveness liveness(function);
borrowedValue.computeTransitiveLiveness(liveness);
DeadEndBlocks deadEndBlocks(function);
return liveness.areUsesWithinBoundary(uses, &deadEndBlocks);
}
return false;
}
bool swift::areUsesWithinValueLifetime(SILValue value, ArrayRef<Operand *> uses,
DeadEndBlocks *deBlocks) {
assert(value->getFunction()->hasOwnership());
if (value->getOwnershipKind() == OwnershipKind::None) {
return true;
}
if (value->getOwnershipKind() != OwnershipKind::Guaranteed &&
value->getOwnershipKind() != OwnershipKind::Owned) {
return false;
}
if (value->getOwnershipKind() == OwnershipKind::Guaranteed) {
// For guaranteed values, we have to find the borrow introducing guaranteed
// reference roots and then ensure uses are within all of their lifetimes.
// For simplicity, we only look through single forwarding operations to find
// a borrow introducer here.
value = findOwnershipReferenceAggregate(value);
BorrowedValue borrowedValue(value);
if (!borrowedValue) {
return false;
}
if (!borrowedValue.isLocalScope()) {
return true;
}
}
SSAPrunedLiveness liveness(value->getFunction());
liveness.initializeDef(value);
liveness.computeSimple();
return liveness.areUsesWithinBoundary(uses, deBlocks);
}
//===----------------------------------------------------------------------===//
// BorrowedLifetimeExtender
//===----------------------------------------------------------------------===//
/// Model an extended borrow scope, including transitive reborrows. This applies
/// to "local" borrow scopes (begin_borrow, load_borrow, & phi).
///
/// Allow extending the lifetime of an owned value that dominates this borrowed
/// value across that extended borrow scope. This handles uses of reborrows that
/// are not dominated by the owned value by generating phis and copying the
/// borrowed values the reach this borrow scope from non-dominated paths.
///
/// This produces somewhat canonical owned phis, although that isn't a
/// requirement for valid SIL. Given an owned value, a dominated borrowed value,
/// and a reborrow:
///
/// %ownedValue = ...
/// %borrowedValue = ...
/// %reborrow = phi(%borrowedValue, %otherBorrowedValue)
///
/// %otherBorrowedValue will always be copied even if %ownedValue also dominates
/// %otherBorrowedValue, as such:
///
/// %otherCopy = copy_value %borrowedValue
/// %newPhi = phi(%ownedValue, %otherCopy)
///
/// The immediate effect is to produce an unnecessary copy, but it avoids
/// extending %ownedValue's liveness to new paths and hopefully simplifies
/// downstream optimization and debugging. Unnecessary copies could be
/// avoided with simple dominance check if it becomes desirable to do so.
class BorrowedLifetimeExtender {
BorrowedValue borrowedValue;
// Owned value currently being extended over borrowedValue.
SILValue currentOwnedValue;
InstModCallbacks &callbacks;
llvm::SmallVector<PhiValue, 4> reborrowedPhis;
llvm::SmallDenseMap<PhiValue, PhiValue, 4> reborrowedToOwnedPhis;
/// Check that all reaching operands are handled. This can be removed once the
/// utility and OSSA representation are stable.
SWIFT_ASSERT_ONLY_DECL(llvm::SmallDenseSet<PhiOperand, 4> reborrowedOperands);
public:
/// Precondition: \p borrowedValue must introduce a local borrow scope
/// (begin_borrow, load_borrow, & phi).
BorrowedLifetimeExtender(BorrowedValue borrowedValue,
InstModCallbacks &callbacks)
: borrowedValue(borrowedValue), callbacks(callbacks) {
assert(borrowedValue.isLocalScope() && "expect a valid borrowed value");
}
/// Extend \p ownedValue over this extended borrow scope.
///
/// Precondition: \p ownedValue dominates this borrowed value.
void extendOverBorrowScopeAndConsume(SILValue ownedValue);
protected:
/// Initially map the reborrowed phi to an invalid value prior to creating the
/// owned phi.
void discoverReborrow(PhiValue reborrowedPhi) {
if (reborrowedToOwnedPhis.try_emplace(reborrowedPhi, PhiValue()).second) {
reborrowedPhis.push_back(reborrowedPhi);
}
}
/// Remap the reborrowed phi to an valid owned phi after creating it.
void mapOwnedPhi(PhiValue reborrowedPhi, PhiValue ownedPhi) {
reborrowedToOwnedPhis[reborrowedPhi] = ownedPhi;
}
/// Get the owned value associated with this reborrowed operand, or return an
/// invalid SILValue indicating that the borrowed lifetime does not reach this
/// operand.
SILValue getExtendedOwnedValue(PhiOperand reborrowedOper) {
// If this operand reborrows the original borrow, then the currentOwned phi
// reaches it directly.
SILValue borrowSource = reborrowedOper.getSource();
if (borrowSource == borrowedValue.value)
return currentOwnedValue;
// Check if the borrowed operand's source is already mapped to an owned phi.
auto reborrowedAndOwnedPhi = reborrowedToOwnedPhis.find(borrowSource);
if (reborrowedAndOwnedPhi != reborrowedToOwnedPhis.end()) {
// Return the already-mapped owned phi.
assert(reborrowedOperands.erase(reborrowedOper));
return reborrowedAndOwnedPhi->second;
}
// The owned value does not reach this reborrowed operand.
assert(
!reborrowedOperands.count(reborrowedOper)
&& "reachable borrowed phi operand must be mapped to an owned value");
return SILValue();
}
void analyzeExtendedScope();
SILValue createCopyAtEdge(PhiOperand reborrowOper);
void destroyAtScopeEnd(SILValue ownedValue, BorrowedValue pairedBorrow);
};
// Gather all transitive phi-reborrows and check that all the borrowed uses can
// be found with no escapes.
//
// Calls discoverReborrow to populate reborrowedPhis.
void BorrowedLifetimeExtender::analyzeExtendedScope() {
auto visitReborrow = [&](Operand *endScope) {
if (auto borrowingOper = BorrowingOperand(endScope)) {
assert(borrowingOper.isReborrow());
SWIFT_ASSERT_ONLY(reborrowedOperands.insert(endScope));
// TODO: if non-phi reborrows are added, handle multiple results.
discoverReborrow(borrowingOper.getBorrowIntroducingUserResult());
}
return true;
};
bool result = borrowedValue.visitLocalScopeEndingUses(visitReborrow);
assert(result && "visitReborrow always succeeds, escapes are irrelevant");
// Note: Iterate in the same manner as findExtendedTransitiveGuaranteedUses(),
// but using BorrowedLifetimeExtender's own reborrowedPhis.
for (unsigned idx = 0; idx < reborrowedPhis.size(); ++idx) {
auto borrowedValue = BorrowedValue(reborrowedPhis[idx]);
result = borrowedValue.visitLocalScopeEndingUses(visitReborrow);
assert(result && "visitReborrow always succeeds, escapes are irrelevant");
}
}
// Insert a copy on this edge. This might not be necessary if the owned
// value dominates this path, but this avoids forcing the owned value to be
// live across new paths.
//
// TODO: consider copying the base of the borrowed value instead of the
// borrowed value directly. It's likely that the copy is used outside of the
// borrow scope, in which case, canonicalizeOSSA will create a copy outside
// the borrow scope anyway. However, we can't be sure that the base is the
// same type.
//
// TODO: consider reusing copies that dominate multiple reborrowed
// operands. However, this requires copying in an earlier block and inserting
// post-dominating destroys, which may be better handled in an ownership phi
// canonicalization pass.
SILValue BorrowedLifetimeExtender::createCopyAtEdge(PhiOperand reborrowOper) {
auto *branch = reborrowOper.getBranch();
auto loc = RegularLocation::getAutoGeneratedLocation(branch->getLoc());
auto *copy = SILBuilderWithScope(branch).createCopyValue(
loc, reborrowOper.getSource());
callbacks.createdNewInst(copy);
return copy;
}
// Destroy \p ownedValue at \p pairedBorrow's scope-ending uses, excluding
// reborrows.
//
// Precondition: ownedValue takes ownership of its value at the same point as
// pairedBorrow. e.g. an owned and guaranteed pair of phis.
void BorrowedLifetimeExtender::destroyAtScopeEnd(SILValue ownedValue,
BorrowedValue pairedBorrow) {
pairedBorrow.visitLocalScopeEndingUses([&](Operand *scopeEnd) {
if (scopeEnd->getOperandOwnership() == OperandOwnership::Reborrow)
return true;
auto *endInst = scopeEnd->getUser();
assert(!isa<TermInst>(endInst) && "branch must be a reborrow");
auto *destroyPt = &*std::next(endInst->getIterator());
auto *destroy = SILBuilderWithScope(destroyPt).createDestroyValue(
destroyPt->getLoc(), ownedValue);
callbacks.createdNewInst(destroy);
return true;
});
}
// Insert and map an owned phi for each reborrowed phi.
//
// For each reborrowed phi, insert a copy on each edge that does not originate
// from the extended borrowedValue.
//
// TODO: If non-phi reborrows are added, they would also need to be
// mapped to their owned counterpart. This means generating new owned
// struct/destructure instructions.
void BorrowedLifetimeExtender::
extendOverBorrowScopeAndConsume(SILValue ownedValue) {
currentOwnedValue = ownedValue;
// Populate the reborrowedPhis vector.
analyzeExtendedScope();
// Warning: don't use the original callbacks in this function after creating a
// deleter.
InstModCallbacks tempCallbacks = callbacks;
InstructionDeleter deleter(std::move(tempCallbacks));
// Generate and map the phis with undef operands first, in case of recursion.
auto undef = SILUndef::get(ownedValue);
for (PhiValue reborrowedPhi : reborrowedPhis) {
auto *phiBlock = reborrowedPhi.phiBlock;
auto *ownedPhi = phiBlock->createPhiArgument(ownedValue->getType(),
OwnershipKind::Owned);
for (auto *predBlock : phiBlock->getPredecessorBlocks()) {
TermInst *ti = predBlock->getTerminator();
addNewEdgeValueToBranch(ti, phiBlock, undef, deleter);
}
mapOwnedPhi(reborrowedPhi, PhiValue(ownedPhi));
}
// Generate copies and set the phi operands.
for (PhiValue reborrowedPhi : reborrowedPhis) {
PhiValue ownedPhi = reborrowedToOwnedPhis[reborrowedPhi];
reborrowedPhi.getValue()->visitIncomingPhiOperands(
// For each reborrowed operand, get the owned value for that edge,
// and set the owned phi's operand.
[&](Operand *reborrowedOper) {
SILValue ownedVal = getExtendedOwnedValue(reborrowedOper);
if (!ownedVal) {
ownedVal = createCopyAtEdge(reborrowedOper);
}
TermInst *branch = PhiOperand(reborrowedOper).getBranch();
branch->getOperandRef(ownedPhi.argIndex).set(ownedVal);
return true;
});
}
assert(reborrowedOperands.empty() && "not all phi operands are handled");
// Create destroys at the last uses.
destroyAtScopeEnd(ownedValue, borrowedValue);
for (PhiValue reborrowedPhi : reborrowedPhis) {
PhiValue ownedPhi = reborrowedToOwnedPhis[reborrowedPhi];
destroyAtScopeEnd(ownedPhi, BorrowedValue(reborrowedPhi));
}
}
//===----------------------------------------------------------------------===//
// Ownership Lifetime Extender
//===----------------------------------------------------------------------===//
namespace {
struct OwnershipLifetimeExtender {
OwnershipFixupContext &ctx;
/// Create a new copy of \p value assuming that our caller will clean up the
/// copy along all paths that go through consuming point. Operationally this
/// means that the API will insert compensating destroy_value on the copy
/// along all paths that do not go through consuming point.
///
/// DISCUSSION: If \p consumingPoint is an instruction that forwards \p value,
/// calling this and then RAUWing with \p value guarantee that \p value will
/// be consumed by the forwarding instruction's results consuming uses.
CopyValueInst *createPlusOneCopy(SILValue value,
SILInstruction *consumingPoint);
/// Create a copy of \p value that covers all of \p range and insert all
/// needed destroy_values. We assume that no uses in \p range consume \p
/// value.
CopyValueInst *createPlusZeroCopy(SILValue value, ArrayRef<Operand *> range) {
return createPlusZeroCopy<ArrayRef<Operand *>>(value, range);
}
/// Create a copy of \p value that covers all of \p range and insert all
/// needed destroy_values. We assume that all uses in \p range do not consume
/// \p value.
///
/// We return our copy_value to the user at +0 to show that they do not need
/// to insert cleanup destroys.
template <typename RangeTy>
CopyValueInst *createPlusZeroCopy(SILValue value, const RangeTy &range);
/// Borrow \p newValue over the extended lifetime of \p borrowedValue.
BeginBorrowInst *borrowCopyOverScope(SILValue newValue,
BorrowedValue borrowedValue);
/// Borrow-copy \p newValue over \p guaranteedUses. Copy newValue, borrow the
/// copy, and extend the lifetime of the borrow-copy over guaranteedUsePoints.
///
/// \p borrowPoint is a value whose definition will be the location of
/// the new borrow.
template <typename RangeTy>
BeginBorrowInst *
borrowCopyOverGuaranteedUses(SILValue newValue,
SILBasicBlock::iterator borrowPoint,
RangeTy guaranteedUsePoints);
template <typename RangeTy>
BeginBorrowInst *
borrowCopyOverGuaranteedUsers(SILValue newValue,
SILBasicBlock::iterator borrowPoint,
RangeTy guaranteedUsers);
/// Borrow \p newValue over the lifetime of \p guaranteedValue. Return the
/// new guaranteed value.
SILValue borrowOverValue(SILValue newValue, SILValue guaranteedValue);
/// Borrow \p newValue over \p singleGuaranteedUse. Return the
/// new guaranteed value.
///
/// Precondition: if \p use ends a borrow scope, then \p newValue dominates
/// the BorrowedValue that begins the scope.
SILValue borrowOverSingleUse(SILValue newValue,
Operand *singleGuaranteedUse);
SILValue
borrowOverSingleNonLifetimeEndingUser(SILValue newValue,
SILInstruction *nonLifetimeEndingUser);
};
} // end anonymous namespace
/// Lifetime extend \p value over \p consumingPoint, assuming that \p
/// consumingPoint will consume \p value after the client performs replacement
/// (this implicit destruction on the caller-side makes it a "plus-one"
/// copy). Destroy \p copy on all paths that don't reach \p consumingPoint.
///
/// Precondition: \p value is owned
///
/// Precondition: \p consumingPoint is dominated by \p value
CopyValueInst *
OwnershipLifetimeExtender::createPlusOneCopy(SILValue value,
SILInstruction *consumingPoint) {
auto *copyPoint = value->getNextInstruction();
auto loc = copyPoint->getLoc();
auto *copy = SILBuilderWithScope(copyPoint).createCopyValue(loc, value);
auto &callbacks = ctx.callbacks;
callbacks.createdNewInst(copy);
auto *result = copy;
findJointPostDominatingSet(
copy->getParent(), consumingPoint->getParent(),
// inputBlocksFoundDuringWalk.
[&](SILBasicBlock *loopBlock) {
// Since copy dominates consumingPoint, it must be outside the
// loop. Otherwise backward traversal would have stopped at copyPoint.
//
// Create an extra copy when the consumingPoint is inside a loop and the
// original copy is outside the loop. The new copy will be consumed
// within the loop in the same block as the consume. The original copy
// will be destroyed on all paths exiting the loop.
assert(loopBlock == consumingPoint->getParent());
auto front = loopBlock->begin();
SILBuilderWithScope newBuilder(front);
result = newBuilder.createCopyValue(front->getLoc(), copy);
callbacks.createdNewInst(result);
},
// Leaky blocks that never reach consumingPoint.
[&](SILBasicBlock *postDomBlock) {
auto front = postDomBlock->begin();
SILBuilderWithScope newBuilder(front);
auto loc = RegularLocation::getAutoGeneratedLocation(front->getLoc());
auto *dvi = newBuilder.createDestroyValue(loc, copy);
callbacks.createdNewInst(dvi);
});
return result;
}
// A copy_value that we lifetime extend with destroy_value over range. We assume
// all instructions passed into range do not consume value.
template <typename RangeTy>
CopyValueInst *
OwnershipLifetimeExtender::createPlusZeroCopy(SILValue value,
const RangeTy &range) {
auto *newValInsertPt = value->getDefiningInsertionPoint();
assert(newValInsertPt);
CopyValueInst *copy;
if (!isa<SILArgument>(value)) {
SILBuilderWithScope::insertAfter(newValInsertPt, [&](SILBuilder &builder) {
copy = builder.createCopyValue(builder.getInsertionPointLoc(), value);
});
} else {
SILBuilderWithScope builder(newValInsertPt);
copy = builder.createCopyValue(newValInsertPt->getLoc(), value);
}
auto &callbacks = ctx.callbacks;
callbacks.createdNewInst(copy);
auto opRange = makeUserRange(range);
ValueLifetimeAnalysis lifetimeAnalysis(copy, opRange);
ValueLifetimeBoundary boundary;
lifetimeAnalysis.computeLifetimeBoundary(boundary);
boundary.visitInsertionPoints(
[&](SILBasicBlock::iterator insertPt) {
SILBuilderWithScope builder(insertPt);
auto *dvi = builder.createDestroyValue(insertPt->getLoc(), copy);
callbacks.createdNewInst(dvi);
},
&ctx.deBlocks);
return copy;
}
/// Borrow \p newValue over the extended lifetime of \p borrowedValue.
///
/// Precondition: \p newValue dominates borrowedValue.
BeginBorrowInst *
OwnershipLifetimeExtender::borrowCopyOverScope(SILValue newValue,
BorrowedValue borrowedValue) {
assert(borrowedValue.isLocalScope() && "SILFunctionArg is already handled");
SILInstruction *borrowPoint = borrowedValue.value->getNextInstruction();
auto loc = RegularLocation::getAutoGeneratedLocation(borrowPoint->getLoc());
SILBuilderWithScope builder(borrowPoint);
auto *copy = builder.createCopyValue(loc, newValue);
ctx.callbacks.createdNewInst(copy);
// Extend the new copy's lifetime over borrowedValue's scope and destroy it on
// all paths through borrowedValue. Since copy is in the same block as
// borrowedValue, no extra destroys are needed.
BorrowedLifetimeExtender(borrowedValue, ctx.callbacks)
.extendOverBorrowScopeAndConsume(copy);
auto *borrow = builder.createBeginBorrow(loc, copy);
ctx.callbacks.createdNewInst(borrow);
return borrow;
}
/// Borrow-copy \p newValue over \p guaranteedUses. Copy newValue, borrow the
/// copy, and extend the lifetime of the borrow-copy over guaranteedUses.
///
/// \p borrowPoint is a the insertion point of the new borrow.
///
/// Precondition: \p newValue dominates \p borrowPoint which dominates \p
/// guaranteedUses
///
/// Precondition: \p guaranteedUses is not empty.
///
/// Precondition: None of \p guaranteedUses are lifetime ending.
template <typename RangeTy>
BeginBorrowInst *OwnershipLifetimeExtender::borrowCopyOverGuaranteedUsers(
SILValue newValue, SILBasicBlock::iterator borrowPoint,
RangeTy guaranteedUsers) {
auto loc = RegularLocation::getAutoGeneratedLocation(borrowPoint->getLoc());
auto *copy = SILBuilderWithScope(newValue->getNextInstruction())
.createCopyValue(loc, newValue);
auto *borrow = SILBuilderWithScope(borrowPoint).createBeginBorrow(loc, copy);
ctx.callbacks.createdNewInst(copy);
ctx.callbacks.createdNewInst(borrow);
// Create end_borrows at the end of the borrow's lifetime.
{
// We don't expect an empty guaranteedUsers. If it happens, then the
// newly created copy will never be destroyed.
assert(!guaranteedUsers.empty());
ValueLifetimeAnalysis lifetimeAnalysis(borrow, guaranteedUsers);
ValueLifetimeBoundary borrowBoundary;
lifetimeAnalysis.computeLifetimeBoundary(borrowBoundary);
borrowBoundary.visitInsertionPoints(
[&](SILBasicBlock::iterator insertPt) {
SILBuilderWithScope builder(insertPt);
// Use an auto-generated location here, because insertPt may have an
// incompatible LocationKind
auto loc =
RegularLocation::getAutoGeneratedLocation(insertPt->getLoc());
auto *endBorrow = builder.createEndBorrow(loc, borrow);
ctx.callbacks.createdNewInst(endBorrow);
},
&ctx.deBlocks);
}
// Create destroys at the end of copy's lifetime. This only needs to consider
// uses that end the borrow scope.
{
ValueLifetimeAnalysis lifetimeAnalysis(copy, borrow->getEndBorrows());
ValueLifetimeBoundary copyBoundary;
lifetimeAnalysis.computeLifetimeBoundary(copyBoundary);
copyBoundary.visitInsertionPoints(
[&](SILBasicBlock::iterator insertPt) {
SILBuilderWithScope builder(insertPt);
auto *destroy = builder.createDestroyValue(loc, copy);
ctx.callbacks.createdNewInst(destroy);
},
&ctx.deBlocks);
}
return borrow;
}
template <typename RangeTy>
BeginBorrowInst *OwnershipLifetimeExtender::borrowCopyOverGuaranteedUses(
SILValue newValue, SILBasicBlock::iterator borrowPoint,
RangeTy guaranteedUsePoints) {
return borrowCopyOverGuaranteedUsers(newValue, borrowPoint,
makeUserRange(guaranteedUsePoints));
}
// Return the borrow position when replacing oldValue.
static SILBasicBlock::iterator getBorrowPoint(SILValue oldValue) {