88#include "llvm/IR/IntrinsicsAArch64.h"
89#include "llvm/IR/IntrinsicsARM.h"
90#include "llvm/IR/IntrinsicsWebAssembly.h"
121 cl::desc(
"Ensure that llvm.experimental.noalias.scope.decl for identical "
122 "scopes are not dominating"));
150 void Write(
const Value *V) {
155 void Write(
const Value &V) {
156 if (isa<Instruction>(V)) {
160 V.printAsOperand(*
OS,
true,
MST);
183 void Write(
Type *
T) {
195 void Write(
const APInt *AI) {
201 void Write(
const unsigned i) { *
OS << i <<
'\n'; }
207 *
OS <<
A->getAsString() <<
'\n';
225 for (
const T &V : Vs)
229 template <
typename T1,
typename... Ts>
230 void WriteTs(
const T1 &V1,
const Ts &... Vs) {
235 template <
typename... Ts>
void WriteTs() {}
244 *
OS << Message <<
'\n';
252 template <
typename T1,
typename... Ts>
262 *
OS << Message <<
'\n';
268 template <
typename T1,
typename... Ts>
289 static constexpr unsigned ParamMaxAlignment = 1 << 14;
309 Type *LandingPadResultTy;
316 bool HasDebugInfo =
false;
364 SawFrameEscape(
false), TBAAVerifyHelper(this) {
365 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
372 "An instance of this class only works with a specific module!");
384 if (!BB.empty() && BB.back().isTerminator())
388 *
OS <<
"Basic Block in function '" <<
F.getName()
389 <<
"' does not have terminator!\n";
390 BB.printAsOperand(*
OS,
true, MST);
399 verifySiblingFuncletUnwinds();
400 InstsInThisBlock.
clear();
402 LandingPadResultTy =
nullptr;
403 SawFrameEscape =
false;
404 SiblingFuncletInfo.
clear();
405 verifyNoAliasScopeDecl();
406 NoAliasScopeDecls.
clear();
417 if (
F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
422 verifyFrameRecoverIndices();
424 visitGlobalVariable(GV);
427 visitGlobalAlias(GA);
430 visitGlobalIFunc(GI);
433 visitNamedMDNode(NMD);
436 visitComdat(SMEC.getValue());
440 visitModuleCommandLines();
442 verifyCompileUnits();
444 verifyDeoptimizeCallingConvs();
445 DISubprogramAttachments.
clear();
451 enum class AreDebugLocsAllowed {
No,
Yes };
462 void visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs);
465 void visitComdat(
const Comdat &
C);
466 void visitModuleIdents();
467 void visitModuleCommandLines();
468 void visitModuleFlags();
469 void visitModuleFlag(
const MDNode *Op,
472 void visitModuleFlagCGProfileEntry(
const MDOperand &MDO);
478 void visitCallStackMetadata(
MDNode *MD);
482 void visitAnnotationMetadata(
MDNode *Annotation);
483 void visitAliasScopeMetadata(
const MDNode *MD);
484 void visitAliasScopeListMetadata(
const MDNode *MD);
485 void visitAccessGroupMetadata(
const MDNode *MD);
487 template <
class Ty>
bool isValidMetadataArray(
const MDTuple &
N);
488#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
489#include "llvm/IR/Metadata.def"
490 void visitDIScope(
const DIScope &
N);
514 void visitPHINode(
PHINode &PN);
523 void visitVAArgInst(
VAArgInst &VAA) { visitInstruction(VAA); }
561 void verifySwiftErrorCall(
CallBase &Call,
const Value *SwiftErrorVal);
562 void verifySwiftErrorValue(
const Value *SwiftErrorVal);
564 void verifyMustTailCall(
CallInst &CI);
565 bool verifyAttributeCount(
AttributeList Attrs,
unsigned Params);
571 const Value *V,
bool IsIntrinsic,
bool IsInlineAsm);
572 void verifyFunctionMetadata(
ArrayRef<std::pair<unsigned, MDNode *>> MDs);
574 void visitConstantExprsRecursively(
const Constant *EntryC);
576 void verifyInlineAsmCall(
const CallBase &Call);
577 void verifyStatepoint(
const CallBase &Call);
578 void verifyFrameRecoverIndices();
579 void verifySiblingFuncletUnwinds();
582 template <
typename ValueOrMetadata>
583 void verifyFragmentExpression(
const DIVariable &V,
585 ValueOrMetadata *Desc);
590 void verifyCompileUnits();
594 void verifyDeoptimizeCallingConvs();
596 void verifyAttachedCallBundle(
const CallBase &Call,
603 void verifyNoAliasScopeDecl();
609#define Check(C, ...) \
612 CheckFailed(__VA_ARGS__); \
619#define CheckDI(C, ...) \
622 DebugInfoCheckFailed(__VA_ARGS__); \
628 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i)
629 Check(
I.getOperand(i) !=
nullptr,
"Operand is null", &
I);
642 while (!WorkList.
empty()) {
644 if (!Visited.
insert(Cur).second)
651void Verifier::visitGlobalValue(
const GlobalValue &GV) {
653 "Global is external, but doesn't have external or weak linkage!", &GV);
655 if (
const GlobalObject *GO = dyn_cast<GlobalObject>(&GV)) {
659 "huge alignment values are unsupported", GO);
662 if (
const MDNode *Associated =
663 GO->getMetadata(LLVMContext::MD_associated)) {
664 Check(Associated->getNumOperands() == 1,
665 "associated metadata must have one operand", &GV, Associated);
666 const Metadata *
Op = Associated->getOperand(0).get();
667 Check(Op,
"associated metadata must have a global value", GO, Associated);
669 const auto *VM = dyn_cast_or_null<ValueAsMetadata>(Op);
670 Check(VM,
"associated metadata must be ValueAsMetadata", GO, Associated);
672 Check(isa<PointerType>(VM->getValue()->getType()),
673 "associated value must be pointer typed", GV, Associated);
676 Check(isa<GlobalObject>(Stripped) || isa<Constant>(Stripped),
677 "associated metadata must point to a GlobalObject", GO, Stripped);
678 Check(Stripped != GO,
679 "global values should not associate to themselves", GO,
685 "Only global variables can have appending linkage!", &GV);
690 "Only global arrays can have appending linkage!", GVar);
694 Check(!GV.
hasComdat(),
"Declaration may not be in a Comdat!", &GV);
698 "dllexport GlobalValue must have default or protected visibility",
703 "dllimport GlobalValue must have default visibility", &GV);
704 Check(!GV.
isDSOLocal(),
"GlobalValue with DLLImport Storage is dso_local!",
710 "Global is marked as dllimport, but not external", &GV);
715 "GlobalValue with local linkage or non-default "
716 "visibility must be dso_local!",
721 if (!
I->getParent() || !
I->getParent()->getParent())
722 CheckFailed(
"Global is referenced by parentless instruction!", &GV, &M,
724 else if (
I->getParent()->getParent()->getParent() != &M)
725 CheckFailed(
"Global is referenced in a different module!", &GV, &M,
I,
726 I->getParent()->getParent(),
727 I->getParent()->getParent()->getParent());
729 }
else if (
const Function *
F = dyn_cast<Function>(V)) {
730 if (
F->getParent() != &M)
731 CheckFailed(
"Global is used by function in a different module", &GV, &M,
742 "Global variable initializer type does not match global "
749 "'common' global must have a zero initializer!", &GV);
752 Check(!GV.
hasComdat(),
"'common' global may not be in a Comdat!", &GV);
757 GV.
getName() ==
"llvm.global_dtors")) {
759 "invalid linkage for intrinsic global variable", &GV);
761 "invalid uses of intrinsic global variable", &GV);
766 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
769 getPointerTo(
DL.getProgramAddressSpace());
773 "wrong type for intrinsic global variable", &GV);
775 "the third field of the element type is mandatory, "
776 "specify ptr null to migrate from the obsoleted 2-field form");
780 cast<PointerType>(ETy)->isOpaqueOrPointeeTypeMatches(Int8Ty),
781 "wrong type for intrinsic global variable", &GV);
786 GV.
getName() ==
"llvm.compiler.used")) {
788 "invalid linkage for intrinsic global variable", &GV);
790 "invalid uses of intrinsic global variable", &GV);
793 if (
ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
794 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
795 Check(PTy,
"wrong type for intrinsic global variable", &GV);
799 Check(InitArray,
"wrong initalizer for intrinsic global variable",
803 Check(isa<GlobalVariable>(V) || isa<Function>(V) ||
807 Twine(
"members of ") + GV.
getName() +
" must be named", V);
816 for (
auto *MD : MDs) {
817 if (
auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
818 visitDIGlobalVariableExpression(*GVE);
820 CheckDI(
false,
"!dbg attachment of global variable must be a "
821 "DIGlobalVariableExpression");
829 "Globals cannot contain scalable vectors", &GV);
831 if (
auto *STy = dyn_cast<StructType>(GV.
getValueType()))
833 "Globals cannot contain scalable vectors", &GV);
837 if (
auto *TTy = dyn_cast<TargetExtType>(GV.
getValueType()))
839 "Global @" + GV.
getName() +
" has illegal target extension type",
843 visitGlobalValue(GV);
850 visitGlobalValue(GV);
856 visitAliaseeSubExpr(Visited, GA,
C);
862 Check(isa<GlobalValue>(
C) &&
863 cast<GlobalValue>(
C).hasAvailableExternallyLinkage(),
864 "available_externally alias must point to available_externally "
868 if (
const auto *GV = dyn_cast<GlobalValue>(&
C)) {
874 if (
const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
875 Check(Visited.
insert(GA2).second,
"Aliases cannot form a cycle", &GA);
877 Check(!GA2->isInterposable(),
878 "Alias cannot point to an interposable alias", &GA);
886 if (
const auto *CE = dyn_cast<ConstantExpr>(&
C))
887 visitConstantExprsRecursively(CE);
889 for (
const Use &U :
C.operands()) {
891 if (
const auto *GA2 = dyn_cast<GlobalAlias>(V))
892 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
893 else if (
const auto *C2 = dyn_cast<Constant>(V))
894 visitAliaseeSubExpr(Visited, GA, *C2);
898void Verifier::visitGlobalAlias(
const GlobalAlias &GA) {
900 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
901 "weak_odr, external, or available_externally linkage!",
904 Check(Aliasee,
"Aliasee cannot be NULL!", &GA);
906 "Alias and aliasee types should match!", &GA);
908 Check(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
909 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
911 visitAliaseeSubExpr(GA, *Aliasee);
913 visitGlobalValue(GA);
916void Verifier::visitGlobalIFunc(
const GlobalIFunc &GI) {
918 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
919 "weak_odr, or external linkage!",
926 "IFunc resolver must be a definition", &GI);
932 Check(isa<PointerType>(
Resolver->getFunctionType()->getReturnType()),
933 "IFunc resolver must return a pointer", &GI);
935 const Type *ResolverFuncTy =
938 "IFunc resolver has incorrect type", &GI);
941void Verifier::visitNamedMDNode(
const NamedMDNode &NMD) {
946 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
948 if (NMD.
getName() ==
"llvm.dbg.cu")
949 CheckDI(MD && isa<DICompileUnit>(MD),
"invalid compile unit", &NMD, MD);
954 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
958void Verifier::visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
961 if (!MDNodes.
insert(&MD).second)
965 "MDNode context does not match Module context!", &MD);
970 case Metadata::MDTupleKind:
972#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
973 case Metadata::CLASS##Kind: \
974 visit##CLASS(cast<CLASS>(MD)); \
976#include "llvm/IR/Metadata.def"
982 Check(!isa<LocalAsMetadata>(Op),
"Invalid operand for global metadata!",
984 CheckDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,
985 "DILocation not allowed within this metadata node", &MD, Op);
986 if (
auto *
N = dyn_cast<MDNode>(Op)) {
987 visitMDNode(*
N, AllowLocs);
990 if (
auto *V = dyn_cast<ValueAsMetadata>(Op)) {
991 visitValueAsMetadata(*V,
nullptr);
1004 "Unexpected metadata round-trip through values", &MD, MD.
getValue());
1006 auto *
L = dyn_cast<LocalAsMetadata>(&MD);
1010 Check(
F,
"function-local metadata used outside a function", L);
1015 if (
Instruction *
I = dyn_cast<Instruction>(
L->getValue())) {
1016 Check(
I->getParent(),
"function-local metadata not in basic block", L,
I);
1017 ActualF =
I->getParent()->getParent();
1018 }
else if (
BasicBlock *BB = dyn_cast<BasicBlock>(
L->getValue()))
1020 else if (
Argument *
A = dyn_cast<Argument>(
L->getValue()))
1021 ActualF =
A->getParent();
1022 assert(ActualF &&
"Unimplemented function local metadata case!");
1024 Check(ActualF ==
F,
"function-local metadata used in wrong function", L);
1029 if (
auto *
N = dyn_cast<MDNode>(MD)) {
1030 visitMDNode(*
N, AreDebugLocsAllowed::No);
1036 if (!MDNodes.
insert(MD).second)
1039 if (
auto *V = dyn_cast<ValueAsMetadata>(MD))
1040 visitValueAsMetadata(*V,
F);
1047void Verifier::visitDILocation(
const DILocation &
N) {
1048 CheckDI(
N.getRawScope() && isa<DILocalScope>(
N.getRawScope()),
1049 "location requires a valid scope", &
N,
N.getRawScope());
1050 if (
auto *IA =
N.getRawInlinedAt())
1051 CheckDI(isa<DILocation>(IA),
"inlined-at should be a location", &
N, IA);
1052 if (
auto *SP = dyn_cast<DISubprogram>(
N.getRawScope()))
1053 CheckDI(SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1060void Verifier::visitDIScope(
const DIScope &
N) {
1061 if (
auto *
F =
N.getRawFile())
1062 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1065void Verifier::visitDISubrange(
const DISubrange &
N) {
1066 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1068 CheckDI(HasAssumedSizedArraySupport ||
N.getRawCountNode() ||
1069 N.getRawUpperBound(),
1070 "Subrange must contain count or upperBound", &
N);
1071 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1072 "Subrange can have any one of count or upperBound", &
N);
1073 auto *CBound =
N.getRawCountNode();
1074 CheckDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
1075 isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1076 "Count must be signed constant or DIVariable or DIExpression", &
N);
1077 auto Count =
N.getCount();
1080 "invalid subrange count", &
N);
1081 auto *LBound =
N.getRawLowerBound();
1082 CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
1083 isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1084 "LowerBound must be signed constant or DIVariable or DIExpression",
1086 auto *UBound =
N.getRawUpperBound();
1087 CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
1088 isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1089 "UpperBound must be signed constant or DIVariable or DIExpression",
1091 auto *Stride =
N.getRawStride();
1092 CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
1093 isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1094 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1098 CheckDI(
N.getTag() == dwarf::DW_TAG_generic_subrange,
"invalid tag", &
N);
1099 CheckDI(
N.getRawCountNode() ||
N.getRawUpperBound(),
1100 "GenericSubrange must contain count or upperBound", &
N);
1101 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1102 "GenericSubrange can have any one of count or upperBound", &
N);
1103 auto *CBound =
N.getRawCountNode();
1104 CheckDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1105 "Count must be signed constant or DIVariable or DIExpression", &
N);
1106 auto *LBound =
N.getRawLowerBound();
1107 CheckDI(LBound,
"GenericSubrange must contain lowerBound", &
N);
1108 CheckDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1109 "LowerBound must be signed constant or DIVariable or DIExpression",
1111 auto *UBound =
N.getRawUpperBound();
1112 CheckDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1113 "UpperBound must be signed constant or DIVariable or DIExpression",
1115 auto *Stride =
N.getRawStride();
1116 CheckDI(Stride,
"GenericSubrange must contain stride", &
N);
1117 CheckDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1118 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1122 CheckDI(
N.getTag() == dwarf::DW_TAG_enumerator,
"invalid tag", &
N);
1126 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type ||
1127 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1128 N.getTag() == dwarf::DW_TAG_string_type,
1133 CheckDI(
N.getTag() == dwarf::DW_TAG_string_type,
"invalid tag", &
N);
1134 CheckDI(!(
N.isBigEndian() &&
N.isLittleEndian()),
"has conflicting flags",
1142 CheckDI(
N.getTag() == dwarf::DW_TAG_typedef ||
1143 N.getTag() == dwarf::DW_TAG_pointer_type ||
1144 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1145 N.getTag() == dwarf::DW_TAG_reference_type ||
1146 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1147 N.getTag() == dwarf::DW_TAG_const_type ||
1148 N.getTag() == dwarf::DW_TAG_immutable_type ||
1149 N.getTag() == dwarf::DW_TAG_volatile_type ||
1150 N.getTag() == dwarf::DW_TAG_restrict_type ||
1151 N.getTag() == dwarf::DW_TAG_atomic_type ||
1152 N.getTag() == dwarf::DW_TAG_member ||
1153 N.getTag() == dwarf::DW_TAG_inheritance ||
1154 N.getTag() == dwarf::DW_TAG_friend ||
1155 N.getTag() == dwarf::DW_TAG_set_type,
1157 if (
N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1158 CheckDI(
isType(
N.getRawExtraData()),
"invalid pointer to member type", &
N,
1159 N.getRawExtraData());
1162 if (
N.getTag() == dwarf::DW_TAG_set_type) {
1163 if (
auto *
T =
N.getRawBaseType()) {
1164 auto *
Enum = dyn_cast_or_null<DICompositeType>(
T);
1165 auto *
Basic = dyn_cast_or_null<DIBasicType>(
T);
1167 (Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1168 (
Basic && (
Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1169 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1170 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1171 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1172 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1173 "invalid set base type", &
N,
T);
1179 N.getRawBaseType());
1181 if (
N.getDWARFAddressSpace()) {
1182 CheckDI(
N.getTag() == dwarf::DW_TAG_pointer_type ||
1183 N.getTag() == dwarf::DW_TAG_reference_type ||
1184 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1185 "DWARF address space only applies to pointer or reference types",
1192 return ((
Flags & DINode::FlagLValueReference) &&
1193 (
Flags & DINode::FlagRValueReference)) ||
1194 ((
Flags & DINode::FlagTypePassByValue) &&
1195 (
Flags & DINode::FlagTypePassByReference));
1198void Verifier::visitTemplateParams(
const MDNode &
N,
const Metadata &RawParams) {
1199 auto *Params = dyn_cast<MDTuple>(&RawParams);
1200 CheckDI(Params,
"invalid template params", &
N, &RawParams);
1201 for (
Metadata *Op : Params->operands()) {
1202 CheckDI(Op && isa<DITemplateParameter>(Op),
"invalid template parameter",
1211 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type ||
1212 N.getTag() == dwarf::DW_TAG_structure_type ||
1213 N.getTag() == dwarf::DW_TAG_union_type ||
1214 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1215 N.getTag() == dwarf::DW_TAG_class_type ||
1216 N.getTag() == dwarf::DW_TAG_variant_part ||
1217 N.getTag() == dwarf::DW_TAG_namelist,
1222 N.getRawBaseType());
1224 CheckDI(!
N.getRawElements() || isa<MDTuple>(
N.getRawElements()),
1225 "invalid composite elements", &
N,
N.getRawElements());
1227 N.getRawVTableHolder());
1229 "invalid reference flags", &
N);
1230 unsigned DIBlockByRefStruct = 1 << 4;
1231 CheckDI((
N.getFlags() & DIBlockByRefStruct) == 0,
1232 "DIBlockByRefStruct on DICompositeType is no longer supported", &
N);
1235 const DINodeArray
Elements =
N.getElements();
1237 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1238 "invalid vector, expected one element of type subrange", &
N);
1241 if (
auto *Params =
N.getRawTemplateParams())
1242 visitTemplateParams(
N, *Params);
1244 if (
auto *
D =
N.getRawDiscriminator()) {
1245 CheckDI(isa<DIDerivedType>(
D) &&
N.getTag() == dwarf::DW_TAG_variant_part,
1246 "discriminator can only appear on variant part");
1249 if (
N.getRawDataLocation()) {
1250 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1251 "dataLocation can only appear in array type");
1254 if (
N.getRawAssociated()) {
1255 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1256 "associated can only appear in array type");
1259 if (
N.getRawAllocated()) {
1260 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1261 "allocated can only appear in array type");
1264 if (
N.getRawRank()) {
1265 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1266 "rank can only appear in array type");
1271 CheckDI(
N.getTag() == dwarf::DW_TAG_subroutine_type,
"invalid tag", &
N);
1272 if (
auto *Types =
N.getRawTypeArray()) {
1273 CheckDI(isa<MDTuple>(Types),
"invalid composite elements", &
N, Types);
1274 for (
Metadata *Ty :
N.getTypeArray()->operands()) {
1275 CheckDI(
isType(Ty),
"invalid subroutine type ref", &
N, Types, Ty);
1279 "invalid reference flags", &
N);
1282void Verifier::visitDIFile(
const DIFile &
N) {
1283 CheckDI(
N.getTag() == dwarf::DW_TAG_file_type,
"invalid tag", &
N);
1284 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum =
N.getChecksum();
1287 "invalid checksum kind", &
N);
1289 switch (Checksum->Kind) {
1300 CheckDI(Checksum->Value.size() ==
Size,
"invalid checksum length", &
N);
1302 "invalid checksum", &
N);
1307 CheckDI(
N.isDistinct(),
"compile units must be distinct", &
N);
1308 CheckDI(
N.getTag() == dwarf::DW_TAG_compile_unit,
"invalid tag", &
N);
1312 CheckDI(
N.getRawFile() && isa<DIFile>(
N.getRawFile()),
"invalid file", &
N,
1314 CheckDI(!
N.getFile()->getFilename().empty(),
"invalid filename", &
N,
1319 verifySourceDebugInfo(
N, *
N.getFile());
1322 "invalid emission kind", &
N);
1324 if (
auto *Array =
N.getRawEnumTypes()) {
1325 CheckDI(isa<MDTuple>(Array),
"invalid enum list", &
N, Array);
1326 for (
Metadata *Op :
N.getEnumTypes()->operands()) {
1327 auto *
Enum = dyn_cast_or_null<DICompositeType>(Op);
1328 CheckDI(Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1329 "invalid enum type", &
N,
N.getEnumTypes(), Op);
1332 if (
auto *Array =
N.getRawRetainedTypes()) {
1333 CheckDI(isa<MDTuple>(Array),
"invalid retained type list", &
N, Array);
1334 for (
Metadata *Op :
N.getRetainedTypes()->operands()) {
1336 Op && (isa<DIType>(Op) || (isa<DISubprogram>(Op) &&
1337 !cast<DISubprogram>(Op)->isDefinition())),
1338 "invalid retained type", &
N, Op);
1341 if (
auto *Array =
N.getRawGlobalVariables()) {
1342 CheckDI(isa<MDTuple>(Array),
"invalid global variable list", &
N, Array);
1343 for (
Metadata *Op :
N.getGlobalVariables()->operands()) {
1344 CheckDI(Op && (isa<DIGlobalVariableExpression>(Op)),
1345 "invalid global variable ref", &
N, Op);
1348 if (
auto *Array =
N.getRawImportedEntities()) {
1349 CheckDI(isa<MDTuple>(Array),
"invalid imported entity list", &
N, Array);
1350 for (
Metadata *Op :
N.getImportedEntities()->operands()) {
1351 CheckDI(Op && isa<DIImportedEntity>(Op),
"invalid imported entity ref",
1355 if (
auto *Array =
N.getRawMacros()) {
1356 CheckDI(isa<MDTuple>(Array),
"invalid macro list", &
N, Array);
1357 for (
Metadata *Op :
N.getMacros()->operands()) {
1358 CheckDI(Op && isa<DIMacroNode>(Op),
"invalid macro ref", &
N, Op);
1365 CheckDI(
N.getTag() == dwarf::DW_TAG_subprogram,
"invalid tag", &
N);
1367 if (
auto *
F =
N.getRawFile())
1368 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1370 CheckDI(
N.getLine() == 0,
"line specified with no file", &
N,
N.getLine());
1371 if (
auto *
T =
N.getRawType())
1372 CheckDI(isa<DISubroutineType>(
T),
"invalid subroutine type", &
N,
T);
1373 CheckDI(
isType(
N.getRawContainingType()),
"invalid containing type", &
N,
1374 N.getRawContainingType());
1375 if (
auto *Params =
N.getRawTemplateParams())
1376 visitTemplateParams(
N, *Params);
1377 if (
auto *S =
N.getRawDeclaration())
1378 CheckDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
1379 "invalid subprogram declaration", &
N, S);
1380 if (
auto *RawNode =
N.getRawRetainedNodes()) {
1381 auto *
Node = dyn_cast<MDTuple>(RawNode);
1382 CheckDI(
Node,
"invalid retained nodes list", &
N, RawNode);
1384 CheckDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op)),
1385 "invalid retained nodes, expected DILocalVariable or DILabel", &
N,
1390 "invalid reference flags", &
N);
1392 auto *Unit =
N.getRawUnit();
1393 if (
N.isDefinition()) {
1395 CheckDI(
N.isDistinct(),
"subprogram definitions must be distinct", &
N);
1396 CheckDI(Unit,
"subprogram definitions must have a compile unit", &
N);
1397 CheckDI(isa<DICompileUnit>(Unit),
"invalid unit type", &
N, Unit);
1399 verifySourceDebugInfo(*
N.getUnit(), *
N.getFile());
1402 CheckDI(!Unit,
"subprogram declarations must not have a compile unit", &
N);
1404 "subprogram declaration must not have a declaration field");
1407 if (
auto *RawThrownTypes =
N.getRawThrownTypes()) {
1408 auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
1409 CheckDI(ThrownTypes,
"invalid thrown types list", &
N, RawThrownTypes);
1410 for (
Metadata *Op : ThrownTypes->operands())
1411 CheckDI(Op && isa<DIType>(Op),
"invalid thrown type", &
N, ThrownTypes,
1415 if (
N.areAllCallsDescribed())
1417 "DIFlagAllCallsDescribed must be attached to a definition");
1421 CheckDI(
N.getTag() == dwarf::DW_TAG_lexical_block,
"invalid tag", &
N);
1422 CheckDI(
N.getRawScope() && isa<DILocalScope>(
N.getRawScope()),
1423 "invalid local scope", &
N,
N.getRawScope());
1424 if (
auto *SP = dyn_cast<DISubprogram>(
N.getRawScope()))
1425 CheckDI(SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1429 visitDILexicalBlockBase(
N);
1432 "cannot have column info without line info", &
N);
1436 visitDILexicalBlockBase(
N);
1440 CheckDI(
N.getTag() == dwarf::DW_TAG_common_block,
"invalid tag", &
N);
1441 if (
auto *S =
N.getRawScope())
1442 CheckDI(isa<DIScope>(S),
"invalid scope ref", &
N, S);
1443 if (
auto *S =
N.getRawDecl())
1444 CheckDI(isa<DIGlobalVariable>(S),
"invalid declaration", &
N, S);
1448 CheckDI(
N.getTag() == dwarf::DW_TAG_namespace,
"invalid tag", &
N);
1449 if (
auto *S =
N.getRawScope())
1450 CheckDI(isa<DIScope>(S),
"invalid scope ref", &
N, S);
1453void Verifier::visitDIMacro(
const DIMacro &
N) {
1456 "invalid macinfo type", &
N);
1457 CheckDI(!
N.getName().empty(),
"anonymous macro", &
N);
1458 if (!
N.getValue().empty()) {
1459 assert(
N.getValue().data()[0] !=
' ' &&
"Macro value has a space prefix");
1465 "invalid macinfo type", &
N);
1466 if (
auto *
F =
N.getRawFile())
1467 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1469 if (
auto *Array =
N.getRawElements()) {
1470 CheckDI(isa<MDTuple>(Array),
"invalid macro list", &
N, Array);
1471 for (
Metadata *Op :
N.getElements()->operands()) {
1472 CheckDI(Op && isa<DIMacroNode>(Op),
"invalid macro ref", &
N, Op);
1477void Verifier::visitDIArgList(
const DIArgList &
N) {
1479 "DIArgList should have no operands other than a list of "
1484void Verifier::visitDIModule(
const DIModule &
N) {
1485 CheckDI(
N.getTag() == dwarf::DW_TAG_module,
"invalid tag", &
N);
1486 CheckDI(!
N.getName().empty(),
"anonymous module", &
N);
1494 visitDITemplateParameter(
N);
1496 CheckDI(
N.getTag() == dwarf::DW_TAG_template_type_parameter,
"invalid tag",
1500void Verifier::visitDITemplateValueParameter(
1502 visitDITemplateParameter(
N);
1504 CheckDI(
N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1505 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1506 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1510void Verifier::visitDIVariable(
const DIVariable &
N) {
1511 if (
auto *S =
N.getRawScope())
1512 CheckDI(isa<DIScope>(S),
"invalid scope", &
N, S);
1513 if (
auto *
F =
N.getRawFile())
1514 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1521 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1524 if (
N.isDefinition())
1525 CheckDI(
N.getType(),
"missing global variable type", &
N);
1526 if (
auto *Member =
N.getRawStaticDataMemberDeclaration()) {
1527 CheckDI(isa<DIDerivedType>(Member),
1528 "invalid static data member declaration", &
N, Member);
1537 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1538 CheckDI(
N.getRawScope() && isa<DILocalScope>(
N.getRawScope()),
1539 "local variable requires a valid scope", &
N,
N.getRawScope());
1540 if (
auto Ty =
N.getType())
1541 CheckDI(!isa<DISubroutineType>(Ty),
"invalid type", &
N,
N.getType());
1544void Verifier::visitDIAssignID(
const DIAssignID &
N) {
1545 CheckDI(!
N.getNumOperands(),
"DIAssignID has no arguments", &
N);
1546 CheckDI(
N.isDistinct(),
"DIAssignID must be distinct", &
N);
1549void Verifier::visitDILabel(
const DILabel &
N) {
1550 if (
auto *S =
N.getRawScope())
1551 CheckDI(isa<DIScope>(S),
"invalid scope", &
N, S);
1552 if (
auto *
F =
N.getRawFile())
1553 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1555 CheckDI(
N.getTag() == dwarf::DW_TAG_label,
"invalid tag", &
N);
1556 CheckDI(
N.getRawScope() && isa<DILocalScope>(
N.getRawScope()),
1557 "label requires a valid scope", &
N,
N.getRawScope());
1561 CheckDI(
N.isValid(),
"invalid expression", &
N);
1564void Verifier::visitDIGlobalVariableExpression(
1568 visitDIGlobalVariable(*Var);
1570 visitDIExpression(*Expr);
1571 if (
auto Fragment = Expr->getFragmentInfo())
1572 verifyFragmentExpression(*GVE.
getVariable(), *Fragment, &GVE);
1577 CheckDI(
N.getTag() == dwarf::DW_TAG_APPLE_property,
"invalid tag", &
N);
1578 if (
auto *
T =
N.getRawType())
1580 if (
auto *
F =
N.getRawFile())
1581 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1585 CheckDI(
N.getTag() == dwarf::DW_TAG_imported_module ||
1586 N.getTag() == dwarf::DW_TAG_imported_declaration,
1588 if (
auto *S =
N.getRawScope())
1589 CheckDI(isa<DIScope>(S),
"invalid scope for imported entity", &
N, S);
1594void Verifier::visitComdat(
const Comdat &
C) {
1597 if (
TT.isOSBinFormatCOFF())
1603void Verifier::visitModuleIdents() {
1604 const NamedMDNode *Idents =
M.getNamedMetadata(
"llvm.ident");
1611 Check(
N->getNumOperands() == 1,
1612 "incorrect number of operands in llvm.ident metadata",
N);
1613 Check(dyn_cast_or_null<MDString>(
N->getOperand(0)),
1614 (
"invalid value for llvm.ident metadata entry operand"
1615 "(the operand should be a string)"),
1620void Verifier::visitModuleCommandLines() {
1621 const NamedMDNode *CommandLines =
M.getNamedMetadata(
"llvm.commandline");
1629 Check(
N->getNumOperands() == 1,
1630 "incorrect number of operands in llvm.commandline metadata",
N);
1631 Check(dyn_cast_or_null<MDString>(
N->getOperand(0)),
1632 (
"invalid value for llvm.commandline metadata entry operand"
1633 "(the operand should be a string)"),
1638void Verifier::visitModuleFlags() {
1646 visitModuleFlag(MDN, SeenIDs, Requirements);
1649 for (
const MDNode *Requirement : Requirements) {
1655 CheckFailed(
"invalid requirement on flag, flag is not present in module",
1660 if (
Op->getOperand(2) != ReqValue) {
1661 CheckFailed((
"invalid requirement on flag, "
1662 "flag does not have the required value"),
1670Verifier::visitModuleFlag(
const MDNode *Op,
1675 Check(
Op->getNumOperands() == 3,
1676 "incorrect number of operands in module flag", Op);
1679 Check(mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(0)),
1680 "invalid behavior operand in module flag (expected constant integer)",
1683 "invalid behavior operand in module flag (unexpected constant)",
1686 MDString *
ID = dyn_cast_or_null<MDString>(
Op->getOperand(1));
1687 Check(
ID,
"invalid ID operand in module flag (expected metadata string)",
1699 auto *
V = mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(2));
1700 Check(V &&
V->getValue().isNonNegative(),
1701 "invalid value for 'min' module flag (expected constant non-negative "
1708 Check(mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(2)),
1709 "invalid value for 'max' module flag (expected constant integer)",
1719 "invalid value for 'require' module flag (expected metadata pair)",
1722 (
"invalid value for 'require' module flag "
1723 "(first value operand should be a string)"),
1724 Value->getOperand(0));
1735 Check(isa<MDNode>(
Op->getOperand(2)),
1736 "invalid value for 'append'-type module flag "
1737 "(expected a metadata node)",
1747 "module flag identifiers must be unique (or of 'require' type)",
ID);
1750 if (
ID->getString() ==
"wchar_size") {
1752 = mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(2));
1753 Check(
Value,
"wchar_size metadata requires constant integer argument");
1756 if (
ID->getString() ==
"Linker Options") {
1760 Check(
M.getNamedMetadata(
"llvm.linker.options"),
1761 "'Linker Options' named metadata no longer supported");
1764 if (
ID->getString() ==
"SemanticInterposition") {
1766 mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(2));
1768 "SemanticInterposition metadata requires constant integer argument");
1771 if (
ID->getString() ==
"CG Profile") {
1772 for (
const MDOperand &MDO : cast<MDNode>(
Op->getOperand(2))->operands())
1773 visitModuleFlagCGProfileEntry(MDO);
1777void Verifier::visitModuleFlagCGProfileEntry(
const MDOperand &MDO) {
1778 auto CheckFunction = [&](
const MDOperand &FuncMDO) {
1781 auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
1782 Check(
F && isa<Function>(
F->getValue()->stripPointerCasts()),
1783 "expected a Function or null", FuncMDO);
1785 auto Node = dyn_cast_or_null<MDNode>(MDO);
1786 Check(
Node &&
Node->getNumOperands() == 3,
"expected a MDNode triple", MDO);
1787 CheckFunction(
Node->getOperand(0));
1788 CheckFunction(
Node->getOperand(1));
1789 auto Count = dyn_cast_or_null<ConstantAsMetadata>(
Node->getOperand(2));
1790 Check(Count && Count->getType()->isIntegerTy(),
1791 "expected an integer constant",
Node->getOperand(2));
1797 if (
A.isStringAttribute()) {
1798#define GET_ATTR_NAMES
1799#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1800#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
1801 if (A.getKindAsString() == #DISPLAY_NAME) { \
1802 auto V = A.getValueAsString(); \
1803 if (!(V.empty() || V == "true" || V == "false")) \
1804 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
1808#include "llvm/IR/Attributes.inc"
1813 CheckFailed(
"Attribute '" +
A.getAsString() +
"' should have an Argument",
1824 if (!
Attrs.hasAttributes())
1827 verifyAttributeTypes(Attrs, V);
1830 Check(Attr.isStringAttribute() ||
1832 "Attribute '" + Attr.getAsString() +
"' does not apply to parameters",
1835 if (
Attrs.hasAttribute(Attribute::ImmArg)) {
1837 "Attribute 'immarg' is incompatible with other attributes", V);
1842 unsigned AttrCount = 0;
1843 AttrCount +=
Attrs.hasAttribute(Attribute::ByVal);
1844 AttrCount +=
Attrs.hasAttribute(Attribute::InAlloca);
1845 AttrCount +=
Attrs.hasAttribute(Attribute::Preallocated);
1846 AttrCount +=
Attrs.hasAttribute(Attribute::StructRet) ||
1847 Attrs.hasAttribute(Attribute::InReg);
1848 AttrCount +=
Attrs.hasAttribute(Attribute::Nest);
1849 AttrCount +=
Attrs.hasAttribute(Attribute::ByRef);
1850 Check(AttrCount <= 1,
1851 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
1852 "'byref', and 'sret' are incompatible!",
1855 Check(!(
Attrs.hasAttribute(Attribute::InAlloca) &&
1856 Attrs.hasAttribute(Attribute::ReadOnly)),
1858 "'inalloca and readonly' are incompatible!",
1861 Check(!(
Attrs.hasAttribute(Attribute::StructRet) &&
1862 Attrs.hasAttribute(Attribute::Returned)),
1864 "'sret and returned' are incompatible!",
1867 Check(!(
Attrs.hasAttribute(Attribute::ZExt) &&
1868 Attrs.hasAttribute(Attribute::SExt)),
1870 "'zeroext and signext' are incompatible!",
1873 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
1874 Attrs.hasAttribute(Attribute::ReadOnly)),
1876 "'readnone and readonly' are incompatible!",
1879 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
1880 Attrs.hasAttribute(Attribute::WriteOnly)),
1882 "'readnone and writeonly' are incompatible!",
1885 Check(!(
Attrs.hasAttribute(Attribute::ReadOnly) &&
1886 Attrs.hasAttribute(Attribute::WriteOnly)),
1888 "'readonly and writeonly' are incompatible!",
1891 Check(!(
Attrs.hasAttribute(Attribute::NoInline) &&
1892 Attrs.hasAttribute(Attribute::AlwaysInline)),
1894 "'noinline and alwaysinline' are incompatible!",
1899 if (!Attr.isStringAttribute() &&
1900 IncompatibleAttrs.
contains(Attr.getKindAsEnum())) {
1901 CheckFailed(
"Attribute '" + Attr.getAsString() +
1902 "' applied to incompatible type!", V);
1907 if (
PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1908 if (
Attrs.hasAttribute(Attribute::ByVal)) {
1909 if (
Attrs.hasAttribute(Attribute::Alignment)) {
1910 Align AttrAlign =
Attrs.getAlignment().valueOrOne();
1911 Align MaxAlign(ParamMaxAlignment);
1912 Check(AttrAlign <= MaxAlign,
1913 "Attribute 'align' exceed the max size 2^14", V);
1916 Check(
Attrs.getByValType()->isSized(&Visited),
1917 "Attribute 'byval' does not support unsized types!", V);
1919 if (
Attrs.hasAttribute(Attribute::ByRef)) {
1921 Check(
Attrs.getByRefType()->isSized(&Visited),
1922 "Attribute 'byref' does not support unsized types!", V);
1924 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
1926 Check(
Attrs.getInAllocaType()->isSized(&Visited),
1927 "Attribute 'inalloca' does not support unsized types!", V);
1929 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
1931 Check(
Attrs.getPreallocatedType()->isSized(&Visited),
1932 "Attribute 'preallocated' does not support unsized types!", V);
1934 if (!PTy->isOpaque()) {
1935 if (!isa<PointerType>(PTy->getNonOpaquePointerElementType()))
1936 Check(!
Attrs.hasAttribute(Attribute::SwiftError),
1937 "Attribute 'swifterror' only applies to parameters "
1938 "with pointer to pointer type!",
1940 if (
Attrs.hasAttribute(Attribute::ByRef)) {
1941 Check(
Attrs.getByRefType() == PTy->getNonOpaquePointerElementType(),
1942 "Attribute 'byref' type does not match parameter!", V);
1945 if (
Attrs.hasAttribute(Attribute::ByVal) &&
Attrs.getByValType()) {
1946 Check(
Attrs.getByValType() == PTy->getNonOpaquePointerElementType(),
1947 "Attribute 'byval' type does not match parameter!", V);
1950 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
1952 PTy->getNonOpaquePointerElementType(),
1953 "Attribute 'preallocated' type does not match parameter!", V);
1956 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
1957 Check(
Attrs.getInAllocaType() == PTy->getNonOpaquePointerElementType(),
1958 "Attribute 'inalloca' type does not match parameter!", V);
1961 if (
Attrs.hasAttribute(Attribute::ElementType)) {
1962 Check(
Attrs.getElementType() == PTy->getNonOpaquePointerElementType(),
1963 "Attribute 'elementtype' type does not match parameter!", V);
1968 if (
Attrs.hasAttribute(Attribute::NoFPClass)) {
1969 uint64_t Val =
Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
1970 Check(Val != 0,
"Attribute 'nofpclass' must have at least one test bit set",
1973 "Invalid value for 'nofpclass' test mask", V);
1979 if (
Attrs.hasFnAttr(Attr)) {
1983 CheckFailed(
"\"" + Attr +
"\" takes an unsigned integer: " + S, V);
1990 const Value *V,
bool IsIntrinsic,
1992 if (
Attrs.isEmpty())
1995 if (AttributeListsVisited.
insert(
Attrs.getRawPointer()).second) {
1997 "Attribute list does not match Module context!", &Attrs, V);
1998 for (
const auto &AttrSet : Attrs) {
1999 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
2000 "Attribute set does not match Module context!", &AttrSet, V);
2001 for (
const auto &
A : AttrSet) {
2002 Check(
A.hasParentContext(Context),
2003 "Attribute does not match Module context!", &
A, V);
2008 bool SawNest =
false;
2009 bool SawReturned =
false;
2010 bool SawSRet =
false;
2011 bool SawSwiftSelf =
false;
2012 bool SawSwiftAsync =
false;
2013 bool SawSwiftError =
false;
2020 "Attribute '" +
RetAttr.getAsString() +
2021 "' does not apply to function return values",
2024 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2027 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2028 Type *Ty = FT->getParamType(i);
2033 "immarg attribute only applies to intrinsics", V);
2036 "Attribute 'elementtype' can only be applied to intrinsics"
2041 verifyParameterAttrs(ArgAttrs, Ty, V);
2044 Check(!SawNest,
"More than one parameter has attribute nest!", V);
2049 Check(!SawReturned,
"More than one parameter has attribute returned!", V);
2051 "Incompatible argument and return types for 'returned' attribute",
2057 Check(!SawSRet,
"Cannot have multiple 'sret' parameters!", V);
2058 Check(i == 0 || i == 1,
2059 "Attribute 'sret' is not on first or second parameter!", V);
2064 Check(!SawSwiftSelf,
"Cannot have multiple 'swiftself' parameters!", V);
2065 SawSwiftSelf =
true;
2069 Check(!SawSwiftAsync,
"Cannot have multiple 'swiftasync' parameters!", V);
2070 SawSwiftAsync =
true;
2074 Check(!SawSwiftError,
"Cannot have multiple 'swifterror' parameters!", V);
2075 SawSwiftError =
true;
2079 Check(i == FT->getNumParams() - 1,
2080 "inalloca isn't on the last parameter!", V);
2084 if (!
Attrs.hasFnAttrs())
2087 verifyAttributeTypes(
Attrs.getFnAttrs(), V);
2091 "Attribute '" +
FnAttr.getAsString() +
2092 "' does not apply to functions!",
2095 Check(!(
Attrs.hasFnAttr(Attribute::NoInline) &&
2096 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2097 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2099 if (
Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2101 "Attribute 'optnone' requires 'noinline'!", V);
2103 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2104 "Attributes 'optsize and optnone' are incompatible!", V);
2107 "Attributes 'minsize and optnone' are incompatible!", V);
2110 if (
Attrs.hasFnAttr(
"aarch64_pstate_sm_enabled")) {
2111 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_sm_compatible"),
2112 "Attributes 'aarch64_pstate_sm_enabled and "
2113 "aarch64_pstate_sm_compatible' are incompatible!",
2117 if (
Attrs.hasFnAttr(
"aarch64_pstate_za_new")) {
2118 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_za_preserved"),
2119 "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_preserved' "
2120 "are incompatible!",
2123 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_za_shared"),
2124 "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_shared' "
2125 "are incompatible!",
2129 if (
Attrs.hasFnAttr(Attribute::JumpTable)) {
2132 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2135 if (
auto Args =
Attrs.getFnAttrs().getAllocSizeArgs()) {
2137 if (ParamNo >= FT->getNumParams()) {
2138 CheckFailed(
"'allocsize' " +
Name +
" argument is out of bounds", V);
2142 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2143 CheckFailed(
"'allocsize' " +
Name +
2144 " argument must refer to an integer parameter",
2152 if (!CheckParam(
"element size",
Args->first))
2155 if (
Args->second && !CheckParam(
"number of elements", *
Args->second))
2159 if (
Attrs.hasFnAttr(Attribute::AllocKind)) {
2167 "'allockind()' requires exactly one of alloc, realloc, and free");
2171 CheckFailed(
"'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2172 "or aligned modifiers.");
2174 if ((K & ZeroedUninit) == ZeroedUninit)
2175 CheckFailed(
"'allockind()' can't be both zeroed and uninitialized");
2178 if (
Attrs.hasFnAttr(Attribute::VScaleRange)) {
2179 unsigned VScaleMin =
Attrs.getFnAttrs().getVScaleRangeMin();
2181 CheckFailed(
"'vscale_range' minimum must be greater than 0", V);
2183 std::optional<unsigned> VScaleMax =
Attrs.getFnAttrs().getVScaleRangeMax();
2184 if (VScaleMax && VScaleMin > VScaleMax)
2185 CheckFailed(
"'vscale_range' minimum cannot be greater than maximum", V);
2188 if (
Attrs.hasFnAttr(
"frame-pointer")) {
2190 if (
FP !=
"all" &&
FP !=
"non-leaf" &&
FP !=
"none")
2191 CheckFailed(
"invalid value for 'frame-pointer' attribute: " +
FP, V);
2194 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-prefix", V);
2195 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-entry", V);
2196 checkUnsignedBaseTenFuncAttr(Attrs,
"warn-stack-size", V);
2199void Verifier::verifyFunctionMetadata(
2200 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2201 for (
const auto &Pair : MDs) {
2202 if (Pair.first == LLVMContext::MD_prof) {
2203 MDNode *MD = Pair.second;
2205 "!prof annotations should have no less than 2 operands", MD);
2208 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null",
2211 "expected string with name of the !prof annotation", MD);
2215 ProfName.
equals(
"synthetic_function_entry_count"),
2216 "first operand should be 'function_entry_count'"
2217 " or 'synthetic_function_entry_count'",
2221 Check(MD->
getOperand(1) !=
nullptr,
"second operand should not be null",
2224 "expected integer argument to function_entry_count", MD);
2225 }
else if (Pair.first == LLVMContext::MD_kcfi_type) {
2226 MDNode *MD = Pair.second;
2228 "!kcfi_type must have exactly one operand", MD);
2229 Check(MD->
getOperand(0) !=
nullptr,
"!kcfi_type operand must not be null",
2232 "expected a constant operand for !kcfi_type", MD);
2234 Check(isa<ConstantInt>(
C),
2235 "expected a constant integer operand for !kcfi_type", MD);
2238 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2243void Verifier::visitConstantExprsRecursively(
const Constant *EntryC) {
2244 if (!ConstantExprVisited.
insert(EntryC).second)
2248 Stack.push_back(EntryC);
2250 while (!
Stack.empty()) {
2254 if (
const auto *CE = dyn_cast<ConstantExpr>(
C))
2255 visitConstantExpr(CE);
2257 if (
const auto *GV = dyn_cast<GlobalValue>(
C)) {
2260 Check(GV->
getParent() == &M,
"Referencing global in another module!",
2266 for (
const Use &U :
C->operands()) {
2267 const auto *OpC = dyn_cast<Constant>(U);
2270 if (!ConstantExprVisited.
insert(OpC).second)
2272 Stack.push_back(OpC);
2277void Verifier::visitConstantExpr(
const ConstantExpr *CE) {
2278 if (
CE->getOpcode() == Instruction::BitCast)
2281 "Invalid bitcast", CE);
2284bool Verifier::verifyAttributeCount(
AttributeList Attrs,
unsigned Params) {
2287 return Attrs.getNumAttrSets() <= Params + 2;
2290void Verifier::verifyInlineAsmCall(
const CallBase &Call) {
2293 unsigned LabelNo = 0;
2304 if (CI.isIndirect) {
2306 Check(
Arg->getType()->isPointerTy(),
2307 "Operand for indirect constraint must have pointer type", &Call);
2310 "Operand for indirect constraint must have elementtype attribute",
2313 Check(!
Call.paramHasAttr(ArgNo, Attribute::ElementType),
2314 "Elementtype attribute can only be applied for indirect "
2322 if (
auto *CallBr = dyn_cast<CallBrInst>(&Call)) {
2323 Check(LabelNo == CallBr->getNumIndirectDests(),
2324 "Number of label constraints does not match number of callbr dests",
2327 Check(LabelNo == 0,
"Label constraints can only be used with callbr",
2333void Verifier::verifyStatepoint(
const CallBase &Call) {
2335 Call.getCalledFunction()->getIntrinsicID() ==
2336 Intrinsic::experimental_gc_statepoint);
2338 Check(!
Call.doesNotAccessMemory() && !
Call.onlyReadsMemory() &&
2339 !
Call.onlyAccessesArgMemory(),
2340 "gc.statepoint must read and write all memory to preserve "
2341 "reordering restrictions required by safepoint semantics",
2344 const int64_t NumPatchBytes =
2345 cast<ConstantInt>(
Call.getArgOperand(1))->getSExtValue();
2346 assert(isInt<32>(NumPatchBytes) &&
"NumPatchBytesV is an i32!");
2347 Check(NumPatchBytes >= 0,
2348 "gc.statepoint number of patchable bytes must be "
2352 Type *TargetElemType =
Call.getParamElementType(2);
2353 Check(TargetElemType,
2354 "gc.statepoint callee argument must have elementtype attribute", Call);
2355 FunctionType *TargetFuncType = dyn_cast<FunctionType>(TargetElemType);
2356 Check(TargetFuncType,
2357 "gc.statepoint callee elementtype must be function type", Call);
2359 const int NumCallArgs = cast<ConstantInt>(
Call.getArgOperand(3))->getZExtValue();
2360 Check(NumCallArgs >= 0,
2361 "gc.statepoint number of arguments to underlying call "
2364 const int NumParams = (int)TargetFuncType->getNumParams();
2365 if (TargetFuncType->isVarArg()) {
2366 Check(NumCallArgs >= NumParams,
2367 "gc.statepoint mismatch in number of vararg call args", Call);
2370 Check(TargetFuncType->getReturnType()->isVoidTy(),
2371 "gc.statepoint doesn't support wrapping non-void "
2372 "vararg functions yet",
2375 Check(NumCallArgs == NumParams,
2376 "gc.statepoint mismatch in number of call args", Call);
2379 = cast<ConstantInt>(
Call.getArgOperand(4))->getZExtValue();
2381 "unknown flag used in gc.statepoint flags argument", Call);
2386 for (
int i = 0; i < NumParams; i++) {
2387 Type *ParamType = TargetFuncType->getParamType(i);
2388 Type *ArgType =
Call.getArgOperand(5 + i)->getType();
2389 Check(ArgType == ParamType,
2390 "gc.statepoint call argument does not match wrapped "
2394 if (TargetFuncType->isVarArg()) {
2397 "Attribute 'sret' cannot be used for vararg call arguments!", Call);
2401 const int EndCallArgsInx = 4 + NumCallArgs;
2403 const Value *NumTransitionArgsV =
Call.getArgOperand(EndCallArgsInx + 1);
2404 Check(isa<ConstantInt>(NumTransitionArgsV),
2405 "gc.statepoint number of transition arguments "
2406 "must be constant integer",
2408 const int NumTransitionArgs =
2409 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
2410 Check(NumTransitionArgs == 0,
2411 "gc.statepoint w/inline transition bundle is deprecated", Call);
2412 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2414 const Value *NumDeoptArgsV =
Call.getArgOperand(EndTransitionArgsInx + 1);
2415 Check(isa<ConstantInt>(NumDeoptArgsV),
2416 "gc.statepoint number of deoptimization arguments "
2417 "must be constant integer",
2419 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
2420 Check(NumDeoptArgs == 0,
2421 "gc.statepoint w/inline deopt operands is deprecated", Call);
2423 const int ExpectedNumArgs = 7 + NumCallArgs;
2424 Check(ExpectedNumArgs == (
int)
Call.arg_size(),
2425 "gc.statepoint too many arguments", Call);
2430 for (
const User *U :
Call.users()) {
2431 const CallInst *UserCall = dyn_cast<const CallInst>(U);
2432 Check(UserCall,
"illegal use of statepoint token", Call, U);
2435 Check(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
2436 "gc.result or gc.relocate are the only value uses "
2437 "of a gc.statepoint",
2439 if (isa<GCResultInst>(UserCall)) {
2441 "gc.result connected to wrong gc.statepoint", Call, UserCall);
2442 }
else if (isa<GCRelocateInst>(Call)) {
2444 "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
2458void Verifier::verifyFrameRecoverIndices() {
2459 for (
auto &Counts : FrameEscapeInfo) {
2461 unsigned EscapedObjectCount = Counts.second.first;
2462 unsigned MaxRecoveredIndex = Counts.second.second;
2463 Check(MaxRecoveredIndex <= EscapedObjectCount,
2464 "all indices passed to llvm.localrecover must be less than the "
2465 "number of arguments passed to llvm.localescape in the parent "
2473 if (
auto *II = dyn_cast<InvokeInst>(Terminator))
2474 UnwindDest = II->getUnwindDest();
2475 else if (
auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
2476 UnwindDest = CSI->getUnwindDest();
2478 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
2482void Verifier::verifySiblingFuncletUnwinds() {
2485 for (
const auto &Pair : SiblingFuncletInfo) {
2487 if (Visited.
count(PredPad))
2493 if (Active.
count(SuccPad)) {
2499 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
2500 if (CycleTerminator != CyclePad)
2503 }
while (CyclePad != SuccPad);
2504 Check(
false,
"EH pads can't handle each other's exceptions",
2508 if (!Visited.
insert(SuccPad).second)
2512 auto TermI = SiblingFuncletInfo.find(PredPad);
2513 if (TermI == SiblingFuncletInfo.end())
2526void Verifier::visitFunction(
const Function &
F) {
2527 visitGlobalValue(
F);
2531 unsigned NumArgs =
F.arg_size();
2533 Check(&Context == &
F.getContext(),
2534 "Function context does not match Module context!", &
F);
2536 Check(!
F.hasCommonLinkage(),
"Functions may not have common linkage", &
F);
2537 Check(FT->getNumParams() == NumArgs,
2538 "# formal arguments must match # of arguments for function type!", &
F,
2540 Check(
F.getReturnType()->isFirstClassType() ||
2541 F.getReturnType()->isVoidTy() ||
F.getReturnType()->isStructTy(),
2542 "Functions cannot return aggregate values!", &
F);
2544 Check(!
F.hasStructRetAttr() ||
F.getReturnType()->isVoidTy(),
2545 "Invalid struct return type!", &
F);
2549 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
2550 "Attribute after last parameter!", &
F);
2552 bool IsIntrinsic =
F.isIntrinsic();
2555 verifyFunctionAttrs(FT, Attrs, &
F, IsIntrinsic,
false);
2561 "Attribute 'builtin' can only be applied to a callsite.", &
F);
2563 Check(!
Attrs.hasAttrSomewhere(Attribute::ElementType),
2564 "Attribute 'elementtype' can only be applied to a callsite.", &
F);
2569 switch (
F.getCallingConv()) {
2574 Check(
F.arg_empty() ||
Attrs.hasParamAttr(0, Attribute::ByVal),
2575 "Calling convention parameter requires byval", &
F);
2580 Check(
F.getReturnType()->isVoidTy(),
2581 "Calling convention requires void return type", &
F);
2588 Check(!
F.hasStructRetAttr(),
"Calling convention does not allow sret", &
F);
2590 const unsigned StackAS =
DL.getAllocaAddrSpace();
2593 Check(!
Attrs.hasParamAttr(i, Attribute::ByVal),
2594 "Calling convention disallows byval", &
F);
2595 Check(!
Attrs.hasParamAttr(i, Attribute::Preallocated),
2596 "Calling convention disallows preallocated", &
F);
2597 Check(!
Attrs.hasParamAttr(i, Attribute::InAlloca),
2598 "Calling convention disallows inalloca", &
F);
2600 if (
Attrs.hasParamAttr(i, Attribute::ByRef)) {
2603 Check(
Arg.getType()->getPointerAddressSpace() != StackAS,
2604 "Calling convention disallows stack byref", &
F);
2618 "Calling convention does not support varargs or "
2619 "perfect forwarding!",
2627 Check(
Arg.getType() == FT->getParamType(i),
2628 "Argument value does not match function argument type!", &
Arg,
2629 FT->getParamType(i));
2630 Check(
Arg.getType()->isFirstClassType(),
2631 "Function arguments must have first-class types!", &
Arg);
2633 Check(!
Arg.getType()->isMetadataTy(),
2634 "Function takes metadata but isn't an intrinsic", &
Arg, &
F);
2636 "Function takes token but isn't an intrinsic", &
Arg, &
F);
2637 Check(!
Arg.getType()->isX86_AMXTy(),
2638 "Function takes x86_amx but isn't an intrinsic", &
Arg, &
F);
2642 if (
Attrs.hasParamAttr(i, Attribute::SwiftError)) {
2643 verifySwiftErrorValue(&
Arg);
2649 Check(!
F.getReturnType()->isTokenTy(),
2650 "Function returns a token but isn't an intrinsic", &
F);
2651 Check(!
F.getReturnType()->isX86_AMXTy(),
2652 "Function returns a x86_amx but isn't an intrinsic", &
F);
2657 F.getAllMetadata(MDs);
2658 assert(
F.hasMetadata() != MDs.
empty() &&
"Bit out-of-sync");
2659 verifyFunctionMetadata(MDs);
2662 if (
F.hasPersonalityFn()) {
2663 auto *Per = dyn_cast<Function>(
F.getPersonalityFn()->stripPointerCasts());
2665 Check(Per->getParent() ==
F.getParent(),
2666 "Referencing personality function in another module!", &
F,
2667 F.getParent(), Per, Per->getParent());
2671 BlockEHFuncletColors.
clear();
2673 if (
F.isMaterializable()) {
2675 Check(MDs.
empty(),
"unmaterialized function cannot have metadata", &
F,
2677 }
else if (
F.isDeclaration()) {
2678 for (
const auto &
I : MDs) {
2680 CheckDI(
I.first != LLVMContext::MD_dbg ||
2681 !cast<DISubprogram>(
I.second)->isDistinct(),
2682 "function declaration may only have a unique !dbg attachment",
2684 Check(
I.first != LLVMContext::MD_prof,
2685 "function declaration may not have a !prof attachment", &
F);
2688 visitMDNode(*
I.second, AreDebugLocsAllowed::Yes);
2690 Check(!
F.hasPersonalityFn(),
2691 "Function declaration shouldn't have a personality routine", &
F);
2695 Check(!IsIntrinsic,
"llvm intrinsics cannot be defined!", &
F);
2700 "Entry block to function must not have predecessors!", Entry);
2703 if (Entry->hasAddressTaken()) {
2705 "blockaddress may not be used with the entry block!", Entry);
2708 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
2709 NumKCFIAttachments = 0;
2711 for (
const auto &
I : MDs) {
2713 auto AllowLocs = AreDebugLocsAllowed::No;
2717 case LLVMContext::MD_dbg: {
2718 ++NumDebugAttachments;
2719 CheckDI(NumDebugAttachments == 1,
2720 "function must have a single !dbg attachment", &
F,
I.second);
2721 CheckDI(isa<DISubprogram>(
I.second),
2722 "function !dbg attachment must be a subprogram", &
F,
I.second);
2723 CheckDI(cast<DISubprogram>(
I.second)->isDistinct(),
2724 "function definition may only have a distinct !dbg attachment",
2727 auto *SP = cast<DISubprogram>(
I.second);
2728 const Function *&AttachedTo = DISubprogramAttachments[SP];
2729 CheckDI(!AttachedTo || AttachedTo == &
F,
2730 "DISubprogram attached to more than one function", SP, &
F);
2732 AllowLocs = AreDebugLocsAllowed::Yes;
2735 case LLVMContext::MD_prof:
2736 ++NumProfAttachments;
2737 Check(NumProfAttachments == 1,
2738 "function must have a single !prof attachment", &
F,
I.second);
2740 case LLVMContext::MD_kcfi_type:
2741 ++NumKCFIAttachments;
2742 Check(NumKCFIAttachments == 1,
2743 "function must have a single !kcfi_type attachment", &
F,
2749 visitMDNode(*
I.second, AllowLocs);
2757 if (
F.isIntrinsic() &&
F.getParent()->isMaterialized()) {
2759 if (
F.hasAddressTaken(&U,
false,
true,
false,
2761 Check(
false,
"Invalid user of intrinsic instruction!", U);
2765 switch (
F.getIntrinsicID()) {
2766 case Intrinsic::experimental_gc_get_pointer_base: {
2768 Check(FT->getNumParams() == 1,
"wrong number of parameters",
F);
2769 Check(isa<PointerType>(
F.getReturnType()),
2770 "gc.get.pointer.base must return a pointer",
F);
2771 Check(FT->getParamType(0) ==
F.getReturnType(),
2772 "gc.get.pointer.base operand and result must be of the same type",
F);
2775 case Intrinsic::experimental_gc_get_pointer_offset: {
2777 Check(FT->getNumParams() == 1,
"wrong number of parameters",
F);
2778 Check(isa<PointerType>(FT->getParamType(0)),
2779 "gc.get.pointer.offset operand must be a pointer",
F);
2780 Check(
F.getReturnType()->isIntegerTy(),
2781 "gc.get.pointer.offset must return integer",
F);
2786 auto *
N =
F.getSubprogram();
2787 HasDebugInfo = (
N !=
nullptr);
2806 CheckDI(Parent && isa<DILocalScope>(Parent),
2807 "DILocation's scope must be a DILocalScope",
N, &
F, &
I,
DL, Parent);
2810 Check(Scope,
"Failed to find DILocalScope",
DL);
2812 if (!Seen.
insert(Scope).second)
2819 if (SP && ((Scope != SP) && !Seen.
insert(SP).second))
2823 "!dbg attachment points at wrong subprogram for function",
N, &
F,
2827 for (
auto &
I : BB) {
2828 VisitDebugLoc(
I,
I.getDebugLoc().getAsMDNode());
2830 if (
auto MD =
I.getMetadata(LLVMContext::MD_loop))
2832 VisitDebugLoc(
I, dyn_cast_or_null<MDNode>(MD->
getOperand(i)));
2833 if (BrokenDebugInfo)
2840void Verifier::visitBasicBlock(
BasicBlock &BB) {
2841 InstsInThisBlock.
clear();
2848 if (isa<PHINode>(BB.
front())) {
2853 Check(PN.getNumIncomingValues() == Preds.size(),
2854 "PHINode should have one entry for each predecessor of its "
2855 "parent basic block!",
2860 Values.
reserve(PN.getNumIncomingValues());
2861 for (
unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2863 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
2866 for (
unsigned i = 0, e = Values.
size(); i != e; ++i) {
2871 Check(i == 0 || Values[i].first != Values[i - 1].first ||
2872 Values[i].second == Values[i - 1].second,
2873 "PHI node has multiple entries for the same basic block with "
2874 "different incoming values!",
2875 &PN, Values[i].first, Values[i].second, Values[i - 1].second);
2879 Check(Values[i].first == Preds[i],
2880 "PHI node entries do not match predecessors!", &PN,
2881 Values[i].first, Preds[i]);
2889 Check(
I.getParent() == &BB,
"Instruction has bogus parent pointer!");
2895 Check(&
I ==
I.getParent()->getTerminator(),
2896 "Terminator found in the middle of a basic block!",
I.getParent());
2900void Verifier::visitBranchInst(
BranchInst &BI) {
2903 "Branch condition is not 'i1' type!", &BI, BI.
getCondition());
2908void Verifier::visitReturnInst(
ReturnInst &RI) {
2911 if (
F->getReturnType()->isVoidTy())
2913 "Found return instr that returns non-void in Function of void "
2915 &RI,
F->getReturnType());
2918 "Function return type does not match operand "
2919 "type of return inst!",
2920 &RI,
F->getReturnType());
2927void Verifier::visitSwitchInst(
SwitchInst &SI) {
2928 Check(
SI.getType()->isVoidTy(),
"Switch must have void result type!", &SI);
2931 Type *SwitchTy =
SI.getCondition()->getType();
2933 for (
auto &Case :
SI.cases()) {
2934 Check(isa<ConstantInt>(
SI.getOperand(Case.getCaseIndex() * 2 + 2)),
2935 "Case value is not a constant integer.", &SI);
2936 Check(Case.getCaseValue()->getType() == SwitchTy,
2937 "Switch constants must all be same type as switch value!", &SI);
2939 "Duplicate integer as switch case", &SI, Case.getCaseValue());
2947 "Indirectbr operand must have pointer type!", &BI);
2950 "Indirectbr destinations must all have pointer type!", &BI);
2955void Verifier::visitCallBrInst(
CallBrInst &CBI) {
2956 Check(CBI.
isInlineAsm(),
"Callbr is currently only used for asm-goto!", &CBI);
2958 Check(!
IA->canThrow(),
"Unwinding from Callbr is not allowed");
2960 verifyInlineAsmCall(CBI);
2964void Verifier::visitSelectInst(
SelectInst &SI) {
2967 "Invalid operands for select instruction!", &SI);
2969 Check(
SI.getTrueValue()->getType() ==
SI.getType(),
2970 "Select values must have same type as select instruction!", &SI);
2978 Check(
false,
"User-defined operators should not live outside of a pass!", &
I);
2983 Type *SrcTy =
I.getOperand(0)->getType();
2984 Type *DestTy =
I.getType();
2993 "trunc source and destination must both be a vector or neither", &
I);
2994 Check(SrcBitSize > DestBitSize,
"DestTy too big for Trunc", &
I);
2999void Verifier::visitZExtInst(
ZExtInst &
I) {
3001 Type *SrcTy =
I.getOperand(0)->getType();
3002 Type *DestTy =
I.getType();
3008 "zext source and destination must both be a vector or neither", &
I);
3012 Check(SrcBitSize < DestBitSize,
"Type too small for ZExt", &
I);
3017void Verifier::visitSExtInst(
SExtInst &
I) {
3019 Type *SrcTy =
I.getOperand(0)->getType();
3020 Type *DestTy =
I.getType();
3029 "sext source and destination must both be a vector or neither", &
I);
3030 Check(SrcBitSize < DestBitSize,
"Type too small for SExt", &
I);
3037 Type *SrcTy =
I.getOperand(0)->getType();
3038 Type *DestTy =
I.getType();
3046 "fptrunc source and destination must both be a vector or neither", &
I);
3047 Check(SrcBitSize > DestBitSize,
"DestTy too big for FPTrunc", &
I);
3054 Type *SrcTy =
I.getOperand(0)->getType();
3055 Type *DestTy =
I.getType();
3064 "fpext source and destination must both be a vector or neither", &
I);
3065 Check(SrcBitSize < DestBitSize,
"DestTy too small for FPExt", &
I);
3072 Type *SrcTy =
I.getOperand(0)->getType();
3073 Type *DestTy =
I.getType();
3078 Check(SrcVec == DstVec,
3079 "UIToFP source and dest must both be vector or scalar", &
I);
3081 "UIToFP source must be integer or integer vector", &
I);
3085 if (SrcVec && DstVec)
3086 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3087 cast<VectorType>(DestTy)->getElementCount(),
3088 "UIToFP source and dest vector length mismatch", &
I);
3095 Type *SrcTy =
I.getOperand(0)->getType();
3096 Type *DestTy =
I.getType();
3101 Check(SrcVec == DstVec,
3102 "SIToFP source and dest must both be vector or scalar", &
I);
3104 "SIToFP source must be integer or integer vector", &
I);
3108 if (SrcVec && DstVec)
3109 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3110 cast<VectorType>(DestTy)->getElementCount(),
3111 "SIToFP source and dest vector length mismatch", &
I);
3118 Type *SrcTy =
I.getOperand(0)->getType();
3119 Type *DestTy =
I.getType();
3124 Check(SrcVec == DstVec,
3125 "FPToUI source and dest must both be vector or scalar", &
I);
3128 "FPToUI result must be integer or integer vector", &
I);
3130 if (SrcVec && DstVec)
3131 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3132 cast<VectorType>(DestTy)->getElementCount(),
3133 "FPToUI source and dest vector length mismatch", &
I);
3140 Type *SrcTy =
I.getOperand(0)->getType();
3141 Type *DestTy =
I.getType();
3146 Check(SrcVec == DstVec,
3147 "FPToSI source and dest must both be vector or scalar", &
I);
3150 "FPToSI result must be integer or integer vector", &
I);
3152 if (SrcVec && DstVec)
3153 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3154 cast<VectorType>(DestTy)->getElementCount(),
3155 "FPToSI source and dest vector length mismatch", &
I);
3162 Type *SrcTy =
I.getOperand(0)->getType();
3163 Type *DestTy =
I.getType();
3172 auto *VSrc = cast<VectorType>(SrcTy);
3173 auto *VDest = cast<VectorType>(DestTy);
3174 Check(VSrc->getElementCount() == VDest->getElementCount(),
3175 "PtrToInt Vector width mismatch", &
I);
3183 Type *SrcTy =
I.getOperand(0)->getType();
3184 Type *DestTy =
I.getType();
3192 auto *VSrc = cast<VectorType>(SrcTy);
3193 auto *VDest = cast<VectorType>(DestTy);
3194 Check(VSrc->getElementCount() == VDest->getElementCount(),
3195 "IntToPtr Vector width mismatch", &
I);
3203 "Invalid bitcast", &
I);
3208 Type *SrcTy =
I.getOperand(0)->getType();
3209 Type *DestTy =
I.getType();
3216 "AddrSpaceCast must be between different address spaces", &
I);
3217 if (
auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
3218 Check(SrcVTy->getElementCount() ==
3219 cast<VectorType>(DestTy)->getElementCount(),
3220 "AddrSpaceCast vector pointer number of elements mismatch", &
I);
3226void Verifier::visitPHINode(
PHINode &PN) {
3233 "PHI nodes not grouped at top of basic block!", &PN, PN.
getParent());
3242 "PHI node operands are not the same type as the result!", &PN);
3250void Verifier::visitCallBase(
CallBase &Call) {
3251 Check(
Call.getCalledOperand()->getType()->isPointerTy(),
3252 "Called function must be a pointer!", Call);
3253 PointerType *FPTy = cast<PointerType>(
Call.getCalledOperand()->getType());
3255 Check(FPTy->isOpaqueOrPointeeTypeMatches(
Call.getFunctionType()),
3256 "Called function is not the same type as the call!", Call);
3261 if (FTy->isVarArg())
3262 Check(
Call.arg_size() >= FTy->getNumParams(),
3263 "Called function requires more parameters than were provided!", Call);
3265 Check(
Call.arg_size() == FTy->getNumParams(),
3266 "Incorrect number of arguments passed to called function!", Call);
3269 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3270 Check(
Call.getArgOperand(i)->getType() == FTy->getParamType(i),
3271 "Call parameter type does not match function signature!",
3272 Call.getArgOperand(i), FTy->getParamType(i), Call);
3276 Check(verifyAttributeCount(Attrs,
Call.arg_size()),
3277 "Attribute after last parameter!", Call);
3280 dyn_cast<Function>(
Call.getCalledOperand()->stripPointerCasts());
3284 "Intrinsic called with incompatible signature", Call);
3286 auto VerifyTypeAlign = [&](
Type *Ty,
const Twine &Message) {
3289 Align ABIAlign =
DL.getABITypeAlign(Ty);
3290 Align MaxAlign(ParamMaxAlignment);
3291 Check(ABIAlign <= MaxAlign,
3292 "Incorrect alignment of " + Message +
" to called function!", Call);
3296 VerifyTypeAlign(FTy->getReturnType(),
"return type");
3297 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3298 Type *Ty = FTy->getParamType(i);
3299 VerifyTypeAlign(Ty,
"argument passed");
3303 if (
Attrs.hasFnAttr(Attribute::Speculatable)) {
3307 "speculatable attribute may not apply to call sites", Call);
3310 if (
Attrs.hasFnAttr(Attribute::Preallocated)) {
3311 Check(
Call.getCalledFunction()->getIntrinsicID() ==
3312 Intrinsic::call_preallocated_arg,
3313 "preallocated as a call site attribute can only be on "
3314 "llvm.call.preallocated.arg");
3318 verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic,
Call.isInlineAsm());
3323 if (
Call.hasInAllocaArgument()) {
3324 Value *InAllocaArg =
Call.getArgOperand(FTy->getNumParams() - 1);
3326 Check(AI->isUsedWithInAlloca(),
3327 "inalloca argument for call has mismatched alloca", AI, Call);
3333 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3334 if (
Call.paramHasAttr(i, Attribute::SwiftError)) {
3335 Value *SwiftErrorArg =
Call.getArgOperand(i);
3337 Check(AI->isSwiftError(),
3338 "swifterror argument for call has mismatched alloca", AI, Call);
3341 auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
3342 Check(ArgI,
"swifterror argument should come from an alloca or parameter",
3343 SwiftErrorArg, Call);
3344 Check(ArgI->hasSwiftErrorAttr(),
3345 "swifterror argument for call has mismatched parameter", ArgI,
3349 if (
Attrs.hasParamAttr(i, Attribute::ImmArg)) {
3353 "immarg may not apply only to call sites",
Call.getArgOperand(i),
3357 if (
Call.paramHasAttr(i, Attribute::ImmArg)) {
3359 Check(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
3360 "immarg operand has non-immediate parameter", ArgVal, Call);
3363 if (
Call.paramHasAttr(i, Attribute::Preallocated)) {
3367 bool isMustTail =
Call.isMustTailCall();
3368 Check(hasOB != isMustTail,
3369 "preallocated operand either requires a preallocated bundle or "
3370 "the call to be musttail (but not both)",
3375 if (FTy->isVarArg()) {
3377 bool SawNest =
false;
3378 bool SawReturned =
false;
3380 for (
unsigned Idx = 0;
Idx < FTy->getNumParams(); ++
Idx) {
3381 if (
Attrs.hasParamAttr(
Idx, Attribute::Nest))
3383 if (
Attrs.hasParamAttr(
Idx, Attribute::Returned))
3388 for (
unsigned Idx = FTy->getNumParams();
Idx <
Call.arg_size(); ++
Idx) {
3391 verifyParameterAttrs(ArgAttrs, Ty, &Call);
3394 Check(!SawNest,
"More than one parameter has attribute nest!", Call);
3399 Check(!SawReturned,
"More than one parameter has attribute returned!",
3402 "Incompatible argument and return types for 'returned' "
3410 if (!
Call.getCalledFunction() ||
3411 Call.getCalledFunction()->getIntrinsicID() !=
3412 Intrinsic::experimental_gc_statepoint)
3414 "Attribute 'sret' cannot be used for vararg call arguments!",
3419 "inalloca isn't on the last argument!", Call);
3425 for (
Type *ParamTy : FTy->params()) {
3426 Check(!ParamTy->isMetadataTy(),
3427 "Function has metadata parameter but isn't an intrinsic", Call);
3428 Check(!ParamTy->isTokenTy(),
3429 "Function has token parameter but isn't an intrinsic", Call);
3434 if (!
Call.getCalledFunction()) {
3435 Check(!FTy->getReturnType()->isTokenTy(),
3436 "Return type cannot be token for indirect call!");
3437 Check(!FTy->getReturnType()->isX86_AMXTy(),
3438 "Return type cannot be x86_amx for indirect call!");
3443 visitIntrinsicCall(
ID, Call);
3448 bool FoundDeoptBundle =
false, FoundFuncletBundle =
false,
3449 FoundGCTransitionBundle =
false, FoundCFGuardTargetBundle =
false,
3450 FoundPreallocatedBundle =
false, FoundGCLiveBundle =
false,
3451 FoundPtrauthBundle =
false, FoundKCFIBundle =
false,
3452 FoundAttachedCallBundle =
false;
3453 for (
unsigned i = 0, e =
Call.getNumOperandBundles(); i < e; ++i) {
3457 Check(!FoundDeoptBundle,
"Multiple deopt operand bundles", Call);
3458 FoundDeoptBundle =
true;
3460 Check(!FoundGCTransitionBundle,
"Multiple gc-transition operand bundles",
3462 FoundGCTransitionBundle =
true;
3464 Check(!FoundFuncletBundle,
"Multiple funclet operand bundles", Call);
3465 FoundFuncletBundle =
true;
3467 "Expected exactly one funclet bundle operand", Call);
3469 "Funclet bundle operands should correspond to a FuncletPadInst",
3472 Check(!FoundCFGuardTargetBundle,
"Multiple CFGuardTarget operand bundles",
3474 FoundCFGuardTargetBundle =
true;
3476 "Expected exactly one cfguardtarget bundle operand", Call);
3478 Check(!FoundPtrauthBundle,
"Multiple ptrauth operand bundles", Call);
3479 FoundPtrauthBundle =
true;
3481 "Expected exactly two ptrauth bundle operands", Call);
3483 BU.
Inputs[0]->getType()->isIntegerTy(32),
3484 "Ptrauth bundle key operand must be an i32 constant", Call);
3486 "Ptrauth bundle discriminator operand must be an i64", Call);
3488 Check(!FoundKCFIBundle,
"Multiple kcfi operand bundles", Call);
3489 FoundKCFIBundle =
true;
3490 Check(BU.
Inputs.size() == 1,
"Expected exactly one kcfi bundle operand",
3493 BU.
Inputs[0]->getType()->isIntegerTy(32),
3494 "Kcfi bundle operand must be an i32 constant", Call);
3496 Check(!FoundPreallocatedBundle,
"Multiple preallocated operand bundles",
3498 FoundPreallocatedBundle =
true;
3500 "Expected exactly one preallocated bundle operand", Call);
3501 auto Input = dyn_cast<IntrinsicInst>(BU.
Inputs.front());
3503 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
3504 "\"preallocated\" argument must be a token from "
3505 "llvm.call.preallocated.setup",
3508 Check(!FoundGCLiveBundle,
"Multiple gc-live operand bundles", Call);
3509 FoundGCLiveBundle =
true;
3511 Check(!FoundAttachedCallBundle,
3512 "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
3513 FoundAttachedCallBundle =
true;
3514 verifyAttachedCallBundle(Call, BU);
3519 Check(!(
Call.getCalledFunction() && FoundPtrauthBundle),
3520 "Direct call cannot have a ptrauth bundle", Call);
3527 if (
Call.getFunction()->getSubprogram() &&
Call.getCalledFunction() &&
3528 !
Call.getCalledFunction()->isInterposable() &&
3529 !
Call.getCalledFunction()->isDeclaration() &&
3530 Call.getCalledFunction()->getSubprogram())
3532 "inlinable function call in a function with "
3533 "debug info must have a !dbg location",
3536 if (
Call.isInlineAsm())
3537 verifyInlineAsmCall(Call);
3542void Verifier::verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs,
3545 Twine(
"inalloca attribute not allowed in ") + Context);
3547 Twine(
"inreg attribute not allowed in ") + Context);
3548 Check(!
Attrs.contains(Attribute::SwiftError),
3549 Twine(
"swifterror attribute not allowed in ") + Context);
3550 Check(!
Attrs.contains(Attribute::Preallocated),
3551 Twine(
"preallocated attribute not allowed in ") + Context);
3553 Twine(
"byref attribute not allowed in ") + Context);
3565 return PL->getAddressSpace() == PR->getAddressSpace();
3570 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
3571 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
3572 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
3575 for (
auto AK : ABIAttrs) {
3576 Attribute Attr = Attrs.getParamAttrs(
I).getAttribute(AK);
3578 Copy.addAttribute(Attr);
3582 if (Attrs.hasParamAttr(
I, Attribute::Alignment) &&
3583 (Attrs.hasParamAttr(
I, Attribute::ByVal) ||
3584 Attrs.hasParamAttr(
I, Attribute::ByRef)))
3585 Copy.addAlignmentAttr(Attrs.getParamAlignment(
I));
3589void Verifier::verifyMustTailCall(
CallInst &CI) {
3595 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
3596 "cannot guarantee tail call due to mismatched varargs", &CI);
3598 "cannot guarantee tail call due to mismatched return types", &CI);
3602 "cannot guarantee tail call due to mismatched calling conv", &CI);
3608 Value *RetVal = &CI;
3612 if (
BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
3614 "bitcast following musttail call must use the call", BI);
3621 Check(Ret,
"musttail call must precede a ret with an optional bitcast", &CI);
3622 Check(!
Ret->getReturnValue() ||
Ret->getReturnValue() == RetVal ||
3623 isa<UndefValue>(
Ret->getReturnValue()),
3624 "musttail call result must be returned", Ret);
3635 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
3638 verifyTailCCMustTailAttrs(ABIAttrs, Context);
3640 for (
unsigned I = 0,
E = CalleeTy->getNumParams();
I !=
E; ++
I) {
3643 verifyTailCCMustTailAttrs(ABIAttrs, Context);
3646 Check(!CallerTy->isVarArg(),
Twine(
"cannot guarantee ") + CCName +
3647 " tail call for varargs function");
3655 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
3656 "cannot guarantee tail call due to mismatched parameter counts", &CI);
3657 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
3660 "cannot guarantee tail call due to mismatched parameter types", &CI);
3666 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
3669 Check(CallerABIAttrs == CalleeABIAttrs,
3670 "cannot guarantee tail call due to mismatched ABI impacting "
3671 "function attributes",
3676void Verifier::visitCallInst(
CallInst &CI) {
3680 verifyMustTailCall(CI);
3683void Verifier::visitInvokeInst(
InvokeInst &II) {
3690 "The unwind destination does not have an exception handling instruction!",
3699 Check(
U.getType() ==
U.getOperand(0)->getType(),
3700 "Unary operators must have same type for"
3701 "operands and result!",
3704 switch (
U.getOpcode()) {
3707 case Instruction::FNeg:
3708 Check(
U.getType()->isFPOrFPVectorTy(),
3709 "FNeg operator only works with float types!", &U);
3722 Check(
B.getOperand(0)->getType() ==
B.getOperand(1)->getType(),
3723 "Both operands to a binary operator are not of the same type!", &
B);
3725 switch (
B.getOpcode()) {
3728 case Instruction::Add:
3729 case Instruction::Sub:
3730 case Instruction::Mul:
3731 case Instruction::SDiv:
3732 case Instruction::UDiv:
3733 case Instruction::SRem:
3734 case Instruction::URem:
3735 Check(
B.getType()->isIntOrIntVectorTy(),
3736 "Integer arithmetic operators only work with integral types!", &
B);
3737 Check(
B.getType() ==
B.getOperand(0)->getType(),
3738 "Integer arithmetic operators must have same type "
3739 "for operands and result!",
3744 case Instruction::FAdd:
3745 case Instruction::FSub:
3746 case Instruction::FMul:
3747 case Instruction::FDiv:
3748 case Instruction::FRem:
3749 Check(
B.getType()->isFPOrFPVectorTy(),
3750 "Floating-point arithmetic operators only work with "
3751 "floating-point types!",
3753 Check(
B.getType() ==
B.getOperand(0)->getType(),
3754 "Floating-point arithmetic operators must have same type "
3755 "for operands and result!",
3759 case Instruction::And:
3760 case Instruction::Or:
3761 case Instruction::Xor:
3762 Check(
B.getType()->isIntOrIntVectorTy(),
3763 "Logical operators only work with integral types!", &
B);
3764 Check(
B.getType() ==
B.getOperand(0)->getType(),
3765 "Logical operators must have same type for operands and result!", &
B);
3767 case Instruction::Shl:
3768 case Instruction::LShr:
3769 case Instruction::AShr:
3770 Check(
B.getType()->isIntOrIntVectorTy(),
3771 "Shifts only work with integral types!", &
B);
3772 Check(
B.getType() ==
B.getOperand(0)->getType(),
3773 "Shift return type must be same as operands!", &
B);
3782void Verifier::visitICmpInst(
ICmpInst &IC) {
3786 Check(Op0Ty == Op1Ty,
3787 "Both operands to ICmp instruction are not of the same type!", &IC);
3790 "Invalid operand types for ICmp instruction", &IC);
3797void Verifier::visitFCmpInst(
FCmpInst &FC) {
3799 Type *Op0Ty =
FC.getOperand(0)->getType();
3800 Type *Op1Ty =
FC.getOperand(1)->getType();
3801 Check(Op0Ty == Op1Ty,
3802 "Both operands to FCmp instruction are not of the same type!", &FC);
3807 Check(
FC.isFPPredicate(),
"Invalid predicate in FCmp instruction!", &FC);
3814 "Invalid extractelement operands!", &EI);
3821 "Invalid insertelement operands!", &IE);
3828 "Invalid shufflevector operands!", &SV);
3833 Type *TargetTy =
GEP.getPointerOperandType()->getScalarType();
3835 Check(isa<PointerType>(TargetTy),
3836 "GEP base pointer is not a vector or a vector of pointers", &
GEP);
3837 Check(
GEP.getSourceElementType()->isSized(),
"GEP into unsized type!", &
GEP);
3841 all_of(Idxs, [](
Value *V) {
return V->getType()->isIntOrIntVectorTy(); }),
3842 "GEP indexes must be integers", &
GEP);
3845 Check(ElTy,
"Invalid indices for GEP pointer type!", &
GEP);
3847 Check(
GEP.getType()->isPtrOrPtrVectorTy() &&
3848 GEP.getResultElementType() == ElTy,
3849 "GEP is not of right type for indices!", &
GEP, ElTy);
3851 if (
auto *GEPVTy = dyn_cast<VectorType>(
GEP.getType())) {
3854 if (
GEP.getPointerOperandType()->isVectorTy())
3857 cast<VectorType>(
GEP.getPointerOperandType())->getElementCount(),
3858 "Vector GEP result width doesn't match operand's", &
GEP);
3860 Type *IndexTy =
Idx->getType();
3861 if (
auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
3863 Check(IndexWidth == GEPWidth,
"Invalid GEP index vector width", &
GEP);
3866 "All GEP indices should be of integer type");
3870 if (
auto *PTy = dyn_cast<PointerType>(
GEP.getType())) {
3871 Check(
GEP.getAddressSpace() == PTy->getAddressSpace(),
3872 "GEP address space doesn't match type", &
GEP);
3879 return A.getUpper() ==
B.getLower() ||
A.getLower() ==
B.getUpper();
3883 assert(Range && Range ==
I.getMetadata(LLVMContext::MD_range) &&
3884 "precondition violation");
3886 unsigned NumOperands =
Range->getNumOperands();
3887 Check(NumOperands % 2 == 0,
"Unfinished range!", Range);
3888 unsigned NumRanges = NumOperands / 2;
3889 Check(NumRanges >= 1,
"It should have at least one range!", Range);
3892 for (
unsigned i = 0; i < NumRanges; ++i) {
3894 mdconst::dyn_extract<ConstantInt>(
Range->getOperand(2 * i));
3895 Check(
Low,
"The lower limit must be an integer!",
Low);
3897 mdconst::dyn_extract<ConstantInt>(
Range->getOperand(2 * i + 1));
3901 "Range types must match instruction type!", &
I);
3906 Check(!CurRange.isEmptySet() && !CurRange.isFullSet(),
3907 "Range must not be empty!", Range);
3909 Check(CurRange.intersectWith(LastRange).isEmptySet(),
3910 "Intervals are overlapping", Range);
3911 Check(LowV.
sgt(LastRange.getLower()),
"Intervals are not in order",
3918 if (NumRanges > 2) {
3920 mdconst::dyn_extract<ConstantInt>(
Range->getOperand(0))->getValue();
3922 mdconst::dyn_extract<ConstantInt>(
Range->getOperand(1))->getValue();
3924 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
3925 "Intervals are overlapping", Range);
3932 unsigned Size =
DL.getTypeSizeInBits(Ty);
3933 Check(
Size >= 8,
"atomic memory access' size must be byte-sized", Ty,
I);
3935 "atomic memory access' operand must have a power-of-two size", Ty,
I);
3938void Verifier::visitLoadInst(
LoadInst &LI) {
3940 Check(PTy,
"Load operand must be a pointer.", &LI);
3944 "huge alignment values are unsupported", &LI);
3946 Check(ElTy->
isSized(),
"loading unsized types is not allowed", &LI);
3950 "Load cannot have Release ordering", &LI);
3952 "atomic load operand must have integer, pointer, or floating point "
3955 checkAtomicMemAccessSize(ElTy, &LI);
3958 "Non-atomic load cannot have SynchronizationScope specified", &LI);
3964void Verifier::visitStoreInst(
StoreInst &SI) {
3965 PointerType *PTy = dyn_cast<PointerType>(
SI.getOperand(1)->getType());
3966 Check(PTy,
"Store operand must be a pointer.", &SI);
3967 Type *ElTy =
SI.getOperand(0)->getType();
3968 Check(PTy->isOpaqueOrPointeeTypeMatches(ElTy),
3969 "Stored value type does not match pointer operand type!", &SI, ElTy);
3972 "huge alignment values are unsupported", &SI);
3974 Check(ElTy->
isSized(),
"storing unsized types is not allowed", &SI);
3975 if (
SI.isAtomic()) {
3978 "Store cannot have Acquire ordering", &SI);
3980 "atomic store operand must have integer, pointer, or floating point "
3983 checkAtomicMemAccessSize(ElTy, &SI);
3986 "Non-atomic store cannot have SynchronizationScope specified", &SI);
3992void Verifier::verifySwiftErrorCall(
CallBase &Call,
3993 const Value *SwiftErrorVal) {
3995 if (
I.value() == SwiftErrorVal) {
3996 Check(
Call.paramHasAttr(
I.index(), Attribute::SwiftError),
3997 "swifterror value when used in a callsite should be marked "
3998 "with swifterror attribute",
3999 SwiftErrorVal, Call);
4004void Verifier::verifySwiftErrorValue(
const Value *SwiftErrorVal) {
4007 for (
const User *U : SwiftErrorVal->
users()) {
4008 Check(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
4010 "swifterror value can only be loaded and stored from, or "
4011 "as a swifterror argument!",
4014 if (
auto StoreI = dyn_cast<StoreInst>(U))
4015 Check(StoreI->getOperand(1) == SwiftErrorVal,
4016 "swifterror value should be the second operand when used "
4019 if (
auto *Call = dyn_cast<CallBase>(U))
4020 verifySwiftErrorCall(*
const_cast<CallBase *
>(Call), SwiftErrorVal);
4024void Verifier::visitAllocaInst(
AllocaInst &AI) {
4027 "Cannot allocate unsized type", &AI);
4029 "Alloca array size must have integer type", &AI);
4032 "huge alignment values are unsupported", &AI);
4037 "swifterror alloca must have pointer type", &AI);
4039 "swifterror alloca must not be array allocation", &AI);
4040 verifySwiftErrorValue(&AI);
4049 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4050 checkAtomicMemAccessSize(ElTy, &CXI);
4056 "atomicrmw instructions cannot be unordered.", &RMWI);
4063 " operand must have integer or floating point type!",
4068 " operand must have floating point type!",
4073 " operand must have integer type!",
4076 checkAtomicMemAccessSize(ElTy, &RMWI);
4078 "Invalid binary operation!", &RMWI);
4082void Verifier::visitFenceInst(
FenceInst &FI) {
4088 "fence instructions may only have acquire, release, acq_rel, or "
4089 "seq_cst ordering.",
4097 "Invalid ExtractValueInst operands!", &EVI);
4106 "Invalid InsertValueInst operands!", &IVI);
4112 if (
auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
4113 return FPI->getParentPad();
4115 return cast<CatchSwitchInst>(EHPad)->getParentPad();
4124 Check(BB != &
F->getEntryBlock(),
"EH pad cannot be in entry block.", &
I);
4126 if (
auto *LPI = dyn_cast<LandingPadInst>(&
I)) {
4131 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
4132 Check(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
4133 "Block containing LandingPadInst must be jumped to "
4134 "only by the unwind edge of an invoke.",
4139 if (
auto *CPI = dyn_cast<CatchPadInst>(&
I)) {
4142 "Block containg CatchPadInst must be jumped to "
4143 "only by its catchswitch.",
4145 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4146 "Catchswitch cannot unwind to one of its catchpads",
4147 CPI->getCatchSwitch(), CPI);
4158 if (
auto *II = dyn_cast<InvokeInst>(TI)) {
4159 Check(II->getUnwindDest() == BB && II->getNormalDest() != BB,
4160 "EH pad must be jumped to via an unwind edge", ToPad, II);
4162 FromPad = Bundle->Inputs[0];
4165 }
else if (
auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
4166 FromPad = CRI->getOperand(0);
4167 Check(FromPad != ToPadParent,
"A cleanupret must exit its cleanup", CRI);
4168 }
else if (
auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4171 Check(
false,
"EH pad must be jumped to via an unwind edge", ToPad, TI);
4177 Check(FromPad != ToPad,
4178 "EH pad cannot handle exceptions raised within it", FromPad, TI);
4179 if (FromPad == ToPadParent) {
4183 Check(!isa<ConstantTokenNone>(FromPad),
4184 "A single unwind edge may only enter one EH pad", TI);
4185 Check(Seen.
insert(FromPad).second,
"EH pad jumps through a cycle of pads",
4190 Check(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
4191 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
4200 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
4202 visitEHPadPredecessors(LPI);
4204 if (!LandingPadResultTy)
4205 LandingPadResultTy = LPI.
getType();
4208 "The landingpad instruction should have a consistent result type "
4209 "inside a function.",
4213 Check(
F->hasPersonalityFn(),
4214 "LandingPadInst needs to be in a function with a personality.", &LPI);
4219 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
4225 "Catch operand does not have pointer type!", &LPI);
4227 Check(LPI.
isFilter(i),
"Clause is neither catch nor filter!", &LPI);
4229 "Filter operand is not an array of constants!", &LPI);
4236void Verifier::visitResumeInst(
ResumeInst &RI) {
4238 "ResumeInst needs to be in a function with a personality.", &RI);
4240 if (!LandingPadResultTy)
4244 "The resume instruction should have a consistent result type "
4245 "inside a function.",
4255 Check(
F->hasPersonalityFn(),
4256 "CatchPadInst needs to be in a function with a personality.", &CPI);
4259 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4265 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
4267 visitEHPadPredecessors(CPI);
4273 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
4283 Check(
F->hasPersonalityFn(),
4284 "CleanupPadInst needs to be in a function with a personality.", &CPI);
4289 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
4292 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4293 "CleanupPadInst has an invalid parent.", &CPI);
4295 visitEHPadPredecessors(CPI);
4300 User *FirstUser =
nullptr;
4301 Value *FirstUnwindPad =
nullptr;
4305 while (!Worklist.empty()) {
4308 "FuncletPadInst must not be nested within itself", CurrentPad);
4309 Value *UnresolvedAncestorPad =
nullptr;
4312 if (
auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
4313 UnwindDest = CRI->getUnwindDest();
4314 }
else if (
auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
4319 if (CSI->unwindsToCaller())
4321 UnwindDest = CSI->getUnwindDest();
4322 }
else if (
auto *II = dyn_cast<InvokeInst>(U)) {
4323 UnwindDest = II->getUnwindDest();
4324 }
else if (isa<CallInst>(U)) {
4329 }
else if (
auto *CPI = dyn_cast<CleanupPadInst>(U)) {
4333 Worklist.push_back(CPI);
4336 Check(isa<CatchReturnInst>(U),
"Bogus funclet pad use", U);
4344 if (!cast<Instruction>(UnwindPad)->isEHPad())
4348 if (UnwindParent == CurrentPad)
4354 Value *ExitedPad = CurrentPad;
4357 if (ExitedPad == &FPI) {
4362 UnresolvedAncestorPad = &FPI;
4366 if (ExitedParent == UnwindParent) {
4370 UnresolvedAncestorPad = ExitedParent;
4373 ExitedPad = ExitedParent;
4374 }
while (!isa<ConstantTokenNone>(ExitedPad));
4379 UnresolvedAncestorPad = &FPI;
4386 Check(UnwindPad == FirstUnwindPad,
4387 "Unwind edges out of a funclet "
4388 "pad must have the same unwind "
4390 &FPI, U, FirstUser);
4393 FirstUnwindPad = UnwindPad;
4395 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
4397 SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
4402 if (CurrentPad != &FPI)
4405 if (UnresolvedAncestorPad) {
4406 if (CurrentPad == UnresolvedAncestorPad) {
4410 assert(CurrentPad == &FPI);
4418 Value *ResolvedPad = CurrentPad;
4419 while (!Worklist.empty()) {
4420 Value *UnclePad = Worklist.back();
4424 while (ResolvedPad != AncestorPad) {
4426 if (ResolvedParent == UnresolvedAncestorPad) {
4429 ResolvedPad = ResolvedParent;
4433 if (ResolvedPad != AncestorPad)
4436 Worklist.pop_back();
4441 if (FirstUnwindPad) {
4442 if (
auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.
getParentPad())) {
4443 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
4444 Value *SwitchUnwindPad;
4445 if (SwitchUnwindDest)
4449 Check(SwitchUnwindPad == FirstUnwindPad,
4450 "Unwind edges out of a catch must have the same unwind dest as "
4451 "the parent catchswitch",
4452 &FPI, FirstUser, CatchSwitch);
4463 Check(
F->hasPersonalityFn(),
4464 "CatchSwitchInst needs to be in a function with a personality.",
4470 "CatchSwitchInst not the first non-PHI instruction in the block.",
4474 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4475 "CatchSwitchInst has an invalid parent.", ParentPad);
4479 Check(
I->isEHPad() && !isa<LandingPadInst>(
I),
4480 "CatchSwitchInst must unwind to an EH block which is not a "
4486 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
4490 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
4493 Check(isa<CatchPadInst>(Handler->getFirstNonPHI()),
4494 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
4497 visitEHPadPredecessors(CatchSwitch);
4503 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
4508 Check(
I->isEHPad() && !isa<LandingPadInst>(
I),
4509 "CleanupReturnInst must unwind to an EH block which is not a "
4517void Verifier::verifyDominatesUse(
Instruction &
I,
unsigned i) {
4522 if (
InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
4523 if (II->getNormalDest() == II->getUnwindDest())
4534 if (!isa<PHINode>(
I) && InstsInThisBlock.
count(Op))
4537 const Use &
U =
I.getOperandUse(i);
4538 Check(DT.
dominates(Op, U),
"Instruction does not dominate all uses!", Op, &
I);
4542 Check(
I.getType()->isPointerTy(),
4543 "dereferenceable, dereferenceable_or_null "
4544 "apply only to pointer types",
4546 Check((isa<LoadInst>(
I) || isa<IntToPtrInst>(
I)),
4547 "dereferenceable, dereferenceable_or_null apply only to load"
4548 " and inttoptr instructions, use attributes for calls or invokes",
4551 "dereferenceable, dereferenceable_or_null "
4552 "take one operand!",
4557 "dereferenceable_or_null metadata value must be an i64!",
4563 "!prof annotations should have no less than 2 operands", MD);
4566 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null", MD);
4568 "expected string with name of the !prof annotation", MD);
4573 if (ProfName.
equals(
"branch_weights")) {
4574 if (isa<InvokeInst>(&
I)) {
4576 "Wrong number of InvokeInst branch_weights operands", MD);
4578 unsigned ExpectedNumOperands = 0;
4581 else if (
SwitchInst *SI = dyn_cast<SwitchInst>(&
I))
4582 ExpectedNumOperands =
SI->getNumSuccessors();
4583 else if (isa<CallInst>(&
I))
4584 ExpectedNumOperands = 1;
4586 ExpectedNumOperands = IBI->getNumDestinations();
4587 else if (isa<SelectInst>(&
I))
4588 ExpectedNumOperands = 2;
4589 else if (
CallBrInst *CI = dyn_cast<CallBrInst>(&
I))
4592 CheckFailed(
"!prof branch_weights are not allowed for this instruction",
4596 "Wrong number of operands", MD);
4600 Check(MDO,
"second operand should not be null", MD);
4601 Check(mdconst::dyn_extract<ConstantInt>(MDO),
4602 "!prof brunch_weights operand is not a const int");
4608 assert(
I.hasMetadata(LLVMContext::MD_DIAssignID));
4609 bool ExpectedInstTy =
4610 isa<AllocaInst>(
I) || isa<StoreInst>(
I) || isa<MemIntrinsic>(
I);
4611 CheckDI(ExpectedInstTy,
"!DIAssignID attached to unexpected instruction kind",
4618 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
4621 if (
auto *DAI = dyn_cast<DbgAssignIntrinsic>(
User))
4622 CheckDI(DAI->getFunction() ==
I.getFunction(),
4623 "dbg.assign not in same function as inst", DAI, &
I);
4628void Verifier::visitCallStackMetadata(
MDNode *MD) {
4632 "call stack metadata should have at least 1 operand", MD);
4634 for (
const auto &Op : MD->
operands())
4635 Check(mdconst::dyn_extract_or_null<ConstantInt>(Op),
4636 "call stack metadata operand should be constant integer", Op);
4640 Check(isa<CallBase>(
I),
"!memprof metadata should only exist on calls", &
I);
4642 "!memprof annotations should have at least 1 metadata operand "
4647 for (
auto &MIBOp : MD->
operands()) {
4648 MDNode *MIB = dyn_cast<MDNode>(MIBOp);
4653 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
4657 "!memprof MemInfoBlock first operand should not be null", MIB);
4659 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
4661 visitCallStackMetadata(StackMD);
4665 [](
const MDOperand &Op) { return isa<MDString>(Op); }),
4666 "Not all !memprof MemInfoBlock operands 1 to N are MDString", MIB);
4671 Check(isa<CallBase>(
I),
"!callsite metadata should only exist on calls", &
I);
4674 visitCallStackMetadata(MD);
4677void Verifier::visitAnnotationMetadata(
MDNode *Annotation) {
4678 Check(isa<MDTuple>(Annotation),
"annotation must be a tuple");
4680 "annotation must have at least one operand");
4682 Check(isa<MDString>(
Op.get()),
"operands must be strings");
4685void Verifier::visitAliasScopeMetadata(
const MDNode *MD) {
4687 Check(NumOps >= 2 && NumOps <= 3,
"scope must have two or three operands",
4690 "first scope operand must be self-referential or s