-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathOwnershipOptUtils.cpp
1383 lines (1217 loc) · 55.6 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/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/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SILOptimizer/Utils/CFGOptUtils.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "swift/SILOptimizer/Utils/ValueLifetime.h"
using namespace swift;
//===----------------------------------------------------------------------===//
// 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");
}
}
static SILPhiArgument *
insertOwnedBaseValueAlongBranchEdge(BranchInst *bi, SILValue innerCopy,
InstModCallbacks &callbacks) {
auto *destBB = bi->getDestBB();
// We need to create the phi argument before calling addNewEdgeValueToBranch
// since it checks that the destination block has enough arguments for the
// argument.
auto *phiArg =
destBB->createPhiArgument(innerCopy->getType(), OwnershipKind::Owned);
addNewEdgeValueToBranch(bi, destBB, innerCopy, callbacks);
// Grab our predecessor blocks, ignoring us, add to the branch edge an
// undef corresponding to our value.
//
// We gather all predecessor blocks in a separate array to avoid
// iterator invalidation issues as we mess with terminators.
SmallVector<SILBasicBlock *, 8> predecessorBlocks(
destBB->getPredecessorBlocks());
for (auto *predBlock : predecessorBlocks) {
if (predBlock == innerCopy->getParentBlock())
continue;
addNewEdgeValueToBranch(
predBlock->getTerminator(), destBB,
SILUndef::get(innerCopy->getType(), *destBB->getParent()), callbacks);
}
return phiArg;
}
//===----------------------------------------------------------------------===//
// 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.
static bool hasValidRAUWOwnership(SILValue oldValue, SILValue newValue) {
auto newOwnershipKind = newValue.getOwnershipKind();
// 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;
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.
//
// This updates the OwnershipFixupContext, populating transitiveBorrowedUses and
// recursiveReborrows.
static bool canFixUpOwnershipForRAUW(SILValue oldValue, SILValue newValue,
OwnershipFixupContext &context) {
if (!hasValidRAUWOwnership(oldValue, newValue))
return false;
if (oldValue.getOwnershipKind() != OwnershipKind::Guaranteed)
return true;
// Check that the old lifetime can be extended and record the necessary
// book-keeping in the OwnershipFixupContext.
context.clear();
// Note: The following code is the same logic as
// findExtendedTransitiveGuaranteedUses(), but it handles the reborrows
// itself to maintain book-keeping. This is intended to be moved into a
// different utility in a follow-up commit.
SmallSetVector<SILValue, 4> reborrows;
auto visitReborrow = [&](Operand *endScope) {
auto borrowingOper = BorrowingOperand(endScope);
assert(borrowingOper.isReborrow());
// TODO: if non-phi reborrows even exist, handle them using a separate
// SILValue list since we don't want to refer directly to phi SILValues.
reborrows.insert(borrowingOper.getBorrowIntroducingUserResult().value);
context.recursiveReborrows.push_back(endScope);
};
if (!findTransitiveGuaranteedUses(oldValue, context.transitiveBorrowedUses,
visitReborrow))
return false;
for (unsigned idx = 0; idx < reborrows.size(); ++idx) {
bool result =
findTransitiveGuaranteedUses(reborrows[idx],
context.transitiveBorrowedUses,
visitReborrow);
// It is impossible to find a Pointer escape while traversing reborrows.
assert(result && "visiting reborrows always succeeds");
(void)result;
}
return true;
}
//===----------------------------------------------------------------------===//
// 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 new borrow scope for \p newValue that is cleaned up along all
/// paths that do not go through consuming point. The caller is expected to
/// consumg \p newValue at \p consumingPoint since we insert a destroy_value
/// right after wards.
BeginBorrowInst *createPlusOneBorrow(SILValue newValue,
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);
/// Create a new borrow scope for \p newValue that contains all uses in \p
/// useRange. We assume that \p useRange does not contain any lifetime ending
/// uses.
template <typename RangeTy>
BeginBorrowInst *createPlusZeroBorrow(SILValue newValue, RangeTy useRange);
/// Create a copy/borrow of \p value that covers all of \p range and insert
/// all needed destroy_values/end_borrow. We assume that no uses in \p range
/// consume \p value.
BeginBorrowInst *createPlusZeroBorrow(SILValue value,
ArrayRef<Operand *> range) {
return createPlusZeroBorrow<ArrayRef<Operand *>>(value, range);
}
};
} // end anonymous namespace
// Lifetime extend newValue over owned oldValue assuming that our copy will have
// its lifetime ended by oldValue's lifetime ending uses after RAUWing by our
// caller.
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(
copyPoint->getParent(), consumingPoint->getParent(),
// inputBlocksFoundDuringWalk.
[&](SILBasicBlock *loopBlock) {
// This must be consumingPoint->getParent() since we only have one
// consuming use. In this case, we know that this is the consuming
// point where we will need a control equivalent copy_value (and that
// destroy_value will be put for the out of loop value as appropriate.
assert(loopBlock == consumingPoint->getParent());
auto front = loopBlock->begin();
SILBuilderWithScope newBuilder(front);
// Create an extra copy when the consuming point is inside a
// loop and both copyPoint and the destroy points are outside the
// loop. This copy will be consumed in the same block. The original
// value will be destroyed on all paths exiting the loop.
//
// Since copyPoint dominates consumingPoint, it must be outside the
// loop. Otherwise backward traversal would have stopped at copyPoint.
result = newBuilder.createCopyValue(front->getLoc(), copy);
callbacks.createdNewInst(result);
},
// Input blocks in joint post dom set. We don't care about thse.
[&](SILBasicBlock *postDomBlock) {
auto front = postDomBlock->begin();
SILBuilderWithScope newBuilder(front);
auto *dvi = newBuilder.createDestroyValue(front->getLoc(), copy);
callbacks.createdNewInst(dvi);
});
return result;
}
BeginBorrowInst *
OwnershipLifetimeExtender::createPlusOneBorrow(SILValue value,
SILInstruction *consumingPoint) {
auto *newValInsertPt = value->getDefiningInsertionPoint();
assert(newValInsertPt);
CopyValueInst *copy;
BeginBorrowInst *borrow;
if (!isa<SILArgument>(value)) {
SILBuilderWithScope::insertAfter(newValInsertPt, [&](SILBuilder &builder) {
copy = builder.createCopyValue(builder.getInsertionPointLoc(), value);
borrow = builder.createBeginBorrow(builder.getInsertionPointLoc(), copy);
});
} else {
SILBuilderWithScope builder(newValInsertPt);
copy = builder.createCopyValue(newValInsertPt->getLoc(), value);
borrow = builder.createBeginBorrow(newValInsertPt->getLoc(), copy);
}
auto &callbacks = ctx.callbacks;
callbacks.createdNewInst(copy);
callbacks.createdNewInst(borrow);
auto *result = borrow;
findJointPostDominatingSet(
newValInsertPt->getParent(), consumingPoint->getParent(),
// inputBlocksFoundDuringWalk.
[&](SILBasicBlock *loopBlock) {
// This must be consumingPoint->getParent() since we only have one
// consuming use. In this case, we know that this is the consuming
// point where we will need a control equivalent copy_value (and that
// destroy_value will be put for the out of loop value as appropriate.
assert(loopBlock == consumingPoint->getParent());
auto front = loopBlock->begin();
SILBuilderWithScope newBuilder(front);
result = newBuilder.createBeginBorrow(front->getLoc(), borrow);
callbacks.createdNewInst(result);
llvm_unreachable("Should never visit this!");
},
// Input blocks in joint post dom set. We don't care about thse.
[&](SILBasicBlock *postDomBlock) {
auto front = postDomBlock->begin();
SILBuilderWithScope newBuilder(front);
auto *ebi = newBuilder.createEndBorrow(front->getLoc(), borrow);
callbacks.createdNewInst(ebi);
auto *dvi = newBuilder.createDestroyValue(front->getLoc(), 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);
ValueLifetimeAnalysis::Frontier frontier;
bool result = lifetimeAnalysis.computeFrontier(
frontier, ValueLifetimeAnalysis::DontModifyCFG, &ctx.deBlocks);
assert(result);
while (!frontier.empty()) {
auto *insertPt = frontier.pop_back_val();
SILBuilderWithScope frontierBuilder(insertPt);
auto *dvi = frontierBuilder.createDestroyValue(insertPt->getLoc(), copy);
callbacks.createdNewInst(dvi);
}
return copy;
}
template <typename RangeTy>
BeginBorrowInst *
OwnershipLifetimeExtender::createPlusZeroBorrow(SILValue newValue,
RangeTy useRange) {
auto *newValInsertPt = newValue->getDefiningInsertionPoint();
assert(newValInsertPt);
CopyValueInst *copy = nullptr;
BeginBorrowInst *borrow = nullptr;
if (!isa<SILArgument>(newValue)) {
SILBuilderWithScope::insertAfter(newValInsertPt, [&](SILBuilder &builder) {
auto loc = builder.getInsertionPointLoc();
copy = builder.createCopyValue(loc, newValue);
borrow = builder.createBeginBorrow(loc, copy);
});
} else {
SILBuilderWithScope builder(newValInsertPt);
auto loc = newValInsertPt->getLoc();
copy = builder.createCopyValue(loc, newValue);
borrow = builder.createBeginBorrow(loc, copy);
}
assert(copy && borrow);
auto opRange = makeUserRange(useRange);
ValueLifetimeAnalysis lifetimeAnalysis(copy, opRange);
ValueLifetimeAnalysis::Frontier frontier;
bool result = lifetimeAnalysis.computeFrontier(
frontier, ValueLifetimeAnalysis::DontModifyCFG, &ctx.deBlocks);
assert(result);
auto &callbacks = ctx.callbacks;
while (!frontier.empty()) {
auto *insertPt = frontier.pop_back_val();
SILBuilderWithScope frontierBuilder(insertPt);
// Use an auto-generated location here, because insertPt may have an
// incompatible LocationKind
auto loc = RegularLocation::getAutoGeneratedLocation(insertPt->getLoc());
auto *ebi = frontierBuilder.createEndBorrow(loc, borrow);
auto *dvi = frontierBuilder.createDestroyValue(loc, copy);
callbacks.createdNewInst(ebi);
callbacks.createdNewInst(dvi);
}
return borrow;
}
//===----------------------------------------------------------------------===//
// Reborrow Elimination
//===----------------------------------------------------------------------===//
static void eliminateReborrowsOfRecursiveBorrows(
ArrayRef<PhiOperand> transitiveReborrows,
SmallVectorImpl<Operand *> &usePoints, InstModCallbacks &callbacks) {
SmallVector<std::pair<SILPhiArgument *, SILPhiArgument *>, 8>
baseBorrowedValuePair;
// Ok, we have transitive reborrows.
for (auto it : transitiveReborrows) {
// We eliminate the reborrow by creating a new copy+borrow at the reborrow
// edge from the base value and using that for the reborrow instead of the
// actual value. We of course insert an end_borrow for our original incoming
// value.
auto *bi = cast<BranchInst>(it.predBlock->getTerminator());
auto &op = bi->getOperandRef(it.argIndex);
BorrowingOperand borrowingOperand(&op);
SILValue value = borrowingOperand->get();
SILBuilderWithScope reborrowBuilder(bi);
// Use an auto-generated location here, because the branch may have an
// incompatible LocationKind
auto loc = RegularLocation::getAutoGeneratedLocation(bi->getLoc());
auto *innerCopy = reborrowBuilder.createCopyValue(loc, value);
auto *innerBorrow = reborrowBuilder.createBeginBorrow(loc, innerCopy);
auto *outerEndBorrow = reborrowBuilder.createEndBorrow(loc, value);
callbacks.createdNewInst(innerCopy);
callbacks.createdNewInst(innerBorrow);
callbacks.createdNewInst(outerEndBorrow);
// Then set our borrowing operand to take our innerBorrow instead of value
// (whose lifetime we just ended).
callbacks.setUseValue(*borrowingOperand, innerBorrow);
// Add our outer end borrow as a use point to make sure that we extend our
// base value to this point.
usePoints.push_back(&outerEndBorrow->getAllOperands()[0]);
// Then check if in our destination block, we have further reborrows. If we
// do, we need to recursively process them.
auto *borrowedArg =
const_cast<SILPhiArgument *>(bi->getArgForOperand(*borrowingOperand));
auto *baseArg =
insertOwnedBaseValueAlongBranchEdge(bi, innerCopy, callbacks);
baseBorrowedValuePair.emplace_back(baseArg, borrowedArg);
}
// Now recursively update all further reborrows...
while (!baseBorrowedValuePair.empty()) {
SILPhiArgument *baseArg;
SILPhiArgument *borrowedArg;
std::tie(baseArg, borrowedArg) = baseBorrowedValuePair.pop_back_val();
for (auto *use : borrowedArg->getConsumingUses()) {
// If our consuming use is an end of scope marker, we need to end
// the lifetime of our base arg.
if (isEndOfScopeMarker(use->getUser())) {
SILBuilderWithScope::insertAfter(use->getUser(), [&](SILBuilder &b) {
auto *dvi = b.createDestroyValue(b.getInsertionPointLoc(), baseArg);
callbacks.createdNewInst(dvi);
});
continue;
}
// Otherwise, we have a reborrow. For now our reborrows must be
// phis. Add our owned value as a new argument of that phi along our
// edge and undef along all other edges.
auto borrowingOp = BorrowingOperand::get(use);
auto *brInst = cast<BranchInst>(borrowingOp.op->getUser());
auto *newBorrowedPhi = brInst->getArgForOperand(*borrowingOp);
auto *newBasePhi =
insertOwnedBaseValueAlongBranchEdge(brInst, baseArg, callbacks);
baseBorrowedValuePair.emplace_back(newBasePhi, newBorrowedPhi);
}
}
}
static void
rewriteReborrows(SILValue newBorrowedValue,
ArrayRef<std::pair<SILBasicBlock *, unsigned>> foundReborrows,
InstModCallbacks &callbacks) {
// Each initial reborrow that we have is a use of oldValue, so we know
// that copy should be valid at the reborrow.
SmallVector<std::pair<SILPhiArgument *, SILPhiArgument *>, 8>
baseBorrowedValuePair;
for (auto it : foundReborrows) {
auto *bi = cast<BranchInst>(it.first->getTerminator());
auto &op = bi->getOperandRef(it.second);
BorrowingOperand reborrow(&op);
SILBuilderWithScope reborrowBuilder(bi);
// Use an auto-generated location here, because the branch may have an
// incompatible LocationKind
auto loc = RegularLocation::getAutoGeneratedLocation(bi->getLoc());
auto *innerCopy = reborrowBuilder.createCopyValue(loc, newBorrowedValue);
auto *innerBorrow = reborrowBuilder.createBeginBorrow(loc, innerCopy);
auto *outerEndBorrow =
reborrowBuilder.createEndBorrow(loc, reborrow.op->get());
callbacks.createdNewInst(innerCopy);
callbacks.createdNewInst(innerBorrow);
callbacks.createdNewInst(outerEndBorrow);
callbacks.setUseValue(*reborrow, innerBorrow);
auto *borrowedArg =
const_cast<SILPhiArgument *>(bi->getArgForOperand(reborrow.op));
auto *baseArg =
insertOwnedBaseValueAlongBranchEdge(bi, innerCopy, callbacks);
baseBorrowedValuePair.emplace_back(baseArg, borrowedArg);
}
// Now, follow through all chains of reborrows.
while (!baseBorrowedValuePair.empty()) {
SILPhiArgument *baseArg;
SILPhiArgument *borrowedArg;
std::tie(baseArg, borrowedArg) = baseBorrowedValuePair.pop_back_val();
for (auto *use : borrowedArg->getConsumingUses()) {
// If our consuming use is an end of scope marker, we need to end
// the lifetime of our base arg.
if (isEndOfScopeMarker(use->getUser())) {
SILBuilderWithScope::insertAfter(use->getUser(), [&](SILBuilder &b) {
auto *dvi = b.createDestroyValue(b.getInsertionPointLoc(), baseArg);
callbacks.createdNewInst(dvi);
});
continue;
}
// Otherwise, we have a reborrow. For now our reborrows must be
// phis. Add our owned value as a new argument of that phi along our
// edge and undef along all other edges.
auto borrowingOp = BorrowingOperand::get(use);
auto *brInst = cast<BranchInst>(borrowingOp.op->getUser());
auto *newBorrowedPhi = brInst->getArgForOperand(*borrowingOp);
auto *newBasePhi =
insertOwnedBaseValueAlongBranchEdge(brInst, baseArg, callbacks);
baseBorrowedValuePair.emplace_back(newBasePhi, newBorrowedPhi);
}
}
}
//===----------------------------------------------------------------------===//
// OwnershipRAUWUtility - RAUW + fix ownership
//===----------------------------------------------------------------------===//
/// Given an old value and a new value, lifetime extend new value as appropriate
/// so we can RAUW new value with old value and preserve ownership
/// invariants. We leave fixing up the lifetime of old value to our caller.
namespace {
struct OwnershipRAUWUtility {
SingleValueInstruction *oldValue;
SILValue newValue;
OwnershipFixupContext &ctx;
SILBasicBlock::iterator handleUnowned();
SILBasicBlock::iterator handleGuaranteed();
SILBasicBlock::iterator perform();
OwnershipLifetimeExtender getLifetimeExtender() { return {ctx}; }
const InstModCallbacks &getCallbacks() const { return ctx.callbacks; }
};
} // anonymous namespace
SILBasicBlock::iterator OwnershipRAUWUtility::handleUnowned() {
auto &callbacks = ctx.callbacks;
switch (newValue.getOwnershipKind()) {
case OwnershipKind::None:
llvm_unreachable("Should have been handled elsewhere");
case OwnershipKind::Any:
llvm_unreachable("Invalid for values");
case OwnershipKind::Unowned:
// An unowned value can always be RAUWed with another unowned value.
return replaceAllUsesAndErase(oldValue, newValue, callbacks);
case OwnershipKind::Guaranteed: {
// If we have an unowned value that we want to replace with a guaranteed
// value, we need to ensure that the guaranteed value is live at all use
// points of the unowned value. If so, just replace and continue.
//
// TODO: Implement this for more interesting cases.
if (isa<SILFunctionArgument>(newValue))
return replaceAllUsesAndErase(oldValue, newValue, callbacks);
// Otherwise, we need to lifetime extend the borrow over all of the use
// points. To do so, we copy the value, borrow it, and insert an unchecked
// ownership conversion to unowned at all uses that are terminator uses.
//
// We need to insert the conversion since if we have a non-argument
// guaranteed value since its scope will end before the terminator so we
// need to convert the value to unowned early.
//
// TODO: Do we need a separate array here?
SmallVector<Operand *, 8> oldValueUses(oldValue->getUses());
for (auto *use : oldValueUses) {
if (auto *ti = dyn_cast<TermInst>(use->getUser())) {
if (ti->isFunctionExiting()) {
SILBuilderWithScope builder(ti);
auto *newInst = builder.createUncheckedOwnershipConversion(
ti->getLoc(), use->get(), OwnershipKind::Unowned);
callbacks.createdNewInst(newInst);
callbacks.setUseValue(use, newInst);
}
}
}
auto extender = getLifetimeExtender();
SILValue borrow =
extender.createPlusZeroBorrow(newValue, oldValue->getUses());
SILBuilderWithScope builder(oldValue);
return replaceAllUsesAndErase(oldValue, borrow, callbacks);
}
case OwnershipKind::Owned: {
// If we have an unowned value that we want to replace with an owned value,
// we first check if the owned value is live over all use points of the old
// value. If so, just RAUW and continue.
//
// TODO: Implement this.
// Otherwise, insert a copy of the owned value and lifetime extend that over
// all uses of the value and then RAUW.
//
// NOTE: For terminator uses, we funnel the use through an
// unchecked_ownership_conversion to ensure that we can end the lifetime of
// our owned/guaranteed value before the terminator.
SmallVector<Operand *, 8> oldValueUses(oldValue->getUses());
for (auto *use : oldValueUses) {
if (auto *ti = dyn_cast<TermInst>(use->getUser())) {
if (ti->isFunctionExiting()) {
SILBuilderWithScope builder(ti);
auto *newInst = builder.createUncheckedOwnershipConversion(
ti->getLoc(), use->get(), OwnershipKind::Unowned);
callbacks.createdNewInst(newInst);
callbacks.setUseValue(use, newInst);
}
}
}
auto extender = getLifetimeExtender();
SILValue copy = extender.createPlusZeroCopy(newValue, oldValue->getUses());
SILBuilderWithScope builder(oldValue);
auto result = replaceAllUsesAndErase(oldValue, copy, callbacks);
return result;
}
}
llvm_unreachable("covered switch isn't covered?!");
}
SILBasicBlock::iterator OwnershipRAUWUtility::handleGuaranteed() {
// If we want to replace a guaranteed value with a value of some other
// ownership whose def dominates our guaranteed value. We first see if all
// uses of the old guaranteed value are within the lifetime of the new
// guaranteed value. If so, we can just RAUW and move on.
//
// TODO: Implement this.
//
// Otherwise, we need to actually modify the IR. We first always first
// lifetime extend newValue to oldValue's transitive uses to set our
// workspace.
// If we have any transitive reborrows on sub-borrows.
if (ctx.recursiveReborrows.size())
eliminateReborrowsOfRecursiveBorrows(ctx.recursiveReborrows,
ctx.transitiveBorrowedUses,
ctx.callbacks);
auto extender = getLifetimeExtender();
SILValue newBorrowedValue =
extender.createPlusZeroBorrow<ArrayRef<Operand *>>(
newValue, ctx.transitiveBorrowedUses);
// Now we need to handle reborrows by eliminating the reborrows from any
// borrowing operands that use old value as well as from oldvalue itself. We
// take advantage of a few properties of reborrows:
//
// 1. A reborrow has to be on a BorrowedValue. This ensures that the same
// base value is propagated through chains of reborrows. (In the future
// this may not be true when destructures are introduced as reborrow
// instructions).
//
// 2. Given that, we change each reborrows into new copy+borrow from the
// owned value that we perform at the reborrow use. What is nice about
// this formulation is that it ensures that we are always working with a
// non-dominating copy value, allowing us to force our borrowing value to
// need a base phi argument (the one of our choosing).
if (auto oldValueBorrowedVal = BorrowedValue(oldValue)) {
SmallVector<std::pair<SILBasicBlock *, unsigned>, 8> foundReborrows;
if (oldValueBorrowedVal.gatherReborrows(foundReborrows)) {
rewriteReborrows(newBorrowedValue, foundReborrows, ctx.callbacks);
}
}
// Then we need to look and see if our oldValue had any transitive uses that
// Ok, we now have eliminated any reborrows if we had any. That means that
// the uses of oldValue should be completely within the lifetime of our new
// borrow.
return replaceAllUsesAndErase(oldValue, newBorrowedValue, ctx.callbacks);
}
SILBasicBlock::iterator OwnershipRAUWUtility::perform() {
assert(oldValue->getFunction()->hasOwnership());
assert(hasValidRAUWOwnership(oldValue, newValue) &&
"Should have checked if can perform this operation before calling it?!");
// If our new value is just none, we can pass anything to do it so just RAUW
// and return.
//
// NOTE: This handles RAUWing with undef.
if (newValue.getOwnershipKind() == OwnershipKind::None)
return replaceAllUsesAndErase(oldValue, newValue, ctx.callbacks);
assert(SILValue(oldValue).getOwnershipKind() != OwnershipKind::None);
switch (SILValue(oldValue).getOwnershipKind()) {
case OwnershipKind::None:
// If our old value was none and our new value is not, we need to do
// something more complex that we do not support yet, so bail. We should
// have not called this function in such a case.
llvm_unreachable("Should have been handled elsewhere");
case OwnershipKind::Any:
llvm_unreachable("Invalid for values");
case OwnershipKind::Guaranteed: {
return handleGuaranteed();
}
case OwnershipKind::Owned: {
// If we have an owned value that we want to replace with a value with any
// other non-None ownership, we need to copy the other value for a
// lifetimeEnding RAUW, then RAUW the value, and insert a destroy_value on
// the original value.
auto extender = getLifetimeExtender();
SILValue copy = extender.createPlusOneCopy(newValue, oldValue);
cleanupOperandsBeforeDeletion(oldValue, ctx.callbacks);
auto result = replaceAllUsesAndErase(oldValue, copy, ctx.callbacks);
return result;
}
case OwnershipKind::Unowned: {
return handleUnowned();
}
}
llvm_unreachable("Covered switch isn't covered?!");
}
//===----------------------------------------------------------------------===//
// Interior Pointer Operand Rebasing
//===----------------------------------------------------------------------===//
SILBasicBlock::iterator
OwnershipRAUWHelper::replaceAddressUses(SingleValueInstruction *oldValue,
SILValue newValue) {
assert(oldValue->getType().isAddress() &&
oldValue->getType() == newValue->getType());
// If we are replacing addresses, see if we need to handle interior pointer
// fixups. If we don't have any extra info, then we know that we can just RAUW
// without any further work.
if (!ctx->extraAddressFixupInfo.intPtrOp)
return replaceAllUsesAndErase(oldValue, newValue, ctx->callbacks);
// We are RAUWing two addresses and we found that:
//
// 1. newValue is an address associated with an interior pointer instruction.
// 2. oldValue has uses that are outside of newValue's borrow scope.
//
// So, we need to copy/borrow the base value of the interior pointer to
// lifetime extend the base value over the new uses. Then we clone the
// interior pointer instruction and change the clone to use our new borrowed
// value. Then we RAUW as appropriate.
OwnershipLifetimeExtender extender{*ctx};
auto &extraInfo = ctx->extraAddressFixupInfo;
auto intPtr = *extraInfo.intPtrOp;
BeginBorrowInst *bbi = extender.createPlusZeroBorrow(
intPtr->get(), llvm::makeArrayRef(extraInfo.allAddressUsesFromOldValue));
auto bbiNext = &*std::next(bbi->getIterator());
auto *newIntPtrUser =
cast<SingleValueInstruction>(intPtr->getUser()->clone(bbiNext));
ctx->callbacks.createdNewInst(newIntPtrUser);
newIntPtrUser->setOperand(0, bbi);
// Now that we have extended our lifetime as appropriate, we need to recreate
// the access path from newValue to intPtr but upon newIntPtr. Then we make it
// use newIntPtr.
auto *intPtrUser = cast<SingleValueInstruction>(intPtr->getUser());
// This cloner invocation must match the canCloneUseDefChain check in the
// constructor.
auto checkBase = [&](SILValue srcAddr) {
return (srcAddr == intPtrUser) ? SILValue(newIntPtrUser) : SILValue();
};
SILValue clonedAddr =
cloneUseDefChain(newValue, /*insetPt*/ oldValue, checkBase);
assert(clonedAddr != newValue && "expect at least the base to be replaced");
// Now that we have an addr that is setup appropriately, RAUW!
return replaceAllUsesAndErase(oldValue, clonedAddr, ctx->callbacks);
}
//===----------------------------------------------------------------------===//
// OwnershipRAUWHelper
//===----------------------------------------------------------------------===//
OwnershipRAUWHelper::OwnershipRAUWHelper(OwnershipFixupContext &inputCtx,
SingleValueInstruction *inputOldValue,
SILValue inputNewValue)
: ctx(&inputCtx), oldValue(inputOldValue), newValue(inputNewValue) {
// If we are already not valid, just bail.
if (!isValid())
return;
// If we are not in ownership, we can always RAUW successfully so just bail
// and leave the object valid.
if (!oldValue->getFunction()->hasOwnership())
return;
// Otherwise, lets check if we can perform this RAUW operation. If we can't,
// set ctx to nullptr to invalidate the helper and return.
if (!canFixUpOwnershipForRAUW(oldValue, newValue, inputCtx)) {
ctx = nullptr;
return;
}
// If we have an object, at this point we are good to go so we can just
// return.
if (newValue->getType().isObject())
return;
// But if we have an address, we need to check if new value is from an
// interior pointer or not in a way that the pass understands. What we do is:
//
// 1. Early exit some cases that we know can never have interior pointers.
//
// 2. Compute the AccessPathWithBase of newValue. If we do not get back a
// valid such object, invalidate and then bail.
//
// 3. Then we check if the base address is the result of an interior pointer
// instruction. If we do not find one we bail.
//
// 4. Then grab the base value of the interior pointer operand. We only
// support cases where we have a single BorrowedValue as our base. This is
// a safe future proof assumption since one reborrows are on
// structs/tuple/destructures, a guaranteed value will always be associated
// with a single BorrowedValue, so this will never fail (and the code will
// probably be DCEed).
//
// 5. Then we compute an AccessPathWithBase for oldValue and then find its
// derived uses. If we fail, we bail.
//
// 6. At this point, we know that we can perform this RAUW. The only question
// is if we need to when we RAUW copy the interior pointer base value. We
// perform this check by making sure all of the old value's derived uses
// are within our BorrowedValue's scope. If so, we clear the extra state we
// were tracking (the interior pointer/oldValue's transitive uses), so we
// perform just a normal RAUW (without inserting the copy) when we RAUW.
//
// We can always RAUW an address with a pointer_to_address since if there
// were any interior pointer constraints on whatever address pointer came
// from, the address_to_pointer producing that value erases that
// information, so we can RAUW without worrying.
//
// NOTE: We also need to handle this here since a pointer_to_address is not a
// valid base value for an access path since it doesn't refer to any storage.
{
auto baseProj =
getUnderlyingObjectStoppingAtObjectToAddrProjections(newValue);
if (isa<PointerToAddressInst>(baseProj)) {
return;
}
}
auto accessPathWithBase = AccessPathWithBase::compute(newValue);
if (!accessPathWithBase.base) {
// Invalidate!
ctx = nullptr;
return;
}
auto &intPtr = ctx->extraAddressFixupInfo.intPtrOp;
intPtr = InteriorPointerOperand::inferFromResult(accessPathWithBase.base);
if (!intPtr) {
// We can optimize! Do not invalidate!
return;
}
auto borrowedValue = intPtr.getSingleBaseValue();
if (!borrowedValue) {
// Invalidate!
ctx = nullptr;
return;
}
// This cloner check must match the later cloner invocation in
// replaceAddressUses()
auto *intPtrUser = cast<SingleValueInstruction>(intPtr->getUser());
auto checkBase = [&](SILValue srcAddr) {
return (srcAddr == intPtrUser) ? SILValue(intPtrUser) : SILValue();
};
if (!canCloneUseDefChain(newValue, checkBase)) {
ctx = nullptr;
return;
}
// For now, just gather up uses
auto &oldValueUses = ctx->extraAddressFixupInfo.allAddressUsesFromOldValue;
if (InteriorPointerOperand::findTransitiveUsesForAddress(oldValue,
oldValueUses)) {
// If we found an error, invalidate and return!
ctx = nullptr;
return;
}
// Ok, at this point we know that we can optimize. The only question is if we
// need to perform the copy or not when we actually RAUW. So perform the is
// within region check. If we succeed, clear our extra state so we perform a
// normal RAUW.
SmallVector<Operand *, 8> scratchSpace;
if (borrowedValue.areUsesWithinScope(oldValueUses, scratchSpace,
ctx->deBlocks)) {
// We do not need to copy the base value! Clear the extra info we have.
ctx->extraAddressFixupInfo.clear();
}
}
SILBasicBlock::iterator
OwnershipRAUWHelper::perform(SingleValueInstruction *maybeTransformedNewValue) {
assert(isValid() && "OwnershipRAUWHelper invalid?!");
SILValue actualNewValue = newValue;
if (maybeTransformedNewValue)
actualNewValue = maybeTransformedNewValue;
if (!oldValue->getFunction()->hasOwnership())
return replaceAllUsesAndErase(oldValue, actualNewValue, ctx->callbacks);
// Make sure to always clear our context after we transform.
SWIFT_DEFER { ctx->clear(); };
if (oldValue->getType().isAddress())
return replaceAddressUses(oldValue, actualNewValue);
OwnershipRAUWUtility utility{oldValue, actualNewValue, *ctx};
return utility.perform();
}
//===----------------------------------------------------------------------===//
// Single Use Replacement
//===----------------------------------------------------------------------===//
namespace {
/// Given a use and a new value, lifetime extend new value as appropriate so we
/// can replace use->get() with newValue and preserve ownership invariants. We
/// assume that old value will be left alone and not deleted so we insert
/// compensating cleanups.
struct SingleUseReplacementUtility {
Operand *use;
SILValue newValue;
OwnershipFixupContext &ctx;