-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathOutliner.cpp
1446 lines (1267 loc) · 50.6 KB
/
Outliner.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
//===------------- Outliner.cpp - Outlining Transformations ---------------===//
//
// 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-outliner"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/Demangling/Demangler.h"
#include "swift/Demangling/ManglingMacros.h"
#include "swift/SIL/ApplySite.h"
#include "swift/SIL/BasicBlockDatastructures.h"
#include "swift/SIL/BasicBlockUtils.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/OwnershipOptUtils.h"
#include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
llvm::cl::opt<std::string> DumpFuncsBeforeOutliner(
"sil-dump-functions-before-outliner", llvm::cl::init(""),
llvm::cl::desc(
"Break before running each function pass on a particular function"));
namespace {
class OutlinerMangler : public Mangle::ASTMangler {
/// The kind of method bridged.
enum MethodKind : unsigned {
BridgedProperty,
BridgedProperty_Consuming,
BridgedPropertyAddress,
BridgedMethod,
};
llvm::BitVector *IsParameterBridged;
llvm::BitVector *IsParameterGuaranteed;
SILDeclRef MethodDecl;
MethodKind Kind;
bool IsReturnBridged;
public:
/// Create an mangler for an outlined bridged method.
OutlinerMangler(SILDeclRef Method, llvm::BitVector *ParameterBridged,
llvm::BitVector *IsParameterGuaranteed, bool ReturnBridged)
: ASTMangler(Method.getASTContext()), IsParameterBridged(ParameterBridged),
IsParameterGuaranteed(IsParameterGuaranteed), MethodDecl(Method),
Kind(BridgedMethod), IsReturnBridged(ReturnBridged) {}
/// Create an mangler for an outlined bridged property.
OutlinerMangler(SILDeclRef Method, bool IsAddress, bool ConsumesValue)
: ASTMangler(Method.getASTContext()), IsParameterBridged(nullptr), IsParameterGuaranteed(nullptr),
MethodDecl(Method),
Kind(IsAddress ? BridgedPropertyAddress
: (ConsumesValue ? BridgedProperty_Consuming
: BridgedProperty)),
IsReturnBridged(true) {}
std::string mangle();
private:
char getMethodKindMangling() {
switch (Kind) {
case BridgedProperty:
return 'p';
case BridgedProperty_Consuming:
return 'o';
case BridgedPropertyAddress:
return 'a';
case BridgedMethod:
return 'm';
}
llvm_unreachable("unhandled kind");
}
};
} // end anonymous namespace.
std::string OutlinerMangler::mangle() {
beginManglingWithoutPrefix();
appendOperator(MethodDecl.mangle());
llvm::SmallString<128> Buffer;
llvm::raw_svector_ostream Out(Buffer);
Out << getMethodKindMangling();
if (IsParameterBridged) {
for (unsigned Idx = 0, E = IsParameterBridged->size(); Idx != E; ++Idx) {
Out << (IsParameterBridged->test(Idx) ? 'b' : 'n');
// NOTE: We must keep owned as having nothing here to preserve ABI since
// mangling is part of ABI.
Out << (IsParameterGuaranteed->test(Idx) ? "g" : "");
}
}
Out << (IsReturnBridged ? 'b' : 'n');
Out << '_';
appendOperator("Te", Buffer);
return finalize();
}
namespace {
class OutlinePattern {
protected:
SILOptFunctionBuilder &FuncBuilder;
InstModCallbacks callbacks;
DeadEndBlocks *deBlocks;
public:
OutlinePattern(SILOptFunctionBuilder &FuncBuilder,
InstModCallbacks callbacks,
DeadEndBlocks *deBlocks)
: FuncBuilder(FuncBuilder), callbacks(callbacks), deBlocks(deBlocks) {}
/// Match the instruction sequence.
virtual bool matchInstSequence(SILBasicBlock::iterator I) = 0;
/// Outline the matched instruction sequence.
///
/// If a new outlined function is created return the function. If the outlined
/// function already existed return null.
/// Returns the last instruction of the matched sequence after the
/// replacement.
virtual std::pair<SILFunction *, SILBasicBlock::iterator>
outline(SILModule &M) = 0;
virtual std::string getOutlinedFunctionName() = 0;
virtual ~OutlinePattern() {}
};
/// Get the bridgeToObjectiveC witness for the type.
static SILDeclRef getBridgeToObjectiveC(CanType NativeType) {
auto &Ctx = NativeType->getASTContext();
auto Proto = Ctx.getProtocol(KnownProtocolKind::ObjectiveCBridgeable);
if (!Proto)
return SILDeclRef();
auto ConformanceRef = lookupConformance(NativeType, Proto);
if (ConformanceRef.isInvalid())
return SILDeclRef();
auto Conformance = ConformanceRef.getConcrete();
// bridgeToObjectiveC
DeclName Name(Ctx, Ctx.Id_bridgeToObjectiveC, llvm::ArrayRef<Identifier>());
auto *Requirement = dyn_cast_or_null<FuncDecl>(
Proto->getSingleRequirement(Name));
if (!Requirement)
return SILDeclRef();
auto Witness = Conformance->getWitnessDecl(Requirement);
return SILDeclRef(Witness);
}
/// Get the _unconditionallyBridgeFromObjectiveC witness for the type.
SILDeclRef getBridgeFromObjectiveC(CanType NativeType) {
auto &Ctx = NativeType->getASTContext();
auto Proto = Ctx.getProtocol(KnownProtocolKind::ObjectiveCBridgeable);
if (!Proto)
return SILDeclRef();
auto ConformanceRef = lookupConformance(NativeType, Proto);
if (ConformanceRef.isInvalid())
return SILDeclRef();
auto Conformance = ConformanceRef.getConcrete();
// _unconditionallyBridgeFromObjectiveC
DeclName Name(Ctx, Ctx.getIdentifier("_unconditionallyBridgeFromObjectiveC"),
llvm::ArrayRef(Identifier()));
auto *Requirement = dyn_cast_or_null<FuncDecl>(
Proto->getSingleRequirement(Name));
if (!Requirement)
return SILDeclRef();
auto Witness = Conformance->getWitnessDecl(Requirement);
return SILDeclRef(Witness);
}
struct SwitchInfo {
SwitchEnumInst *SwitchEnum = nullptr;
SILBasicBlock *SomeBB = nullptr;
SILBasicBlock *NoneBB = nullptr;
BranchInst *Br = nullptr;
};
/// Pattern for a bridged property call.
///
/// bb7:
/// %30 = unchecked_take_enum_data_addr %19 : $*Optional<UITextField>, #Optional.some!enumelt
/// %31 = load %30 : $*UITextField
/// strong_retain %31 : $UITextField
/// %33 = objc_method %31 : $UITextField, #UITextField.text!getter.foreign : (UITextField) -> () -> String?, $@convention(objc_method) (UITextField) -> @autoreleased Optional<NSString>
/// %34 = apply %33(%31) : $@convention(objc_method) (UITextField) -> @autoreleased Optional<NSString>
/// switch_enum %34 : $Optional<NSString>, case #Optional.some!enumelt: bb8, case #Optional.none!enumelt: bb9
///
/// bb8(%36 : $NSString):
/// // function_ref static String._unconditionallyBridgeFromObjectiveC(_:)
/// %37 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
/// %38 = enum $Optional<NSString>, #Optional.some!enumelt, %36 : $NSString
/// %39 = metatype $@thin String.Type
/// %40 = apply %37(%38, %39) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
/// %41 = enum $Optional<String>, #Optional.some!enumelt, %40 : $String
/// br bb10(%41 : $Optional<String>)
///
/// bb9:
/// %43 = enum $Optional<String>, #Optional.none!enumelt
/// br bb10(%43 : $Optional<String>)
///
/// bb10(%45 : $Optional<String>):
class BridgedProperty : public OutlinePattern {
std::string OutlinedName;
SingleValueInstruction *FirstInst; // A load or class_method
SILBasicBlock *StartBB;
SwitchInfo switchInfo;
ObjCMethodInst *ObjCMethod;
SILInstruction *Release;
ApplyInst *PropApply;
SILInstruction *UnpairedRelease; // A release_value | destroy_value following
// the apply which isn't paired to
// load [copy] | strong_retain first value.
public:
bool matchInstSequence(SILBasicBlock::iterator I) override;
std::pair<SILFunction *, SILBasicBlock::iterator>
outline(SILModule &M) override;
BridgedProperty(SILOptFunctionBuilder &FuncBuilder,
InstModCallbacks callbacks,
DeadEndBlocks *deBlocks)
: OutlinePattern(FuncBuilder, callbacks, deBlocks) {
clearState();
}
BridgedProperty(const BridgedProperty&) = delete;
BridgedProperty& operator=(const BridgedProperty&) = delete;
virtual ~BridgedProperty() {}
std::string getOutlinedFunctionName() override;
private:
bool matchMethodCall(SILBasicBlock::iterator, LoadInst *);
CanSILFunctionType getOutlinedFunctionType(SILModule &M);
void clearState();
};
}
void BridgedProperty::clearState() {
FirstInst = nullptr;
StartBB = nullptr;
switchInfo = SwitchInfo();
ObjCMethod = nullptr;
Release = nullptr;
PropApply = nullptr;
UnpairedRelease = nullptr;
OutlinedName.clear();
}
std::string BridgedProperty::getOutlinedFunctionName() {
if (OutlinedName.empty()) {
OutlinerMangler Mangler(ObjCMethod->getMember(), isa<LoadInst>(FirstInst),
UnpairedRelease);
OutlinedName = Mangler.mangle();
}
return OutlinedName;
}
/// Returns the outlined function type.
///
/// This depends on the first instruction we matched. Either we matched a load
/// or we started the match at the class method instruction.
///
/// load %30 : *UITextField:
/// (@in_guaranteed InstanceType) -> (@owned Optional<BridgedInstanceType>)
/// objc_method %31 : UITextField
/// (@unowned InstanceType) -> (@owned Optional<BridgedInstanceType>)
///
CanSILFunctionType BridgedProperty::getOutlinedFunctionType(SILModule &M) {
SmallVector<SILParameterInfo, 4> Parameters;
if (auto *Load = dyn_cast<LoadInst>(FirstInst))
Parameters.push_back(
SILParameterInfo(Load->getType().getASTType(),
ParameterConvention::Indirect_In_Guaranteed));
else
Parameters.push_back(SILParameterInfo(
cast<ObjCMethodInst>(FirstInst)->getOperand()->getType().getASTType(),
UnpairedRelease ? ParameterConvention::Direct_Owned
: ParameterConvention::Direct_Unowned));
SmallVector<SILResultInfo, 4> Results;
Results.push_back(SILResultInfo(
switchInfo.Br->getArg(0)->getType().getASTType(),
ResultConvention::Owned));
auto ExtInfo = SILFunctionType::ExtInfo::getThin();
auto FunctionType = SILFunctionType::get(
nullptr, ExtInfo, SILCoroutineKind::None,
ParameterConvention::Direct_Unowned, Parameters, /*yields*/ {}, Results,
std::nullopt, SubstitutionMap(), SubstitutionMap(), M.getASTContext());
return FunctionType;
}
static void eraseBlock(SILBasicBlock *block) {
for (SILInstruction &inst : *block) {
inst.replaceAllUsesOfAllResultsWithUndef();
}
block->eraseFromParent();
}
std::pair<SILFunction *, SILBasicBlock::iterator>
BridgedProperty::outline(SILModule &M) {
// Get the function type.
auto FunctionType = getOutlinedFunctionType(M);
std::string nameTmp = getOutlinedFunctionName();
auto name = M.allocateCopy(nameTmp);
auto *Fun = FuncBuilder.getOrCreateFunction(
ObjCMethod->getLoc(), name, SILLinkage::Shared, FunctionType, IsNotBare,
IsNotTransparent, IsSerialized, IsNotDynamic, IsNotDistributed,
IsNotRuntimeAccessible);
bool NeedsDefinition = Fun->empty();
if (Release) {
// Move the release after the call.
Release->moveBefore(StartBB->getTerminator());
}
// [StartBB]
// / \
// [NoneBB] [SomeBB]
// \ /
// [OldMergeBB]
//
// Split to:
//
// [StartBB]
// |
// [OutlinedEntryBB] }
// / \ }
// [NoneBB] [SomeBB] } outlined
// \ / }
// [OldMergeBB] }
// |
// [NewTailBB]
//
auto *OutlinedEntryBB = StartBB->split(SILBasicBlock::iterator(FirstInst));
auto *OldMergeBB = switchInfo.Br->getDestBB();
auto *NewTailBB = OldMergeBB->split(OldMergeBB->begin());
if (deBlocks) {
deBlocks->updateForNewBlock(NewTailBB);
}
// Call the outlined function.
{
SILBuilder Builder(StartBB);
auto Loc = FirstInst->getLoc();
SILValue FunRef(Builder.createFunctionRef(Loc, Fun));
SILValue Apply(
Builder.createApply(Loc, FunRef, SubstitutionMap(),
{FirstInst->getOperand(0)}));
Builder.createBranch(Loc, NewTailBB);
OldMergeBB->getArgument(0)->replaceAllUsesWith(Apply);
}
if (!NeedsDefinition) {
// Delete the outlined instructions/blocks.
if (Release)
Release->eraseFromParent();
eraseBlock(OutlinedEntryBB);
eraseBlock(switchInfo.NoneBB);
eraseBlock(switchInfo.SomeBB);
eraseBlock(OldMergeBB);
return std::make_pair(nullptr, std::prev(StartBB->end()));
}
if (!OutlinedEntryBB->getParent()->hasOwnership())
Fun->setOwnershipEliminated();
Fun->setInlineStrategy(NoInline);
// Move the blocks into the new function.
Fun->moveBlockFromOtherFunction(OldMergeBB, Fun->begin());
Fun->moveBlockFromOtherFunction(switchInfo.NoneBB, Fun->begin());
Fun->moveBlockFromOtherFunction(switchInfo.SomeBB, Fun->begin());
Fun->moveBlockFromOtherFunction(OutlinedEntryBB, Fun->begin());
// Create the function argument and return.
auto *Load = dyn_cast<LoadInst>(FirstInst);
SILBuilder Builder(FirstInst);
if (Load) {
OutlinedEntryBB->createFunctionArgument(Load->getOperand()->getType());
auto *NewLoad =
Builder.createLoad(Load->getLoc(), OutlinedEntryBB->getArgument(0),
Load->getOwnershipQualifier());
Load->replaceAllUsesWith(NewLoad);
Load->eraseFromParent();
} else {
OutlinedEntryBB->createFunctionArgument(
FirstInst->getOperand(0)->getType());
auto *Arg = OutlinedEntryBB->getArgument(0);
FirstInst->setOperand(0, Arg);
if (UnpairedRelease)
UnpairedRelease->setOperand(0, Arg);
PropApply->setArgument(0, Arg);
}
Builder.setInsertionPoint(OldMergeBB);
Builder.createReturn(ObjCMethod->getLoc(), OldMergeBB->getArgument(0));
return std::make_pair(Fun, std::prev(StartBB->end()));
}
#define ADVANCE_ITERATOR_OR_RETURN_FALSE(It) \
do { \
if (It->getParent()->end() == ++It) \
return false; \
} while (0);
static bool matchSwitch(SwitchInfo &SI, SILInstruction *Inst,
SILValue SwitchOperand) {
auto *SwitchEnum = dyn_cast<SwitchEnumInst>(Inst);
if (!SwitchEnum || SwitchEnum->getNumCases() != 2 ||
SwitchEnum->getOperand() != SwitchOperand)
return false;
auto *SwitchBB = SwitchEnum->getParent();
SILBasicBlock *SomeBB = SwitchEnum->getCase(0).second;
SILBasicBlock *NoneBB = SwitchEnum->getCase(1).second;
if (NoneBB->getSinglePredecessorBlock() != SwitchBB)
return false;
if (SomeBB->getSinglePredecessorBlock() != SwitchBB)
return false;
if (NoneBB->args_size() == 1)
std::swap(NoneBB, SomeBB);
if (SomeBB->args_size() != 1 || NoneBB->args_size() != 0)
return false;
// bb9:
// %43 = enum $Optional<String>, #Optional.none!enumelt
auto It = NoneBB->begin();
auto *NoneEnum = dyn_cast<EnumInst>(It);
if (!NoneEnum || NoneEnum->hasOperand() || !NoneEnum->hasOneUse())
return false;
// br bb10(%43 : $Optional<String>)
ADVANCE_ITERATOR_OR_RETURN_FALSE(It);
auto *Br1 = dyn_cast<BranchInst>(It);
if (!Br1 || Br1->getNumArgs() != 1 || Br1->getArg(0) != NoneEnum)
return false;
auto *MergeBB = Br1->getDestBB();
// bb8(%36 : $NSString):
It = SomeBB->begin();
auto *SomeBBArg = SomeBB->getArgument(0);
if (!SomeBBArg->hasOneUse())
return false;
// %37 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
auto *FunRef = dyn_cast<FunctionRefInst>(It);
if (!FunRef || !FunRef->hasOneUse())
return false;
// %38 = enum $Optional<NSString>, #Optional.some!enumelt, %36 : $NSString
ADVANCE_ITERATOR_OR_RETURN_FALSE(It);
auto *SomeEnum = dyn_cast<EnumInst>(It);
if (!SomeEnum || !SomeEnum->hasOperand() || SomeEnum->getOperand() != SomeBBArg)
return false;
size_t numSomeEnumUses = std::distance(SomeEnum->use_begin(), SomeEnum->use_end());
if (numSomeEnumUses > 2)
return false;
// %39 = metatype $@thin String.Type
ADVANCE_ITERATOR_OR_RETURN_FALSE(It);
auto *Metatype = dyn_cast<MetatypeInst>(It);
if (!Metatype || !Metatype->hasOneUse())
return false;
// %40 = apply %37(%38, %39) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
ADVANCE_ITERATOR_OR_RETURN_FALSE(It);
auto *Apply = dyn_cast<ApplyInst>(It);
if (!Apply || !Apply->hasOneUse() || Apply->getCallee() != FunRef ||
Apply->getNumArguments() != 2 || Apply->getArgument(0) != SomeEnum ||
Apply->getArgument(1) != Metatype ||
Apply->getSubstCalleeType()->getNumResults() != 1)
return false;
if (Apply->getSubstCalleeType()->getSingleResult().getConvention() !=
ResultConvention::Owned)
return false;
// Check that we call the _unconditionallyBridgeFromObjectiveC witness.
auto NativeType = Apply->getType().getASTType();
auto *BridgeFun = FunRef->getReferencedFunction();
// Not every type conforms to the ObjectiveCBridgeable protocol in such a case
// getBridgeFromObjectiveC returns SILDeclRef().
auto bridgeWitness = getBridgeFromObjectiveC(NativeType);
if (bridgeWitness == SILDeclRef() ||
BridgeFun->getName() != bridgeWitness.mangle())
return false;
// %41 = enum $Optional<String>, #Optional.some!enumelt, %40 : $String
ADVANCE_ITERATOR_OR_RETURN_FALSE(It);
auto *Enum3 = dyn_cast<EnumInst>(It);
if (!Enum3 || !Enum3->hasOneUse() || !Enum3->hasOperand() ||
Enum3->getOperand() != Apply)
return false;
if (numSomeEnumUses == 2) {
// [release_value | destroy_value] %38 : $Optional<NSString>
ADVANCE_ITERATOR_OR_RETURN_FALSE(It);
bool hasOwnership = It->getFunction()->hasOwnership();
if (hasOwnership) {
auto *DVI = dyn_cast<DestroyValueInst>(It);
if (!DVI || DVI->getOperand() != SomeEnum)
return false;
} else {
auto *RVI = dyn_cast<ReleaseValueInst>(It);
if (!RVI || RVI->getOperand() != SomeEnum)
return false;
}
}
// br bb10(%41 : $Optional<String>)
ADVANCE_ITERATOR_OR_RETURN_FALSE(It);
auto *Br = dyn_cast<BranchInst>(It);
if (!Br || Br->getDestBB() != MergeBB || Br->getNumArgs() != 1 ||
Br->getArg(0) != Enum3)
return false;
SI.SwitchEnum = SwitchEnum;
SI.SomeBB = SomeBB;
SI.NoneBB = NoneBB;
SI.Br = Br;
return true;
}
bool BridgedProperty::matchMethodCall(SILBasicBlock::iterator It,
LoadInst *Load) {
// Matches:
// %33 = objc_method %31 : $UITextField, #UITextField.text!getter.foreign : (UITextField) -> () -> String?, $@convention(objc_method) (UITextField) -> @autoreleased Optional<NSString>
// %34 = apply %33(%31) : $@convention(objc_method) (UITextField) -> @autoreleased Optional<NSString>
// switch_enum %34 : $Optional<NSString>, case #Optional.some!enumelt: bb8, case #Optional.none!enumelt: bb9
//
// bb8(%36 : $NSString):
// %37 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
// %38 = enum $Optional<NSString>, #Optional.some!enumelt, %36 : $NSString
// %39 = metatype $@thin String.Type
// %40 = apply %37(%38, %39) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
// %41 = enum $Optional<String>, #Optional.some!enumelt, %40 : $String
// br bb10(%41 : $Optional<String>)
//
// bb9:
// %43 = enum $Optional<String>, #Optional.none!enumelt
// br bb10(%43 : $Optional<String>)
//
// bb10(%45 : $Optional<String>):
//
// %33 = objc_method %31 : $UITextField, #UITextField.text!getter.foreign
ObjCMethod = dyn_cast<ObjCMethodInst>(It);
SILValue Instance =
FirstInst != ObjCMethod ? FirstInst : ObjCMethod->getOperand();
if (!ObjCMethod || !ObjCMethod->hasOneUse() ||
ObjCMethod->getOperand() != Instance ||
ObjCMethod->getFunction()->getLoweredFunctionType()->isPolymorphic() ||
ObjCMethod->getType().castTo<SILFunctionType>()->isPolymorphic() ||
ObjCMethod->getType().castTo<SILFunctionType>()->hasOpenedExistential())
return false;
// %34 = apply %33(%31) : $@convention(objc_method) (UITextField) -> @autoreleased Optional<NSString>
ADVANCE_ITERATOR_OR_RETURN_FALSE(It);
PropApply = dyn_cast<ApplyInst>(It);
if (!PropApply || PropApply->getCallee() != ObjCMethod ||
PropApply->getNumArguments() != 1 ||
PropApply->getArgument(0) != Instance || !PropApply->hasOneUse())
return false;
if (Load) {
// In OSSA, there will be a destroy_value matching the earlier load [copy].
// In non-ossa, there will be a release matching the earlier retain. The
// only user of the retained value is the unowned objective-c method
// consumer.
unsigned NumUses = 0;
Release = nullptr;
bool hasOwnership = Load->getFunction()->hasOwnership();
for (auto *Use : Load->getUses()) {
++NumUses;
SILInstruction *R;
if (hasOwnership) {
R = dyn_cast<DestroyValueInst>(Use->getUser());
} else {
R = dyn_cast<StrongReleaseInst>(Use->getUser());
}
if (R) {
if (!Release) {
Release = R;
} else {
Release = nullptr;
break;
}
}
}
if (!Release)
return false;
if (hasOwnership) {
if (NumUses != 3)
return false;
} else {
if (NumUses != 4)
return false;
}
ADVANCE_ITERATOR_OR_RETURN_FALSE(It);
if (Release != &*It)
return false;
}
ADVANCE_ITERATOR_OR_RETURN_FALSE(It);
if (auto *dvi = dyn_cast<DestroyValueInst>(*&It)) {
if (Load)
return false;
if (dvi->getOperand() != Instance)
return false;
UnpairedRelease = dvi;
ADVANCE_ITERATOR_OR_RETURN_FALSE(It);
}
// Don't outline in the outlined function.
if (ObjCMethod->getFunction()->getName() == getOutlinedFunctionName())
return false;
// switch_enum %34 : $Optional<NSString>, case #Optional.some!enumelt: bb8,
// case #Optional.none!enumelt: bb9
return matchSwitch(switchInfo, &*It, PropApply);
}
bool BridgedProperty::matchInstSequence(SILBasicBlock::iterator It) {
// Matches:
// [ optionally:
// %31 = load %30 : $*UITextField or %31 = load [copy] %30 : $*UITextField
// strong_retain %31 : $UITextField
// ]
// %33 = objc_method %31 : $UITextField, #UITextField.text!getter.foreign : (UITextField) -> () -> String?, $@convention(objc_method) (UITextField) -> @autoreleased Optional<NSString>
// %34 = apply %33(%31) : $@convention(objc_method) (UITextField) -> @autoreleased Optional<NSString>
// switch_enum %34 : $Optional<NSString>, case #Optional.some!enumelt: bb8, case #Optional.none!enumelt: bb9
//
// bb8(%36 : $NSString):
// %37 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
// %38 = enum $Optional<NSString>, #Optional.some!enumelt, %36 : $NSString
// %39 = metatype $@thin String.Type
// %40 = apply %37(%38, %39) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
// %41 = enum $Optional<String>, #Optional.some!enumelt, %40 : $String
// br bb10(%41 : $Optional<String>)
//
// bb9:
// %43 = enum $Optional<String>, #Optional.none!enumelt
// br bb10(%43 : $Optional<String>)
//
// bb10(%45 : $Optional<String>):
clearState();
// %31 = load %30 : $*UITextField
auto *Load = dyn_cast<LoadInst>(It);
// Otherwise, trying matching from the method call.
if (!Load) {
// Try to match without the load/strong_retain prefix.
auto *CMI = dyn_cast<ObjCMethodInst>(It);
if (!CMI || CMI->getFunction()->getLoweredFunctionType()->isPolymorphic() ||
CMI->getType().castTo<SILFunctionType>()->isPolymorphic() ||
CMI->getType().castTo<SILFunctionType>()->hasOpenedExistential())
return false;
FirstInst = CMI;
} else
FirstInst = Load;
StartBB = FirstInst->getParent();
if (Load) {
if (Load->getFunction()->hasOwnership()) {
if (Load->getOwnershipQualifier() != LoadOwnershipQualifier::Copy)
return false;
ADVANCE_ITERATOR_OR_RETURN_FALSE(It);
} else {
// strong_retain %31 : $UITextField
ADVANCE_ITERATOR_OR_RETURN_FALSE(It);
auto *Retain = dyn_cast<StrongRetainInst>(It);
if (!Retain || Retain->getOperand() != Load)
return false;
ADVANCE_ITERATOR_OR_RETURN_FALSE(It);
}
}
if (!matchMethodCall(It, Load))
return false;
return true;
}
namespace {
/// Match a bridged argument.
///
///
/// %15 = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
/// %16 = apply %15(%14) :
/// $@convention(method) (@guaranteed String) -> @owned NSString
/// %17 = enum $Optional<NSString>, #Optional.some!enumelt, %16 : $NSString
/// release_value %14 : $String
///
/// apply %objcMethod(%17, ...) : $@convention(objc_method) (Optional<NSString> ...) ->
/// release_value %17 : $Optional<NSString>
///
/// NOTE: If release_value %14 is found, our outlined function will have an
/// owned convention for self. Otherwise, if we do not find it, we will have a
/// guaranteed one.
class BridgedArgument {
public:
FunctionRefInst *BridgeFun;
ApplyInst *BridgeCall;
EnumInst *OptionalResult;
SILValue BridgedValue;
SILInstruction *ReleaseAfterBridge;
SILInstruction *ReleaseArgAfterCall;
unsigned Idx = 0;
// Matched bridged argument.
BridgedArgument(unsigned Idx, FunctionRefInst *F, ApplyInst *A, EnumInst *E,
SILInstruction *R0, SILInstruction *R1)
: BridgeFun(F), BridgeCall(A), OptionalResult(E),
BridgedValue(FullApplySite(A).getSelfArgument()),
ReleaseAfterBridge(R0), ReleaseArgAfterCall(R1), Idx(Idx) {
assert(!R0 || isa<ReleaseValueInst>(R0) || isa<DestroyValueInst>(R0));
}
/// Invalid argument constructor.
BridgedArgument()
: BridgeFun(nullptr), BridgeCall(nullptr), OptionalResult(nullptr),
ReleaseAfterBridge(nullptr), ReleaseArgAfterCall(nullptr), Idx(0) {}
static BridgedArgument match(unsigned ArgIdx, SILValue Arg, ApplyInst *AI,
DeadEndBlocks *deBlocks);
operator bool() const { return BridgeFun != nullptr; }
SILValue bridgedValue() { return BridgedValue; }
bool isGuaranteed() const { return ReleaseAfterBridge == nullptr; }
ParameterConvention getConvention() const {
if (isGuaranteed())
return ParameterConvention::Direct_Guaranteed;
return ParameterConvention::Direct_Owned;
}
void eraseFromParent();
/// Move the bridged argument sequence to the bridged call block.
/// Precondition: The bridged call has already been moved to the outlined
/// function.
void transferTo(SILValue BridgedValueFunArg, ApplyInst *BridgedCall);
};
}
void BridgedArgument::transferTo(SILValue BridgedValue,
ApplyInst *BridgedCall) {
assert(BridgedCall->getParent() != BridgeFun->getParent());
// Move the instructions to the bridged call that we have already moved and
// update the uses of the bridge value by the function argument value passed
// to this function.
auto *DestBB = BridgedCall->getParent();
DestBB->moveTo(SILBasicBlock::iterator(BridgedCall), BridgeFun);
DestBB->moveTo(SILBasicBlock::iterator(BridgedCall), BridgeCall);
BridgeCall->setArgument(0, BridgedValue);
DestBB->moveTo(SILBasicBlock::iterator(BridgedCall), OptionalResult);
if (ReleaseAfterBridge) {
DestBB->moveTo(SILBasicBlock::iterator(BridgedCall), ReleaseAfterBridge);
ReleaseAfterBridge->setOperand(0, BridgedValue);
}
auto AfterCall = std::next(SILBasicBlock::iterator(BridgedCall));
DestBB->moveTo(SILBasicBlock::iterator(AfterCall), ReleaseArgAfterCall);
}
void BridgedArgument::eraseFromParent() {
if (ReleaseAfterBridge)
ReleaseAfterBridge->eraseFromParent();
ReleaseArgAfterCall->eraseFromParent();
OptionalResult->eraseFromParent();
BridgeCall->eraseFromParent();
BridgeFun->eraseFromParent();
}
static SILInstruction *findReleaseOf(SILValue releasedValue,
SILBasicBlock::iterator from,
SILBasicBlock::iterator to) {
bool hasOwnership = releasedValue->getFunction()->hasOwnership();
while (from != to) {
if (hasOwnership) {
auto destroy = dyn_cast<DestroyValueInst>(&*from);
if (destroy && destroy->getOperand() == releasedValue)
return destroy;
} else {
auto release = dyn_cast<ReleaseValueInst>(&*from);
if (release && release->getOperand() == releasedValue)
return release;
}
++from;
}
return nullptr;
}
BridgedArgument BridgedArgument::match(unsigned ArgIdx, SILValue Arg,
ApplyInst *AI, DeadEndBlocks *deBlocks) {
// Match
// %15 = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// %16 = apply %15(%14) : $@convention(method) (@guaranteed String) -> @owned NSString
// %17 = enum $Optional<NSString>, #Optional.some!enumelt, %16 : $NSString
// [release_value | destroy_value] %14 : $String
// ...
// apply %objcMethod(%17, ...) : $@convention(objc_method) (Optional<NSString>...) ->
// release_value ...
// [release_value | destroy_value] %17 : $Optional<NSString>
//
auto *Enum = dyn_cast<EnumInst>(Arg);
if (!Enum || !Enum->hasOperand())
return BridgedArgument();
if (SILBasicBlock::iterator(Enum) == Enum->getParent()->begin())
return BridgedArgument();
auto *BridgeCall =
dyn_cast<ApplyInst>(std::prev(SILBasicBlock::iterator(Enum)));
if (!BridgeCall || BridgeCall->getNumArguments() != 1 ||
Enum->getOperand() != BridgeCall || !BridgeCall->hasOneUse() ||
!FullApplySite(BridgeCall).hasSelfArgument())
return BridgedArgument();
auto &selfArg = FullApplySite(BridgeCall).getSelfArgumentOperand();
auto selfConvention =
FullApplySite(BridgeCall).getArgumentConvention(selfArg);
if (selfConvention != SILArgumentConvention::Direct_Guaranteed &&
selfConvention != SILArgumentConvention::Direct_Owned)
return BridgedArgument();
auto BridgedValue = BridgeCall->getArgument(0);
auto Next = std::next(SILBasicBlock::iterator(Enum));
if (Next == Enum->getParent()->end())
return BridgedArgument();
// Make sure that if we have a bridged value release that it is on the bridged
// value.
if (Enum->getParent() != AI->getParent())
return BridgedArgument();
bool hasOwnership = AI->getFunction()->hasOwnership();
auto *BridgedValueRelease =
findReleaseOf(BridgedValue, std::next(SILBasicBlock::iterator(Enum)),
SILBasicBlock::iterator(AI));
assert(!BridgedValueRelease ||
(hasOwnership && isa<DestroyValueInst>(BridgedValueRelease)) ||
isa<ReleaseValueInst>(BridgedValueRelease));
if (BridgedValueRelease && BridgedValueRelease->getOperand(0) != BridgedValue)
return BridgedArgument();
if (SILBasicBlock::iterator(BridgeCall) == BridgeCall->getParent()->begin())
return BridgedArgument();
auto *FunRef =
dyn_cast<FunctionRefInst>(std::prev(SILBasicBlock::iterator(BridgeCall)));
if (!FunRef || !FunRef->hasOneUse() || BridgeCall->getCallee() != FunRef)
return BridgedArgument();
SILInstruction *ReleaseAfter = nullptr;
for (auto *Use : Enum->getUses()) {
if (Use->getUser() == AI)
continue;
// The enum must only have two uses the release and the apply.
if (ReleaseAfter)
return BridgedArgument();
if (hasOwnership) {
ReleaseAfter = dyn_cast<DestroyValueInst>(Use->getUser());
} else {
ReleaseAfter = dyn_cast<ReleaseValueInst>(Use->getUser());
}
if (!ReleaseAfter)
return BridgedArgument();
}
// Make sure we are calling the actual bridge witness.
auto NativeType = BridgedValue->getType().getASTType();
auto *BridgeFun = FunRef->getReferencedFunction();
// Not every type conforms to the ObjectiveCBridgeable protocol in such a case
// getBridgeToObjectiveC returns SILDeclRef().
auto bridgeWitness = getBridgeToObjectiveC(NativeType);
if (bridgeWitness == SILDeclRef() ||
BridgeFun->getName() != bridgeWitness.mangle())
return BridgedArgument();
if (hasOwnership && !BridgedValueRelease) {
SmallVector<Operand *> newUses{&AI->getOperandRef(ArgIdx)};
if (!areUsesWithinValueLifetime(BridgedValue, newUses, deBlocks)) {
return BridgedArgument();
}
}
return BridgedArgument(ArgIdx, FunRef, BridgeCall, Enum, BridgedValueRelease,
ReleaseAfter);
}
namespace {
// Match the return value bridging pattern.
// switch_enum %20 : $Optional<NSString>, case #O.some: bb1, case #O.none: bb2
//
// bb1(%23 : $NSString):
// %24 = function_ref @_unconditionallyBridgeFromObjectiveC
// %25 = enum $Optional<NSString>, #Optional.some!enumelt, %23 : $NSString
// %26 = metatype $@thin String.Type
// %27 = apply %24(%25, %26)
// %28 = enum $Optional<String>, #Optional.some!enumelt, %27 : $String
// br bb3(%28 : $Optional<String>)
//
// bb2:
// %30 = enum $Optional<String>, #Optional.none!enumelt
// br bb3(%30 : $Optional<String>)
//
// bb3(%32 : $Optional<String>):
class BridgedReturn {
DeadEndBlocks *deBlocks;
SwitchInfo switchInfo;
public:
BridgedReturn(DeadEndBlocks *deBlocks) : deBlocks(deBlocks) {}
bool match(ApplyInst *BridgedCall) {
switchInfo = SwitchInfo();
auto *SwitchBB = BridgedCall->getParent();
return matchSwitch(switchInfo, SwitchBB->getTerminator(), BridgedCall);
}
operator bool() { return switchInfo.SomeBB != nullptr; }
CanType getReturnType() {
return switchInfo.Br->getArg(0)->getType().getASTType();
}
/// Outline the return value bridging blocks.
void outline(SILFunction *Fun, ApplyInst *NewOutlinedCall);
};
}
void BridgedReturn::outline(SILFunction *Fun, ApplyInst *NewOutlinedCall) {
// Outline the bridged return result blocks.
// switch_enum %20 : $Optional<NSString>, case #O.some: bb1, case #O.none: bb2
//
// bb1(%23 : $NSString):
// %24 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveC
// %25 = enum $Optional<NSString>, #Optional.some!enumelt, %23 : $NSString
// %26 = metatype $@thin String.Type
// %27 = apply %24(%25, %26)
// %28 = enum $Optional<String>, #Optional.some!enumelt, %27 : $String
// br bb3(%28 : $Optional<String>)
//
// bb2:
// %30 = enum $Optional<String>, #Optional.none!enumelt
// br bb3(%30 : $Optional<String>)
//
// bb3(%32 : $Optional<String>):
auto *StartBB = switchInfo.SwitchEnum->getParent();
auto *OutlinedEntryBB = StartBB->split(SILBasicBlock::iterator(switchInfo.SwitchEnum));
auto *OldMergeBB = switchInfo.Br->getDestBB();
auto *NewTailBB = OldMergeBB->split(OldMergeBB->begin());
if (deBlocks) {
deBlocks->updateForNewBlock(NewTailBB);
}
auto Loc = switchInfo.SwitchEnum->getLoc();
{
SILBuilder Builder(StartBB);
Builder.createBranch(Loc, NewTailBB);
OldMergeBB->getArgument(0)->replaceAllUsesWith(NewOutlinedCall);
}
// Outlined function already existed. Just delete instructions and wire up