-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathPredictableMemOpt.cpp
2874 lines (2449 loc) · 111 KB
/
PredictableMemOpt.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
//===--- PredictableMemOpt.cpp - Perform predictable memory optzns --------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "predictable-memopt"
#include "PMOMemoryUseCollector.h"
#include "swift/Basic/BlotMapVector.h"
#include "swift/Basic/BlotSetVector.h"
#include "swift/Basic/FrozenMultiMap.h"
#include "swift/Basic/STLExtras.h"
#include "swift/SIL/BasicBlockBits.h"
#include "swift/SIL/BasicBlockUtils.h"
#include "swift/SIL/LinearLifetimeChecker.h"
#include "swift/SIL/OSSALifetimeCompletion.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/CFGOptUtils.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "swift/SILOptimizer/Utils/OwnershipOptUtils.h"
#include "swift/SILOptimizer/Utils/SILSSAUpdater.h"
#include "swift/SILOptimizer/Utils/ValueLifetime.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
using namespace swift;
STATISTIC(NumLoadPromoted, "Number of loads promoted");
STATISTIC(NumLoadTakePromoted, "Number of load takes promoted");
STATISTIC(NumDestroyAddrPromoted, "Number of destroy_addrs promoted");
STATISTIC(NumAllocRemoved, "Number of allocations completely removed");
//===----------------------------------------------------------------------===//
// Subelement Analysis
//===----------------------------------------------------------------------===//
// We can only analyze components of structs whose storage is fully accessible
// from Swift.
static StructDecl *
getFullyReferenceableStruct(SILType Ty) {
auto SD = Ty.getStructOrBoundGenericStruct();
if (!SD || SD->hasUnreferenceableStorage())
return nullptr;
return SD;
}
static unsigned getNumSubElements(SILType T, SILModule &M,
TypeExpansionContext context) {
if (auto TT = T.getAs<TupleType>()) {
unsigned NumElements = 0;
for (auto index : indices(TT.getElementTypes()))
NumElements +=
getNumSubElements(T.getTupleElementType(index), M, context);
return NumElements;
}
if (auto *SD = getFullyReferenceableStruct(T)) {
unsigned NumElements = 0;
for (auto *D : SD->getStoredProperties())
NumElements +=
getNumSubElements(T.getFieldType(D, M, context), M, context);
return NumElements;
}
// If this isn't a tuple or struct, it is a single element.
return 1;
}
/// getAccessPathRoot - Given an address, dive through any tuple/struct element
/// addresses to get the underlying value.
static SILValue getAccessPathRoot(SILValue pointer) {
while (true) {
if (auto *TEAI = dyn_cast<TupleElementAddrInst>(pointer)) {
pointer = TEAI->getOperand();
continue;
}
if (auto *SEAI = dyn_cast<StructElementAddrInst>(pointer)) {
pointer = SEAI->getOperand();
continue;
}
if (auto *BAI = dyn_cast<BeginAccessInst>(pointer)) {
pointer = BAI->getSource();
continue;
}
return pointer;
}
}
/// Compute the subelement number indicated by the specified pointer (which is
/// derived from the root by a series of tuple/struct element addresses) by
/// treating the type as a linearized namespace with sequential elements. For
/// example, given:
///
/// root = alloc { a: { c: i64, d: i64 }, b: (i64, i64) }
/// tmp1 = struct_element_addr root, 1
/// tmp2 = tuple_element_addr tmp1, 0
///
/// This will return a subelement number of 2.
///
/// If this pointer is to within an existential projection, it returns ~0U.
static unsigned computeSubelement(SILValue Pointer,
SingleValueInstruction *RootInst) {
unsigned SubElementNumber = 0;
SILModule &M = RootInst->getModule();
while (1) {
// If we got to the root, we're done.
if (RootInst == Pointer)
return SubElementNumber;
if (auto *PBI = dyn_cast<ProjectBoxInst>(Pointer)) {
Pointer = PBI->getOperand();
continue;
}
if (auto *BAI = dyn_cast<BeginAccessInst>(Pointer)) {
Pointer = BAI->getSource();
continue;
}
if (auto *TEAI = dyn_cast<TupleElementAddrInst>(Pointer)) {
SILType TT = TEAI->getOperand()->getType();
// Keep track of what subelement is being referenced.
for (unsigned i = 0, e = TEAI->getFieldIndex(); i != e; ++i) {
SubElementNumber +=
getNumSubElements(TT.getTupleElementType(i), M,
TypeExpansionContext(*RootInst->getFunction()));
}
Pointer = TEAI->getOperand();
continue;
}
if (auto *SEAI = dyn_cast<StructElementAddrInst>(Pointer)) {
SILType ST = SEAI->getOperand()->getType();
// Keep track of what subelement is being referenced.
StructDecl *SD = SEAI->getStructDecl();
for (auto *D : SD->getStoredProperties()) {
if (D == SEAI->getField()) break;
auto context = TypeExpansionContext(*RootInst->getFunction());
SubElementNumber +=
getNumSubElements(ST.getFieldType(D, M, context), M, context);
}
Pointer = SEAI->getOperand();
continue;
}
// This fails when we visit unchecked_take_enum_data_addr. We should just
// add support for enums.
assert(isa<InitExistentialAddrInst>(Pointer) &&
"Unknown access path instruction");
// Cannot promote loads and stores from within an existential projection.
return ~0U;
}
}
//===----------------------------------------------------------------------===//
// Available Value
//===----------------------------------------------------------------------===//
namespace {
class AvailableValueAggregator;
struct AvailableValue {
friend class AvailableValueAggregator;
SILValue Value;
unsigned SubElementNumber;
/// If this gets too expensive in terms of copying, we can use an arena and a
/// FrozenPtrSet like we do in ARC.
llvm::SmallSetVector<StoreInst *, 1> InsertionPoints;
/// Just for updating.
SmallVectorImpl<PMOMemoryUse> *Uses;
public:
AvailableValue() = default;
/// Main initializer for available values.
///
/// *NOTE* We assume that all available values start with a singular insertion
/// point and insertion points are added by merging.
AvailableValue(SILValue Value, unsigned SubElementNumber,
StoreInst *InsertPoint)
: Value(Value), SubElementNumber(SubElementNumber), InsertionPoints() {
InsertionPoints.insert(InsertPoint);
}
/// Deleted copy constructor. This is a move only type.
AvailableValue(const AvailableValue &) = delete;
/// Deleted copy operator. This is a move only type.
AvailableValue &operator=(const AvailableValue &) = delete;
/// Move constructor.
AvailableValue(AvailableValue &&Other)
: Value(nullptr), SubElementNumber(~0), InsertionPoints() {
std::swap(Value, Other.Value);
std::swap(SubElementNumber, Other.SubElementNumber);
std::swap(InsertionPoints, Other.InsertionPoints);
}
/// Move operator.
AvailableValue &operator=(AvailableValue &&Other) {
std::swap(Value, Other.Value);
std::swap(SubElementNumber, Other.SubElementNumber);
std::swap(InsertionPoints, Other.InsertionPoints);
return *this;
}
operator bool() const { return bool(Value); }
bool operator==(const AvailableValue &Other) const {
return Value == Other.Value && SubElementNumber == Other.SubElementNumber;
}
bool operator!=(const AvailableValue &Other) const {
return !(*this == Other);
}
SILValue getValue() const { return Value; }
SILType getType() const { return Value->getType(); }
unsigned getSubElementNumber() const { return SubElementNumber; }
ArrayRef<StoreInst *> getInsertionPoints() const {
return InsertionPoints.getArrayRef();
}
void mergeInsertionPoints(const AvailableValue &Other) & {
assert(Value == Other.Value && SubElementNumber == Other.SubElementNumber);
InsertionPoints.set_union(Other.InsertionPoints);
}
void addInsertionPoint(StoreInst *si) & { InsertionPoints.insert(si); }
AvailableValue emitStructExtract(SILBuilder &B, SILLocation Loc, VarDecl *D,
unsigned SubElementNumber) const {
SILValue NewValue = B.emitStructExtract(Loc, Value, D);
return {NewValue, SubElementNumber, InsertionPoints};
}
AvailableValue emitTupleExtract(SILBuilder &B, SILLocation Loc,
unsigned EltNo,
unsigned SubElementNumber) const {
SILValue NewValue = B.emitTupleExtract(Loc, Value, EltNo);
return {NewValue, SubElementNumber, InsertionPoints};
}
AvailableValue emitBeginBorrow(SILBuilder &b, SILLocation loc) const {
// If we do not have ownership or already are guaranteed, just return a copy
// of our state.
if (!b.hasOwnership() ||
Value->getOwnershipKind().isCompatibleWith(OwnershipKind::Guaranteed)) {
return {Value, SubElementNumber, InsertionPoints};
}
// Otherwise, return newValue.
return {b.createBeginBorrow(loc, Value), SubElementNumber, InsertionPoints};
}
void dump() const LLVM_ATTRIBUTE_USED;
void print(llvm::raw_ostream &os) const;
private:
/// Private constructor.
AvailableValue(SILValue Value, unsigned SubElementNumber,
const decltype(InsertionPoints) &InsertPoints)
: Value(Value), SubElementNumber(SubElementNumber),
InsertionPoints(InsertPoints) {}
};
} // end anonymous namespace
void AvailableValue::dump() const { print(llvm::dbgs()); }
void AvailableValue::print(llvm::raw_ostream &os) const {
os << "Available Value Dump. Value: ";
if (getValue()) {
os << getValue();
} else {
os << "NoValue;\n";
}
os << "SubElementNumber: " << getSubElementNumber() << "\n";
os << "Insertion Points:\n";
for (auto *I : getInsertionPoints()) {
os << *I;
}
}
namespace llvm {
llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const AvailableValue &V) {
V.print(os);
return os;
}
} // end llvm namespace
//===----------------------------------------------------------------------===//
// Subelement Extraction
//===----------------------------------------------------------------------===//
/// Given an aggregate value and an access path, non-destructively extract the
/// value indicated by the path.
static SILValue nonDestructivelyExtractSubElement(const AvailableValue &Val,
SILBuilder &B,
SILLocation Loc) {
SILType ValTy = Val.getType();
unsigned SubElementNumber = Val.SubElementNumber;
// Extract tuple elements.
if (auto TT = ValTy.getAs<TupleType>()) {
for (unsigned EltNo : indices(TT.getElementTypes())) {
// Keep track of what subelement is being referenced.
SILType EltTy = ValTy.getTupleElementType(EltNo);
unsigned NumSubElt = getNumSubElements(
EltTy, B.getModule(), TypeExpansionContext(B.getFunction()));
if (SubElementNumber < NumSubElt) {
auto BorrowedVal = Val.emitBeginBorrow(B, Loc);
auto NewVal =
BorrowedVal.emitTupleExtract(B, Loc, EltNo, SubElementNumber);
SILValue result = nonDestructivelyExtractSubElement(NewVal, B, Loc);
// If our original value wasn't guaranteed and we did actually perform a
// borrow as a result, insert the end_borrow.
if (BorrowedVal.getValue() != Val.getValue())
B.createEndBorrow(Loc, BorrowedVal.getValue());
return result;
}
SubElementNumber -= NumSubElt;
}
llvm_unreachable("Didn't find field");
}
// Extract struct elements.
if (auto *SD = getFullyReferenceableStruct(ValTy)) {
for (auto *D : SD->getStoredProperties()) {
auto fieldType = ValTy.getFieldType(
D, B.getModule(), TypeExpansionContext(B.getFunction()));
unsigned NumSubElt = getNumSubElements(
fieldType, B.getModule(), TypeExpansionContext(B.getFunction()));
if (SubElementNumber < NumSubElt) {
auto BorrowedVal = Val.emitBeginBorrow(B, Loc);
auto NewVal =
BorrowedVal.emitStructExtract(B, Loc, D, SubElementNumber);
SILValue result = nonDestructivelyExtractSubElement(NewVal, B, Loc);
// If our original value wasn't guaranteed and we did actually perform a
// borrow as a result, insert the end_borrow.
if (BorrowedVal.getValue() != Val.getValue())
B.createEndBorrow(Loc, BorrowedVal.getValue());
return result;
}
SubElementNumber -= NumSubElt;
}
llvm_unreachable("Didn't find field");
}
// Otherwise, we're down to a scalar. If we have ownership enabled,
// we return a copy. Otherwise, there we can ignore ownership
// issues. This is ok since in [ossa] we are going to eliminate a
// load [copy] or a load [trivial], while in non-[ossa] SIL we will
// be replacing unqualified loads.
assert(SubElementNumber == 0 && "Miscalculation indexing subelements");
if (!B.hasOwnership())
return Val.getValue();
return B.emitCopyValueOperation(Loc, Val.getValue());
}
//===----------------------------------------------------------------------===//
// Available Value Aggregation
//===----------------------------------------------------------------------===//
static bool anyMissing(unsigned StartSubElt, unsigned NumSubElts,
ArrayRef<AvailableValue> &Values) {
while (NumSubElts) {
if (!Values[StartSubElt])
return true;
++StartSubElt;
--NumSubElts;
}
return false;
}
namespace {
enum class AvailableValueExpectedOwnership {
Take,
Borrow,
Copy,
};
/// A class that aggregates available values, loading them if they are not
/// available.
class AvailableValueAggregator {
SILModule &M;
SILBuilderWithScope B;
SILLocation Loc;
MutableArrayRef<AvailableValue> AvailableValueList;
SmallVectorImpl<PMOMemoryUse> &Uses;
DeadEndBlocks &deadEndBlocks;
AvailableValueExpectedOwnership expectedOwnership;
/// Keep track of all instructions that we have added. Once we are done
/// promoting a value, we need to make sure that if we need to balance any
/// copies (to avoid leaks), we do so. This is not used if we are performing a
/// take.
SmallVector<SILInstruction *, 16> insertedInsts;
/// The list of phi nodes inserted by the SSA updater.
SmallVector<SILPhiArgument *, 16> insertedPhiNodes;
/// A set of copy_values whose lifetime we balanced while inserting phi
/// nodes. This means that these copy_value must be skipped in
/// addMissingDestroysForCopiedValues.
SmallPtrSet<CopyValueInst *, 16> copyValueProcessedWithPhiNodes;
public:
AvailableValueAggregator(SILInstruction *Inst,
MutableArrayRef<AvailableValue> AvailableValueList,
SmallVectorImpl<PMOMemoryUse> &Uses,
DeadEndBlocks &deadEndBlocks,
AvailableValueExpectedOwnership expectedOwnership)
: M(Inst->getModule()), B(Inst), Loc(Inst->getLoc()),
AvailableValueList(AvailableValueList), Uses(Uses),
deadEndBlocks(deadEndBlocks), expectedOwnership(expectedOwnership) {}
// This is intended to be passed by reference only once constructed.
AvailableValueAggregator(const AvailableValueAggregator &) = delete;
AvailableValueAggregator(AvailableValueAggregator &&) = delete;
AvailableValueAggregator &
operator=(const AvailableValueAggregator &) = delete;
AvailableValueAggregator &operator=(AvailableValueAggregator &&) = delete;
SILValue aggregateValues(SILType LoadTy, SILValue Address, unsigned FirstElt,
bool isTopLevel = true);
bool canTake(SILType loadTy, unsigned firstElt) const;
void print(llvm::raw_ostream &os) const;
void dump() const LLVM_ATTRIBUTE_USED;
bool isTake() const {
return expectedOwnership == AvailableValueExpectedOwnership::Take;
}
bool isBorrow() const {
return expectedOwnership == AvailableValueExpectedOwnership::Borrow;
}
bool isCopy() const {
return expectedOwnership == AvailableValueExpectedOwnership::Copy;
}
/// Given a load_borrow that we have aggregated a new value for, fixup the
/// reference counts of the intermediate copies and phis to ensure that all
/// forwarding operations in the CFG are strongly control equivalent (i.e. run
/// the same number of times).
void fixupOwnership(SILInstruction *load, SILValue newVal) {
assert(isa<LoadBorrowInst>(load) || isa<LoadInst>(load));
addHandOffCopyDestroysForPhis(load, newVal);
addMissingDestroysForCopiedValues(load, newVal);
}
private:
SILValue aggregateFullyAvailableValue(SILType loadTy, unsigned firstElt);
SILValue aggregateTupleSubElts(TupleType *tt, SILType loadTy,
SILValue address, unsigned firstElt);
SILValue aggregateStructSubElts(StructDecl *sd, SILType loadTy,
SILValue address, unsigned firstElt);
SILValue handlePrimitiveValue(SILType loadTy, SILValue address,
unsigned firstElt);
bool isFullyAvailable(SILType loadTy, unsigned firstElt) const;
/// If as a result of us copying values, we may have unconsumed destroys, find
/// the appropriate location and place the values there. Only used when
/// ownership is enabled.
void addMissingDestroysForCopiedValues(SILInstruction *load, SILValue newVal);
/// As a result of us using the SSA updater, insert hand off copy/destroys at
/// each phi and make sure that intermediate phis do not leak by inserting
/// destroys along paths that go through the intermediate phi that do not also
/// go through the
void addHandOffCopyDestroysForPhis(SILInstruction *load, SILValue newVal);
};
} // end anonymous namespace
void AvailableValueAggregator::dump() const { print(llvm::dbgs()); }
void AvailableValueAggregator::print(llvm::raw_ostream &os) const {
os << "Available Value List, N = " << AvailableValueList.size()
<< ". Elts:\n";
for (auto &V : AvailableValueList) {
os << V;
}
}
bool AvailableValueAggregator::isFullyAvailable(SILType loadTy,
unsigned firstElt) const {
if (firstElt >= AvailableValueList.size()) { // #Elements may be zero.
return false;
}
auto &firstVal = AvailableValueList[firstElt];
// Make sure that the first element is available and is the correct type.
if (!firstVal || firstVal.getType() != loadTy)
return false;
return llvm::all_of(range(getNumSubElements(
loadTy, M, TypeExpansionContext(B.getFunction()))),
[&](unsigned index) -> bool {
auto &val = AvailableValueList[firstElt + index];
return val.getValue() == firstVal.getValue() &&
val.getSubElementNumber() == index;
});
}
// We can only take if we never have to split a larger value to promote this
// address.
bool AvailableValueAggregator::canTake(SILType loadTy,
unsigned firstElt) const {
// If we do not have ownership, we can always take since we do not need to
// keep any ownership invariants up to date. In the future, we should be able
// to chop up larger values before they are being stored.
if (!B.hasOwnership())
return true;
// If we are trivially fully available, just return true.
if (isFullyAvailable(loadTy, firstElt))
return true;
// Otherwise see if we are an aggregate with fully available leaf types.
if (TupleType *tt = loadTy.getAs<TupleType>()) {
return llvm::all_of(indices(tt->getElements()), [&](unsigned eltNo) {
SILType eltTy = loadTy.getTupleElementType(eltNo);
unsigned numSubElt =
getNumSubElements(eltTy, M, TypeExpansionContext(B.getFunction()));
bool success = canTake(eltTy, firstElt);
firstElt += numSubElt;
return success;
});
}
if (auto *sd = getFullyReferenceableStruct(loadTy)) {
return llvm::all_of(sd->getStoredProperties(), [&](VarDecl *decl) -> bool {
auto context = TypeExpansionContext(B.getFunction());
SILType eltTy = loadTy.getFieldType(decl, M, context);
unsigned numSubElt = getNumSubElements(eltTy, M, context);
bool success = canTake(eltTy, firstElt);
firstElt += numSubElt;
return success;
});
}
// Otherwise, fail. The value is not fully available at its leafs. We can not
// perform a take.
return false;
}
/// Given a bunch of primitive subelement values, build out the right aggregate
/// type (LoadTy) by emitting tuple and struct instructions as necessary.
SILValue AvailableValueAggregator::aggregateValues(SILType LoadTy,
SILValue Address,
unsigned FirstElt,
bool isTopLevel) {
// If we are performing a take, make sure that we have available values for
// /all/ of our values. Otherwise, bail.
if (isTopLevel && isTake() && !canTake(LoadTy, FirstElt)) {
return SILValue();
}
// Check to see if the requested value is fully available, as an aggregate.
// This is a super-common case for single-element structs, but is also a
// general answer for arbitrary structs and tuples as well.
if (SILValue Result = aggregateFullyAvailableValue(LoadTy, FirstElt)) {
return Result;
}
// If we have a tuple type, then aggregate the tuple's elements into a full
// tuple value.
if (TupleType *tupleType = LoadTy.getAs<TupleType>()) {
SILValue result =
aggregateTupleSubElts(tupleType, LoadTy, Address, FirstElt);
if (isTopLevel && result->getOwnershipKind() == OwnershipKind::Guaranteed) {
SILValue borrowedResult = result;
SILBuilderWithScope builder(&*B.getInsertionPoint(), &insertedInsts);
result = builder.emitCopyValueOperation(Loc, borrowedResult);
SmallVector<BorrowedValue, 4> introducers;
bool foundIntroducers =
getAllBorrowIntroducingValues(borrowedResult, introducers);
(void)foundIntroducers;
assert(foundIntroducers);
for (auto value : introducers) {
builder.emitEndBorrowOperation(Loc, value.value);
}
}
return result;
}
// If we have a struct type, then aggregate the struct's elements into a full
// struct value.
if (auto *structDecl = getFullyReferenceableStruct(LoadTy)) {
SILValue result =
aggregateStructSubElts(structDecl, LoadTy, Address, FirstElt);
if (isTopLevel && result->getOwnershipKind() == OwnershipKind::Guaranteed) {
SILValue borrowedResult = result;
SILBuilderWithScope builder(&*B.getInsertionPoint(), &insertedInsts);
result = builder.emitCopyValueOperation(Loc, borrowedResult);
SmallVector<BorrowedValue, 4> introducers;
bool foundIntroducers =
getAllBorrowIntroducingValues(borrowedResult, introducers);
(void)foundIntroducers;
assert(foundIntroducers);
for (auto value : introducers) {
builder.emitEndBorrowOperation(Loc, value.value);
}
}
return result;
}
// Otherwise, we have a non-aggregate primitive. Load or extract the value.
//
// NOTE: We should never call this when taking since when taking we know that
// our underlying value is always fully available.
assert(!isTake());
return handlePrimitiveValue(LoadTy, Address, FirstElt);
}
// See if we have this value is fully available. In such a case, return it as an
// aggregate. This is a super-common case for single-element structs, but is
// also a general answer for arbitrary structs and tuples as well.
SILValue
AvailableValueAggregator::aggregateFullyAvailableValue(SILType loadTy,
unsigned firstElt) {
// Check if our underlying type is fully available. If it isn't, bail.
if (!isFullyAvailable(loadTy, firstElt))
return SILValue();
// Ok, grab out first value. (note: any actually will do).
auto &firstVal = AvailableValueList[firstElt];
// Ok, we know that all of our available values are all parts of the same
// value. Without ownership, we can just return the underlying first value.
if (!B.hasOwnership())
return firstVal.getValue();
// Otherwise, we need to put in a copy. This is b/c we only propagate along +1
// values and we are eliminating a load [copy].
ArrayRef<StoreInst *> insertPts = firstVal.getInsertionPoints();
if (insertPts.size() == 1) {
// Use the scope and location of the store at the insertion point.
SILBuilderWithScope builder(insertPts[0], &insertedInsts);
SILLocation loc = insertPts[0]->getLoc();
// If we have a take, just return the value.
if (isTake())
return firstVal.getValue();
// Otherwise, return a copy of the value.
return builder.emitCopyValueOperation(loc, firstVal.getValue());
}
// If we have multiple insertion points, put copies at each point and use the
// SSA updater to get a value. The reason why this is safe is that we can only
// have multiple insertion points if we are storing exactly the same value
// implying that we can just copy firstVal at each insertion point.
SILSSAUpdater updater(&insertedPhiNodes);
updater.initialize(&B.getFunction(), loadTy,
B.hasOwnership() ? OwnershipKind::Owned
: OwnershipKind::None);
std::optional<SILValue> singularValue;
for (auto *insertPt : insertPts) {
// Use the scope and location of the store at the insertion point.
SILBuilderWithScope builder(insertPt, &insertedInsts);
SILLocation loc = insertPt->getLoc();
SILValue eltVal = firstVal.getValue();
// If we are not taking, copy the element value.
if (!isTake()) {
eltVal = builder.emitCopyValueOperation(loc, eltVal);
}
if (!singularValue.has_value()) {
singularValue = eltVal;
} else if (*singularValue != eltVal) {
singularValue = SILValue();
}
// And then put the value into the SSA updater.
updater.addAvailableValue(insertPt->getParent(), eltVal);
}
// If we only are tracking a singular value, we do not need to construct
// SSA. Just return that value.
if (auto val = singularValue.value_or(SILValue())) {
// This assert documents that we are expecting that if we are in ossa, have
// a non-trivial value, and are not taking, we should never go down this
// code path. If we did, we would need to insert a copy here. The reason why
// we know we will never go down this code path is since we have been
// inserting copy_values implying that our potential singular value would be
// of the copy_values which are guaranteed to all be different.
assert((!B.hasOwnership() || isTake() ||
val->getType().isTrivial(*B.getInsertionBB()->getParent())) &&
"Should never reach this code path if we are in ossa and have a "
"non-trivial value");
return val;
}
// Finally, grab the value from the SSA updater.
SILValue result = updater.getValueInMiddleOfBlock(B.getInsertionBB());
assert(result->getOwnershipKind().isCompatibleWith(OwnershipKind::Owned));
if (isTake() || !B.hasOwnership()) {
return result;
}
// Be careful with this value and insert a copy in our load block to prevent
// any weird control equivalence issues.
SILBuilderWithScope builder(&*B.getInsertionPoint(), &insertedInsts);
return builder.emitCopyValueOperation(Loc, result);
}
SILValue AvailableValueAggregator::aggregateTupleSubElts(TupleType *TT,
SILType LoadTy,
SILValue Address,
unsigned FirstElt) {
SmallVector<SILValue, 4> ResultElts;
for (unsigned EltNo : indices(TT->getElements())) {
SILType EltTy = LoadTy.getTupleElementType(EltNo);
unsigned NumSubElt =
getNumSubElements(EltTy, M, TypeExpansionContext(B.getFunction()));
// If we are missing any of the available values in this struct element,
// compute an address to load from.
SILValue EltAddr;
if (anyMissing(FirstElt, NumSubElt, AvailableValueList)) {
assert(!isTake() && "When taking, values should never be missing?!");
EltAddr =
B.createTupleElementAddr(Loc, Address, EltNo, EltTy.getAddressType());
}
ResultElts.push_back(
aggregateValues(EltTy, EltAddr, FirstElt, /*isTopLevel*/ false));
FirstElt += NumSubElt;
}
// If we are going to use this to promote a borrowed value, insert borrow
// operations. Eventually I am going to do this for everything, but this
// should make it easier to bring up.
if (!isTake()) {
for (unsigned i : indices(ResultElts)) {
ResultElts[i] = B.emitBeginBorrowOperation(Loc, ResultElts[i]);
}
}
return B.createTuple(Loc, LoadTy, ResultElts);
}
SILValue AvailableValueAggregator::aggregateStructSubElts(StructDecl *sd,
SILType loadTy,
SILValue address,
unsigned firstElt) {
SmallVector<SILValue, 4> resultElts;
for (auto *decl : sd->getStoredProperties()) {
auto context = TypeExpansionContext(B.getFunction());
SILType eltTy = loadTy.getFieldType(decl, M, context);
unsigned numSubElt = getNumSubElements(eltTy, M, context);
// If we are missing any of the available values in this struct element,
// compute an address to load from.
SILValue eltAddr;
if (anyMissing(firstElt, numSubElt, AvailableValueList)) {
assert(!isTake() && "When taking, values should never be missing?!");
eltAddr =
B.createStructElementAddr(Loc, address, decl, eltTy.getAddressType());
}
resultElts.push_back(
aggregateValues(eltTy, eltAddr, firstElt, /*isTopLevel*/ false));
firstElt += numSubElt;
}
if (!isTake()) {
for (unsigned i : indices(resultElts)) {
resultElts[i] = B.emitBeginBorrowOperation(Loc, resultElts[i]);
}
}
return B.createStruct(Loc, loadTy, resultElts);
}
// We have looked through all of the aggregate values and finally found a value
// that is not available without transforming, i.e. a "primitive value". If the
// value is available, use it (extracting if we need to), otherwise emit a load
// of the value with the appropriate qualifier.
SILValue AvailableValueAggregator::handlePrimitiveValue(SILType loadTy,
SILValue address,
unsigned firstElt) {
assert(!isTake() && "Should only take fully available values?!");
// If the value is not available, load the value and update our use list.
auto &val = AvailableValueList[firstElt];
if (!val) {
LoadInst *load = ([&]() {
if (B.hasOwnership()) {
SILBuilderWithScope builder(&*B.getInsertionPoint(), &insertedInsts);
return builder.createTrivialLoadOr(Loc, address,
LoadOwnershipQualifier::Copy);
}
return B.createLoad(Loc, address, LoadOwnershipQualifier::Unqualified);
}());
Uses.emplace_back(load, PMOUseKind::Load);
return load;
}
// If we have 1 insertion point, just extract the value and return.
//
// This saves us from having to spend compile time in the SSA updater in this
// case.
ArrayRef<StoreInst *> insertPts = val.getInsertionPoints();
if (insertPts.size() == 1) {
// Use the scope and location of the store at the insertion point.
SILBuilderWithScope builder(insertPts[0], &insertedInsts);
SILLocation loc = insertPts[0]->getLoc();
SILValue eltVal = nonDestructivelyExtractSubElement(val, builder, loc);
assert(!builder.hasOwnership() ||
eltVal->getOwnershipKind().isCompatibleWith(OwnershipKind::Owned));
assert(eltVal->getType() == loadTy && "Subelement types mismatch");
if (!builder.hasOwnership()) {
return eltVal;
}
SILBuilderWithScope builder2(&*B.getInsertionPoint(), &insertedInsts);
return builder2.emitCopyValueOperation(Loc, eltVal);
}
// If we have an available value, then we want to extract the subelement from
// the borrowed aggregate before each insertion point. Note that since we have
// inserted copies at each of these insertion points, we know that we will
// never have the same value along all paths unless we have a trivial value
// meaning the SSA updater given a non-trivial value must /always/ be used.
SILSSAUpdater updater(&insertedPhiNodes);
updater.initialize(&B.getFunction(), loadTy,
B.hasOwnership() ? OwnershipKind::Owned
: OwnershipKind::None);
std::optional<SILValue> singularValue;
for (auto *i : insertPts) {
// Use the scope and location of the store at the insertion point.
SILBuilderWithScope builder(i, &insertedInsts);
SILLocation loc = i->getLoc();
SILValue eltVal = nonDestructivelyExtractSubElement(val, builder, loc);
assert(!builder.hasOwnership() ||
eltVal->getOwnershipKind().isCompatibleWith(OwnershipKind::Owned));
if (!singularValue.has_value()) {
singularValue = eltVal;
} else if (*singularValue != eltVal) {
singularValue = SILValue();
}
updater.addAvailableValue(i->getParent(), eltVal);
}
SILBasicBlock *insertBlock = B.getInsertionBB();
// If we are not in ossa and have a singular value or if we are in ossa and
// have a trivial singular value, just return that value.
//
// This can never happen for non-trivial values in ossa since we never should
// visit this code path if we have a take implying that non-trivial values
// /will/ have a copy and thus are guaranteed (since each copy yields a
// different value) to not be singular values.
if (auto val = singularValue.value_or(SILValue())) {
assert((!B.hasOwnership() ||
val->getType().isTrivial(*insertBlock->getParent())) &&
"Should have inserted copies for each insertion point, so shouldn't "
"have a singular value if non-trivial?!");
return val;
}
// Finally, grab the value from the SSA updater.
SILValue eltVal = updater.getValueInMiddleOfBlock(insertBlock);
assert(!B.hasOwnership() ||
eltVal->getOwnershipKind().isCompatibleWith(OwnershipKind::Owned));
assert(eltVal->getType() == loadTy && "Subelement types mismatch");
if (!B.hasOwnership())
return eltVal;
SILBuilderWithScope builder(&*B.getInsertionPoint(), &insertedInsts);
return builder.emitCopyValueOperation(Loc, eltVal);
}
static SILInstruction *
getNonPhiBlockIncomingValueDef(SILValue incomingValue,
SingleValueInstruction *phiCopy) {
assert(isa<CopyValueInst>(phiCopy));
auto *phiBlock = phiCopy->getParent();
if (phiBlock == incomingValue->getParentBlock()) {
return nullptr;
}
if (auto *cvi = dyn_cast<CopyValueInst>(incomingValue)) {
return cvi;
}
assert(isa<SILPhiArgument>(incomingValue));
// Otherwise, our copy_value may not be post-dominated by our phi. To
// work around that, we need to insert destroys along the other
// paths. So set base to the first instruction in our argument's block,
// so we can insert destroys for our base.
return &*incomingValue->getParentBlock()->begin();
}
static bool
terminatorHasAnyKnownPhis(TermInst *ti,
ArrayRef<SILPhiArgument *> insertedPhiNodesSorted) {
for (auto succArgList : ti->getSuccessorBlockArgumentLists()) {
if (llvm::any_of(succArgList, [&](SILArgument *arg) {
return binary_search(insertedPhiNodesSorted,
cast<SILPhiArgument>(arg));
})) {
return true;
}
}
return false;
}
namespace {
class PhiNodeCopyCleanupInserter {
llvm::SmallMapVector<SILValue, unsigned, 8> incomingValues;
/// Map from index -> (incomingValueIndex, copy).
///
/// We are going to stable_sort this array using the indices of
/// incomingValueIndex. This will ensure that we always visit in
/// insertion order our incoming values (since the indices we are
/// sorting by are the count of incoming values we have seen so far
/// when we see the incoming value) and maintain the internal
/// insertion sort within our range as well. This ensures that we
/// visit our incoming values in visitation order and that within
/// their own values, also visit them in visitation order with
/// respect to each other.
SmallFrozenMultiMap<unsigned, SingleValueInstruction *, 16> copiesToCleanup;
/// The lifetime frontier that we use to compute lifetime endpoints
/// when emitting cleanups.
ValueLifetimeAnalysis::Frontier lifetimeFrontier;
public:
PhiNodeCopyCleanupInserter() = default;
void trackNewCleanup(SILValue incomingValue, CopyValueInst *copy) {
auto entry = std::make_pair(incomingValue, incomingValues.size());
auto iter = incomingValues.insert(entry);
// If we did not succeed, then iter.first.second is the index of
// incoming value. Otherwise, it will be nextIndex.
copiesToCleanup.insert(iter.first->second, copy);
}
void emit(DeadEndBlocks &deadEndBlocks) &&;
};
} // end anonymous namespace
void PhiNodeCopyCleanupInserter::emit(DeadEndBlocks &deadEndBlocks) && {
// READ THIS: We are being very careful here to avoid allowing for
// non-determinism to enter here.
//
// 1. First we create a list of indices of our phi node data. Then we use a
// stable sort those indices into the order in which our phi node cleanups
// would be in if we compared just using incomingValues. We use a stable