-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSILCodeMotion.cpp
1839 lines (1533 loc) · 65.3 KB
/
SILCodeMotion.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
//===--- SILCodeMotion.cpp - Code Motion Optimizations --------------------===//
//
// 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 "sil-codemotion"
#include "swift/AST/Module.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/BlotMapVector.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/SILValue.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILOptimizer/Analysis/ARCAnalysis.h"
#include "swift/SILOptimizer/Analysis/AliasAnalysis.h"
#include "swift/SILOptimizer/Analysis/PostOrderAnalysis.h"
#include "swift/SILOptimizer/Analysis/RCIdentityAnalysis.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "swift/SILOptimizer/Utils/OwnershipOptUtils.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include <optional>
STATISTIC(NumSunk, "Number of instructions sunk");
STATISTIC(NumRefCountOpsSimplified, "Number of enum ref count ops simplified");
STATISTIC(NumHoisted, "Number of instructions hoisted");
STATISTIC(NumSILArgumentReleaseHoisted, "Number of silargument release instructions hoisted");
llvm::cl::opt<bool> DisableSILRRCodeMotion("disable-sil-cm-rr-cm", llvm::cl::init(true));
using namespace swift;
namespace {
//===----------------------------------------------------------------------===//
// Utility
//===----------------------------------------------------------------------===//
static void createRefCountOpForPayload(SILBuilder &Builder, SILInstruction *I,
EnumElementDecl *EnumDecl,
SILValue DefOfEnum = SILValue()) {
assert(EnumDecl->hasAssociatedValues() &&
"We assume enumdecl has an argument type");
SILModule &Mod = I->getModule();
// The enum value is either passed as an extra argument if we are moving an
// retain that does not refer to the enum typed value - otherwise it is the
// argument to the refcount instruction.
SILValue EnumVal = DefOfEnum ? DefOfEnum : I->getOperand(0);
SILType ArgType = EnumVal->getType().getEnumElementType(
EnumDecl, Mod, TypeExpansionContext(Builder.getFunction()));
auto *UEDI =
Builder.createUncheckedEnumData(I->getLoc(), EnumVal, EnumDecl, ArgType);
SILType UEDITy = UEDI->getType();
// If our payload is trivial, we do not need to insert any retain or release
// operations.
if (UEDITy.isTrivial(*I->getFunction()))
return;
++NumRefCountOpsSimplified;
// If we have a retain value...
if (auto RCI = dyn_cast<RetainValueInst>(I)) {
// And our payload is refcounted, insert a strong_retain onto the
// payload.
if (UEDITy.isReferenceCounted(Mod)) {
Builder.createStrongRetain(I->getLoc(), UEDI, RCI->getAtomicity());
return;
}
// Otherwise, insert a retain_value on the payload.
Builder.createRetainValue(I->getLoc(), UEDI, RCI->getAtomicity());
return;
}
// At this point we know that we must have a release_value and a non-trivial
// payload.
assert(isa<ReleaseValueInst>(I) && "If I is not a retain value here, it must "
"be a release value since enums do not have reference semantics.");
auto *RCI = cast<ReleaseValueInst>(I);
// If our payload has reference semantics, insert the strong release.
if (UEDITy.isReferenceCounted(Mod)) {
Builder.createStrongRelease(I->getLoc(), UEDI, RCI->getAtomicity());
return;
}
// Otherwise if our payload is non-trivial but lacking reference semantics,
// insert the release_value.
Builder.createReleaseValue(I->getLoc(), UEDI, RCI->getAtomicity());
}
//===----------------------------------------------------------------------===//
// Enum Tag Dataflow
//===----------------------------------------------------------------------===//
namespace {
class EnumCaseDataflowContext;
using EnumBBCaseList =
llvm::SmallVector<std::pair<SILBasicBlock *, EnumElementDecl *>, 2>;
/// Class that performs enum tag state dataflow on the given BB.
class BBEnumTagDataflowState
: public SILInstructionVisitor<BBEnumTagDataflowState, bool> {
EnumCaseDataflowContext *Context;
NullablePtr<SILBasicBlock> BB;
SmallBlotMapVector<unsigned, EnumElementDecl *, 4> ValueToCaseMap;
SmallBlotMapVector<unsigned, EnumBBCaseList, 4> EnumToEnumBBCaseListMap;
public:
BBEnumTagDataflowState() = default;
BBEnumTagDataflowState(const BBEnumTagDataflowState &Other) = default;
~BBEnumTagDataflowState() = default;
SWIFT_DEBUG_DUMP;
bool init(EnumCaseDataflowContext &Context, SILBasicBlock *NewBB);
SILBasicBlock *getBB() { return BB.get(); }
using iterator = decltype(ValueToCaseMap)::iterator;
iterator begin() { return ValueToCaseMap.getItems().begin(); }
iterator end() { return ValueToCaseMap.getItems().end(); }
void clear() { ValueToCaseMap.clear(); }
bool visitSILInstruction(SILInstruction *I) { return false; }
bool visitEnumInst(EnumInst *EI);
bool visitUncheckedEnumDataInst(UncheckedEnumDataInst *UEDI);
bool visitRetainValueInst(RetainValueInst *RVI);
bool visitReleaseValueInst(ReleaseValueInst *RVI);
bool process();
bool hoistDecrementsIntoSwitchRegions(AliasAnalysis *AA);
bool sinkIncrementsOutOfSwitchRegions(AliasAnalysis *AA,
RCIdentityFunctionInfo *RCIA);
void handlePredSwitchEnum(SwitchEnumInst *S);
void handlePredCondSelectEnum(CondBranchInst *CondBr);
/// Helper method which initializes this state map with the data from the
/// first predecessor BB.
///
/// We will be performing an intersection in a later step of the merging.
bool initWithFirstPred(SILBasicBlock *FirstPredBB);
/// Top level merging function for predecessors.
void mergePredecessorStates();
/// If we have a single predecessor, see if the predecessor's terminator was a
/// switch_enum or a (cond_br + select_enum). If so, track in this block the
/// enum state of the operand.
void mergeSinglePredTermInfoIntoState(SILBasicBlock *Pred);
private:
EnumCaseDataflowContext &getContext() const;
unsigned getIDForValue(SILValue V) const;
SILValue getValueForID(unsigned ID) const;
};
/// Map all blocks to BBEnumTagDataflowState in RPO order.
class EnumCaseDataflowContext {
PostOrderFunctionInfo *PO;
std::vector<BBEnumTagDataflowState> BBToStateVec;
std::vector<SILValue> IDToEnumValueMap;
llvm::DenseMap<SILValue, unsigned> EnumValueToIDMap;
public:
EnumCaseDataflowContext(PostOrderFunctionInfo *PO) : PO(PO), BBToStateVec() {
BBToStateVec.resize(PO->size());
unsigned RPOIdx = 0;
for (SILBasicBlock *BB : PO->getReversePostOrder()) {
BBToStateVec[RPOIdx].init(*this, BB);
++RPOIdx;
}
}
/// Return true if we have a valid value for the given ID;
bool hasValueForID(unsigned ID) const {
return ID < IDToEnumValueMap.size() && IDToEnumValueMap[ID];
}
SILValue getValueForID(unsigned ID) const { return IDToEnumValueMap[ID]; }
unsigned getIDForValue(SILValue V) const {
// We are being a little tricky here. Here is what is happening:
//
// 1. When we start we do not know if we are already tracking V, so we
// prepare /as if/ V was new.
//
// 2. When we perform the insertion, if V already has a value associated
// with it, we return the iterator to that value. The iterator contains
// inside of it the actual index.
//
// 3. Otherwise, we initialize V in EnumValueToIDMap with NewID. Rather than
// re-accessing the iterator, we just return the value we have already
// computed.
unsigned NewID = IDToEnumValueMap.size();
auto &This = const_cast<EnumCaseDataflowContext &>(*this);
auto Iter = This.EnumValueToIDMap.insert({V, NewID});
if (!Iter.second)
return Iter.first->second;
This.IDToEnumValueMap.emplace_back(V);
return NewID;
}
void blotValue(SILValue V) {
unsigned ID = getIDForValue(V);
IDToEnumValueMap[ID] = SILValue();
}
unsigned size() const { return BBToStateVec.size(); }
BBEnumTagDataflowState &getRPOState(unsigned RPOIdx) {
return BBToStateVec[RPOIdx];
}
/// \return BBEnumTagDataflowState or NULL for unreachable blocks.
BBEnumTagDataflowState *getBBState(SILBasicBlock *BB) {
if (auto ID = PO->getRPONumber(BB)) {
return &getRPOState(*ID);
}
return nullptr;
}
};
} // end anonymous namespace
EnumCaseDataflowContext &BBEnumTagDataflowState::getContext() const {
// Context and BB are initialized together, so we only need to check one.
assert(BB.isNonNull() && "Uninitialized state?!");
return *Context;
}
unsigned BBEnumTagDataflowState::getIDForValue(SILValue V) const {
return getContext().getIDForValue(V);
}
SILValue BBEnumTagDataflowState::getValueForID(unsigned ID) const {
return getContext().getValueForID(ID);
}
void BBEnumTagDataflowState::handlePredSwitchEnum(SwitchEnumInst *S) {
// Find the tag associated with our BB and set the state of the
// enum we switch on to that value. This is important so we can determine
// covering switches for enums that have cases without payload.
// Next check if we are the target of a default switch_enum case. If we are,
// no interesting information can be extracted, so bail...
if (S->hasDefault() && S->getDefaultBB() == getBB())
return;
// Otherwise, attempt to find the tag associated with this BB in the switch
// enum...
for (unsigned i = 0, e = S->getNumCases(); i != e; ++i) {
auto P = S->getCase(i);
// If this case of the switch is not matched up with this BB, skip the
// case...
if (P.second != getBB())
continue;
// Ok, we found the case for our BB. If we don't have an enum tag (which can
// happen if we have a default statement), return. There is nothing more we
// can do.
if (!P.first)
return;
// Ok, we have a matching BB and a matching enum tag. Set the state and
// return.
ValueToCaseMap[getIDForValue(S->getOperand())] = P.first;
return;
}
llvm_unreachable("A successor of a switch_enum terminated BB should be in "
"the switch_enum.");
}
void BBEnumTagDataflowState::handlePredCondSelectEnum(CondBranchInst *CondBr) {
auto *EITI = dyn_cast<SelectEnumInst>(CondBr->getCondition());
if (!EITI)
return;
NullablePtr<EnumElementDecl> TrueElement = EITI->getSingleTrueElement();
if (TrueElement.isNull())
return;
// Find the tag associated with our BB and set the state of the
// enum we switch on to that value. This is important so we can determine
// covering switches for enums that have cases without payload.
// Check if we are the true case, ie, we know that we are the given tag.
const auto &Operand = EITI->getEnumOperand();
if (CondBr->getTrueBB() == getBB()) {
ValueToCaseMap[getIDForValue(Operand)] = TrueElement.get();
return;
}
// If the enum only has 2 values and its tag isn't the true branch, then we
// know the true branch must be the other tag.
if (EnumDecl *E = Operand->getType().getEnumOrBoundGenericEnum()) {
// We can't do this optimization on non-exhaustive enums.
const SILFunction *Fn = CondBr->getFunction();
bool IsExhaustive =
E->isEffectivelyExhaustive(Fn->getModule().getSwiftModule(),
Fn->getResilienceExpansion());
if (!IsExhaustive)
return;
// Look for a single other element on this enum.
EnumElementDecl *OtherElt = nullptr;
for (EnumElementDecl *Elt : E->getAllElements()) {
// Skip the case where we find the select_enum element
if (Elt == TrueElement.get())
continue;
// If we find another element, then we must have more than 2, so bail.
if (OtherElt)
return;
OtherElt = Elt;
}
// Only a single enum element? How would this even get here? We should
// handle it in SILCombine.
if (!OtherElt)
return;
// FIXME: Can we ever not be the false BB here?
if (CondBr->getTrueBB() != getBB()) {
ValueToCaseMap[getIDForValue(Operand)] = OtherElt;
return;
}
}
}
bool BBEnumTagDataflowState::initWithFirstPred(SILBasicBlock *FirstPredBB) {
// Try to look up the state for the first pred BB.
BBEnumTagDataflowState *FirstPredState = getContext().getBBState(FirstPredBB);
// If we fail, we found an unreachable block, bail.
if (FirstPredState == nullptr) {
LLVM_DEBUG(llvm::dbgs() << " Found an unreachable block!\n");
return false;
}
// Ok, our state is in the map, copy in the predecessors value to case map.
ValueToCaseMap = FirstPredState->ValueToCaseMap;
// If we are predecessors only successor, we can potentially hoist releases
// into it, so associate the first pred BB and the case for each value that we
// are tracking with it.
//
// TODO: I am writing this too fast. Clean this up later.
if (FirstPredBB->getSingleSuccessorBlock()) {
for (auto P : ValueToCaseMap.getItems()) {
if (!P.has_value())
continue;
EnumToEnumBBCaseListMap[P->first].push_back({FirstPredBB, P->second});
}
}
return true;
}
void BBEnumTagDataflowState::mergeSinglePredTermInfoIntoState(
SILBasicBlock *Pred) {
// Grab the terminator of our one predecessor and if it is a switch enum, mix
// it into this state.
TermInst *PredTerm = Pred->getTerminator();
if (auto *S = dyn_cast<SwitchEnumInst>(PredTerm)) {
handlePredSwitchEnum(S);
return;
}
auto *CondBr = dyn_cast<CondBranchInst>(PredTerm);
if (!CondBr)
return;
handlePredCondSelectEnum(CondBr);
}
void BBEnumTagDataflowState::mergePredecessorStates() {
// If we have no predecessors, there is nothing to do so return early...
if (getBB()->pred_empty()) {
LLVM_DEBUG(llvm::dbgs() << " No Preds.\n");
return;
}
auto PI = getBB()->pred_begin(), PE = getBB()->pred_end();
if (*PI == getBB()) {
LLVM_DEBUG(llvm::dbgs() << " Found a self loop. Bailing!\n");
return;
}
// Grab the first predecessor BB.
SILBasicBlock *FirstPred = *PI;
++PI;
// Attempt to initialize our state with our first predecessor's state by just
// copying. We will be doing an intersection with all of the other BB.
if (!initWithFirstPred(FirstPred))
return;
// If we only have one predecessor see if we can gain any information and or
// knowledge from the terminator of our one predecessor. There is nothing more
// that we can do, return.
//
// This enables us to get enum information from switch_enum and cond_br about
// the value that an enum can take in our block. This is a common case that
// comes up.
if (PI == PE) {
mergeSinglePredTermInfoIntoState(FirstPred);
return;
}
LLVM_DEBUG(llvm::dbgs() <<" Merging in rest of predecessors...\n");
// Enum values that while merging we found conflicting values for. We blot
// them after the loop in order to ensure that we can still find the ends of
// switch regions.
llvm::SmallVector<unsigned, 4> CurBBValuesToBlot;
// If we do not find state for a specific value in any of our predecessor BBs,
// we cannot be the end of a switch region since we cannot cover our
// predecessor BBs with enum decls. Blot after the loop.
llvm::SmallVector<unsigned, 4> PredBBValuesToBlot;
// And for each remaining predecessor...
do {
// If we loop on ourselves, bail...
if (*PI == getBB()) {
LLVM_DEBUG(llvm::dbgs() << " Found a self loop. Bailing!\n");
return;
}
// Grab the predecessors state...
SILBasicBlock *PredBB = *PI;
BBEnumTagDataflowState *PredBBState = getContext().getBBState(PredBB);
if (PredBBState == nullptr) {
LLVM_DEBUG(llvm::dbgs() << " Found an unreachable block!\n");
return;
}
++PI;
// Then for each (SILValue, Enum Tag) that we are tracking...
for (auto P : ValueToCaseMap.getItems()) {
// If this SILValue was blotted, there is nothing left to do, we found
// some sort of conflicting definition and are being conservative.
if (!P.has_value())
continue;
// Then attempt to look up the enum state associated in our SILValue in
// the predecessor we are processing.
auto PredIter = PredBBState->ValueToCaseMap.find(P->first);
// If we cannot find the state associated with this SILValue in this
// predecessor or the ID in the corresponding predecessor was blotted, we
// cannot find a covering switch for this BB or forward any enum tag
// information for this enum value.
if (PredIter == PredBBState->ValueToCaseMap.end() ||
!(*PredIter).has_value()) {
// Otherwise, we are conservative and do not forward the EnumTag that we
// are tracking. Blot it!
LLVM_DEBUG(llvm::dbgs() << " Blotting: " << P->first);
CurBBValuesToBlot.push_back(P->first);
PredBBValuesToBlot.push_back(P->first);
continue;
}
// Then try to lookup the actual value associated with the ID. If we do
// not find one, then the enum was destroyed by another part of the pass.
SILValue PredValue = getValueForID((*PredIter)->first);
if (!PredValue)
continue;
// Check if out predecessor has any other successors. If that is true we
// clear all the state since we cannot hoist safely.
if (!PredBB->getSingleSuccessorBlock()) {
EnumToEnumBBCaseListMap.clear();
LLVM_DEBUG(llvm::dbgs() << " Predecessor has other "
"successors. Clearing BB cast list map.\n");
} else {
// Otherwise, add this case to our predecessor case list. We will unique
// this after we have finished processing all predecessors.
auto Case = std::make_pair(PredBB, (*PredIter)->second);
EnumToEnumBBCaseListMap[(*PredIter)->first].push_back(Case);
}
// And the states match, the enum state propagates to this BB.
if ((*PredIter)->second == P->second)
continue;
// Otherwise, we are conservative and do not forward the EnumTag that we
// are tracking. Blot it!
LLVM_DEBUG(llvm::dbgs() << " Blotting: " << P->first);
CurBBValuesToBlot.push_back(P->first);
}
} while (PI != PE);
for (unsigned ID : CurBBValuesToBlot) {
ValueToCaseMap.erase(ID);
}
for (unsigned ID : PredBBValuesToBlot) {
EnumToEnumBBCaseListMap.erase(ID);
}
}
bool BBEnumTagDataflowState::visitEnumInst(EnumInst *EI) {
unsigned ID = getIDForValue(SILValue(EI));
LLVM_DEBUG(llvm::dbgs() << " Storing enum into map. ID: " << ID
<< ". Value: " << *EI);
ValueToCaseMap[ID] = EI->getElement();
return false;
}
bool BBEnumTagDataflowState::visitUncheckedEnumDataInst(
UncheckedEnumDataInst *UEDI) {
unsigned ID = getIDForValue(UEDI->getOperand());
LLVM_DEBUG(llvm::dbgs() << " Storing unchecked enum data into map. ID: "
<< ID << ". Value: " << *UEDI);
ValueToCaseMap[ID] = UEDI->getElement();
return false;
}
bool BBEnumTagDataflowState::visitRetainValueInst(RetainValueInst *RVI) {
auto FindResult = ValueToCaseMap.find(getIDForValue(RVI->getOperand()));
if (FindResult == ValueToCaseMap.end())
return false;
// If we do not have any argument, kill the retain_value.
if (!(*FindResult)->second->hasAssociatedValues()) {
RVI->eraseFromParent();
return true;
}
LLVM_DEBUG(llvm::dbgs() << " Found RetainValue: " << *RVI);
LLVM_DEBUG(llvm::dbgs() << " Paired to Enum Oracle: "
<< (*FindResult)->first);
SILBuilderWithScope Builder(RVI);
createRefCountOpForPayload(Builder, RVI, (*FindResult)->second);
RVI->eraseFromParent();
return true;
}
bool BBEnumTagDataflowState::visitReleaseValueInst(ReleaseValueInst *RVI) {
auto FindResult = ValueToCaseMap.find(getIDForValue(RVI->getOperand()));
if (FindResult == ValueToCaseMap.end())
return false;
// If the enum has a deinit, preserve the original release.
if (hasValueDeinit(RVI->getOperand()))
return false;
// If we do not have any argument, just delete the release value.
if (!(*FindResult)->second->hasAssociatedValues()) {
RVI->eraseFromParent();
return true;
}
LLVM_DEBUG(llvm::dbgs() << " Found ReleaseValue: " << *RVI);
LLVM_DEBUG(llvm::dbgs() << " Paired to Enum Oracle: "
<< (*FindResult)->first);
SILBuilderWithScope Builder(RVI);
createRefCountOpForPayload(Builder, RVI, (*FindResult)->second);
RVI->eraseFromParent();
return true;
}
bool BBEnumTagDataflowState::process() {
bool Changed = false;
auto SI = getBB()->begin();
while (SI != getBB()->end()) {
SILInstruction *I = &*SI;
++SI;
Changed |= visit(I);
}
return Changed;
}
bool BBEnumTagDataflowState::hoistDecrementsIntoSwitchRegions(
AliasAnalysis *AA) {
bool Changed = false;
unsigned NumPreds = std::distance(getBB()->pred_begin(), getBB()->pred_end());
for (auto II = getBB()->begin(), IE = getBB()->end(); II != IE;) {
auto *RVI = dyn_cast<ReleaseValueInst>(&*II);
++II;
// If this instruction is not a release, skip it...
if (!RVI)
continue;
LLVM_DEBUG(llvm::dbgs() << " Visiting release: " << *RVI);
// Grab the operand of the release value inst.
SILValue Op = RVI->getOperand();
// Lookup the [(BB, EnumTag)] list for this operand.
unsigned ID = getIDForValue(Op);
auto R = EnumToEnumBBCaseListMap.find(ID);
// If we don't have one, skip this release value inst.
if (R == EnumToEnumBBCaseListMap.end()) {
LLVM_DEBUG(llvm::dbgs() << " Could not find [(BB, EnumTag)] "
"list for release_value's operand. Bailing!\n");
continue;
}
// If the enum has a deinit, preserve the original release.
if (hasValueDeinit(Op))
return false;
auto &EnumBBCaseList = (*R)->second;
// If we don't have an enum tag for each predecessor of this BB, bail since
// we do not know how to handle that BB.
if (EnumBBCaseList.size() != NumPreds) {
LLVM_DEBUG(llvm::dbgs() << " Found [(BB, EnumTag)] list for "
"release_value's operand, but we do not have "
"an enum tag for each predecessor. Bailing!\n");
LLVM_DEBUG(llvm::dbgs() << " List:\n");
LLVM_DEBUG(for (auto P : EnumBBCaseList) {
llvm::dbgs() << " ";
P.second->dump(llvm::dbgs());
});
continue;
}
// Finally ensure that we have no users of this operand preceding the
// release_value in this BB. If we have users like that we cannot hoist the
// release past them unless we know that there is an additional set of
// releases that together post-dominate this release. If we cannot do this,
// skip this release.
//
// TODO: We need information from the ARC optimizer to prove that property
// if we are going to use it.
if (valueHasARCUsesInInstructionRange(Op, getBB()->begin(),
SILBasicBlock::iterator(RVI), AA)) {
LLVM_DEBUG(llvm::dbgs() << " Release value has use that stops "
"hoisting! Bailing!\n");
continue;
}
LLVM_DEBUG(llvm::dbgs() << " Its safe to perform the "
"transformation!\n");
// Otherwise perform the transformation.
for (auto P : EnumBBCaseList) {
// If we don't have an argument for this case, there is nothing to
// do... continue...
if (!P.second->hasAssociatedValues())
continue;
// Otherwise create the release_value before the terminator of the
// predecessor.
assert(P.first->getSingleSuccessorBlock() &&
"Cannot hoist release into BB that has multiple successors");
SILBuilderWithScope Builder(P.first->getTerminator(), RVI);
createRefCountOpForPayload(Builder, RVI, P.second);
}
RVI->eraseFromParent();
++NumHoisted;
Changed = true;
}
return Changed;
}
static SILInstruction *findLastSinkableMatchingEnumValueRCIncrementInPred(
AliasAnalysis *AA, RCIdentityFunctionInfo *RCIA, SILValue EnumValue,
SILBasicBlock *BB) {
// Otherwise, see if we can find a retain_value or strong_retain associated
// with that enum in the relevant predecessor.
auto FirstInc = std::find_if(
BB->rbegin(), BB->rend(),
[&RCIA, &EnumValue](const SILInstruction &I) -> bool {
// If I is not an increment, ignore it.
if (!isa<StrongRetainInst>(I) && !isa<RetainValueInst>(I))
return false;
// Otherwise, if the increments operand stripped of RC identity
// preserving
// ops matches EnumValue, it is the first increment we are interested
// in.
return EnumValue == RCIA->getRCIdentityRoot(I.getOperand(0));
});
// If we do not find a ref count increment in the relevant BB, skip this
// enum since there is nothing we can do.
if (FirstInc == BB->rend())
return nullptr;
// Otherwise, see if there are any instructions in between FirstPredInc and
// the end of the given basic block that could decrement first pred. If such
// an instruction exists, we cannot perform this optimization so continue.
if (valueHasARCDecrementOrCheckInInstructionRange(
EnumValue, (*FirstInc).getIterator(),
BB->getTerminator()->getIterator(), AA))
return nullptr;
return &*FirstInc;
}
static bool findRetainsSinkableFromSwitchRegionForEnum(
AliasAnalysis *AA, RCIdentityFunctionInfo *RCIA, SILValue EnumValue,
EnumBBCaseList &Map, SmallVectorImpl<SILInstruction *> &DeleteList) {
// For each predecessor with argument type...
for (auto &P : Map) {
SILBasicBlock *PredBB = P.first;
EnumElementDecl *Decl = P.second;
// If the case does not have an argument type, skip the predecessor since
// there will not be a retain to sink.
if (!Decl->hasAssociatedValues())
continue;
// Ok, we found a payloaded predecessor. Look backwards through the
// predecessor for the first ref count increment on EnumValue. If there
// are no ref count decrements in between the increment and the terminator
// of the BB, then we can sink the retain out of the switch enum.
auto *Inc = findLastSinkableMatchingEnumValueRCIncrementInPred(
AA, RCIA, EnumValue, PredBB);
// If we do not find such an increment, there is nothing we can do, bail.
if (!Inc)
return false;
// Otherwise add the increment to the delete list.
DeleteList.push_back(Inc);
}
// If we were able to process each predecessor successfully, return true.
return true;
}
bool BBEnumTagDataflowState::sinkIncrementsOutOfSwitchRegions(
AliasAnalysis *AA, RCIdentityFunctionInfo *RCIA) {
bool Changed = false;
unsigned NumPreds = std::distance(getBB()->pred_begin(), getBB()->pred_end());
llvm::SmallVector<SILInstruction *, 4> DeleteList;
// For each (EnumValue, [(BB, EnumTag)]) that we are tracking...
for (auto &P : EnumToEnumBBCaseListMap) {
// Clear our delete list.
DeleteList.clear();
// If EnumValue is null, we deleted this entry. There is nothing to do for
// this value... Skip it.
if (!P.has_value())
continue;
// Look up the actual enum value using our index to make sure that other
// parts of the pass have not destroyed the value. In such a case, just
// continue.
SILValue EnumValue = getContext().getValueForID(P->first);
if (!EnumValue)
continue;
EnumValue = RCIA->getRCIdentityRoot(EnumValue);
EnumBBCaseList &Map = P->second;
// If we do not have a tag associated with this enum value for each
// predecessor, we are not a switch region exit for this enum value. Skip
// this value.
if (Map.size() != NumPreds)
continue;
// Look through our predecessors for a set of ref count increments on our
// enum value for every payloaded case that *could* be sunk. If we miss an
// increment from any of the payloaded case there is nothing we can do here,
// so skip this enum value.
if (!findRetainsSinkableFromSwitchRegionForEnum(AA, RCIA, EnumValue, Map,
DeleteList))
continue;
// If we do not have any payload arguments, then we should have an empty
// delete list and there is nothing to do here.
if (DeleteList.empty())
continue;
// Ok, we can perform this transformation! Insert the new retain_value and
// delete all of the ref count increments from the predecessor BBs.
//
// TODO: Which debug loc should we use here? Using one of the locs from the
// delete list seems reasonable for now...
SILBuilder Builder(getBB()->begin());
Builder.createRetainValue(
DeleteList[0]->getLoc(), EnumValue,
cast<RefCountingInst>(DeleteList[0])->getAtomicity());
for (auto *I : DeleteList)
I->eraseFromParent();
++NumSunk;
Changed = true;
}
return Changed;
}
void BBEnumTagDataflowState::dump() const {
#ifndef NDEBUG
llvm::dbgs() << "Dumping state for BB" << BB.get()->getDebugID() << "\n";
llvm::dbgs() << "Block States:\n";
for (auto &P : ValueToCaseMap) {
if (!P) {
llvm::dbgs() << " Skipping blotted value.\n";
continue;
}
unsigned ID = P->first;
SILValue V = getContext().getValueForID(ID);
if (!V) {
llvm::dbgs() << " ID: " << ID << ". Value: BLOTTED.\n";
continue;
}
llvm::dbgs() << " ID: " << ID << ". Value: " << V;
}
llvm::dbgs() << "Predecessor States:\n";
// For each (EnumValue, [(BB, EnumTag)]) that we are tracking...
for (auto &P : EnumToEnumBBCaseListMap) {
if (!P) {
llvm::dbgs() << " Skipping blotted value.\n";
continue;
}
unsigned ID = P->first;
SILValue V = getContext().getValueForID(ID);
if (!V) {
llvm::dbgs() << " ID: " << ID << ". Value: BLOTTED.\n";
continue;
}
llvm::dbgs() << " ID: " << ID << ". Value: " << V;
llvm::dbgs() << " Case List:\n";
for (auto &P2 : P->second) {
llvm::dbgs() << " BB" << P2.first->getDebugID() << ": ";
P2.second->dump(llvm::dbgs());
llvm::dbgs() << "\n";
}
llvm::dbgs() << " End Case List.\n";
}
#endif
}
bool BBEnumTagDataflowState::init(EnumCaseDataflowContext &NewContext,
SILBasicBlock *NewBB) {
assert(NewBB && "NewBB should not be null");
Context = &NewContext;
BB = NewBB;
return true;
}
//===----------------------------------------------------------------------===//
// Generic Sinking Code
//===----------------------------------------------------------------------===//
/// Hoist release on a SILArgument to its predecessors.
static bool hoistSILArgumentReleaseInst(SILBasicBlock *BB) {
// There is no block to hoist releases to.
if (BB->pred_empty())
return false;
// Only try to hoist the first instruction. RRCM should have hoisted the
// release
// to the beginning of the block if it can.
auto Head = &*BB->begin();
// Make sure it is a release instruction.
if (!isReleaseInstruction(&*Head))
return false;
// Make sure it is a release on a SILArgument of the current basic block..
auto *SA = dyn_cast<SILArgument>(Head->getOperand(0));
if (!SA || SA->getParent() != BB)
return false;
// Make sure the release will not be blocked by the terminator instructions
// Make sure the terminator does not block, nor is a branch with multiple
// targets.
for (auto P : BB->getPredecessorBlocks()) {
if (!isa<BranchInst>(P->getTerminator()))
return false;
}
// Make sure we can get all the incoming values.
llvm::SmallVector<SILValue, 4> PredValues;
if (!SA->getIncomingPhiValues(PredValues))
return false;
// Ok, we can get all the incoming values and create releases for them.
unsigned indices = 0;
for (auto P : BB->getPredecessorBlocks()) {
createDecrementBefore(PredValues[indices++], P->getTerminator());
}
// Erase the old instruction.
Head->eraseFromParent();
++NumSILArgumentReleaseHoisted;
return true;
}
static const int SinkSearchWindow = 6;
/// Returns True if we can sink this instruction to another basic block.
static bool canSinkInstruction(SILInstruction *Inst) {
if (hasOwnershipOperandsOrResults(Inst))
return false;
return !Inst->hasUsesOfAnyResult() && !isa<TermInst>(Inst);
}
/// Returns true if this instruction is a skip barrier, which means that
/// we can't sink other instructions past it.
static bool isSinkBarrier(SILInstruction *Inst) {
if (isa<TermInst>(Inst))
return false;
if (Inst->mayHaveSideEffects())
return true;
return false;
}
using ValueInBlock = std::pair<SILValue, SILBasicBlock *>;
using ValueToBBArgIdxMap = llvm::DenseMap<ValueInBlock, int>;
enum OperandRelation {
/// Uninitialized state.
NotDeterminedYet,
/// The original operand values are equal.
AlwaysEqual,
/// The operand values are equal after replacing with the successor block
/// arguments.
EqualAfterMove
};
/// Find a root value for operand \p In. This function inspects a sil
/// value and strips trivial conversions such as values that are passed
/// as arguments to basic blocks with a single predecessor or type casts.
/// This is a shallow one-step search and not a deep recursive search.
///
/// For example, in the SIL code below, the root of %10 is %3, because it is
/// the only possible incoming value.
///
/// bb1:
/// %3 = unchecked_enum_data %0 : $Optional<X>, #Optional.Some!enumelt
/// checked_cast_br [exact] X in %3 : $X to $X, bb4, bb5 // id: %4
///
/// bb4(%10 : $X): // Preds: bb1
/// strong_release %10 : $X
/// br bb2
///
static SILValue findValueShallowRoot(const SILValue &In) {
// If this is a basic block argument with a single caller
// then we know exactly which value is passed to the argument.
if (auto *Arg = dyn_cast<SILArgument>(In)) {
SILBasicBlock *Parent = Arg->getParent();
SILBasicBlock *Pred = Parent->getSinglePredecessorBlock();
if (!Pred)
return In;
// If the terminator is a cast instruction then use the pre-cast value.
if (auto CCBI = dyn_cast<CheckedCastBranchInst>(Pred->getTerminator())) {
assert(CCBI->getSuccessBB() == Parent && "Inspecting the wrong block");
// In swift it is legal to cast non reference-counted references into
// object references. For example: func f(x : C.Type) -> Any {return x}
// Here we check that the uncasted reference is reference counted.
SILValue V = CCBI->getOperand();
if (V->getType().isReferenceCounted(Pred->getParent()->getModule())) {
return V;
}
}
// If the single predecessor terminator is a branch then the root is
// the argument to the terminator.
if (auto BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
assert(BI->getDestBB() == Parent && "Invalid terminator");
unsigned Idx = Arg->getIndex();
return BI->getArg(Idx);
}
if (auto CBI = dyn_cast<CondBranchInst>(Pred->getTerminator())) {
return CBI->getArgForDestBB(Parent, Arg);