-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathInstOptUtils.cpp
2121 lines (1870 loc) · 78.3 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/GenericSignature.h"
#include "swift/AST/SemanticAttrs.h"
#include "swift/AST/SubstitutionMap.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/SILBuilder.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/SILOptimizer/Analysis/ARCAnalysis.h"
#include "swift/SILOptimizer/Analysis/Analysis.h"
#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h"
#include "swift/SILOptimizer/Utils/CFGOptUtils.h"
#include "swift/SILOptimizer/Utils/ConstExpr.h"
#include "swift/SILOptimizer/Utils/ValueLifetime.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));
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"));
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 None;
}
/// 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());
}
static bool isOSSAEndScopeWithNoneOperand(SILInstruction *i) {
if (!isa<EndBorrowInst>(i) && !isa<DestroyValueInst>(i))
return false;
return i->getOperand(0).getOwnershipKind() == OwnershipKind::None;
}
/// 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) || isa<DebugValueAddrInst>(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() &&
isOSSAEndScopeWithNoneOperand(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;
}
static bool hasOnlyEndOfScopeOrDestroyUses(SILInstruction *inst) {
for (SILValue result : inst->getResults()) {
for (Operand *use : result->getUses()) {
SILInstruction *user = use->getUser();
bool isDebugUser = user->isDebugInstruction();
if (!isa<DestroyValueInst>(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;
}
/// Return true iff the \p applySite calls a constant-evaluable function and
/// it is non-generic and read/destroy only, which means that the call can do
/// only the following and nothing else:
/// (1) The call may read any memory location.
/// (2) The call may destroy owned parameters i.e., consume them.
/// (3) The call may write into memory locations newly created by the call.
/// (4) The call may use assertions, which traps at runtime on failure.
/// (5) The call may return a non-generic value.
/// Essentially, these are calls whose "effect" is visible only in their return
/// value or through the parameters that are destroyed. The return value
/// is also guaranteed to have value semantics as it is non-generic and
/// reference semantics is not constant evaluable.
static bool isNonGenericReadOnlyConstantEvaluableCall(FullApplySite applySite) {
assert(applySite);
SILFunction *callee = applySite.getCalleeFunction();
if (!callee || !isConstantEvaluable(callee)) {
return false;
}
return !applySite.hasSubstitutions() && !getNumInOutArguments(applySite) &&
!applySite.getNumIndirectSILResults();
}
/// A scope-affecting instruction is an instruction which may end the scope of
/// its operand or may produce scoped results that require cleaning up. E.g.
/// begin_borrow, begin_access, copy_value, a call that produces a owned value
/// are scoped instructions. The scope of the results of the first two
/// instructions end with an end_borrow/acess instruction, while those of the
/// latter two end with a consuming operation like destroy_value instruction.
/// These instruction may also end the scope of its operand e.g. a call could
/// consume owned arguments thereby ending its scope. Dead-code eliminating a
/// scope-affecting instruction requires fixing the lifetime of the non-trivial
/// operands of the instruction and requires cleaning up the end-of-scope uses
/// of non-trivial results.
///
/// \param inst instruction that checked for liveness.
static bool isScopeAffectingInstructionDead(SILInstruction *inst) {
SILFunction *fun = inst->getFunction();
assert(fun && "Instruction has no function.");
// Only support ownership SIL for scoped instructions.
if (!fun->hasOwnership()) {
return false;
}
// If the instruction has any use other than end of scope use or destroy_value
// use, bail out.
if (!hasOnlyEndOfScopeOrDestroyUses(inst)) {
return false;
}
// If inst is a copy or beginning of scope, inst is dead, since we know that
// it is used only in a destroy_value or end-of-scope instruction.
if (getSingleValueCopyOrCast(inst))
return true;
switch (inst->getKind()) {
case SILInstructionKind::LoadBorrowInst: {
// A load_borrow only used in an end_borrow is dead.
return true;
}
case SILInstructionKind::LoadInst: {
LoadOwnershipQualifier loadOwnershipQual =
cast<LoadInst>(inst)->getOwnershipQualifier();
// If the load creates a copy, it is dead, since we know that if at all it
// is used, it is only in a destroy_value instruction.
return (loadOwnershipQual == LoadOwnershipQualifier::Copy ||
loadOwnershipQual == LoadOwnershipQualifier::Trivial);
// TODO: we can handle load [take] but we would have to know that the
// operand has been consumed. Note that OperandOwnershipKind map does not
// say this for load.
}
case SILInstructionKind::PartialApplyInst: {
// Partial applies that are only used in destroys cannot have any effect on
// the program state, provided the values they capture are explicitly
// destroyed.
return true;
}
case SILInstructionKind::StructInst:
case SILInstructionKind::EnumInst:
case SILInstructionKind::TupleInst:
case SILInstructionKind::ConvertFunctionInst:
case SILInstructionKind::DestructureStructInst:
case SILInstructionKind::DestructureTupleInst: {
// All these ownership forwarding instructions that are only used in
// destroys are dead provided the values they consume are destroyed
// explicitly.
return true;
}
case SILInstructionKind::ApplyInst: {
// The following property holds for constant-evaluable functions that do
// not take arguments of generic type:
// 1. they do not create objects having deinitializers with global
// side effects, as they can only create objects consisting of trivial
// values, (non-generic) arrays and strings.
// 2. they do not use global variables or call arbitrary functions with
// side effects.
// The above two properties imply that a value returned by a constant
// evaluable function does not have a deinitializer with global side
// effects. Therefore, the deinitializer can be sinked.
//
// A generic, read-only constant evaluable call only reads and/or
// destroys its (non-generic) parameters. It therefore cannot have any
// side effects (note that parameters being non-generic have value
// semantics). Therefore, the constant evaluable call can be removed
// provided the parameter lifetimes are handled correctly, which is taken
// care of by the function: \c deleteInstruction.
FullApplySite applySite(cast<ApplyInst>(inst));
return isNonGenericReadOnlyConstantEvaluableCall(applySite);
}
default: {
return false;
}
}
}
void InstructionDeleter::trackIfDead(SILInstruction *inst) {
if (isInstructionTriviallyDead(inst) ||
isScopeAffectingInstructionDead(inst)) {
assert(!isIncidentalUse(inst) && !isa<DestroyValueInst>(inst) &&
"Incidental uses cannot be removed in isolation. "
"They would be removed iff the operand is dead");
deadInstructions.insert(inst);
}
}
/// Given an \p operand that belongs to an instruction that will be removed,
/// destroy the operand just before the instruction, if the instruction consumes
/// \p operand. This function will result in a double consume, which is expected
/// to be resolved when the caller deletes the original instruction. This
/// function works only on ownership SIL.
static void destroyConsumedOperandOfDeadInst(Operand &operand) {
assert(operand.get() && operand.getUser());
SILInstruction *deadInst = operand.getUser();
SILFunction *fun = deadInst->getFunction();
assert(fun->hasOwnership());
SILValue operandValue = operand.get();
if (operandValue->getType().isTrivial(*fun))
return;
// Ignore type-dependent operands which are not real operands but are just
// there to create use-def dependencies.
if (deadInst->isTypeDependentOperand(operand))
return;
// A scope ending instruction cannot be deleted in isolation without removing
// the instruction defining its operand as well.
assert(!isEndOfScopeMarker(deadInst) && !isa<DestroyValueInst>(deadInst) &&
!isa<DestroyAddrInst>(deadInst) &&
"lifetime ending instruction is deleted without its operand");
if (operand.isLifetimeEnding()) {
// Since deadInst cannot be an end-of-scope instruction (asserted above),
// this must be a consuming use of an owned value.
assert(operandValue.getOwnershipKind() == OwnershipKind::Owned);
SILBuilderWithScope builder(deadInst);
builder.emitDestroyValueOperation(deadInst->getLoc(), operandValue);
}
}
namespace {
using CallbackTy = llvm::function_ref<void(SILInstruction *)>;
} // namespace
void InstructionDeleter::deleteInstruction(SILInstruction *inst,
CallbackTy callback,
bool fixOperandLifetimes) {
// We cannot fix operand lifetimes in non-ownership SIL.
assert(!fixOperandLifetimes || inst->getFunction()->hasOwnership());
// Collect instruction and its immediate uses and check if they are all
// incidental uses. Also, invoke the callback on the instruction and its uses.
// Note that the Callback is invoked before deleting anything to ensure that
// the SIL is valid at the time of the callback.
SmallVector<SILInstruction *, 4> toDeleteInsts;
toDeleteInsts.push_back(inst);
callback(inst);
for (SILValue result : inst->getResults()) {
for (Operand *use : result->getUses()) {
SILInstruction *user = use->getUser();
assert(isIncidentalUse(user) || isa<DestroyValueInst>(user));
callback(user);
toDeleteInsts.push_back(user);
}
}
// Record definitions of instruction's operands. Also, in case an operand is
// consumed by inst, emit necessary compensation code.
SmallVector<SILInstruction *, 4> operandDefinitions;
for (Operand &operand : inst->getAllOperands()) {
SILValue operandValue = operand.get();
assert(operandValue &&
"Instruction's operand are deleted before the instruction");
SILInstruction *defInst = operandValue->getDefiningInstruction();
// If the operand has a defining instruction, it could be potentially
// dead. Therefore, record the definition.
if (defInst)
operandDefinitions.push_back(defInst);
// The scope of the operand could be ended by inst. Therefore, emit
// any compensating code needed to end the scope of the operand value
// once inst is deleted.
if (fixOperandLifetimes)
destroyConsumedOperandOfDeadInst(operand);
}
// First drop all references from all instructions to be deleted and then
// erase the instruction. Note that this is done in this order so that when an
// instruction is deleted, its uses would have dropped their references.
// Note that the toDeleteInsts must also be removed from the tracked
// deadInstructions.
for (SILInstruction *inst : toDeleteInsts) {
deadInstructions.remove(inst);
inst->dropAllReferences();
}
for (SILInstruction *inst : toDeleteInsts) {
inst->eraseFromParent();
}
// Record operand definitions that become dead now.
for (SILInstruction *operandValInst : operandDefinitions) {
trackIfDead(operandValInst);
}
}
void InstructionDeleter::cleanUpDeadInstructions(CallbackTy callback) {
SILFunction *fun = nullptr;
if (!deadInstructions.empty())
fun = deadInstructions.front()->getFunction();
while (!deadInstructions.empty()) {
SmallVector<SILInstruction *, 8> currentDeadInsts(deadInstructions.begin(),
deadInstructions.end());
// Though deadInstructions is cleared here, calls to deleteInstruction may
// append to deadInstructions. So we need to iterate until this it is empty.
deadInstructions.clear();
for (SILInstruction *deadInst : currentDeadInsts) {
// deadInst will not have been deleted in the previous iterations,
// because, by definition, deleteInstruction will only delete an earlier
// instruction and its incidental/destroy uses. The former cannot be
// deadInst as deadInstructions is a set vector, and the latter cannot be
// in deadInstructions as they are incidental uses which are never added
// to deadInstructions.
deleteInstruction(deadInst, callback, /*Fix lifetime of operands*/
fun->hasOwnership());
}
}
}
static bool hasOnlyIncidentalUses(SILInstruction *inst,
bool disallowDebugUses = false) {
for (SILValue result : inst->getResults()) {
for (Operand *use : result->getUses()) {
SILInstruction *user = use->getUser();
if (!isIncidentalUse(user))
return false;
if (disallowDebugUses && user->isDebugInstruction())
return false;
}
}
return true;
}
void InstructionDeleter::deleteIfDead(SILInstruction *inst,
CallbackTy callback) {
if (isInstructionTriviallyDead(inst) ||
isScopeAffectingInstructionDead(inst)) {
deleteInstruction(inst, callback,
/*Fix lifetime of operands*/ inst->getFunction()->hasOwnership());
}
}
void InstructionDeleter::forceDeleteAndFixLifetimes(SILInstruction *inst,
CallbackTy callback) {
SILFunction *fun = inst->getFunction();
assert(fun->hasOwnership());
bool disallowDebugUses =
fun->getEffectiveOptimizationMode() <= OptimizationMode::NoOptimization;
assert(hasOnlyIncidentalUses(inst, disallowDebugUses));
deleteInstruction(inst, callback, /*Fix lifetime of operands*/ true);
}
void InstructionDeleter::forceDelete(SILInstruction *inst,
CallbackTy callback) {
bool disallowDebugUses =
inst->getFunction()->getEffectiveOptimizationMode() <=
OptimizationMode::NoOptimization;
assert(hasOnlyIncidentalUses(inst, disallowDebugUses));
deleteInstruction(inst, callback, /*Fix lifetime of operands*/ false);
}
void InstructionDeleter::recursivelyDeleteUsersIfDead(SILInstruction *inst,
CallbackTy callback) {
SmallVector<SILInstruction *, 8> users;
for (SILValue result : inst->getResults())
for (Operand *use : result->getUses())
users.push_back(use->getUser());
for (SILInstruction *user : users)
recursivelyDeleteUsersIfDead(user, callback);
deleteIfDead(inst, callback);
}
void InstructionDeleter::recursivelyForceDeleteUsersAndFixLifetimes(
SILInstruction *inst, CallbackTy callback) {
for (SILValue result : inst->getResults()) {
while (!result->use_empty()) {
SILInstruction *user = result->use_begin()->getUser();
recursivelyForceDeleteUsersAndFixLifetimes(user);
}
}
if (isIncidentalUse(inst) || isa<DestroyValueInst>(inst)) {
forceDelete(inst);
return;
}
forceDeleteAndFixLifetimes(inst);
}
void swift::eliminateDeadInstruction(SILInstruction *inst,
CallbackTy callback) {
InstructionDeleter deleter;
deleter.trackIfDead(inst);
deleter.cleanUpDeadInstructions(callback);
}
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 *inst : ia) {
// If the instruction is not dead and force is false, do nothing.
if (force || isInstructionTriviallyDead(inst))
deadInsts.insert(inst);
}
llvm::SmallPtrSet<SILInstruction *, 8> nextInsts;
while (!deadInsts.empty()) {
for (auto inst : deadInsts) {
// Call the callback before we mutate the to be deleted instruction in any
// way.
callback(inst);
// Check if any of the operands will become dead as well.
MutableArrayRef<Operand> operands = inst->getAllOperands();
for (Operand &operand : operands) {
SILValue operandVal = operand.get();
if (!operandVal)
continue;
// Remove the reference from the instruction being deleted to this
// operand.
operand.drop();
// If the operand is an instruction that is only used by the instruction
// being deleted, delete it.
if (auto *operandValInst = operandVal->getDefiningInstruction())
if (!deadInsts.count(operandValInst) &&
isInstructionTriviallyDead(operandValInst))
nextInsts.insert(operandValInst);
}
// If we have a function ref inst, we need to especially drop its function
// argument so that it gets a proper ref decrement.
if (auto *fri = dyn_cast<FunctionRefBaseInst>(inst))
fri->dropReferencedFunction();
}
for (auto inst : deadInsts) {
// This will remove this instruction and all its uses.
eraseFromParentWithDebugInsts(inst, callback);
}
nextInsts.swap(deadInsts);
nextInsts.clear();
}
}
/// 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,
CallbackTy callback) {
ArrayRef<SILInstruction *> ai = ArrayRef<SILInstruction *>(inst);
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 &operand : user->getAllOperands()) {
if (auto *operandI = operand.get()->getDefiningInstruction()) {
// Don't recursively delete the instruction we're working on.
// FIXME: what if we're being recursively invoked?
if (operandI != inst) {
operand.drop();
recursivelyDeleteTriviallyDeadInstructions(operandI, 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 inst : insts) {
inst->replaceAllUsesOfAllResultsWithUndef();
inst->eraseFromParent();
}
}
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::DebugValueAddrInst:
case SILInstructionKind::LoadInst:
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::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 arg : cbi->getTrueArgs())
trueArgs.push_back(arg);
for (auto arg : cbi->getFalseArgs())
falseArgs.push_back(arg);
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 arg : bi->getArgs())
args.push_back(arg);
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->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;
}
/// 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, 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.