forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSILVerifier.cpp
4268 lines (3739 loc) · 181 KB
/
SILVerifier.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
//===--- Verifier.cpp - Verification of Swift SIL Code --------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-verifier"
#include "swift/AST/ASTContext.h"
#include "swift/AST/AnyFunctionRef.h"
#include "swift/AST/Decl.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Module.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Range.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/SIL/Dominance.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/PostOrder.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/SILDebugScope.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILOpenedArchetypesTracker.h"
#include "swift/SIL/SILVTable.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SIL/TransitivelyUnreachableBlocks.h"
#include "swift/SIL/TypeLowering.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
using namespace swift;
using Lowering::AbstractionPattern;
// This flag is used only to check that sil-combine can properly
// remove any code after unreachable, thus bringing SIL into
// its canonical form which may get temporarily broken during
// intermediate transformations.
static llvm::cl::opt<bool> SkipUnreachableMustBeLastErrors(
"verify-skip-unreachable-must-be-last",
llvm::cl::init(false));
// The verifier is basically all assertions, so don't compile it with NDEBUG to
// prevent release builds from triggering spurious unused variable warnings.
#ifndef NDEBUG
//===----------------------------------------------------------------------===//
// SILVerifier
//===----------------------------------------------------------------------===//
/// Returns true if A is an opened existential type or is equal to an
/// archetype from F's generic context.
static bool isArchetypeValidInFunction(ArchetypeType *A, SILFunction *F) {
if (!A->getOpenedExistentialType().isNull())
return true;
// Find the primary archetype.
A = A->getPrimary();
// Ok, we have a primary archetype, make sure it is in the nested generic
// environment of our caller.
if (auto *genericEnv = F->getGenericEnvironment())
if (genericEnv->containsPrimaryArchetype(A))
return true;
return false;
}
namespace {
/// Metaprogramming-friendly base class.
template <class Impl>
class SILVerifierBase : public SILVisitor<Impl> {
public:
// visitCLASS calls visitPARENT and checkCLASS.
// checkCLASS does nothing by default.
#define VALUE(CLASS, PARENT) \
void visit##CLASS(CLASS *I) { \
static_cast<Impl*>(this)->visit##PARENT(I); \
static_cast<Impl*>(this)->check##CLASS(I); \
} \
void check##CLASS(CLASS *I) {}
#include "swift/SIL/SILNodes.def"
void visitValueBase(ValueBase *V) {
static_cast<Impl*>(this)->checkValueBase(V);
}
void checkValueBase(ValueBase *V) {}
};
} // end anonymous namespace
namespace {
/// The SIL verifier walks over a SIL function / basic block / instruction,
/// checking and enforcing its invariants.
class SILVerifier : public SILVerifierBase<SILVerifier> {
ModuleDecl *M;
const SILFunction &F;
SILFunctionConventions fnConv;
Lowering::TypeConverter &TC;
SILOpenedArchetypesTracker OpenedArchetypes;
SmallVector<StringRef, 16> DebugVars;
const SILInstruction *CurInstruction = nullptr;
DominanceInfo *Dominance = nullptr;
llvm::Optional<PostOrderFunctionInfo> PostOrderInfo;
llvm::Optional<TransitivelyUnreachableBlocksInfo> UnreachableBlockInfo;
bool SingleFunction = true;
SILVerifier(const SILVerifier&) = delete;
void operator=(const SILVerifier&) = delete;
public:
bool isSILOwnershipEnabled() const {
return F.getModule().getOptions().EnableSILOwnership;
}
bool areCOWExistentialsEnabled() const {
return F.getModule().getOptions().UseCOWExistentials;
}
void _require(bool condition, const Twine &complaint,
const std::function<void()> &extraContext = nullptr) {
if (condition) return;
llvm::dbgs() << "SIL verification failed: " << complaint << "\n";
if (extraContext) extraContext();
if (CurInstruction) {
llvm::dbgs() << "Verifying instruction:\n";
CurInstruction->printInContext(llvm::dbgs());
llvm::dbgs() << "In function:\n";
F.print(llvm::dbgs());
} else {
llvm::dbgs() << "In function:\n";
F.print(llvm::dbgs());
}
abort();
}
#define require(condition, complaint) \
_require(bool(condition), complaint ": " #condition)
template <class T> typename CanTypeWrapperTraits<T>::type
_requireObjectType(SILType type, const Twine &valueDescription,
const char *typeName) {
_require(type.isObject(), valueDescription + " must be an object");
auto result = type.getAs<T>();
_require(bool(result), valueDescription + " must have type " + typeName);
return result;
}
template <class T> typename CanTypeWrapperTraits<T>::type
_requireObjectType(SILValue value, const Twine &valueDescription,
const char *typeName) {
return _requireObjectType<T>(value->getType(), valueDescription, typeName);
}
#define requireObjectType(type, value, valueDescription) \
_requireObjectType<type>(value, valueDescription, #type)
template <class T>
typename CanTypeWrapperTraits<T>::type
_forbidObjectType(SILType type, const Twine &valueDescription,
const char *typeName) {
_require(type.isObject(), valueDescription + " must be an object");
auto result = type.getAs<T>();
_require(!bool(result),
valueDescription + " must not have type " + typeName);
return result;
}
template <class T>
typename CanTypeWrapperTraits<T>::type
_forbidObjectType(SILValue value, const Twine &valueDescription,
const char *typeName) {
return _forbidObjectType<T>(value->getType(), valueDescription, typeName);
}
#define forbidObjectType(type, value, valueDescription) \
_forbidObjectType<type>(value, valueDescription, #type)
// Require that the operand is a non-optional, non-unowned reference-counted
// type.
void requireReferenceValue(SILValue value, const Twine &valueDescription) {
require(value->getType().isObject(), valueDescription +" must be an object");
require(value->getType().isReferenceCounted(F.getModule()),
valueDescription + " must have reference semantics");
forbidObjectType(UnownedStorageType, value, valueDescription);
}
// Require that the operand is a reference-counted type, or an Optional
// thereof.
void requireReferenceOrOptionalReferenceValue(SILValue value,
const Twine &valueDescription) {
require(value->getType().isObject(), valueDescription +" must be an object");
auto objectTy = value->getType().unwrapAnyOptionalType();
require(objectTy.isReferenceCounted(F.getModule()),
valueDescription + " must have reference semantics");
}
// Require that the operand is a type that supports reference storage
// modifiers.
void requireReferenceStorageCapableValue(SILValue value,
const Twine &valueDescription) {
requireReferenceOrOptionalReferenceValue(value, valueDescription);
require(!value->getType().is<SILFunctionType>(),
valueDescription + " cannot apply to a function type");
}
/// Assert that two types are equal.
void requireSameType(SILType type1, SILType type2, const Twine &complaint) {
_require(type1 == type2, complaint, [&] {
llvm::dbgs() << " " << type1 << "\n " << type2 << '\n';
});
}
/// Require two function types to be ABI-compatible.
void requireABICompatibleFunctionTypes(CanSILFunctionType type1,
CanSILFunctionType type2,
const Twine &what) {
auto complain = [=](const char *msg) -> std::function<void()> {
return [=]{
llvm::dbgs() << " " << msg << '\n'
<< " " << type1 << "\n " << type2 << '\n';
};
};
auto complainBy = [=](std::function<void()> msg) -> std::function<void()> {
return [=]{
msg();
llvm::dbgs() << '\n';
llvm::dbgs() << " " << type1 << "\n " << type2 << '\n';
};
};
// The calling convention and function representation can't be changed.
_require(type1->getRepresentation() == type2->getRepresentation(), what,
complain("Different function representations"));
// TODO: We should compare generic signatures. Class and witness methods
// allow variance in "self"-fulfilled parameters; other functions must
// match exactly.
// TODO: More sophisticated param and return ABI compatibility rules could
// diverge.
std::function<bool (SILType, SILType)>
areABICompatibleParamsOrReturns = [&](SILType a, SILType b) -> bool {
// Address parameters are all ABI-compatible, though the referenced
// values may not be. Assume whoever's doing this knows what they're
// doing.
if (a.isAddress() && b.isAddress())
return true;
// Addresses aren't compatible with values.
// TODO: An exception for pointerish types?
else if (a.isAddress() || b.isAddress())
return false;
// Tuples are ABI compatible if their elements are.
// TODO: Should destructure recursively.
SmallVector<CanType, 1> aElements, bElements;
if (auto tup = a.getAs<TupleType>()) {
auto types = tup.getElementTypes();
aElements.append(types.begin(), types.end());
} else {
aElements.push_back(a.getSwiftRValueType());
}
if (auto tup = b.getAs<TupleType>()) {
auto types = tup.getElementTypes();
bElements.append(types.begin(), types.end());
} else {
bElements.push_back(b.getSwiftRValueType());
}
if (aElements.size() != bElements.size())
return false;
for (unsigned i : indices(aElements)) {
auto aa = SILType::getPrimitiveObjectType(aElements[i]),
bb = SILType::getPrimitiveObjectType(bElements[i]);
// Equivalent types are always ABI-compatible.
if (aa == bb)
continue;
// FIXME: If one or both types are dependent, we can't accurately assess
// whether they're ABI-compatible without a generic context. We can
// do a better job here when dependent types are related to their
// generic signatures.
if (aa.hasTypeParameter() || bb.hasTypeParameter())
continue;
// Bridgeable object types are interchangeable.
if (aa.isBridgeableObjectType() && bb.isBridgeableObjectType())
continue;
// Optional and IUO are interchangeable if their elements are.
auto aObject = aa.getAnyOptionalObjectType();
auto bObject = bb.getAnyOptionalObjectType();
if (aObject && bObject
&& areABICompatibleParamsOrReturns(aObject, bObject))
continue;
// Optional objects are ABI-interchangeable with non-optionals;
// None is represented by a null pointer.
if (aObject && aObject.isBridgeableObjectType()
&& bb.isBridgeableObjectType())
continue;
if (bObject && bObject.isBridgeableObjectType()
&& aa.isBridgeableObjectType())
continue;
// Optional thick metatypes are ABI-interchangeable with non-optionals
// too.
if (aObject)
if (auto aObjMeta = aObject.getAs<MetatypeType>())
if (auto bMeta = bb.getAs<MetatypeType>())
if (aObjMeta->getRepresentation() == bMeta->getRepresentation()
&& bMeta->getRepresentation() != MetatypeRepresentation::Thin)
continue;
if (bObject)
if (auto aMeta = aa.getAs<MetatypeType>())
if (auto bObjMeta = bObject.getAs<MetatypeType>())
if (aMeta->getRepresentation() == bObjMeta->getRepresentation()
&& aMeta->getRepresentation() != MetatypeRepresentation::Thin)
continue;
// Function types are interchangeable if they're also ABI-compatible.
if (auto aFunc = aa.getAs<SILFunctionType>())
if (auto bFunc = bb.getAs<SILFunctionType>()) {
// FIXME
requireABICompatibleFunctionTypes(aFunc, bFunc, what);
return true;
}
// Metatypes are interchangeable with metatypes with the same
// representation.
if (auto aMeta = aa.getAs<MetatypeType>())
if (auto bMeta = bb.getAs<MetatypeType>())
if (aMeta->getRepresentation() == bMeta->getRepresentation())
continue;
// Other types must match exactly.
return false;
}
return true;
};
// Check the results.
_require(type1->getNumResults() == type2->getNumResults(), what,
complain("different number of results"));
for (unsigned i : indices(type1->getResults())) {
auto result1 = type1->getResults()[i];
auto result2 = type2->getResults()[i];
_require(result1.getConvention() == result2.getConvention(), what,
complain("Different return value conventions"));
_require(areABICompatibleParamsOrReturns(result1.getSILStorageType(),
result2.getSILStorageType()),
what, complain("ABI-incompatible return values"));
}
// Our error result conventions are designed to be ABI compatible
// with functions lacking error results. Just make sure that the
// actual conventions match up.
if (type1->hasErrorResult() && type2->hasErrorResult()) {
auto error1 = type1->getErrorResult();
auto error2 = type2->getErrorResult();
_require(error1.getConvention() == error2.getConvention(), what,
complain("Different error result conventions"));
_require(areABICompatibleParamsOrReturns(error1.getSILStorageType(),
error2.getSILStorageType()),
what, complain("ABI-incompatible error results"));
}
// Check the parameters.
// TODO: Could allow known-empty types to be inserted or removed, but SIL
// doesn't know what empty types are yet.
_require(type1->getParameters().size() == type2->getParameters().size(),
what, complain("different number of parameters"));
for (unsigned i : indices(type1->getParameters())) {
auto param1 = type1->getParameters()[i];
auto param2 = type2->getParameters()[i];
_require(param1.getConvention() == param2.getConvention(), what,
complainBy([=] {
llvm::dbgs() << "Different conventions for parameter " << i;
}));
_require(areABICompatibleParamsOrReturns(param1.getSILStorageType(),
param2.getSILStorageType()),
what, complainBy([=] {
llvm::dbgs() << "ABI-incompatible types for parameter " << i;
}));
}
}
void requireSameFunctionComponents(CanSILFunctionType type1,
CanSILFunctionType type2,
const Twine &what) {
require(type1->getNumResults() == type2->getNumResults(),
"results of " + what + " do not match in count");
for (auto i : indices(type1->getResults())) {
require(type1->getResults()[i] == type2->getResults()[i],
"result " + Twine(i) + " of " + what + " do not match");
}
require(type1->getParameters().size() ==
type2->getParameters().size(),
"inputs of " + what + " do not match in count");
for (auto i : indices(type1->getParameters())) {
require(type1->getParameters()[i] ==
type2->getParameters()[i],
"input " + Twine(i) + " of " + what + " do not match");
}
}
SILVerifier(const SILFunction &F, bool SingleFunction = true)
: M(F.getModule().getSwiftModule()), F(F),
fnConv(F.getLoweredFunctionType(), F.getModule()),
TC(F.getModule().Types), OpenedArchetypes(F), Dominance(nullptr),
PostOrderInfo(), UnreachableBlockInfo(),
SingleFunction(SingleFunction) {
if (F.isExternalDeclaration())
return;
// Check to make sure that all blocks are well formed. If not, the
// SILVerifier object will explode trying to compute dominance info.
for (auto &BB : F) {
require(!BB.empty(), "Basic blocks cannot be empty");
require(isa<TermInst>(BB.back()),
"Basic blocks must end with a terminator instruction");
}
Dominance = new DominanceInfo(const_cast<SILFunction *>(&F));
if (isSILOwnershipEnabled()) {
PostOrderInfo.emplace(const_cast<SILFunction *>(&F));
UnreachableBlockInfo.emplace(PostOrderInfo.getValue());
}
auto *DebugScope = F.getDebugScope();
require(DebugScope, "All SIL functions must have a debug scope");
require(DebugScope->Parent.get<SILFunction *>() == &F,
"Scope of SIL function points to different function");
}
~SILVerifier() {
if (Dominance)
delete Dominance;
}
void visitSILArgument(SILArgument *arg) {
checkLegalType(arg->getFunction(), arg, nullptr);
checkValueBaseOwnership(arg);
}
void visitSILInstruction(SILInstruction *I) {
CurInstruction = I;
OpenedArchetypes.registerOpenedArchetypes(I);
checkSILInstruction(I);
// Check the SILLLocation attached to the instruction.
checkInstructionsSILLocation(I);
checkLegalType(I->getFunction(), I, I);
// Check ownership.
SILFunction *F = I->getFunction();
assert(F && "Expected value base with parent function");
// Check ownership.
checkValueBaseOwnership(I);
}
void checkValueBaseOwnership(ValueBase *V) {
// If ownership is not enabled, bail.
if (!isSILOwnershipEnabled())
return;
// If V does not have a value, bail.
if (!V->hasValue())
return;
SILFunction *F = V->getFunction();
assert(F && "Expected value base with parent function");
// If we do not have qualified ownership, then do not verify value base
// ownership.
if (!F->hasQualifiedOwnership())
return;
SILValue(V).verifyOwnership(F->getModule(),
&UnreachableBlockInfo.getValue());
}
void checkSILInstruction(SILInstruction *I) {
const SILBasicBlock *BB = I->getParent();
require(BB, "Instruction with null parent");
require(I->getFunction(), "Instruction not in function");
// Check that non-terminators look ok.
if (!isa<TermInst>(I)) {
require(!BB->empty(), "Can't be in a parent block if it is empty");
require(&*BB->rbegin() != I,
"Non-terminators cannot be the last in a block");
} else {
// Skip the check for UnreachableInst, if explicitly asked to do so.
if (!isa<UnreachableInst>(I) || !SkipUnreachableMustBeLastErrors)
require(&*BB->rbegin() == I,
"Terminator must be the last in block");
}
// Verify that all of our uses are in this function.
for (Operand *use : I->getUses()) {
auto user = use->getUser();
require(user, "instruction user is null?");
require(isa<SILInstruction>(user),
"instruction used by non-instruction");
auto userI = cast<SILInstruction>(user);
require(userI->getParent(),
"instruction used by unparented instruction");
require(userI->getFunction() == &F,
"instruction used by instruction in different function");
auto operands = userI->getAllOperands();
require(operands.begin() <= use && use <= operands.end(),
"use doesn't actually belong to instruction it claims to");
}
// Verify some basis structural stuff about an instruction's operands.
for (auto &operand : I->getAllOperands()) {
require(operand.get(), "instruction has null operand");
if (auto *valueI = dyn_cast<SILInstruction>(operand.get())) {
require(valueI->getParent(),
"instruction uses value of unparented instruction");
require(valueI->getFunction() == &F,
"instruction uses value of instruction from another function");
require(Dominance->properlyDominates(valueI, I),
"instruction isn't dominated by its operand");
}
if (auto *valueBBA = dyn_cast<SILArgument>(operand.get())) {
require(valueBBA->getParent(),
"instruction uses value of unparented instruction");
require(valueBBA->getFunction() == &F,
"bb argument value from another function");
require(Dominance->dominates(valueBBA->getParent(), I->getParent()),
"instruction isn't dominated by its bb argument operand");
}
require(operand.getUser() == I,
"instruction's operand's owner isn't the instruction");
require(isInValueUses(&operand), "operand value isn't used by operand");
if (I->isTypeDependentOperand(operand)) {
require(isa<SILInstruction>(I),
"opened archetype operand should refer to a SILInstruction");
}
// Make sure that if operand is generic that its primary archetypes match
// the function context.
checkLegalType(I->getFunction(), operand.get(), I);
}
// TODO: There should be a use of an opened archetype inside the instruction for
// each opened archetype operand of the instruction.
}
void checkInstructionsSILLocation(SILInstruction *I) {
// Check the debug scope.
auto *DS = I->getDebugScope();
if (DS && !maybeScopeless(*I))
require(DS, "instruction has a location, but no scope");
require(!DS || DS->getParentFunction() == I->getFunction(),
"debug scope of instruction belongs to a different function");
// Check the location kind.
SILLocation L = I->getLoc();
SILLocation::LocationKind LocKind = L.getKind();
ValueKind InstKind = I->getKind();
// Check that there is at most one debug variable defined
// for each argument slot. This catches SIL transformations
// that accidentally remove inline information (stored in the SILDebugScope)
// from debug-variable-carrying instructions.
if (!DS->InlinedCallSite) {
SILDebugVariable VarInfo;
if (auto *DI = dyn_cast<AllocStackInst>(I)) {
VarInfo = DI->getVarInfo();
} else if (auto *DI = dyn_cast<AllocBoxInst>(I)) {
VarInfo = DI->getVarInfo();
} else if (auto *DI = dyn_cast<DebugValueInst>(I)) {
VarInfo = DI->getVarInfo();
} else if (auto *DI = dyn_cast<DebugValueAddrInst>(I)) {
VarInfo = DI->getVarInfo();
}
if (unsigned ArgNo = VarInfo.ArgNo) {
// It is a function argument.
if (ArgNo < DebugVars.size() && !DebugVars[ArgNo].empty()) {
require(DebugVars[ArgNo] == VarInfo.Name,
"Scope contains conflicting debug variables for one function "
"argument");
} else {
// Reserve enough space.
while (DebugVars.size() <= ArgNo) {
DebugVars.push_back(StringRef());
}
}
DebugVars[ArgNo] = VarInfo.Name;
}
}
// Regular locations are allowed on all instructions.
if (LocKind == SILLocation::RegularKind)
return;
#if 0
// FIXME: This check was tautological before the removal of
// AutoreleaseReturnInst, and it turns out that we're violating it.
// Fix incoming.
if (LocKind == SILLocation::CleanupKind ||
LocKind == SILLocation::InlinedKind)
require(InstKind != ValueKind::ReturnInst ||
InstKind != ValueKind::AutoreleaseReturnInst,
"cleanup and inlined locations are not allowed on return instructions");
#endif
if (LocKind == SILLocation::ReturnKind ||
LocKind == SILLocation::ImplicitReturnKind)
require(InstKind == ValueKind::BranchInst ||
InstKind == ValueKind::ReturnInst ||
InstKind == ValueKind::UnreachableInst,
"return locations are only allowed on branch and return instructions");
if (LocKind == SILLocation::ArtificialUnreachableKind)
require(InstKind == ValueKind::UnreachableInst,
"artificial locations are only allowed on Unreachable instructions");
}
/// Check that the types of this value producer are all legal in the function
/// context in which it exists.
void checkLegalType(SILFunction *F, ValueBase *value, SILInstruction *I) {
if (SILType type = value->getType()) {
checkLegalType(F, type, I);
}
}
/// Check that the given type is a legal SIL value type.
void checkLegalType(SILFunction *F, SILType type, SILInstruction *I) {
checkLegalSILType(F, type.getSwiftRValueType(), I);
}
/// Check that the given type is a legal SIL value type.
void checkLegalSILType(SILFunction *F, CanType rvalueType, SILInstruction *I) {
// These types should have been removed by lowering.
require(!isa<LValueType>(rvalueType),
"l-value types are not legal in SIL");
require(!isa<AnyFunctionType>(rvalueType),
"AST function types are not legal in SIL");
// Tuples should have had their element lowered.
if (auto tuple = dyn_cast<TupleType>(rvalueType)) {
for (auto eltTy : tuple.getElementTypes()) {
checkLegalSILType(F, eltTy, I);
}
return;
}
// Optionals should have had their objects lowered.
OptionalTypeKind optKind;
if (auto objectType = rvalueType.getAnyOptionalObjectType(optKind)) {
require(optKind == OTK_Optional,
"ImplicitlyUnwrappedOptional is not legal in SIL values");
return checkLegalSILType(F, objectType, I);
}
// Metatypes should have explicit representations.
if (auto metatype = dyn_cast<AnyMetatypeType>(rvalueType)) {
require(metatype->hasRepresentation(),
"metatypes in SIL must have a representation");;
// fallthrough for archetype check
}
rvalueType.visit([&](CanType t) {
auto A = dyn_cast<ArchetypeType>(t);
if (!A)
return;
require(isArchetypeValidInFunction(A, F),
"Operand is of an ArchetypeType that does not exist in the "
"Caller's generic param list.");
if (auto OpenedA = getOpenedArchetypeOf(A)) {
auto Def = OpenedArchetypes.getOpenedArchetypeDef(OpenedA);
require (Def, "Opened archetype should be registered in SILFunction");
require(I == nullptr || Def == I ||
Dominance->properlyDominates(cast<SILInstruction>(Def), I),
"Use of an opened archetype should be dominated by a "
"definition of this opened archetype");
}
});
}
/// Check that this operand appears in the use-chain of the value it uses.
static bool isInValueUses(const Operand *operand) {
for (auto use : operand->get()->getUses())
if (use == operand)
return true;
return false;
}
/// \return True if all of the users of the AllocStack instruction \p ASI are
/// inside the same basic block.
static bool isSingleBlockUsage(AllocStackInst *ASI, DominanceInfo *Dominance){
SILBasicBlock *BB = ASI->getParent();
for (auto UI = ASI->use_begin(), E = ASI->use_end(); UI != E; ++UI)
if (UI->getUser()->getParent() != BB &&
Dominance->isReachableFromEntry(UI->getUser()->getParent()))
return false;
return true;
}
void checkAllocStackInst(AllocStackInst *AI) {
require(AI->getType().isAddress(),
"result of alloc_stack must be an address type");
verifyOpenedArchetype(AI, AI->getElementType().getSwiftRValueType());
// Scan the parent block of AI and check that the users of AI inside this
// block are inside the lifetime of the allocated memory.
SILBasicBlock *SBB = AI->getParent();
bool Allocated = true;
for (auto Inst = AI->getIterator(), E = SBB->end(); Inst != E; ++Inst) {
if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
if (LI->getOperand() == AI)
require(Allocated, "AllocStack used by Load outside its lifetime");
if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
if (SI->getDest() == AI)
require(Allocated, "AllocStack used by Store outside its lifetime");
if (DeallocStackInst *DSI = dyn_cast<DeallocStackInst>(Inst))
if (DSI->getOperand() == AI)
Allocated = false;
}
// If the AllocStackInst is also deallocated inside the allocation block
// then make sure that all the users are inside that block.
if (!Allocated) {
require(isSingleBlockUsage(AI, Dominance),
"AllocStack has users in other basic blocks after allocation");
}
}
void checkAllocRefBase(AllocRefInstBase *ARI) {
requireReferenceValue(ARI, "Result of alloc_ref");
verifyOpenedArchetype(ARI, ARI->getType().getSwiftRValueType());
auto Types = ARI->getTailAllocatedTypes();
auto Counts = ARI->getTailAllocatedCounts();
unsigned NumTypes = Types.size();
require(NumTypes == Counts.size(), "Mismatching types and counts");
require(NumTypes == 0 || !ARI->isObjC(),
"Can't tail allocate with ObjC class");
for (unsigned Idx = 0; Idx < NumTypes; ++Idx) {
verifyOpenedArchetype(ARI, Types[Idx].getSwiftRValueType());
require(Counts[Idx].get()->getType().is<BuiltinIntegerType>(),
"count needs integer type");
}
}
void checkAllocRefInst(AllocRefInst *AI) {
require(AI->isObjC() || AI->getType().getClassOrBoundGenericClass(),
"alloc_ref must allocate class");
checkAllocRefBase(AI);
}
void checkAllocRefDynamicInst(AllocRefDynamicInst *ARDI) {
SILValue Metadata = ARDI->getMetatypeOperand();
require(Metadata->getType().is<AnyMetatypeType>(),
"operand of alloc_ref_dynamic must be of metatype type");
auto metaTy = Metadata->getType().castTo<AnyMetatypeType>();
require(metaTy->hasRepresentation(),
"operand of alloc_ref_dynamic must have a metatype representation");
if (ARDI->isObjC()) {
require(metaTy->getRepresentation() == MetatypeRepresentation::ObjC,
"alloc_ref_dynamic @objc requires operand of ObjC metatype");
} else {
require(metaTy->getRepresentation() == MetatypeRepresentation::Thick,
"alloc_ref_dynamic requires operand of thick metatype");
}
checkAllocRefBase(ARDI);
}
/// Check the substitutions passed to an apply or partial_apply.
CanSILFunctionType checkApplySubstitutions(SubstitutionList subs,
SILType calleeTy) {
auto fnTy = requireObjectType(SILFunctionType, calleeTy, "callee operand");
// If there are substitutions, verify them and apply them to the callee.
if (subs.empty()) {
require(!fnTy->isPolymorphic(),
"callee of apply without substitutions must not be polymorphic");
return fnTy;
}
require(fnTy->isPolymorphic(),
"callee of apply with substitutions must be polymorphic");
// Apply the substitutions.
return fnTy->substGenericArgs(F.getModule(), subs);
}
/// Check that for each opened archetype or dynamic self type in substitutions
/// or the calle type, there is a type dependent operand.
void checkApplyTypeDependentArguments(ApplySite AS) {
SILInstruction *AI = AS.getInstruction();
llvm::DenseSet<ArchetypeType *> FoundOpenedArchetypes;
unsigned hasDynamicSelf = 0;
// Function to collect opened archetypes in FoundOpenedArchetypes and set
// hasDynamicSelf.
auto HandleType = [&](CanType Ty) {
if (Ty->isOpenedExistential()) {
auto A = cast<ArchetypeType>(Ty);
require(isArchetypeValidInFunction(A, AI->getFunction()),
"Archetype to be substituted must be valid in function.");
// Collect all opened archetypes used in the substitutions list.
FoundOpenedArchetypes.insert(A);
// Also check that they are properly tracked inside the current
// function.
auto Def = OpenedArchetypes.getOpenedArchetypeDef(A);
require(Def, "Opened archetype should be registered in SILFunction");
require(Def == AI ||
Dominance->properlyDominates(cast<SILInstruction>(Def), AI),
"Use of an opened archetype should be dominated by a "
"definition of this opened archetype");
}
if (Ty->hasDynamicSelfType()) {
hasDynamicSelf = 1;
}
};
// Search for opened archetypes and dynamic self.
for (auto &Sub : AS.getSubstitutions()) {
Sub.getReplacement()->getCanonicalType().visit(HandleType);
}
AS.getSubstCalleeType().visit(HandleType);
require(FoundOpenedArchetypes.size() + hasDynamicSelf ==
AI->getTypeDependentOperands().size(),
"Number of opened archetypes and dynamic self in the substitutions "
"list should match the number of type dependent operands");
for (auto &Op : AI->getTypeDependentOperands()) {
auto V = Op.get();
if (isa<SILArgument>(V)) {
require(hasDynamicSelf,
"dynamic self operand without dynamic self type");
require(AI->getFunction()->hasSelfMetadataParam(),
"self metadata operand in function without self metadata param");
require((ValueBase *)V == AI->getFunction()->getSelfMetadataArgument(),
"wrong self metadata operand");
} else {
require(isa<SILInstruction>(V),
"opened archetype operand should refer to a SIL instruction");
auto Archetype = getOpenedArchetypeOf(cast<SILInstruction>(V));
require(Archetype,
"opened archetype operand should define an opened archetype");
require(FoundOpenedArchetypes.count(Archetype),
"opened archetype operand does not correspond to any opened "
"archetype from the substitutions list");
}
}
}
void checkFullApplySite(FullApplySite site) {
checkApplyTypeDependentArguments(site);
// Then make sure that we have a type that can be substituted for the
// callee.
auto substTy = checkApplySubstitutions(site.getSubstitutions(),
site.getCallee()->getType());
require(site.getOrigCalleeType()->getRepresentation() ==
site.getSubstCalleeType()->getRepresentation(),
"calling convention difference between types");
require(!site.getSubstCalleeType()->isPolymorphic(),
"substituted callee type should not be generic");
requireSameType(SILType::getPrimitiveObjectType(substTy),
SILType::getPrimitiveObjectType(site.getSubstCalleeType()),
"substituted callee type does not match substitutions");
// Check that the arguments and result match.
SILFunctionConventions substConv(substTy, F.getModule());
//require(site.getArguments().size() == substTy->getNumSILArguments(),
require(site.getNumCallArguments() == substConv.getNumSILArguments(),
"apply doesn't have right number of arguments for function");
for (size_t i = 0, size = site.getNumCallArguments(); i < size; ++i) {
requireSameType(site.getArguments()[i]->getType(),
substConv.getSILArgumentType(i),
"operand of 'apply' doesn't match function input type");
}
}
void checkApplyInst(ApplyInst *AI) {
checkFullApplySite(AI);
SILFunctionConventions calleeConv(AI->getSubstCalleeType(), F.getModule());
require(AI->getType() == calleeConv.getSILResultType(),
"type of apply instruction doesn't match function result type");
if (AI->isNonThrowing()) {
require(calleeConv.funcTy->hasErrorResult(),
"nothrow flag used for callee without error result");
} else {
require(!calleeConv.funcTy->hasErrorResult(),
"apply instruction cannot call function with error result");
}
// Check that if the apply is of a noreturn callee, make sure that an
// unreachable is the next instruction.
if (AI->getModule().getStage() == SILStage::Raw ||
!AI->isCalleeNoReturn())
return;
require(isa<UnreachableInst>(std::next(SILBasicBlock::iterator(AI))),
"No return apply without an unreachable as a next instruction.");
}
void checkTryApplyInst(TryApplyInst *AI) {
checkFullApplySite(AI);
SILFunctionConventions calleeConv(AI->getSubstCalleeType(), F.getModule());
auto normalBB = AI->getNormalBB();
require(normalBB->args_size() == 1,
"normal destination of try_apply must take one argument");
requireSameType((*normalBB->args_begin())->getType(),
calleeConv.getSILResultType(),
"normal destination of try_apply must take argument "
"of normal result type");
auto errorBB = AI->getErrorBB();
require(calleeConv.funcTy->hasErrorResult(),
"try_apply must call function with error result");
require(errorBB->args_size() == 1,
"error destination of try_apply must take one argument");
requireSameType((*errorBB->args_begin())->getType(),
calleeConv.getSILErrorType(),
"error destination of try_apply must take argument "
"of error result type");
}
void verifyLLVMIntrinsic(BuiltinInst *BI, llvm::Intrinsic::ID ID) {
// Certain llvm intrinsic require constant values as their operands.
// Consequently, these must not be phi nodes (aka. basic block arguments).
switch (ID) {
default:
break;
case llvm::Intrinsic::ctlz: // llvm.ctlz
case llvm::Intrinsic::cttz: // llvm.cttz
break;
case llvm::Intrinsic::memcpy:
case llvm::Intrinsic::memmove:
case llvm::Intrinsic::memset:
require(!isa<SILArgument>(BI->getArguments()[3]),
"alignment argument of memory intrinsics must be an integer "
"literal");
require(!isa<SILArgument>(BI->getArguments()[4]),
"isvolatile argument of memory intrinsics must be an integer "
"literal");
break;
case llvm::Intrinsic::lifetime_start:
case llvm::Intrinsic::lifetime_end:
case llvm::Intrinsic::invariant_start:
require(!isa<SILArgument>(BI->getArguments()[0]),
"size argument of memory use markers must be an integer literal");
break;
case llvm::Intrinsic::invariant_end:
require(!isa<SILArgument>(BI->getArguments()[1]),
"llvm.invariant.end parameter #2 must be an integer literal");
break;
}
}
void checkPartialApplyInst(PartialApplyInst *PAI) {
auto resultInfo = requireObjectType(SILFunctionType, PAI,
"result of partial_apply");
verifySILFunctionType(resultInfo);
require(resultInfo->getExtInfo().hasContext(),
"result of closure cannot have a thin function type");
checkApplyTypeDependentArguments(PAI);
auto substTy = checkApplySubstitutions(PAI->getSubstitutions(),
PAI->getCallee()->getType());