-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathInstOptUtils.cpp
2601 lines (2275 loc) · 92.6 KB
/
InstOptUtils.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
//===--- InstOptUtils.cpp - SILOptimizer instruction utilities ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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/InstOptUtils.h"
#include "swift/AST/CanTypeVisitor.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/SemanticAttrs.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/SmallPtrSetVector.h"
#include "swift/SIL/ApplySite.h"
#include "swift/SIL/BasicBlockUtils.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBridging.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILDebugInfoExpression.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/ScopedAddressUtils.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/SILOptimizer/Analysis/ARCAnalysis.h"
#include "swift/SILOptimizer/Analysis/Analysis.h"
#include "swift/SILOptimizer/Analysis/ArraySemantic.h"
#include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h"
#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h"
#include "swift/SILOptimizer/Analysis/DestructorAnalysis.h"
#include "swift/SILOptimizer/OptimizerBridging.h"
#include "swift/SILOptimizer/Utils/CFGOptUtils.h"
#include "swift/SILOptimizer/Utils/DebugOptUtils.h"
#include "swift/SILOptimizer/Utils/OwnershipOptUtils.h"
#include "swift/SILOptimizer/Utils/ValueLifetime.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 <optional>
using namespace swift;
static llvm::cl::opt<bool> KeepWillThrowCall(
"keep-will-throw-call", llvm::cl::init(false),
llvm::cl::desc(
"Keep calls to swift_willThrow, even if the throw is optimized away"));
std::optional<SILBasicBlock::iterator>
swift::getInsertAfterPoint(SILValue val) {
if (auto *inst = val->getDefiningInstruction()) {
return std::next(inst->getIterator());
}
if (isa<SILArgument>(val)) {
return cast<SILArgument>(val)->getParentBlock()->begin();
}
return std::nullopt;
}
/// 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 builder(insertPt);
auto loc = RegularLocation::getAutoGeneratedLocation();
// If we have a trivial type, just bail, there is no work to do.
if (ptr->getType().isTrivial(builder.getFunction()))
return nullptr;
// If Ptr is refcounted itself, create the strong_retain and
// return.
if (ptr->getType().isReferenceCounted(builder.getModule())) {
#define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
if (ptr->getType().is<Name##StorageType>()) \
return builder.create##Name##Retain(loc, ptr, \
builder.getDefaultAtomicity());
#include "swift/AST/ReferenceStorage.def"
return builder.createStrongRetain(loc, ptr,
builder.getDefaultAtomicity());
}
// Otherwise, create the retain_value.
return builder.createRetainValue(loc, ptr, builder.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 builder(insertPt);
auto loc = RegularLocation::getAutoGeneratedLocation();
if (ptr->getType().isTrivial(builder.getFunction()))
return nullptr;
// If ptr has reference semantics itself, create a strong_release.
if (ptr->getType().isReferenceCounted(builder.getModule())) {
#define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
if (ptr->getType().is<Name##StorageType>()) \
return builder.create##Name##Release(loc, ptr, \
builder.getDefaultAtomicity());
#include "swift/AST/ReferenceStorage.def"
return builder.createStrongRelease(loc, ptr,
builder.getDefaultAtomicity());
}
// Otherwise create a release value.
return builder.createReleaseValue(loc, ptr, builder.getDefaultAtomicity());
}
/// Returns true if OSSA scope ending instructions end_borrow/destroy_value can
/// be deleted trivially
bool swift::canTriviallyDeleteOSSAEndScopeInst(SILInstruction *i) {
if (!isa<EndBorrowInst>(i) && !isa<DestroyValueInst>(i))
return false;
if (isa<StoreBorrowInst>(i->getOperand(0)))
return false;
auto opValue = i->getOperand(0);
// We can delete destroy_value with operands of none ownership unless
// they are move-only values, which can have custom deinit
return opValue->getOwnershipKind() == OwnershipKind::None &&
!opValue->getType().isMoveOnly();
}
/// 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 *inst) {
// At Onone, consider all uses, including the debug_info.
// This way, debug_info is preserved at Onone.
if (inst->hasUsesOfAnyResult()
&& inst->getFunction()->getEffectiveOptimizationMode()
<= OptimizationMode::NoOptimization)
return false;
if (!onlyHaveDebugUsesOfAllResults(inst) || isa<TermInst>(inst))
return false;
if (auto *bi = dyn_cast<BuiltinInst>(inst)) {
// 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>(inst))
if (auto *ili = dyn_cast<IntegerLiteralInst>(cfi->getOperand()))
if (!ili->getValue())
return true;
// mark_uninitialized is never dead.
if (isa<MarkUninitializedInst>(inst))
return false;
if (isa<DebugValueInst>(inst))
return false;
// A dead borrowed-from can only be removed if the argument (= operand) is also removed.
if (isa<BorrowedFromInst>(inst))
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>(inst))
return true;
// An ossa end scope instruction is trivially dead if its operand has
// OwnershipKind::None. This can occur after CFG simplification in the
// presence of non-payloaded or trivial payload cases of non-trivial enums.
//
// Examples of ossa end_scope instructions: end_borrow, destroy_value.
if (inst->getFunction()->hasOwnership() &&
canTriviallyDeleteOSSAEndScopeInst(inst))
return true;
if (!inst->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 *inst,
EpilogueARCFunctionInfo *eafi) {
// Check whether this is a release instruction.
if (!isa<StrongReleaseInst>(inst) && !isa<ReleaseValueInst>(inst))
return false;
// OK. we have a release instruction.
// Check whether this is a release on part of a guaranteed function argument.
SILValue Op = stripValueProjections(inst->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(inst))
return true;
// Failed to prove anything.
return false;
}
bool swift::hasOnlyEndOfScopeOrEndOfLifetimeUses(SILInstruction *inst) {
for (SILValue result : inst->getResults()) {
for (Operand *use : result->getUses()) {
SILInstruction *user = use->getUser();
bool isDebugUser = user->isDebugInstruction();
if (!isa<DestroyValueInst>(user) && !isa<EndLifetimeInst>(user)
&& !isa<DeallocStackInst>(user) && !isEndOfScopeMarker(user)
&& !isDebugUser) {
return false;
}
// Include debug uses only in Onone mode.
if (isDebugUser && inst->getFunction()->getEffectiveOptimizationMode() <=
OptimizationMode::NoOptimization)
return false;
}
}
return true;
}
unsigned swift::getNumInOutArguments(FullApplySite applySite) {
assert(applySite);
auto substConv = applySite.getSubstCalleeConv();
unsigned numIndirectResults = substConv.getNumIndirectSILResults();
unsigned numInOutArguments = 0;
for (unsigned argIndex = 0; argIndex < applySite.getNumArguments();
argIndex++) {
// Skip indirect results.
if (argIndex < numIndirectResults) {
continue;
}
auto paramNumber = argIndex - numIndirectResults;
auto ParamConvention =
substConv.getParameters()[paramNumber].getConvention();
switch (ParamConvention) {
case ParameterConvention::Indirect_Inout:
case ParameterConvention::Indirect_InoutAliasable: {
++numInOutArguments;
break;
default:
break;
}
}
}
return numInOutArguments;
}
/// If the given instruction is dead, delete it along with its dead
/// operands.
///
/// \param inst 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 *inst, bool force, InstModCallbacks callbacks) {
ArrayRef<SILInstruction *> ai = ArrayRef<SILInstruction *>(inst);
recursivelyDeleteTriviallyDeadInstructions(ai, force, callbacks);
}
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 inst : insts) {
inst->replaceAllUsesOfAllResultsWithUndef();
inst->eraseFromParent();
}
}
bool swift::hasValueDeinit(SILType type) {
// Do not look inside an aggregate type that has a user-deinit, for which
// memberwise-destruction is not equivalent to aggregate destruction.
if (auto *nominal = type.getNominalOrBoundGenericNominal()) {
return nominal->getValueTypeDestructor() != nullptr;
}
return false;
}
SILValue swift::
getConcreteValueOfExistentialBox(AllocExistentialBoxInst *existentialBox,
SILInstruction *ignoreUser) {
StoreInst *singleStore = nullptr;
SmallPtrSetVector<Operand *, 32> worklist;
for (auto *use : getNonDebugUses(existentialBox)) {
worklist.insert(use);
}
while (!worklist.empty()) {
auto *use = worklist.pop_back_val();
SILInstruction *user = use->getUser();
switch (user->getKind()) {
case SILInstructionKind::StrongRetainInst:
case SILInstructionKind::StrongReleaseInst:
case SILInstructionKind::DestroyValueInst:
case SILInstructionKind::EndBorrowInst:
break;
case SILInstructionKind::CopyValueInst:
case SILInstructionKind::BeginBorrowInst:
// Look through copy_value, begin_borrow
for (SILValue result : user->getResults())
for (auto *transitiveUse : result->getUses())
worklist.insert(transitiveUse);
break;
case SILInstructionKind::ProjectExistentialBoxInst: {
auto *projectedAddr = cast<ProjectExistentialBoxInst>(user);
for (Operand *addrUse : getNonDebugUses(projectedAddr)) {
if (auto *store = dyn_cast<StoreInst>(addrUse->getUser())) {
assert(store->getSrc() != projectedAddr && "cannot store an address");
// Bail if there are multiple stores.
if (singleStore)
return SILValue();
singleStore = store;
continue;
}
// If there are other users to the box value address then bail out.
return SILValue();
}
break;
}
case SILInstructionKind::BuiltinInst: {
auto *builtin = cast<BuiltinInst>(user);
if (KeepWillThrowCall ||
builtin->getBuiltinInfo().ID != BuiltinValueKind::WillThrow) {
return SILValue();
}
break;
}
default:
if (user != ignoreUser)
return SILValue();
break;
}
}
if (!singleStore)
return SILValue();
return singleStore->getSrc();
}
SILValue swift::
getConcreteValueOfExistentialBoxAddr(SILValue addr, SILInstruction *ignoreUser) {
auto *stackLoc = dyn_cast<AllocStackInst>(addr);
if (!stackLoc)
return SILValue();
StoreInst *singleStackStore = nullptr;
for (Operand *stackUse : stackLoc->getUses()) {
SILInstruction *stackUser = stackUse->getUser();
switch (stackUser->getKind()) {
case SILInstructionKind::DestroyAddrInst: {
// Make sure the destroy_addr is the instruction before one of our
// dealloc_stack insts and is directly on the stack location.
auto next = std::next(stackUser->getIterator());
if (auto *dsi = dyn_cast<DeallocStackInst>(next))
if (dsi->getOperand() != stackLoc)
return SILValue();
break;
}
case SILInstructionKind::DeallocStackInst:
case SILInstructionKind::LoadInst:
break;
case SILInstructionKind::DebugValueInst:
if (!DebugValueInst::hasAddrVal(stackUser)) {
if (stackUser != ignoreUser)
return SILValue();
}
break;
case SILInstructionKind::StoreInst: {
auto *store = cast<StoreInst>(stackUser);
assert(store->getSrc() != stackLoc && "cannot store an address");
// Bail if there are multiple stores.
if (singleStackStore)
return SILValue();
singleStackStore = store;
break;
}
default:
if (stackUser != ignoreUser)
return SILValue();
break;
}
}
if (!singleStackStore)
return SILValue();
// Look through copy value insts.
SILValue val = singleStackStore->getSrc();
while (auto *cvi = dyn_cast<CopyValueInst>(val))
val = cvi->getOperand();
auto *box = dyn_cast<AllocExistentialBoxInst>(val);
if (!box)
return SILValue();
return getConcreteValueOfExistentialBox(box, singleStackStore);
}
bool swift::mayBindDynamicSelf(SILFunction *F) {
if (!F->hasDynamicSelfMetadata())
return false;
SILValue mdArg = F->getDynamicSelfMetadata();
for (Operand *mdUse : mdArg->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 *domInfo) {
FunctionRefInst *funcRef = cast<FunctionRefInst>(ai->getCallee());
SILBasicBlock *domBB = domInfo->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::addArgumentsToBranch(ArrayRef<SILValue> vals,
SILBasicBlock *dest, TermInst *branch) {
SILBuilderWithScope builder(branch);
if (auto *cbi = dyn_cast<CondBranchInst>(branch)) {
SmallVector<SILValue, 8> trueArgs;
SmallVector<SILValue, 8> falseArgs;
for (auto arg : cbi->getTrueArgs())
trueArgs.push_back(arg);
for (auto arg : cbi->getFalseArgs())
falseArgs.push_back(arg);
if (dest == cbi->getTrueBB()) {
for (auto val : vals)
trueArgs.push_back(val);
assert(trueArgs.size() == dest->getNumArguments());
} else {
for (auto val : vals)
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 arg : bi->getArgs())
args.push_back(arg);
for (auto val : vals)
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 linkage) {
if (hasPrivateVisibility(linkage) && !f->isAnySerialized()) {
// 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;
}
/// 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.
/// Return the cast value and true if a CFG modification was required
/// 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.
///
/// \p usePoints are required when \p value has guaranteed ownership. It must be
/// the last users of the returned, casted value. A usePoint cannot be a
/// BranchInst (a phi is never the last guaranteed user). \p builder's current
/// insertion point must dominate all \p usePoints. \p usePoints must
/// collectively post-dominate \p builder's current insertion point.
///
/// NOTE: The implementation of this function is very closely related to the
/// rules checked by SILVerifier::requireABICompatibleFunctionTypes. It must
/// handle all cases recognized by SILFunctionType::isABICompatibleWith (see
/// areABICompatibleParamsOrReturns()).
std::pair<SILValue, bool /* changedCFG */>
swift::castValueToABICompatibleType(SILBuilder *builder, SILPassManager *pm,
SILLocation loc,
SILValue value, SILType srcTy,
SILType destTy,
ArrayRef<SILInstruction *> usePoints) {
assert(value->getOwnershipKind() != OwnershipKind::Guaranteed ||
!usePoints.empty() && "guaranteed value must have use points");
// No cast is required if types are the same.
if (srcTy == destTy)
return {value, false};
if (srcTy.isAddress() && destTy.isAddress()) {
// Cast between two addresses and that's it.
return {builder->createUncheckedAddrCast(loc, value, destTy), false};
}
// If both types are classes and dest is the superclass of src,
// simply perform an upcast.
if (destTy.isExactSuperclassOf(srcTy)) {
return {builder->createUpcast(loc, value, destTy), false};
}
if (srcTy.isHeapObjectReferenceType() && destTy.isHeapObjectReferenceType()) {
return {builder->createUncheckedRefCast(loc, value, destTy), false};
}
if (auto mt1 = srcTy.getAs<AnyMetatypeType>()) {
if (auto mt2 = destTy.getAs<AnyMetatypeType>()) {
if (mt1->getRepresentation() == mt2->getRepresentation()) {
// If builder.Type needs to be casted to A.Type and
// A is a superclass of builder, then it can be done by means
// of a simple upcast.
if (mt2.getInstanceType()->isExactSuperclassOf(mt1.getInstanceType())) {
return {builder->createUpcast(loc, value, destTy), false};
}
// Cast between two metatypes and that's it.
return {builder->createUncheckedReinterpretCast(loc, value, destTy),
false};
}
}
}
// 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 {builder->createUpcast(loc, value, destTy), false};
}
// Unwrap the original optional value.
auto *someDecl = builder->getASTContext().getOptionalSomeDecl();
auto *curBB = builder->getInsertionPoint()->getParent();
auto *contBB = curBB->split(builder->getInsertionPoint());
auto *someBB = builder->getFunction().createBasicBlockAfter(curBB);
auto *noneBB = builder->getFunction().createBasicBlockAfter(someBB);
auto *phi = contBB->createPhiArgument(destTy, value->getOwnershipKind());
SmallVector<std::pair<EnumElementDecl *, SILBasicBlock *>, 1> caseBBs;
caseBBs.push_back(std::make_pair(someDecl, someBB));
builder->setInsertionPoint(curBB);
auto *switchEnum = builder->createSwitchEnum(loc, value, noneBB, caseBBs);
// In OSSA switch_enum destinations have terminator results.
//
// TODO: This should be in a switchEnum utility.
SILValue unwrappedValue;
if (builder->hasOwnership()) {
unwrappedValue = switchEnum->createOptionalSomeResult();
builder->setInsertionPoint(someBB);
} else {
builder->setInsertionPoint(someBB);
unwrappedValue = builder->createUncheckedEnumData(loc, value, someDecl);
}
// Cast the unwrapped value.
SILValue castedUnwrappedValue;
std::tie(castedUnwrappedValue, std::ignore) = castValueToABICompatibleType(
builder, pm, loc, unwrappedValue, optionalSrcTy, optionalDestTy, usePoints);
// Wrap into optional. An owned value is forwarded through the cast and into
// the Optional. A borrowed value will have a nested borrow for the
// rewrapped Optional.
SILValue someValue =
builder->createOptionalSome(loc, castedUnwrappedValue, destTy);
builder->createBranch(loc, contBB, {someValue});
// Handle the None case.
builder->setInsertionPoint(noneBB);
SILValue noneValue = builder->createOptionalNone(loc, destTy);
builder->createBranch(loc, contBB, {noneValue});
builder->setInsertionPoint(contBB->begin());
updateGuaranteedPhis(pm, { phi });
return {lookThroughBorrowedFromUser(phi), true};
}
// 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 =
builder->createOptionalSome(loc, value, loweredOptionalSrcType);
// Cast the wrapped value.
return castValueToABICompatibleType(builder, pm, loc, wrappedValue,
wrappedValue->getType(), destTy,
usePoints);
}
// Handle tuple types.
// Extract elements, cast each of them, create a new tuple.
if (auto srcTupleTy = srcTy.getAs<TupleType>()) {
SmallVector<SILValue, 8> expectedTuple;
bool changedCFG = false;
auto castElement = [&](unsigned idx, SILValue element) {
// Cast the value if necessary.
bool neededCFGChange;
std::tie(element, neededCFGChange) = castValueToABICompatibleType(
builder, pm, loc, element, srcTy.getTupleElementType(idx),
destTy.getTupleElementType(idx), usePoints);
changedCFG |= neededCFGChange;
expectedTuple.push_back(element);
};
builder->emitDestructureValueOperation(loc, value, castElement);
return {builder->createTuple(loc, destTy, expectedTuple), changedCFG};
}
// 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 {builder->createConvertFunction(loc, value, destTy,
/*WithoutActuallyEscaping=*/false),
false};
}
}
NominalTypeDecl *srcNominal = srcTy.getNominalOrBoundGenericNominal();
NominalTypeDecl *destNominal = destTy.getNominalOrBoundGenericNominal();
if (srcNominal && srcNominal == destNominal &&
!layoutIsTypeDependent(srcNominal) &&
srcTy.isObject() && destTy.isObject()) {
// This can be a result from whole-module reasoning of protocol conformances.
// If a protocol only has a single conformance where the associated type (`ID`) is some
// concrete type (e.g. `Int`), then the devirtualizer knows that `p.get()`
// can only return an `Int`:
// ```
// public struct X2<ID> {
// let p: any P2<ID>
// public func testit(i: ID, x: ID) -> S2<ID> {
// return p.get(x: x)
// }
// }
// ```
// and after devirtualizing the `get` function, its result must be cast from `Int` to `ID`.
//
// The `layoutIsTypeDependent` utility is basically only used here to assert that this
// cast can only happen between layout compatible types.
return {builder->createUncheckedForwardingCast(loc, value, destTy), false};
}
llvm::errs() << "Source type: " << srcTy << "\n";
llvm::errs() << "Destination type: " << destTy << "\n";
llvm_unreachable("Unknown combination of types for casting");
}
namespace {
class TypeDependentVisitor : public CanTypeVisitor<TypeDependentVisitor, bool> {
public:
// If the type isn't actually dependent, we're okay.
bool visit(CanType type) {
if (!type->hasArchetype() && !type->hasTypeParameter())
return false;
return CanTypeVisitor::visit(type);
}
bool visitStructType(CanStructType type) {
return visitStructDecl(type->getDecl());
}
bool visitBoundGenericStructType(CanBoundGenericStructType type) {
return visitStructDecl(type->getDecl());
}
bool visitStructDecl(StructDecl *decl) {
auto rawLayout = decl->getAttrs().getAttribute<RawLayoutAttr>();
if (rawLayout) {
if (auto likeType = rawLayout->getResolvedScalarLikeType(decl)) {
return visit((*likeType)->getCanonicalType());
} else if (auto likeArray = rawLayout->getResolvedArrayLikeTypeAndCount(decl)) {
return visit(likeArray->first->getCanonicalType());
}
}
for (auto field : decl->getStoredProperties()) {
if (visit(field->getInterfaceType()->getCanonicalType()))
return true;
}
return false;
}
bool visitEnumType(CanEnumType type) {
return visitEnumDecl(type->getDecl());
}
bool visitBoundGenericEnumType(CanBoundGenericEnumType type) {
return visitEnumDecl(type->getDecl());
}
bool visitEnumDecl(EnumDecl *decl) {
if (decl->isIndirect())
return false;
for (auto elt : decl->getAllElements()) {
if (!elt->hasAssociatedValues() || elt->isIndirect())
continue;
if (visit(elt->getPayloadInterfaceType()->getCanonicalType()))
return true;
}
return false;
}
bool visitTupleType(CanTupleType type) {
for (auto eltTy : type.getElementTypes()) {
if (visit(eltTy->getCanonicalType()))
return true;
}
return false;
}
// A class reference does not depend on the layout of the class.
bool visitClassType(CanClassType type) {
return false;
}
bool visitBoundGenericClassType(CanBoundGenericClassType type) {
return false;
}
// The same for non-strong references.
bool visitReferenceStorageType(CanReferenceStorageType type) {
return false;
}
// All function types have the same layout.
bool visitAnyFunctionType(CanAnyFunctionType type) {
return false;
}
// The safe default for types we didn't handle above.
bool visitType(CanType type) {
return true;
}
};
} // end anonymous namespace
bool swift::layoutIsTypeDependent(NominalTypeDecl *decl) {
if (isa<ClassDecl>(decl)) {
return false;
} else if (auto *structDecl = dyn_cast<StructDecl>(decl)) {
return TypeDependentVisitor().visitStructDecl(structDecl);
} else {
auto *enumDecl = cast<EnumDecl>(decl);
return TypeDependentVisitor().visitEnumDecl(enumDecl);
}
}
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 builder(nextInst);
return builder.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;
InjectEnumAddrInst *singleInject = nullptr;
InitEnumDataAddrInst *singleInit = nullptr;
for (auto use : asi->getUses()) {
auto *user = use->getUser();
if (user == utedai)
continue;
// If there is a single init_enum_data_addr and a single inject_enum_addr,
// those instructions must dominate the unchecked_take_enum_data_addr.
// Otherwise the enum wouldn't be initialized on all control flow paths.
if (auto *inj = dyn_cast<InjectEnumAddrInst>(user)) {
if (singleInject)
return nullptr;
singleInject = inj;
continue;
}
if (auto *init = dyn_cast<InitEnumDataAddrInst>(user)) {
if (singleInit)
return nullptr;
singleInit = init;
continue;
}
if (isa<DeallocStackInst>(user) || isa<DebugValueInst>(user))
continue;
}
return singleInit;
}
//===----------------------------------------------------------------------===//
// Closure Deletion
//===----------------------------------------------------------------------===//
/// NOTE: Instructions with transitive ownership kind are assumed to not keep
/// the underlying value alive as well. This is meant for instructions only
/// with non-transitive users.
static bool useDoesNotKeepValueAlive(const SILInstruction *inst) {
switch (inst->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 *inst) {
// 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>(inst))
return true;
// Look through copy_value, begin_borrow, move_value. They are inert for our
// purposes, but we need to look through it.
return isa<CopyValueInst>(inst) || isa<BeginBorrowInst>(inst) ||
isa<MoveValueInst>(inst);
}
static bool shouldDestroyPartialApplyCapturedArg(SILValue arg,
SILParameterInfo paramInfo,
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.
if (paramInfo.isIndirectMutating())
return false;
// If we have a trivial type, we do not need to put in any extra releases.
if (arg->getType().isTrivial(F))
return false;
// We handle all other cases.
return true;
}
void swift::emitDestroyOperation(SILBuilder &builder, SILLocation loc,
SILValue operand, InstModCallbacks callbacks) {
// If we have an address, we insert a destroy_addr and return. Any live range
// issues must have been dealt with by our caller.
if (operand->getType().isAddress()) {
// Then emit the destroy_addr for this operand. This function does not
// delete any instructions
SILInstruction *newInst = builder.emitDestroyAddrAndFold(loc, operand);
if (newInst != nullptr)
callbacks.createdNewInst(newInst);
return;