forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLocal.cpp
1889 lines (1617 loc) · 66.7 KB
/
Local.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
//===--- Local.cpp - Functions that perform local SIL 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
//
//===----------------------------------------------------------------------===//
#include "swift/SILOptimizer/Utils/Local.h"
#include "swift/SILOptimizer/Utils/CFG.h"
#include "swift/SILOptimizer/Analysis/Analysis.h"
#include "swift/SILOptimizer/Analysis/ARCAnalysis.h"
#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/BasicBlockUtils.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include <deque>
using namespace swift;
static llvm::cl::opt<bool> EnableExpandAll("enable-expand-all",
llvm::cl::init(false));
/// Creates an increment on \p Ptr before insertion point \p InsertPt that
/// creates a strong_retain if \p Ptr has reference semantics itself or a
/// retain_value if \p Ptr is a non-trivial value without reference-semantics.
NullablePtr<SILInstruction>
swift::createIncrementBefore(SILValue Ptr, SILInstruction *InsertPt) {
// Set up the builder we use to insert at our insertion point.
SILBuilder B(InsertPt);
auto Loc = RegularLocation::getAutoGeneratedLocation();
// If we have a trivial type, just bail, there is no work to do.
if (Ptr->getType().isTrivial(B.getFunction()))
return nullptr;
// If Ptr is refcounted itself, create the strong_retain and
// return.
if (Ptr->getType().isReferenceCounted(B.getModule())) {
if (Ptr->getType().is<UnownedStorageType>())
return B.createUnownedRetain(Loc, Ptr, B.getDefaultAtomicity());
else
return B.createStrongRetain(Loc, Ptr, B.getDefaultAtomicity());
}
// Otherwise, create the retain_value.
return B.createRetainValue(Loc, Ptr, B.getDefaultAtomicity());
}
/// Creates a decrement on \p Ptr before insertion point \p InsertPt that
/// creates a strong_release if \p Ptr has reference semantics itself or
/// a release_value if \p Ptr is a non-trivial value without reference-semantics.
NullablePtr<SILInstruction>
swift::createDecrementBefore(SILValue Ptr, SILInstruction *InsertPt) {
// Setup the builder we will use to insert at our insertion point.
SILBuilder B(InsertPt);
auto Loc = RegularLocation::getAutoGeneratedLocation();
if (Ptr->getType().isTrivial(B.getFunction()))
return nullptr;
// If Ptr has reference semantics itself, create a strong_release.
if (Ptr->getType().isReferenceCounted(B.getModule())) {
if (Ptr->getType().is<UnownedStorageType>())
return B.createUnownedRelease(Loc, Ptr, B.getDefaultAtomicity());
else
return B.createStrongRelease(Loc, Ptr, B.getDefaultAtomicity());
}
// Otherwise create a release value.
return B.createReleaseValue(Loc, Ptr, B.getDefaultAtomicity());
}
/// Perform a fast local check to see if the instruction is dead.
///
/// This routine only examines the state of the instruction at hand.
bool
swift::isInstructionTriviallyDead(SILInstruction *I) {
// At Onone, consider all uses, including the debug_info.
// This way, debug_info is preserved at Onone.
if (I->hasUsesOfAnyResult() &&
I->getFunction()->getEffectiveOptimizationMode() <=
OptimizationMode::NoOptimization)
return false;
if (!onlyHaveDebugUsesOfAllResults(I) || isa<TermInst>(I))
return false;
if (auto *BI = dyn_cast<BuiltinInst>(I)) {
// Although the onFastPath builtin has no side-effects we don't want to
// remove it.
if (BI->getBuiltinInfo().ID == BuiltinValueKind::OnFastPath)
return false;
return !BI->mayHaveSideEffects();
}
// condfail instructions that obviously can't fail are dead.
if (auto *CFI = dyn_cast<CondFailInst>(I))
if (auto *ILI = dyn_cast<IntegerLiteralInst>(CFI->getOperand()))
if (!ILI->getValue())
return true;
// mark_uninitialized is never dead.
if (isa<MarkUninitializedInst>(I))
return false;
if (isa<DebugValueInst>(I) || isa<DebugValueAddrInst>(I))
return false;
// These invalidate enums so "write" memory, but that is not an essential
// operation so we can remove these if they are trivially dead.
if (isa<UncheckedTakeEnumDataAddrInst>(I))
return true;
if (!I->mayHaveSideEffects())
return true;
return false;
}
/// Return true if this is a release instruction and the released value
/// is a part of a guaranteed parameter.
bool swift::isIntermediateRelease(SILInstruction *I,
EpilogueARCFunctionInfo *EAFI) {
// Check whether this is a release instruction.
if (!isa<StrongReleaseInst>(I) && !isa<ReleaseValueInst>(I))
return false;
// OK. we have a release instruction.
// Check whether this is a release on part of a guaranteed function argument.
SILValue Op = stripValueProjections(I->getOperand(0));
auto *Arg = dyn_cast<SILFunctionArgument>(Op);
if (!Arg)
return false;
// This is a release on a guaranteed parameter. Its not the final release.
if (Arg->hasConvention(SILArgumentConvention::Direct_Guaranteed))
return true;
// This is a release on an owned parameter and its not the epilogue release.
// Its not the final release.
auto Rel = EAFI->computeEpilogueARCInstructions(
EpilogueARCContext::EpilogueARCKind::Release, Arg);
if (Rel.size() && !Rel.count(I))
return true;
// Failed to prove anything.
return false;
}
namespace {
using CallbackTy = llvm::function_ref<void(SILInstruction *)>;
} // end anonymous namespace
void swift::recursivelyDeleteTriviallyDeadInstructions(
ArrayRef<SILInstruction *> IA, bool Force, CallbackTy Callback) {
// Delete these instruction and others that become dead after it's deleted.
llvm::SmallPtrSet<SILInstruction *, 8> DeadInsts;
for (auto I : IA) {
// If the instruction is not dead and force is false, do nothing.
if (Force || isInstructionTriviallyDead(I))
DeadInsts.insert(I);
}
llvm::SmallPtrSet<SILInstruction *, 8> NextInsts;
while (!DeadInsts.empty()) {
for (auto I : DeadInsts) {
// Call the callback before we mutate the to be deleted instruction in any
// way.
Callback(I);
// Check if any of the operands will become dead as well.
MutableArrayRef<Operand> Ops = I->getAllOperands();
for (Operand &Op : Ops) {
SILValue OpVal = Op.get();
if (!OpVal)
continue;
// Remove the reference from the instruction being deleted to this
// operand.
Op.drop();
// If the operand is an instruction that is only used by the instruction
// being deleted, delete it.
if (auto *OpValInst = OpVal->getDefiningInstruction())
if (!DeadInsts.count(OpValInst) &&
isInstructionTriviallyDead(OpValInst))
NextInsts.insert(OpValInst);
}
// If we have a function ref inst, we need to especially drop its function
// argument so that it gets a proper ref decrement.
auto *FRI = dyn_cast<FunctionRefInst>(I);
if (FRI && FRI->getInitiallyReferencedFunction())
FRI->dropReferencedFunction();
auto *DFRI = dyn_cast<DynamicFunctionRefInst>(I);
if (DFRI && DFRI->getInitiallyReferencedFunction())
DFRI->dropReferencedFunction();
auto *PFRI = dyn_cast<PreviousDynamicFunctionRefInst>(I);
if (PFRI && PFRI->getInitiallyReferencedFunction())
PFRI->dropReferencedFunction();
}
for (auto I : DeadInsts) {
// This will remove this instruction and all its uses.
eraseFromParentWithDebugInsts(I, Callback);
}
NextInsts.swap(DeadInsts);
NextInsts.clear();
}
}
/// If the given instruction is dead, delete it along with its dead
/// operands.
///
/// \param I The instruction to be deleted.
/// \param Force If Force is set, don't check if the top level instruction is
/// considered dead - delete it regardless.
void swift::recursivelyDeleteTriviallyDeadInstructions(SILInstruction *I,
bool Force,
CallbackTy Callback) {
ArrayRef<SILInstruction *> AI = ArrayRef<SILInstruction *>(I);
recursivelyDeleteTriviallyDeadInstructions(AI, Force, Callback);
}
void swift::eraseUsesOfInstruction(SILInstruction *Inst,
CallbackTy Callback) {
for (auto result : Inst->getResults()) {
while (!result->use_empty()) {
auto UI = result->use_begin();
auto *User = UI->getUser();
assert(User && "User should never be NULL!");
// If the instruction itself has any uses, recursively zap them so that
// nothing uses this instruction.
eraseUsesOfInstruction(User, Callback);
// Walk through the operand list and delete any random instructions that
// will become trivially dead when this instruction is removed.
for (auto &Op : User->getAllOperands()) {
if (auto *OpI = Op.get()->getDefiningInstruction()) {
// Don't recursively delete the instruction we're working on.
// FIXME: what if we're being recursively invoked?
if (OpI != Inst) {
Op.drop();
recursivelyDeleteTriviallyDeadInstructions(OpI, false, Callback);
}
}
}
Callback(User);
User->eraseFromParent();
}
}
}
void swift::
collectUsesOfValue(SILValue V, llvm::SmallPtrSetImpl<SILInstruction *> &Insts) {
for (auto UI = V->use_begin(), E = V->use_end(); UI != E; UI++) {
auto *User = UI->getUser();
// Instruction has been processed.
if (!Insts.insert(User).second)
continue;
// Collect the users of this instruction.
for (auto result : User->getResults())
collectUsesOfValue(result, Insts);
}
}
void swift::eraseUsesOfValue(SILValue V) {
llvm::SmallPtrSet<SILInstruction *, 4> Insts;
// Collect the uses.
collectUsesOfValue(V, Insts);
// Erase the uses, we can have instructions that become dead because
// of the removal of these instructions, leave to DCE to cleanup.
// Its not safe to do recursively delete here as some of the SILInstruction
// maybe tracked by this set.
for (auto I : Insts) {
I->replaceAllUsesOfAllResultsWithUndef();
I->eraseFromParent();
}
}
// Devirtualization of functions with covariant return types produces
// a result that is not an apply, but takes an apply as an
// argument. Attempt to dig the apply out from this result.
FullApplySite swift::findApplyFromDevirtualizedResult(SILValue V) {
if (auto Apply = FullApplySite::isa(V))
return Apply;
if (isa<UpcastInst>(V) || isa<EnumInst>(V) || isa<UncheckedRefCastInst>(V))
return findApplyFromDevirtualizedResult(
cast<SingleValueInstruction>(V)->getOperand(0));
return FullApplySite();
}
bool swift::mayBindDynamicSelf(SILFunction *F) {
if (!F->hasSelfMetadataParam())
return false;
SILValue MDArg = F->getSelfMetadataArgument();
for (Operand *MDUse : F->getSelfMetadataArgument()->getUses()) {
SILInstruction *MDUser = MDUse->getUser();
for (Operand &TypeDepOp : MDUser->getTypeDependentOperands()) {
if (TypeDepOp.get() == MDArg)
return true;
}
}
return false;
}
static SILValue skipAddrProjections(SILValue V) {
for (;;) {
switch (V->getKind()) {
case ValueKind::IndexAddrInst:
case ValueKind::IndexRawPointerInst:
case ValueKind::StructElementAddrInst:
case ValueKind::TupleElementAddrInst:
V = cast<SingleValueInstruction>(V)->getOperand(0);
break;
default:
return V;
}
}
llvm_unreachable("there is no escape from an infinite loop");
}
/// Check whether the \p addr is an address of a tail-allocated array element.
bool swift::isAddressOfArrayElement(SILValue addr) {
addr = stripAddressProjections(addr);
if (auto *MD = dyn_cast<MarkDependenceInst>(addr))
addr = stripAddressProjections(MD->getValue());
// High-level SIL: check for an get_element_address array semantics call.
if (auto *PtrToAddr = dyn_cast<PointerToAddressInst>(addr))
if (auto *SEI = dyn_cast<StructExtractInst>(PtrToAddr->getOperand())) {
ArraySemanticsCall Call(SEI->getOperand());
if (Call && Call.getKind() == ArrayCallKind::kGetElementAddress)
return true;
}
// Check for an tail-address (of an array buffer object).
if (isa<RefTailAddrInst>(skipAddrProjections(addr)))
return true;
return false;
}
/// Find a new position for an ApplyInst's FuncRef so that it dominates its
/// use. Not that FunctionRefInsts may be shared by multiple ApplyInsts.
void swift::placeFuncRef(ApplyInst *AI, DominanceInfo *DT) {
FunctionRefInst *FuncRef = cast<FunctionRefInst>(AI->getCallee());
SILBasicBlock *DomBB =
DT->findNearestCommonDominator(AI->getParent(), FuncRef->getParent());
if (DomBB == AI->getParent() && DomBB != FuncRef->getParent())
// Prefer to place the FuncRef immediately before the call. Since we're
// moving FuncRef up, this must be the only call to it in the block.
FuncRef->moveBefore(AI);
else
// Otherwise, conservatively stick it at the beginning of the block.
FuncRef->moveBefore(&*DomBB->begin());
}
/// Add an argument, \p val, to the branch-edge that is pointing into
/// block \p Dest. Return a new instruction and do not erase the old
/// instruction.
TermInst *swift::addArgumentToBranch(SILValue Val, SILBasicBlock *Dest,
TermInst *Branch) {
SILBuilderWithScope Builder(Branch);
if (auto *CBI = dyn_cast<CondBranchInst>(Branch)) {
SmallVector<SILValue, 8> TrueArgs;
SmallVector<SILValue, 8> FalseArgs;
for (auto A : CBI->getTrueArgs())
TrueArgs.push_back(A);
for (auto A : CBI->getFalseArgs())
FalseArgs.push_back(A);
if (Dest == CBI->getTrueBB()) {
TrueArgs.push_back(Val);
assert(TrueArgs.size() == Dest->getNumArguments());
} else {
FalseArgs.push_back(Val);
assert(FalseArgs.size() == Dest->getNumArguments());
}
return Builder.createCondBranch(CBI->getLoc(), CBI->getCondition(), CBI->getTrueBB(), TrueArgs, CBI->getFalseBB(), FalseArgs, CBI->getTrueBBCount(), CBI->getFalseBBCount());
}
if (auto *BI = dyn_cast<BranchInst>(Branch)) {
SmallVector<SILValue, 8> Args;
for (auto A : BI->getArgs())
Args.push_back(A);
Args.push_back(Val);
assert(Args.size() == Dest->getNumArguments());
return Builder.createBranch(BI->getLoc(), BI->getDestBB(), Args);
}
llvm_unreachable("unsupported terminator");
}
SILLinkage swift::getSpecializedLinkage(SILFunction *F, SILLinkage L) {
if (hasPrivateVisibility(L) &&
!F->isSerialized()) {
// Specializations of private symbols should remain so, unless
// they were serialized, which can only happen when specializing
// definitions from a standard library built with -sil-serialize-all.
return SILLinkage::Private;
}
return SILLinkage::Shared;
}
/// Remove all instructions in the body of \p BB in safe manner by using
/// undef.
void swift::clearBlockBody(SILBasicBlock *BB) {
// Instructions in the dead block may be used by other dead blocks. Replace
// any uses of them with undef values.
while (!BB->empty()) {
// Grab the last instruction in the BB.
auto *Inst = &BB->back();
// Replace any still-remaining uses with undef values and erase.
Inst->replaceAllUsesOfAllResultsWithUndef();
Inst->eraseFromParent();
}
}
// Handle the mechanical aspects of removing an unreachable block.
void swift::removeDeadBlock(SILBasicBlock *BB) {
// Clear the body of BB.
clearBlockBody(BB);
// Now that the BB is empty, eliminate it.
BB->eraseFromParent();
}
/// Cast a value into the expected, ABI compatible type if necessary.
/// This may happen e.g. when:
/// - a type of the return value is a subclass of the expected return type.
/// - actual return type and expected return type differ in optionality.
/// - both types are tuple-types and some of the elements need to be casted.
///
/// If CheckOnly flag is set, then this function only checks if the
/// required casting is possible. If it is not possible, then None
/// is returned.
///
/// If CheckOnly is not set, then a casting code is generated and the final
/// casted value is returned.
///
/// NOTE: We intentionally combine the checking of the cast's handling possibility
/// and the transformation performing the cast in the same function, to avoid
/// any divergence between the check and the implementation in the future.
///
/// NOTE: The implementation of this function is very closely related to the
/// rules checked by SILVerifier::requireABICompatibleFunctionTypes.
SILValue swift::castValueToABICompatibleType(SILBuilder *B, SILLocation Loc,
SILValue Value,
SILType SrcTy, SILType DestTy) {
// No cast is required if types are the same.
if (SrcTy == DestTy)
return Value;
assert(SrcTy.isAddress() == DestTy.isAddress() &&
"Addresses aren't compatible with values");
if (SrcTy.isAddress() && DestTy.isAddress()) {
// Cast between two addresses and that's it.
return B->createUncheckedAddrCast(Loc, Value, DestTy);
}
// If both types are classes and dest is the superclass of src,
// simply perform an upcast.
if (DestTy.isExactSuperclassOf(SrcTy)) {
return B->createUpcast(Loc, Value, DestTy);
}
if (SrcTy.isHeapObjectReferenceType() &&
DestTy.isHeapObjectReferenceType()) {
return B->createUncheckedRefCast(Loc, Value, DestTy);
}
if (auto mt1 = SrcTy.getAs<AnyMetatypeType>()) {
if (auto mt2 = DestTy.getAs<AnyMetatypeType>()) {
if (mt1->getRepresentation() == mt2->getRepresentation()) {
// If B.Type needs to be casted to A.Type and
// A is a superclass of B, then it can be done by means
// of a simple upcast.
if (mt2.getInstanceType()->isExactSuperclassOf(
mt1.getInstanceType())) {
return B->createUpcast(Loc, Value, DestTy);
}
// Cast between two metatypes and that's it.
return B->createUncheckedBitCast(Loc, Value, DestTy);
}
}
}
// Check if src and dest types are optional.
auto OptionalSrcTy = SrcTy.getOptionalObjectType();
auto OptionalDestTy = DestTy.getOptionalObjectType();
// Both types are optional.
if (OptionalDestTy && OptionalSrcTy) {
// If both wrapped types are classes and dest is the superclass of src,
// simply perform an upcast.
if (OptionalDestTy.isExactSuperclassOf(OptionalSrcTy)) {
// Insert upcast.
return B->createUpcast(Loc, Value, DestTy);
}
// Unwrap the original optional value.
auto *SomeDecl = B->getASTContext().getOptionalSomeDecl();
auto *NoneBB = B->getFunction().createBasicBlock();
auto *SomeBB = B->getFunction().createBasicBlock();
auto *CurBB = B->getInsertionPoint()->getParent();
auto *ContBB = CurBB->split(B->getInsertionPoint());
ContBB->createPhiArgument(DestTy, ValueOwnershipKind::Owned);
SmallVector<std::pair<EnumElementDecl *, SILBasicBlock *>, 1> CaseBBs;
CaseBBs.push_back(std::make_pair(SomeDecl, SomeBB));
B->setInsertionPoint(CurBB);
B->createSwitchEnum(Loc, Value, NoneBB, CaseBBs);
// Handle the Some case.
B->setInsertionPoint(SomeBB);
SILValue UnwrappedValue = B->createUncheckedEnumData(Loc, Value,
SomeDecl);
// Cast the unwrapped value.
auto CastedUnwrappedValue =
castValueToABICompatibleType(B, Loc, UnwrappedValue,
OptionalSrcTy,
OptionalDestTy);
// Wrap into optional.
auto CastedValue = B->createOptionalSome(Loc, CastedUnwrappedValue, DestTy);
B->createBranch(Loc, ContBB, {CastedValue});
// Handle the None case.
B->setInsertionPoint(NoneBB);
CastedValue = B->createOptionalNone(Loc, DestTy);
B->createBranch(Loc, ContBB, {CastedValue});
B->setInsertionPoint(ContBB->begin());
return ContBB->getArgument(0);
}
// Src is not optional, but dest is optional.
if (!OptionalSrcTy && OptionalDestTy) {
auto OptionalSrcCanTy = OptionalType::get(SrcTy.getASTType())
->getCanonicalType();
auto LoweredOptionalSrcType = SILType::getPrimitiveObjectType(
OptionalSrcCanTy);
// Wrap the source value into an optional first.
SILValue WrappedValue = B->createOptionalSome(Loc, Value,
LoweredOptionalSrcType);
// Cast the wrapped value.
return castValueToABICompatibleType(B, Loc, WrappedValue,
WrappedValue->getType(),
DestTy);
}
// Handle tuple types.
// Extract elements, cast each of them, create a new tuple.
if (auto SrcTupleTy = SrcTy.getAs<TupleType>()) {
SmallVector<SILValue, 8> ExpectedTuple;
for (unsigned i = 0, e = SrcTupleTy->getNumElements(); i < e; i++) {
SILValue Element = B->createTupleExtract(Loc, Value, i);
// Cast the value if necessary.
Element = castValueToABICompatibleType(B, Loc, Element,
SrcTy.getTupleElementType(i),
DestTy.getTupleElementType(i));
ExpectedTuple.push_back(Element);
}
return B->createTuple(Loc, DestTy, ExpectedTuple);
}
// Function types are interchangeable if they're also ABI-compatible.
if (SrcTy.is<SILFunctionType>()) {
if (DestTy.is<SILFunctionType>()) {
assert(SrcTy.getAs<SILFunctionType>()->isNoEscape() ==
DestTy.getAs<SILFunctionType>()->isNoEscape() ||
SrcTy.getAs<SILFunctionType>()->getRepresentation() !=
SILFunctionType::Representation::Thick &&
"Swift thick functions that differ in escapeness are not ABI "
"compatible");
// Insert convert_function.
return B->createConvertFunction(Loc, Value, DestTy,
/*WithoutActuallyEscaping=*/false);
}
}
llvm::errs() << "Source type: " << SrcTy << "\n";
llvm::errs() << "Destination type: " << DestTy << "\n";
llvm_unreachable("Unknown combination of types for casting");
}
ProjectBoxInst *swift::getOrCreateProjectBox(AllocBoxInst *ABI, unsigned Index){
SILBasicBlock::iterator Iter(ABI);
Iter++;
assert(Iter != ABI->getParent()->end() &&
"alloc_box cannot be the last instruction of a block");
SILInstruction *NextInst = &*Iter;
if (auto *PBI = dyn_cast<ProjectBoxInst>(NextInst)) {
if (PBI->getOperand() == ABI && PBI->getFieldIndex() == Index)
return PBI;
}
SILBuilder B(NextInst);
return B.createProjectBox(ABI->getLoc(), ABI, Index);
}
// Peek through trivial Enum initialization, typically for pointless
// Optionals.
//
// Given an UncheckedTakeEnumDataAddrInst, check that there are no
// other uses of the Enum value and return the address used to initialized the
// enum's payload:
//
// %stack_adr = alloc_stack
// %data_adr = init_enum_data_addr %stk_adr
// %enum_adr = inject_enum_addr %stack_adr
// %copy_src = unchecked_take_enum_data_addr %enum_adr
// dealloc_stack %stack_adr
// (No other uses of %stack_adr.)
InitEnumDataAddrInst *
swift::findInitAddressForTrivialEnum(UncheckedTakeEnumDataAddrInst *UTEDAI) {
auto *ASI = dyn_cast<AllocStackInst>(UTEDAI->getOperand());
if (!ASI)
return nullptr;
SILInstruction *singleUser = nullptr;
for (auto use : ASI->getUses()) {
auto *user = use->getUser();
if (user == UTEDAI)
continue;
// As long as there's only one UncheckedTakeEnumDataAddrInst and one
// InitEnumDataAddrInst, we don't care how many InjectEnumAddr and
// DeallocStack users there are.
if (isa<InjectEnumAddrInst>(user) || isa<DeallocStackInst>(user))
continue;
if (singleUser)
return nullptr;
singleUser = user;
}
if (!singleUser)
return nullptr;
// Assume, without checking, that the returned InitEnumDataAddr dominates the
// given UncheckedTakeEnumDataAddrInst, because that's how SIL is defined. I
// don't know where this is actually verified.
return dyn_cast<InitEnumDataAddrInst>(singleUser);
}
//===----------------------------------------------------------------------===//
// String Concatenation Optimizer
//===----------------------------------------------------------------------===//
namespace {
/// This is a helper class that performs optimization of string literals
/// concatenation.
class StringConcatenationOptimizer {
/// Apply instruction being optimized.
ApplyInst *AI;
/// Builder to be used for creation of new instructions.
SILBuilder &Builder;
/// Left string literal operand of a string concatenation.
StringLiteralInst *SLILeft = nullptr;
/// Right string literal operand of a string concatenation.
StringLiteralInst *SLIRight = nullptr;
/// Function used to construct the left string literal.
FunctionRefInst *FRILeft = nullptr;
/// Function used to construct the right string literal.
FunctionRefInst *FRIRight = nullptr;
/// Apply instructions used to construct left string literal.
ApplyInst *AILeft = nullptr;
/// Apply instructions used to construct right string literal.
ApplyInst *AIRight = nullptr;
/// String literal conversion function to be used.
FunctionRefInst *FRIConvertFromBuiltin = nullptr;
/// Result type of a function producing the concatenated string literal.
SILValue FuncResultType;
/// Internal helper methods
bool extractStringConcatOperands();
void adjustEncodings();
APInt getConcatenatedLength();
bool isAscii() const;
public:
StringConcatenationOptimizer(ApplyInst *AI, SILBuilder &Builder)
: AI(AI), Builder(Builder) {}
/// Tries to optimize a given apply instruction if it is a
/// concatenation of string literals.
///
/// Returns a new instruction if optimization was possible.
SingleValueInstruction *optimize();
};
} // end anonymous namespace
/// Checks operands of a string concatenation operation to see if
/// optimization is applicable.
///
/// Returns false if optimization is not possible.
/// Returns true and initializes internal fields if optimization is possible.
bool StringConcatenationOptimizer::extractStringConcatOperands() {
auto *Fn = AI->getReferencedFunctionOrNull();
if (!Fn)
return false;
if (AI->getNumArguments() != 3 || !Fn->hasSemanticsAttr("string.concat"))
return false;
// Left and right operands of a string concatenation operation.
AILeft = dyn_cast<ApplyInst>(AI->getOperand(1));
AIRight = dyn_cast<ApplyInst>(AI->getOperand(2));
if (!AILeft || !AIRight)
return false;
FRILeft = dyn_cast<FunctionRefInst>(AILeft->getCallee());
FRIRight = dyn_cast<FunctionRefInst>(AIRight->getCallee());
if (!FRILeft || !FRIRight)
return false;
auto *FRILeftFun = FRILeft->getReferencedFunctionOrNull();
auto *FRIRightFun = FRIRight->getReferencedFunctionOrNull();
if (FRILeftFun->getEffectsKind() >= EffectsKind::ReleaseNone ||
FRIRightFun->getEffectsKind() >= EffectsKind::ReleaseNone)
return false;
if (!FRILeftFun->hasSemanticsAttrs() || !FRIRightFun->hasSemanticsAttrs())
return false;
auto AILeftOperandsNum = AILeft->getNumOperands();
auto AIRightOperandsNum = AIRight->getNumOperands();
// makeUTF8 should have following parameters:
// (start: RawPointer, utf8CodeUnitCount: Word, isASCII: Int1)
if (!((FRILeftFun->hasSemanticsAttr("string.makeUTF8") &&
AILeftOperandsNum == 5) ||
(FRIRightFun->hasSemanticsAttr("string.makeUTF8") &&
AIRightOperandsNum == 5)))
return false;
SLILeft = dyn_cast<StringLiteralInst>(AILeft->getOperand(1));
SLIRight = dyn_cast<StringLiteralInst>(AIRight->getOperand(1));
if (!SLILeft || !SLIRight)
return false;
// Only UTF-8 and UTF-16 encoded string literals are supported by this
// optimization.
if (SLILeft->getEncoding() != StringLiteralInst::Encoding::UTF8 &&
SLILeft->getEncoding() != StringLiteralInst::Encoding::UTF16)
return false;
if (SLIRight->getEncoding() != StringLiteralInst::Encoding::UTF8 &&
SLIRight->getEncoding() != StringLiteralInst::Encoding::UTF16)
return false;
return true;
}
/// Ensures that both string literals to be concatenated use the same
/// UTF encoding. Converts UTF-8 into UTF-16 if required.
void StringConcatenationOptimizer::adjustEncodings() {
if (SLILeft->getEncoding() == SLIRight->getEncoding()) {
FRIConvertFromBuiltin = FRILeft;
if (SLILeft->getEncoding() == StringLiteralInst::Encoding::UTF8) {
FuncResultType = AILeft->getOperand(4);
} else {
FuncResultType = AILeft->getOperand(3);
}
return;
}
Builder.setCurrentDebugScope(AI->getDebugScope());
// If one of the string literals is UTF8 and another one is UTF16,
// convert the UTF8-encoded string literal into UTF16-encoding first.
if (SLILeft->getEncoding() == StringLiteralInst::Encoding::UTF8 &&
SLIRight->getEncoding() == StringLiteralInst::Encoding::UTF16) {
FuncResultType = AIRight->getOperand(3);
FRIConvertFromBuiltin = FRIRight;
// Convert UTF8 representation into UTF16.
SLILeft = Builder.createStringLiteral(AI->getLoc(), SLILeft->getValue(),
StringLiteralInst::Encoding::UTF16);
}
if (SLIRight->getEncoding() == StringLiteralInst::Encoding::UTF8 &&
SLILeft->getEncoding() == StringLiteralInst::Encoding::UTF16) {
FuncResultType = AILeft->getOperand(3);
FRIConvertFromBuiltin = FRILeft;
// Convert UTF8 representation into UTF16.
SLIRight = Builder.createStringLiteral(AI->getLoc(), SLIRight->getValue(),
StringLiteralInst::Encoding::UTF16);
}
// It should be impossible to have two operands with different
// encodings at this point.
assert(SLILeft->getEncoding() == SLIRight->getEncoding() &&
"Both operands of string concatenation should have the same encoding");
}
/// Computes the length of a concatenated string literal.
APInt StringConcatenationOptimizer::getConcatenatedLength() {
// Real length of string literals computed based on its contents.
// Length is in code units.
auto SLILenLeft = SLILeft->getCodeUnitCount();
(void) SLILenLeft;
auto SLILenRight = SLIRight->getCodeUnitCount();
(void) SLILenRight;
// Length of string literals as reported by string.make functions.
auto *LenLeft = dyn_cast<IntegerLiteralInst>(AILeft->getOperand(2));
auto *LenRight = dyn_cast<IntegerLiteralInst>(AIRight->getOperand(2));
// Real and reported length should be the same.
assert(SLILenLeft == LenLeft->getValue() &&
"Size of string literal in @_semantics(string.make) is wrong");
assert(SLILenRight == LenRight->getValue() &&
"Size of string literal in @_semantics(string.make) is wrong");
// Compute length of the concatenated literal.
return LenLeft->getValue() + LenRight->getValue();
}
/// Computes the isAscii flag of a concatenated UTF8-encoded string literal.
bool StringConcatenationOptimizer::isAscii() const{
// Add the isASCII argument in case of UTF8.
// IsASCII is true only if IsASCII of both literals is true.
auto *AsciiLeft = dyn_cast<IntegerLiteralInst>(AILeft->getOperand(3));
auto *AsciiRight = dyn_cast<IntegerLiteralInst>(AIRight->getOperand(3));
auto IsAsciiLeft = AsciiLeft->getValue() == 1;
auto IsAsciiRight = AsciiRight->getValue() == 1;
return IsAsciiLeft && IsAsciiRight;
}
SingleValueInstruction *StringConcatenationOptimizer::optimize() {
// Bail out if string literals concatenation optimization is
// not possible.
if (!extractStringConcatOperands())
return nullptr;
// Perform string literal encodings adjustments if needed.
adjustEncodings();
// Arguments of the new StringLiteralInst to be created.
SmallVector<SILValue, 4> Arguments;
// Encoding to be used for the concatenated string literal.
auto Encoding = SLILeft->getEncoding();
// Create a concatenated string literal.
Builder.setCurrentDebugScope(AI->getDebugScope());
auto LV = SLILeft->getValue();
auto RV = SLIRight->getValue();
auto *NewSLI =
Builder.createStringLiteral(AI->getLoc(), LV + Twine(RV), Encoding);
Arguments.push_back(NewSLI);
// Length of the concatenated literal according to its encoding.
auto *Len = Builder.createIntegerLiteral(
AI->getLoc(), AILeft->getOperand(2)->getType(), getConcatenatedLength());
Arguments.push_back(Len);
// isAscii flag for UTF8-encoded string literals.
if (Encoding == StringLiteralInst::Encoding::UTF8) {
bool IsAscii = isAscii();
auto ILType = AILeft->getOperand(3)->getType();
auto *Ascii =
Builder.createIntegerLiteral(AI->getLoc(), ILType, intmax_t(IsAscii));
Arguments.push_back(Ascii);
}
// Type.
Arguments.push_back(FuncResultType);
return Builder.createApply(AI->getLoc(), FRIConvertFromBuiltin,
SubstitutionMap(), Arguments);
}
/// Top level entry point
SingleValueInstruction *
swift::tryToConcatenateStrings(ApplyInst *AI, SILBuilder &B) {
return StringConcatenationOptimizer(AI, B).optimize();
}
//===----------------------------------------------------------------------===//
// Closure Deletion
//===----------------------------------------------------------------------===//
/// NOTE: Instructions with transitive ownership kind are assumed to not keep
/// the underlying closure alive as well. This is meant for instructions only
/// with non-transitive users.
static bool useDoesNotKeepClosureAlive(const SILInstruction *I) {
switch (I->getKind()) {
case SILInstructionKind::StrongRetainInst:
case SILInstructionKind::StrongReleaseInst:
case SILInstructionKind::DestroyValueInst:
case SILInstructionKind::RetainValueInst:
case SILInstructionKind::ReleaseValueInst:
case SILInstructionKind::DebugValueInst:
case SILInstructionKind::EndBorrowInst:
return true;
default:
return false;
}
}
static bool useHasTransitiveOwnership(const SILInstruction *I) {
// convert_escape_to_noescape is used to convert to a @noescape function type.
// It does not change ownership of the function value.
if (isa<ConvertEscapeToNoEscapeInst>(I))
return true;
// Look through copy_value, begin_borrow. They are inert for our purposes, but
// we need to look through it.
return isa<CopyValueInst>(I) || isa<BeginBorrowInst>(I);
}
static SILValue createLifetimeExtendedAllocStack(
SILBuilder &Builder, SILLocation Loc, SILValue Arg,
ArrayRef<SILBasicBlock *> ExitingBlocks, InstModCallbacks Callbacks) {
AllocStackInst *ASI = nullptr;
{
// Save our insert point and create a new alloc_stack in the initial BB and
// dealloc_stack in all exit blocks.
auto *OldInsertPt = &*Builder.getInsertionPoint();
Builder.setInsertionPoint(Builder.getFunction().begin()->begin());
ASI = Builder.createAllocStack(Loc, Arg->getType());
Callbacks.CreatedNewInst(ASI);
for (auto *BB : ExitingBlocks) {
Builder.setInsertionPoint(BB->getTerminator());
Callbacks.CreatedNewInst(Builder.createDeallocStack(Loc, ASI));
}
Builder.setInsertionPoint(OldInsertPt);
}
assert(ASI != nullptr);
// Then perform a copy_addr [take] [init] right after the partial_apply from
// the original address argument to the new alloc_stack that we have
// created.
Callbacks.CreatedNewInst(
Builder.createCopyAddr(Loc, Arg, ASI, IsTake, IsInitialization));
// Return the new alloc_stack inst that has the appropriate live range to
// destroy said values.
return ASI;
}
static bool shouldDestroyPartialApplyCapturedArg(SILValue Arg,
SILParameterInfo PInfo,
const SILFunction &F) {
// If we have a non-trivial type and the argument is passed in @inout, we do
// not need to destroy it here. This is something that is implicit in the
// partial_apply design that will be revisited when partial_apply is
// redesigned.