87 #include "llvm/IR/IntrinsicsAArch64.h"
88 #include "llvm/IR/IntrinsicsARM.h"
89 #include "llvm/IR/IntrinsicsWebAssembly.h"
115 using namespace llvm;
119 cl::desc(
"Ensure that llvm.experimental.noalias.scope.decl for identical "
120 "scopes are not dominating"));
148 void Write(
const Value *V) {
153 void Write(
const Value &V) {
154 if (isa<Instruction>(V)) {
181 void Write(
Type *
T) {
193 void Write(
const APInt *AI) {
199 void Write(
const unsigned i) { *
OS <<
i <<
'\n'; }
205 *
OS <<
A->getAsString() <<
'\n';
223 for (
const T &V : Vs)
227 template <
typename T1,
typename... Ts>
228 void WriteTs(
const T1 &V1,
const Ts &... Vs) {
233 template <
typename... Ts>
void WriteTs() {}
242 *
OS << Message <<
'\n';
250 template <
typename T1,
typename... Ts>
260 *
OS << Message <<
'\n';
266 template <
typename T1,
typename... Ts>
287 static constexpr
unsigned ParamMaxAlignment = 1 << 14;
307 Type *LandingPadResultTy;
314 bool HasDebugInfo =
false;
358 SawFrameEscape(
false), TBAAVerifyHelper(
this) {
359 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
362 bool hasBrokenDebugInfo()
const {
return BrokenDebugInfo; }
366 "An instance of this class only works with a specific module!");
378 if (!
BB.empty() &&
BB.back().isTerminator())
382 *OS <<
"Basic Block in function '" <<
F.getName()
383 <<
"' does not have terminator!\n";
384 BB.printAsOperand(*OS,
true, MST);
393 verifySiblingFuncletUnwinds();
394 InstsInThisBlock.
clear();
396 LandingPadResultTy =
nullptr;
397 SawFrameEscape =
false;
398 SiblingFuncletInfo.
clear();
399 verifyNoAliasScopeDecl();
400 NoAliasScopeDecls.
clear();
411 if (
F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
412 DeoptimizeDeclarations.push_back(&
F);
416 verifyFrameRecoverIndices();
418 visitGlobalVariable(GV);
421 visitGlobalAlias(GA);
424 visitGlobalIFunc(GI);
427 visitNamedMDNode(NMD);
430 visitComdat(SMEC.getValue());
434 visitModuleCommandLines();
436 verifyCompileUnits();
438 verifyDeoptimizeCallingConvs();
439 DISubprogramAttachments.
clear();
445 enum class AreDebugLocsAllowed {
No,
Yes };
456 void visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs);
459 void visitComdat(
const Comdat &
C);
460 void visitModuleIdents();
461 void visitModuleCommandLines();
462 void visitModuleFlags();
463 void visitModuleFlag(
const MDNode *
Op,
466 void visitModuleFlagCGProfileEntry(
const MDOperand &MDO);
472 void visitAnnotationMetadata(
MDNode *Annotation);
473 void visitAliasScopeMetadata(
const MDNode *MD);
474 void visitAliasScopeListMetadata(
const MDNode *MD);
475 void visitAccessGroupMetadata(
const MDNode *MD);
477 template <
class Ty>
bool isValidMetadataArray(
const MDTuple &
N);
478 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
479 #include "llvm/IR/Metadata.def"
480 void visitDIScope(
const DIScope &
N);
504 void visitPHINode(
PHINode &PN);
513 void visitVAArgInst(
VAArgInst &VAA) { visitInstruction(VAA); }
551 void verifySwiftErrorCall(
CallBase &Call,
const Value *SwiftErrorVal);
552 void verifySwiftErrorValue(
const Value *SwiftErrorVal);
554 void verifyMustTailCall(
CallInst &CI);
561 const Value *V,
bool IsIntrinsic,
bool IsInlineAsm);
562 void verifyFunctionMetadata(
ArrayRef<std::pair<unsigned, MDNode *>> MDs);
564 void visitConstantExprsRecursively(
const Constant *EntryC);
566 void verifyInlineAsmCall(
const CallBase &Call);
567 void verifyStatepoint(
const CallBase &Call);
568 void verifyFrameRecoverIndices();
569 void verifySiblingFuncletUnwinds();
572 template <
typename ValueOrMetadata>
573 void verifyFragmentExpression(
const DIVariable &V,
575 ValueOrMetadata *Desc);
580 void verifyCompileUnits();
584 void verifyDeoptimizeCallingConvs();
586 void verifyAttachedCallBundle(
const CallBase &Call,
593 void verifyNoAliasScopeDecl();
599 #define Check(C, ...) \
602 CheckFailed(__VA_ARGS__); \
609 #define CheckDI(C, ...) \
612 DebugInfoCheckFailed(__VA_ARGS__); \
618 for (
unsigned i = 0,
e =
I.getNumOperands();
i !=
e; ++
i)
619 Check(
I.getOperand(
i) !=
nullptr,
"Operand is null", &
I);
632 while (!WorkList.empty()) {
634 if (!Visited.
insert(Cur).second)
641 void Verifier::visitGlobalValue(
const GlobalValue &GV) {
643 "Global is external, but doesn't have external or weak linkage!", &GV);
645 if (
const GlobalObject *GO = dyn_cast<GlobalObject>(&GV)) {
649 "huge alignment values are unsupported", GO);
653 "Only global variables can have appending linkage!", &GV);
658 "Only global arrays can have appending linkage!", GVar);
662 Check(!GV.
hasComdat(),
"Declaration may not be in a Comdat!", &GV);
665 Check(!GV.
isDSOLocal(),
"GlobalValue with DLLImport Storage is dso_local!",
671 "Global is marked as dllimport, but not external", &GV);
676 "GlobalValue with local linkage or non-default "
677 "visibility must be dso_local!",
682 if (!
I->getParent() || !
I->getParent()->getParent())
683 CheckFailed(
"Global is referenced by parentless instruction!", &GV, &M,
685 else if (
I->getParent()->getParent()->getParent() != &M)
686 CheckFailed(
"Global is referenced in a different module!", &GV, &M,
I,
687 I->getParent()->getParent(),
688 I->getParent()->getParent()->getParent());
690 }
else if (
const Function *
F = dyn_cast<Function>(V)) {
691 if (
F->getParent() != &M)
692 CheckFailed(
"Global is used by function in a different module", &GV, &M,
703 "Global variable initializer type does not match global "
710 "'common' global must have a zero initializer!", &GV);
713 Check(!GV.
hasComdat(),
"'common' global may not be in a Comdat!", &GV);
718 GV.
getName() ==
"llvm.global_dtors")) {
720 "invalid linkage for intrinsic global variable", &GV);
724 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
727 getPointerTo(
DL.getProgramAddressSpace());
731 "wrong type for intrinsic global variable", &GV);
733 "the third field of the element type is mandatory, "
734 "specify i8* null to migrate from the obsoleted 2-field form");
738 cast<PointerType>(ETy)->isOpaqueOrPointeeTypeMatches(Int8Ty),
739 "wrong type for intrinsic global variable", &GV);
744 GV.
getName() ==
"llvm.compiler.used")) {
746 "invalid linkage for intrinsic global variable", &GV);
748 if (
ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
749 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
750 Check(PTy,
"wrong type for intrinsic global variable", &GV);
754 Check(InitArray,
"wrong initalizer for intrinsic global variable",
757 Value *V =
Op->stripPointerCasts();
758 Check(isa<GlobalVariable>(V) || isa<Function>(V) ||
762 Twine(
"members of ") + GV.
getName() +
" must be named", V);
771 for (
auto *MD : MDs) {
772 if (
auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
773 visitDIGlobalVariableExpression(*GVE);
775 CheckDI(
false,
"!dbg attachment of global variable must be a "
776 "DIGlobalVariableExpression");
784 "Globals cannot contain scalable vectors", &GV);
786 if (
auto *STy = dyn_cast<StructType>(GV.
getValueType()))
788 "Globals cannot contain scalable vectors", &GV);
791 visitGlobalValue(GV);
798 visitGlobalValue(GV);
804 visitAliaseeSubExpr(Visited, GA,
C);
809 if (
const auto *GV = dyn_cast<GlobalValue>(&
C)) {
813 if (
const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
814 Check(Visited.
insert(GA2).second,
"Aliases cannot form a cycle", &GA);
816 Check(!GA2->isInterposable(),
817 "Alias cannot point to an interposable alias", &GA);
825 if (
const auto *CE = dyn_cast<ConstantExpr>(&
C))
826 visitConstantExprsRecursively(CE);
828 for (
const Use &U :
C.operands()) {
830 if (
const auto *GA2 = dyn_cast<GlobalAlias>(V))
831 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
832 else if (
const auto *C2 = dyn_cast<Constant>(V))
833 visitAliaseeSubExpr(Visited, GA, *C2);
837 void Verifier::visitGlobalAlias(
const GlobalAlias &GA) {
839 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
840 "weak_odr, or external linkage!",
843 Check(Aliasee,
"Aliasee cannot be NULL!", &GA);
845 "Alias and aliasee types should match!", &GA);
847 Check(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
848 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
850 visitAliaseeSubExpr(GA, *Aliasee);
852 visitGlobalValue(GA);
855 void Verifier::visitGlobalIFunc(
const GlobalIFunc &GI) {
857 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
858 "weak_odr, or external linkage!",
865 "IFunc resolver must be a definition", &GI);
870 const Type *ResolverFuncTy =
873 "IFunc resolver has incorrect type", &GI);
876 void Verifier::visitNamedMDNode(
const NamedMDNode &NMD) {
881 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
883 if (NMD.
getName() ==
"llvm.dbg.cu")
884 CheckDI(MD && isa<DICompileUnit>(MD),
"invalid compile unit", &NMD, MD);
889 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
893 void Verifier::visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
896 if (!MDNodes.
insert(&MD).second)
900 "MDNode context does not match Module context!", &MD);
905 case Metadata::MDTupleKind:
907 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
908 case Metadata::CLASS##Kind: \
909 visit##CLASS(cast<CLASS>(MD)); \
911 #include "llvm/IR/Metadata.def"
917 Check(!isa<LocalAsMetadata>(
Op),
"Invalid operand for global metadata!",
919 CheckDI(!isa<DILocation>(
Op) || AllowLocs == AreDebugLocsAllowed::Yes,
920 "DILocation not allowed within this metadata node", &MD,
Op);
921 if (
auto *
N = dyn_cast<MDNode>(
Op)) {
922 visitMDNode(*
N, AllowLocs);
925 if (
auto *V = dyn_cast<ValueAsMetadata>(
Op)) {
926 visitValueAsMetadata(*V,
nullptr);
939 "Unexpected metadata round-trip through values", &MD, MD.
getValue());
941 auto *L = dyn_cast<LocalAsMetadata>(&MD);
945 Check(
F,
"function-local metadata used outside a function", L);
950 if (
Instruction *
I = dyn_cast<Instruction>(L->getValue())) {
951 Check(
I->getParent(),
"function-local metadata not in basic block", L,
I);
952 ActualF =
I->getParent()->getParent();
953 }
else if (
BasicBlock *
BB = dyn_cast<BasicBlock>(L->getValue()))
954 ActualF =
BB->getParent();
955 else if (
Argument *A = dyn_cast<Argument>(L->getValue()))
956 ActualF =
A->getParent();
957 assert(ActualF &&
"Unimplemented function local metadata case!");
959 Check(ActualF ==
F,
"function-local metadata used in wrong function", L);
964 if (
auto *
N = dyn_cast<MDNode>(MD)) {
965 visitMDNode(*
N, AreDebugLocsAllowed::No);
971 if (!MDNodes.
insert(MD).second)
974 if (
auto *V = dyn_cast<ValueAsMetadata>(MD))
975 visitValueAsMetadata(*V,
F);
982 void Verifier::visitDILocation(
const DILocation &
N) {
983 CheckDI(
N.getRawScope() && isa<DILocalScope>(
N.getRawScope()),
984 "location requires a valid scope", &
N,
N.getRawScope());
985 if (
auto *IA =
N.getRawInlinedAt())
986 CheckDI(isa<DILocation>(IA),
"inlined-at should be a location", &
N, IA);
987 if (
auto *SP = dyn_cast<DISubprogram>(
N.getRawScope()))
988 CheckDI(SP->isDefinition(),
"scope points into the type hierarchy", &
N);
995 void Verifier::visitDIScope(
const DIScope &
N) {
996 if (
auto *
F =
N.getRawFile())
997 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1000 void Verifier::visitDISubrange(
const DISubrange &
N) {
1001 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1003 CheckDI(HasAssumedSizedArraySupport ||
N.getRawCountNode() ||
1004 N.getRawUpperBound(),
1005 "Subrange must contain count or upperBound", &
N);
1006 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1007 "Subrange can have any one of count or upperBound", &
N);
1008 auto *CBound =
N.getRawCountNode();
1009 CheckDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
1010 isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1011 "Count must be signed constant or DIVariable or DIExpression", &
N);
1012 auto Count =
N.getCount();
1015 "invalid subrange count", &
N);
1016 auto *LBound =
N.getRawLowerBound();
1017 CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
1018 isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1019 "LowerBound must be signed constant or DIVariable or DIExpression",
1021 auto *UBound =
N.getRawUpperBound();
1022 CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
1023 isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1024 "UpperBound must be signed constant or DIVariable or DIExpression",
1026 auto *Stride =
N.getRawStride();
1027 CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
1028 isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1029 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1033 CheckDI(
N.getTag() == dwarf::DW_TAG_generic_subrange,
"invalid tag", &
N);
1034 CheckDI(
N.getRawCountNode() ||
N.getRawUpperBound(),
1035 "GenericSubrange must contain count or upperBound", &
N);
1036 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1037 "GenericSubrange can have any one of count or upperBound", &
N);
1038 auto *CBound =
N.getRawCountNode();
1039 CheckDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1040 "Count must be signed constant or DIVariable or DIExpression", &
N);
1041 auto *LBound =
N.getRawLowerBound();
1042 CheckDI(LBound,
"GenericSubrange must contain lowerBound", &
N);
1043 CheckDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1044 "LowerBound must be signed constant or DIVariable or DIExpression",
1046 auto *UBound =
N.getRawUpperBound();
1047 CheckDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1048 "UpperBound must be signed constant or DIVariable or DIExpression",
1050 auto *Stride =
N.getRawStride();
1051 CheckDI(Stride,
"GenericSubrange must contain stride", &
N);
1052 CheckDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1053 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1057 CheckDI(
N.getTag() == dwarf::DW_TAG_enumerator,
"invalid tag", &
N);
1060 void Verifier::visitDIBasicType(
const DIBasicType &
N) {
1061 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type ||
1062 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1063 N.getTag() == dwarf::DW_TAG_string_type,
1068 CheckDI(
N.getTag() == dwarf::DW_TAG_string_type,
"invalid tag", &
N);
1069 CheckDI(!(
N.isBigEndian() &&
N.isLittleEndian()),
"has conflicting flags",
1077 CheckDI(
N.getTag() == dwarf::DW_TAG_typedef ||
1078 N.getTag() == dwarf::DW_TAG_pointer_type ||
1079 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1080 N.getTag() == dwarf::DW_TAG_reference_type ||
1081 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1082 N.getTag() == dwarf::DW_TAG_const_type ||
1083 N.getTag() == dwarf::DW_TAG_immutable_type ||
1084 N.getTag() == dwarf::DW_TAG_volatile_type ||
1085 N.getTag() == dwarf::DW_TAG_restrict_type ||
1086 N.getTag() == dwarf::DW_TAG_atomic_type ||
1087 N.getTag() == dwarf::DW_TAG_member ||
1088 N.getTag() == dwarf::DW_TAG_inheritance ||
1089 N.getTag() == dwarf::DW_TAG_friend ||
1090 N.getTag() == dwarf::DW_TAG_set_type,
1092 if (
N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1093 CheckDI(
isType(
N.getRawExtraData()),
"invalid pointer to member type", &
N,
1094 N.getRawExtraData());
1097 if (
N.getTag() == dwarf::DW_TAG_set_type) {
1098 if (
auto *
T =
N.getRawBaseType()) {
1099 auto *
Enum = dyn_cast_or_null<DICompositeType>(
T);
1100 auto *
Basic = dyn_cast_or_null<DIBasicType>(
T);
1102 (Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1103 (Basic && (
Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1104 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1105 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1106 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1107 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1108 "invalid set base type", &
N,
T);
1114 N.getRawBaseType());
1116 if (
N.getDWARFAddressSpace()) {
1117 CheckDI(
N.getTag() == dwarf::DW_TAG_pointer_type ||
1118 N.getTag() == dwarf::DW_TAG_reference_type ||
1119 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1120 "DWARF address space only applies to pointer or reference types",
1127 return ((Flags & DINode::FlagLValueReference) &&
1128 (Flags & DINode::FlagRValueReference)) ||
1129 ((Flags & DINode::FlagTypePassByValue) &&
1130 (Flags & DINode::FlagTypePassByReference));
1133 void Verifier::visitTemplateParams(
const MDNode &
N,
const Metadata &RawParams) {
1134 auto *Params = dyn_cast<MDTuple>(&RawParams);
1135 CheckDI(Params,
"invalid template params", &
N, &RawParams);
1137 CheckDI(
Op && isa<DITemplateParameter>(
Op),
"invalid template parameter",
1146 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type ||
1147 N.getTag() == dwarf::DW_TAG_structure_type ||
1148 N.getTag() == dwarf::DW_TAG_union_type ||
1149 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1150 N.getTag() == dwarf::DW_TAG_class_type ||
1151 N.getTag() == dwarf::DW_TAG_variant_part ||
1152 N.getTag() == dwarf::DW_TAG_namelist,
1157 N.getRawBaseType());
1159 CheckDI(!
N.getRawElements() || isa<MDTuple>(
N.getRawElements()),
1160 "invalid composite elements", &
N,
N.getRawElements());
1162 N.getRawVTableHolder());
1164 "invalid reference flags", &
N);
1165 unsigned DIBlockByRefStruct = 1 << 4;
1166 CheckDI((
N.getFlags() & DIBlockByRefStruct) == 0,
1167 "DIBlockByRefStruct on DICompositeType is no longer supported", &
N);
1170 const DINodeArray Elements =
N.getElements();
1171 CheckDI(Elements.size() == 1 &&
1172 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1173 "invalid vector, expected one element of type subrange", &
N);
1176 if (
auto *Params =
N.getRawTemplateParams())
1177 visitTemplateParams(
N, *Params);
1179 if (
auto *
D =
N.getRawDiscriminator()) {
1180 CheckDI(isa<DIDerivedType>(
D) &&
N.getTag() == dwarf::DW_TAG_variant_part,
1181 "discriminator can only appear on variant part");
1184 if (
N.getRawDataLocation()) {
1185 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1186 "dataLocation can only appear in array type");
1189 if (
N.getRawAssociated()) {
1190 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1191 "associated can only appear in array type");
1194 if (
N.getRawAllocated()) {
1195 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1196 "allocated can only appear in array type");
1199 if (
N.getRawRank()) {
1200 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1201 "rank can only appear in array type");
1206 CheckDI(
N.getTag() == dwarf::DW_TAG_subroutine_type,
"invalid tag", &
N);
1207 if (
auto *Types =
N.getRawTypeArray()) {
1208 CheckDI(isa<MDTuple>(Types),
"invalid composite elements", &
N, Types);
1209 for (
Metadata *Ty :
N.getTypeArray()->operands()) {
1210 CheckDI(
isType(Ty),
"invalid subroutine type ref", &
N, Types, Ty);
1214 "invalid reference flags", &
N);
1217 void Verifier::visitDIFile(
const DIFile &
N) {
1218 CheckDI(
N.getTag() == dwarf::DW_TAG_file_type,
"invalid tag", &
N);
1221 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1222 "invalid checksum kind", &
N);
1224 switch (Checksum->Kind) {
1235 CheckDI(Checksum->Value.size() == Size,
"invalid checksum length", &
N);
1237 "invalid checksum", &
N);
1242 CheckDI(
N.isDistinct(),
"compile units must be distinct", &
N);
1243 CheckDI(
N.getTag() == dwarf::DW_TAG_compile_unit,
"invalid tag", &
N);
1247 CheckDI(
N.getRawFile() && isa<DIFile>(
N.getRawFile()),
"invalid file", &
N,
1249 CheckDI(!
N.getFile()->getFilename().empty(),
"invalid filename", &
N,
1254 verifySourceDebugInfo(
N, *
N.getFile());
1257 "invalid emission kind", &
N);
1259 if (
auto *Array =
N.getRawEnumTypes()) {
1260 CheckDI(isa<MDTuple>(Array),
"invalid enum list", &
N, Array);
1261 for (
Metadata *
Op :
N.getEnumTypes()->operands()) {
1262 auto *
Enum = dyn_cast_or_null<DICompositeType>(
Op);
1263 CheckDI(Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1264 "invalid enum type", &
N,
N.getEnumTypes(),
Op);
1267 if (
auto *Array =
N.getRawRetainedTypes()) {
1268 CheckDI(isa<MDTuple>(Array),
"invalid retained type list", &
N, Array);
1269 for (
Metadata *
Op :
N.getRetainedTypes()->operands()) {
1271 Op && (isa<DIType>(
Op) || (isa<DISubprogram>(
Op) &&
1272 !cast<DISubprogram>(
Op)->isDefinition())),
1273 "invalid retained type", &
N,
Op);
1276 if (
auto *Array =
N.getRawGlobalVariables()) {
1277 CheckDI(isa<MDTuple>(Array),
"invalid global variable list", &
N, Array);
1278 for (
Metadata *
Op :
N.getGlobalVariables()->operands()) {
1279 CheckDI(
Op && (isa<DIGlobalVariableExpression>(
Op)),
1280 "invalid global variable ref", &
N,
Op);
1283 if (
auto *Array =
N.getRawImportedEntities()) {
1284 CheckDI(isa<MDTuple>(Array),
"invalid imported entity list", &
N, Array);
1285 for (
Metadata *
Op :
N.getImportedEntities()->operands()) {
1286 CheckDI(
Op && isa<DIImportedEntity>(
Op),
"invalid imported entity ref",
1290 if (
auto *Array =
N.getRawMacros()) {
1291 CheckDI(isa<MDTuple>(Array),
"invalid macro list", &
N, Array);
1293 CheckDI(
Op && isa<DIMacroNode>(
Op),
"invalid macro ref", &
N,
Op);
1300 CheckDI(
N.getTag() == dwarf::DW_TAG_subprogram,
"invalid tag", &
N);
1302 if (
auto *
F =
N.getRawFile())
1303 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1305 CheckDI(
N.getLine() == 0,
"line specified with no file", &
N,
N.getLine());
1306 if (
auto *
T =
N.getRawType())
1307 CheckDI(isa<DISubroutineType>(
T),
"invalid subroutine type", &
N,
T);
1308 CheckDI(
isType(
N.getRawContainingType()),
"invalid containing type", &
N,
1309 N.getRawContainingType());
1310 if (
auto *Params =
N.getRawTemplateParams())
1311 visitTemplateParams(
N, *Params);
1312 if (
auto *
S =
N.getRawDeclaration())
1313 CheckDI(isa<DISubprogram>(
S) && !cast<DISubprogram>(
S)->isDefinition(),
1314 "invalid subprogram declaration", &
N,
S);
1315 if (
auto *RawNode =
N.getRawRetainedNodes()) {
1316 auto *Node = dyn_cast<MDTuple>(RawNode);
1317 CheckDI(Node,
"invalid retained nodes list", &
N, RawNode);
1319 CheckDI(
Op && (isa<DILocalVariable>(
Op) || isa<DILabel>(
Op)),
1320 "invalid retained nodes, expected DILocalVariable or DILabel", &
N,
1325 "invalid reference flags", &
N);
1327 auto *Unit =
N.getRawUnit();
1328 if (
N.isDefinition()) {
1330 CheckDI(
N.isDistinct(),
"subprogram definitions must be distinct", &
N);
1331 CheckDI(Unit,
"subprogram definitions must have a compile unit", &
N);
1332 CheckDI(isa<DICompileUnit>(Unit),
"invalid unit type", &
N, Unit);
1334 verifySourceDebugInfo(*
N.getUnit(), *
N.getFile());
1337 CheckDI(!Unit,
"subprogram declarations must not have a compile unit", &
N);
1340 if (
auto *RawThrownTypes =
N.getRawThrownTypes()) {
1341 auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
1342 CheckDI(ThrownTypes,
"invalid thrown types list", &
N, RawThrownTypes);
1344 CheckDI(
Op && isa<DIType>(
Op),
"invalid thrown type", &
N, ThrownTypes,
1348 if (
N.areAllCallsDescribed())
1350 "DIFlagAllCallsDescribed must be attached to a definition");
1354 CheckDI(
N.getTag() == dwarf::DW_TAG_lexical_block,
"invalid tag", &
N);
1355 CheckDI(
N.getRawScope() && isa<DILocalScope>(
N.getRawScope()),
1356 "invalid local scope", &
N,
N.getRawScope());
1357 if (
auto *SP = dyn_cast<DISubprogram>(
N.getRawScope()))
1358 CheckDI(SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1362 visitDILexicalBlockBase(
N);
1365 "cannot have column info without line info", &
N);
1369 visitDILexicalBlockBase(
N);
1373 CheckDI(
N.getTag() == dwarf::DW_TAG_common_block,
"invalid tag", &
N);
1374 if (
auto *
S =
N.getRawScope())
1375 CheckDI(isa<DIScope>(
S),
"invalid scope ref", &
N,
S);
1376 if (
auto *
S =
N.getRawDecl())
1377 CheckDI(isa<DIGlobalVariable>(
S),
"invalid declaration", &
N,
S);
1380 void Verifier::visitDINamespace(
const DINamespace &
N) {
1381 CheckDI(
N.getTag() == dwarf::DW_TAG_namespace,
"invalid tag", &
N);
1382 if (
auto *
S =
N.getRawScope())
1383 CheckDI(isa<DIScope>(
S),
"invalid scope ref", &
N,
S);
1386 void Verifier::visitDIMacro(
const DIMacro &
N) {
1389 "invalid macinfo type", &
N);
1390 CheckDI(!
N.getName().empty(),
"anonymous macro", &
N);
1391 if (!
N.getValue().empty()) {
1392 assert(
N.getValue().data()[0] !=
' ' &&
"Macro value has a space prefix");
1396 void Verifier::visitDIMacroFile(
const DIMacroFile &
N) {
1398 "invalid macinfo type", &
N);
1399 if (
auto *
F =
N.getRawFile())
1400 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1402 if (
auto *Array =
N.getRawElements()) {
1403 CheckDI(isa<MDTuple>(Array),
"invalid macro list", &
N, Array);
1404 for (
Metadata *
Op :
N.getElements()->operands()) {
1405 CheckDI(
Op && isa<DIMacroNode>(
Op),
"invalid macro ref", &
N,
Op);
1410 void Verifier::visitDIArgList(
const DIArgList &
N) {
1412 "DIArgList should have no operands other than a list of "
1417 void Verifier::visitDIModule(
const DIModule &
N) {
1418 CheckDI(
N.getTag() == dwarf::DW_TAG_module,
"invalid tag", &
N);
1419 CheckDI(!
N.getName().empty(),
"anonymous module", &
N);
1427 visitDITemplateParameter(
N);
1429 CheckDI(
N.getTag() == dwarf::DW_TAG_template_type_parameter,
"invalid tag",
1433 void Verifier::visitDITemplateValueParameter(
1435 visitDITemplateParameter(
N);
1437 CheckDI(
N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1438 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1439 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1443 void Verifier::visitDIVariable(
const DIVariable &
N) {
1444 if (
auto *
S =
N.getRawScope())
1445 CheckDI(isa<DIScope>(
S),
"invalid scope", &
N,
S);
1446 if (
auto *
F =
N.getRawFile())
1447 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1454 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1457 if (
N.isDefinition())
1458 CheckDI(
N.getType(),
"missing global variable type", &
N);
1459 if (
auto *Member =
N.getRawStaticDataMemberDeclaration()) {
1460 CheckDI(isa<DIDerivedType>(Member),
1461 "invalid static data member declaration", &
N, Member);
1470 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1471 CheckDI(
N.getRawScope() && isa<DILocalScope>(
N.getRawScope()),
1472 "local variable requires a valid scope", &
N,
N.getRawScope());
1473 if (
auto Ty =
N.getType())
1474 CheckDI(!isa<DISubroutineType>(Ty),
"invalid type", &
N,
N.getType());
1477 void Verifier::visitDILabel(
const DILabel &
N) {
1478 if (
auto *
S =
N.getRawScope())
1479 CheckDI(isa<DIScope>(
S),
"invalid scope", &
N,
S);
1480 if (
auto *
F =
N.getRawFile())
1481 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1483 CheckDI(
N.getTag() == dwarf::DW_TAG_label,
"invalid tag", &
N);
1484 CheckDI(
N.getRawScope() && isa<DILocalScope>(
N.getRawScope()),
1485 "label requires a valid scope", &
N,
N.getRawScope());
1489 CheckDI(
N.isValid(),
"invalid expression", &
N);
1492 void Verifier::visitDIGlobalVariableExpression(
1496 visitDIGlobalVariable(*Var);
1498 visitDIExpression(*Expr);
1499 if (
auto Fragment = Expr->getFragmentInfo())
1500 verifyFragmentExpression(*GVE.
getVariable(), *Fragment, &GVE);
1505 CheckDI(
N.getTag() == dwarf::DW_TAG_APPLE_property,
"invalid tag", &
N);
1506 if (
auto *
T =
N.getRawType())
1508 if (
auto *
F =
N.getRawFile())
1509 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1513 CheckDI(
N.getTag() == dwarf::DW_TAG_imported_module ||
1514 N.getTag() == dwarf::DW_TAG_imported_declaration,
1516 if (
auto *
S =
N.getRawScope())
1517 CheckDI(isa<DIScope>(
S),
"invalid scope for imported entity", &
N,
S);
1522 void Verifier::visitComdat(
const Comdat &
C) {
1525 if (
TT.isOSBinFormatCOFF())
1531 void Verifier::visitModuleIdents() {
1532 const NamedMDNode *Idents =
M.getNamedMetadata(
"llvm.ident");
1539 Check(
N->getNumOperands() == 1,
1540 "incorrect number of operands in llvm.ident metadata",
N);
1541 Check(dyn_cast_or_null<MDString>(
N->getOperand(0)),
1542 (
"invalid value for llvm.ident metadata entry operand"
1543 "(the operand should be a string)"),
1548 void Verifier::visitModuleCommandLines() {
1549 const NamedMDNode *CommandLines =
M.getNamedMetadata(
"llvm.commandline");
1557 Check(
N->getNumOperands() == 1,
1558 "incorrect number of operands in llvm.commandline metadata",
N);
1559 Check(dyn_cast_or_null<MDString>(
N->getOperand(0)),
1560 (
"invalid value for llvm.commandline metadata entry operand"
1561 "(the operand should be a string)"),
1566 void Verifier::visitModuleFlags() {
1574 visitModuleFlag(MDN, SeenIDs, Requirements);
1583 CheckFailed(
"invalid requirement on flag, flag is not present in module",
1588 if (
Op->getOperand(2) != ReqValue) {
1589 CheckFailed((
"invalid requirement on flag, "
1590 "flag does not have the required value"),
1598 Verifier::visitModuleFlag(
const MDNode *
Op,
1603 Check(
Op->getNumOperands() == 3,
1604 "incorrect number of operands in module flag",
Op);
1607 Check(mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(0)),
1608 "invalid behavior operand in module flag (expected constant integer)",
1611 "invalid behavior operand in module flag (unexpected constant)",
1614 MDString *
ID = dyn_cast_or_null<MDString>(
Op->getOperand(1));
1615 Check(
ID,
"invalid ID operand in module flag (expected metadata string)",
1627 Check(mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(2)),
1628 "invalid value for 'min' module flag (expected constant integer)",
1634 Check(mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(2)),
1635 "invalid value for 'max' module flag (expected constant integer)",
1645 "invalid value for 'require' module flag (expected metadata pair)",
1648 (
"invalid value for 'require' module flag "
1649 "(first value operand should be a string)"),
1650 Value->getOperand(0));
1654 Requirements.push_back(
Value);
1661 Check(isa<MDNode>(
Op->getOperand(2)),
1662 "invalid value for 'append'-type module flag "
1663 "(expected a metadata node)",
1671 bool Inserted = SeenIDs.
insert(std::make_pair(
ID,
Op)).second;
1673 "module flag identifiers must be unique (or of 'require' type)",
ID);
1676 if (
ID->getString() ==
"wchar_size") {
1678 = mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(2));
1679 Check(
Value,
"wchar_size metadata requires constant integer argument");
1682 if (
ID->getString() ==
"Linker Options") {
1686 Check(
M.getNamedMetadata(
"llvm.linker.options"),
1687 "'Linker Options' named metadata no longer supported");
1690 if (
ID->getString() ==
"SemanticInterposition") {
1692 mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(2));
1694 "SemanticInterposition metadata requires constant integer argument");
1697 if (
ID->getString() ==
"CG Profile") {
1698 for (
const MDOperand &MDO : cast<MDNode>(
Op->getOperand(2))->operands())
1699 visitModuleFlagCGProfileEntry(MDO);
1703 void Verifier::visitModuleFlagCGProfileEntry(
const MDOperand &MDO) {
1704 auto CheckFunction = [&](
const MDOperand &FuncMDO) {
1707 auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
1708 Check(
F && isa<Function>(
F->getValue()->stripPointerCasts()),
1709 "expected a Function or null", FuncMDO);
1711 auto Node = dyn_cast_or_null<MDNode>(MDO);
1712 Check(Node && Node->getNumOperands() == 3,
"expected a MDNode triple", MDO);
1713 CheckFunction(Node->getOperand(0));
1714 CheckFunction(Node->getOperand(1));
1715 auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
1716 Check(Count && Count->getType()->isIntegerTy(),
1717 "expected an integer constant", Node->getOperand(2));
1723 if (
A.isStringAttribute()) {
1724 #define GET_ATTR_NAMES
1725 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1726 #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
1727 if (A.getKindAsString() == #DISPLAY_NAME) { \
1728 auto V = A.getValueAsString(); \
1729 if (!(V.empty() || V == "true" || V == "false")) \
1730 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
1734 #include "llvm/IR/Attributes.inc"
1739 CheckFailed(
"Attribute '" +
A.getAsString() +
"' should have an Argument",
1750 if (!
Attrs.hasAttributes())
1753 verifyAttributeTypes(
Attrs, V);
1756 Check(Attr.isStringAttribute() ||
1758 "Attribute '" + Attr.getAsString() +
"' does not apply to parameters",
1761 if (
Attrs.hasAttribute(Attribute::ImmArg)) {
1763 "Attribute 'immarg' is incompatible with other attributes", V);
1768 unsigned AttrCount = 0;
1769 AttrCount +=
Attrs.hasAttribute(Attribute::ByVal);
1770 AttrCount +=
Attrs.hasAttribute(Attribute::InAlloca);
1771 AttrCount +=
Attrs.hasAttribute(Attribute::Preallocated);
1772 AttrCount +=
Attrs.hasAttribute(Attribute::StructRet) ||
1773 Attrs.hasAttribute(Attribute::InReg);
1774 AttrCount +=
Attrs.hasAttribute(Attribute::Nest);
1775 AttrCount +=
Attrs.hasAttribute(Attribute::ByRef);
1776 Check(AttrCount <= 1,
1777 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
1778 "'byref', and 'sret' are incompatible!",
1781 Check(!(
Attrs.hasAttribute(Attribute::InAlloca) &&
1782 Attrs.hasAttribute(Attribute::ReadOnly)),
1784 "'inalloca and readonly' are incompatible!",
1787 Check(!(
Attrs.hasAttribute(Attribute::StructRet) &&
1788 Attrs.hasAttribute(Attribute::Returned)),
1790 "'sret and returned' are incompatible!",
1793 Check(!(
Attrs.hasAttribute(Attribute::ZExt) &&
1794 Attrs.hasAttribute(Attribute::SExt)),
1796 "'zeroext and signext' are incompatible!",
1799 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
1800 Attrs.hasAttribute(Attribute::ReadOnly)),
1802 "'readnone and readonly' are incompatible!",
1805 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
1806 Attrs.hasAttribute(Attribute::WriteOnly)),
1808 "'readnone and writeonly' are incompatible!",
1811 Check(!(
Attrs.hasAttribute(Attribute::ReadOnly) &&
1812 Attrs.hasAttribute(Attribute::WriteOnly)),
1814 "'readonly and writeonly' are incompatible!",
1817 Check(!(
Attrs.hasAttribute(Attribute::NoInline) &&
1818 Attrs.hasAttribute(Attribute::AlwaysInline)),
1820 "'noinline and alwaysinline' are incompatible!",
1825 if (!Attr.isStringAttribute() &&
1826 IncompatibleAttrs.
contains(Attr.getKindAsEnum())) {
1827 CheckFailed(
"Attribute '" + Attr.getAsString() +
1828 "' applied to incompatible type!", V);
1833 if (
PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1834 if (
Attrs.hasAttribute(Attribute::ByVal)) {
1835 if (
Attrs.hasAttribute(Attribute::Alignment)) {
1837 Align MaxAlign(ParamMaxAlignment);
1838 Check(AttrAlign <= MaxAlign,
1839 "Attribute 'align' exceed the max size 2^14", V);
1842 Check(
Attrs.getByValType()->isSized(&Visited),
1843 "Attribute 'byval' does not support unsized types!", V);
1845 if (
Attrs.hasAttribute(Attribute::ByRef)) {
1847 Check(
Attrs.getByRefType()->isSized(&Visited),
1848 "Attribute 'byref' does not support unsized types!", V);
1850 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
1852 Check(
Attrs.getInAllocaType()->isSized(&Visited),
1853 "Attribute 'inalloca' does not support unsized types!", V);
1855 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
1857 Check(
Attrs.getPreallocatedType()->isSized(&Visited),
1858 "Attribute 'preallocated' does not support unsized types!", V);
1862 Check(!
Attrs.hasAttribute(Attribute::SwiftError),
1863 "Attribute 'swifterror' only applies to parameters "
1864 "with pointer to pointer type!",
1866 if (
Attrs.hasAttribute(Attribute::ByRef)) {
1868 "Attribute 'byref' type does not match parameter!", V);
1871 if (
Attrs.hasAttribute(Attribute::ByVal) &&
Attrs.getByValType()) {
1873 "Attribute 'byval' type does not match parameter!", V);
1876 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
1879 "Attribute 'preallocated' type does not match parameter!", V);
1882 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
1884 "Attribute 'inalloca' type does not match parameter!", V);
1887 if (
Attrs.hasAttribute(Attribute::ElementType)) {
1889 "Attribute 'elementtype' type does not match parameter!", V);
1897 if (
Attrs.hasFnAttr(Attr)) {
1900 if (
S.getAsInteger(10,
N))
1901 CheckFailed(
"\"" + Attr +
"\" takes an unsigned integer: " +
S, V);
1908 const Value *V,
bool IsIntrinsic,
1910 if (
Attrs.isEmpty())
1913 if (AttributeListsVisited.
insert(
Attrs.getRawPointer()).second) {
1915 "Attribute list does not match Module context!", &
Attrs, V);
1916 for (
const auto &AttrSet :
Attrs) {
1917 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(
Context),
1918 "Attribute set does not match Module context!", &AttrSet, V);
1919 for (
const auto &A : AttrSet) {
1921 "Attribute does not match Module context!", &A, V);
1926 bool SawNest =
false;
1927 bool SawReturned =
false;
1928 bool SawSRet =
false;
1929 bool SawSwiftSelf =
false;
1930 bool SawSwiftAsync =
false;
1931 bool SawSwiftError =
false;
1938 "Attribute '" +
RetAttr.getAsString() +
1939 "' does not apply to function return values",
1951 "immarg attribute only applies to intrinsics", V);
1954 "Attribute 'elementtype' can only be applied to intrinsics"
1959 verifyParameterAttrs(ArgAttrs, Ty, V);
1962 Check(!SawNest,
"More than one parameter has attribute nest!", V);
1967 Check(!SawReturned,
"More than one parameter has attribute returned!", V);
1969 "Incompatible argument and return types for 'returned' attribute",
1975 Check(!SawSRet,
"Cannot have multiple 'sret' parameters!", V);
1977 "Attribute 'sret' is not on first or second parameter!", V);
1982 Check(!SawSwiftSelf,
"Cannot have multiple 'swiftself' parameters!", V);
1983 SawSwiftSelf =
true;
1987 Check(!SawSwiftAsync,
"Cannot have multiple 'swiftasync' parameters!", V);
1988 SawSwiftAsync =
true;
1992 Check(!SawSwiftError,
"Cannot have multiple 'swifterror' parameters!", V);
1993 SawSwiftError =
true;
1998 "inalloca isn't on the last parameter!", V);
2002 if (!
Attrs.hasFnAttrs())
2005 verifyAttributeTypes(
Attrs.getFnAttrs(), V);
2009 "Attribute '" +
FnAttr.getAsString() +
2010 "' does not apply to functions!",
2013 Check(!(
Attrs.hasFnAttr(Attribute::ReadNone) &&
2014 Attrs.hasFnAttr(Attribute::ReadOnly)),
2015 "Attributes 'readnone and readonly' are incompatible!", V);
2017 Check(!(
Attrs.hasFnAttr(Attribute::ReadNone) &&
2018 Attrs.hasFnAttr(Attribute::WriteOnly)),
2019 "Attributes 'readnone and writeonly' are incompatible!", V);
2021 Check(!(
Attrs.hasFnAttr(Attribute::ReadOnly) &&
2022 Attrs.hasFnAttr(Attribute::WriteOnly)),
2023 "Attributes 'readonly and writeonly' are incompatible!", V);
2025 Check(!(
Attrs.hasFnAttr(Attribute::ReadNone) &&
2026 Attrs.hasFnAttr(Attribute::InaccessibleMemOrArgMemOnly)),
2027 "Attributes 'readnone and inaccessiblemem_or_argmemonly' are "
2031 Check(!(
Attrs.hasFnAttr(Attribute::ReadNone) &&
2032 Attrs.hasFnAttr(Attribute::InaccessibleMemOnly)),
2033 "Attributes 'readnone and inaccessiblememonly' are incompatible!", V);
2035 Check(!(
Attrs.hasFnAttr(Attribute::NoInline) &&
2036 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2037 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2039 if (
Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2041 "Attribute 'optnone' requires 'noinline'!", V);
2043 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2044 "Attributes 'optsize and optnone' are incompatible!", V);
2047 "Attributes 'minsize and optnone' are incompatible!", V);
2053 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2056 if (
Attrs.hasFnAttr(Attribute::AllocSize)) {
2057 std::pair<unsigned, Optional<unsigned>>
Args =
2058 Attrs.getFnAttrs().getAllocSizeArgs();
2062 CheckFailed(
"'allocsize' " +
Name +
" argument is out of bounds", V);
2067 CheckFailed(
"'allocsize' " +
Name +
2068 " argument must refer to an integer parameter",
2076 if (!CheckParam(
"element size",
Args.first))
2079 if (
Args.second && !CheckParam(
"number of elements", *
Args.second))
2083 if (
Attrs.hasFnAttr(Attribute::VScaleRange)) {
2084 unsigned VScaleMin =
Attrs.getFnAttrs().getVScaleRangeMin();
2086 CheckFailed(
"'vscale_range' minimum must be greater than 0", V);
2089 if (VScaleMax && VScaleMin > VScaleMax)
2090 CheckFailed(
"'vscale_range' minimum cannot be greater than maximum", V);
2093 if (
Attrs.hasFnAttr(
"frame-pointer")) {
2095 if (FP !=
"all" && FP !=
"non-leaf" && FP !=
"none")
2096 CheckFailed(
"invalid value for 'frame-pointer' attribute: " + FP, V);
2099 checkUnsignedBaseTenFuncAttr(
Attrs,
"patchable-function-prefix", V);
2100 checkUnsignedBaseTenFuncAttr(
Attrs,
"patchable-function-entry", V);
2101 checkUnsignedBaseTenFuncAttr(
Attrs,
"warn-stack-size", V);
2104 void Verifier::verifyFunctionMetadata(
2105 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2106 for (
const auto &Pair : MDs) {
2107 if (Pair.first == LLVMContext::MD_prof) {
2108 MDNode *MD = Pair.second;
2110 "!prof annotations should have no less than 2 operands", MD);
2113 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null",
2116 "expected string with name of the !prof annotation", MD);
2120 ProfName.
equals(
"synthetic_function_entry_count"),
2121 "first operand should be 'function_entry_count'"
2122 " or 'synthetic_function_entry_count'",
2126 Check(MD->
getOperand(1) !=
nullptr,
"second operand should not be null",
2129 "expected integer argument to function_entry_count", MD);
2134 void Verifier::visitConstantExprsRecursively(
const Constant *EntryC) {
2135 if (!ConstantExprVisited.
insert(EntryC).second)
2139 Stack.push_back(EntryC);
2141 while (!
Stack.empty()) {
2145 if (
const auto *CE = dyn_cast<ConstantExpr>(
C))
2146 visitConstantExpr(CE);
2148 if (
const auto *GV = dyn_cast<GlobalValue>(
C)) {
2151 Check(GV->
getParent() == &M,
"Referencing global in another module!",
2157 for (
const Use &U :
C->operands()) {
2158 const auto *OpC = dyn_cast<Constant>(U);
2161 if (!ConstantExprVisited.
insert(OpC).second)
2163 Stack.push_back(OpC);
2168 void Verifier::visitConstantExpr(
const ConstantExpr *CE) {
2169 if (
CE->getOpcode() == Instruction::BitCast)
2172 "Invalid bitcast", CE);
2178 return Attrs.getNumAttrSets() <= Params + 2;
2181 void Verifier::verifyInlineAsmCall(
const CallBase &Call) {
2182 const InlineAsm *IA = cast<InlineAsm>(
Call.getCalledOperand());
2189 if (CI.isIndirect) {
2191 Check(
Arg->getType()->isPointerTy(),
2192 "Operand for indirect constraint must have pointer type", &Call);
2195 "Operand for indirect constraint must have elementtype attribute",
2198 Check(!
Call.paramHasAttr(ArgNo, Attribute::ElementType),
2199 "Elementtype attribute can only be applied for indirect "
2209 void Verifier::verifyStatepoint(
const CallBase &Call) {
2211 Call.getCalledFunction()->getIntrinsicID() ==
2212 Intrinsic::experimental_gc_statepoint);
2214 Check(!
Call.doesNotAccessMemory() && !
Call.onlyReadsMemory() &&
2215 !
Call.onlyAccessesArgMemory(),
2216 "gc.statepoint must read and write all memory to preserve "
2217 "reordering restrictions required by safepoint semantics",
2220 const int64_t NumPatchBytes =
2221 cast<ConstantInt>(
Call.getArgOperand(1))->getSExtValue();
2223 Check(NumPatchBytes >= 0,
2224 "gc.statepoint number of patchable bytes must be "
2228 Type *TargetElemType =
Call.getParamElementType(2);
2229 Check(TargetElemType,
2230 "gc.statepoint callee argument must have elementtype attribute", Call);
2231 FunctionType *TargetFuncType = dyn_cast<FunctionType>(TargetElemType);
2232 Check(TargetFuncType,
2233 "gc.statepoint callee elementtype must be function type", Call);
2235 const int NumCallArgs = cast<ConstantInt>(
Call.getArgOperand(3))->getZExtValue();
2236 Check(NumCallArgs >= 0,
2237 "gc.statepoint number of arguments to underlying call "
2242 Check(NumCallArgs >= NumParams,
2243 "gc.statepoint mismatch in number of vararg call args", Call);
2247 "gc.statepoint doesn't support wrapping non-void "
2248 "vararg functions yet",
2251 Check(NumCallArgs == NumParams,
2252 "gc.statepoint mismatch in number of call args", Call);
2255 = cast<ConstantInt>(
Call.getArgOperand(4))->getZExtValue();
2257 "unknown flag used in gc.statepoint flags argument", Call);
2262 for (
int i = 0;
i < NumParams;
i++) {
2264 Type *ArgType =
Call.getArgOperand(5 +
i)->getType();
2265 Check(ArgType == ParamType,
2266 "gc.statepoint call argument does not match wrapped "
2273 "Attribute 'sret' cannot be used for vararg call arguments!", Call);
2277 const int EndCallArgsInx = 4 + NumCallArgs;
2279 const Value *NumTransitionArgsV =
Call.getArgOperand(EndCallArgsInx + 1);
2280 Check(isa<ConstantInt>(NumTransitionArgsV),
2281 "gc.statepoint number of transition arguments "
2282 "must be constant integer",
2284 const int NumTransitionArgs =
2285 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
2286 Check(NumTransitionArgs == 0,
2287 "gc.statepoint w/inline transition bundle is deprecated", Call);
2288 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2290 const Value *NumDeoptArgsV =
Call.getArgOperand(EndTransitionArgsInx + 1);
2291 Check(isa<ConstantInt>(NumDeoptArgsV),
2292 "gc.statepoint number of deoptimization arguments "
2293 "must be constant integer",
2295 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
2296 Check(NumDeoptArgs == 0,
2297 "gc.statepoint w/inline deopt operands is deprecated", Call);
2299 const int ExpectedNumArgs = 7 + NumCallArgs;
2300 Check(ExpectedNumArgs == (
int)
Call.arg_size(),
2301 "gc.statepoint too many arguments", Call);
2306 for (
const User *U :
Call.users()) {
2307 const CallInst *UserCall = dyn_cast<const CallInst>(U);
2308 Check(UserCall,
"illegal use of statepoint token", Call, U);
2311 Check(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
2312 "gc.result or gc.relocate are the only value uses "
2313 "of a gc.statepoint",
2315 if (isa<GCResultInst>(UserCall)) {
2317 "gc.result connected to wrong gc.statepoint", Call, UserCall);
2318 }
else if (isa<GCRelocateInst>(Call)) {
2320 "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
2334 void Verifier::verifyFrameRecoverIndices() {
2335 for (
auto &Counts : FrameEscapeInfo) {
2337 unsigned EscapedObjectCount = Counts.second.first;
2338 unsigned MaxRecoveredIndex = Counts.second.second;
2339 Check(MaxRecoveredIndex <= EscapedObjectCount,
2340 "all indices passed to llvm.localrecover must be less than the "
2341 "number of arguments passed to llvm.localescape in the parent "
2349 if (
auto *II = dyn_cast<InvokeInst>(
Terminator))
2350 UnwindDest = II->getUnwindDest();
2351 else if (
auto *CSI = dyn_cast<CatchSwitchInst>(
Terminator))
2352 UnwindDest = CSI->getUnwindDest();
2354 UnwindDest = cast<CleanupReturnInst>(
Terminator)->getUnwindDest();
2358 void Verifier::verifySiblingFuncletUnwinds() {
2361 for (
const auto &Pair : SiblingFuncletInfo) {
2363 if (Visited.
count(PredPad))
2369 if (Active.
count(SuccPad)) {
2374 CycleNodes.push_back(CyclePad);
2375 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
2376 if (CycleTerminator != CyclePad)
2377 CycleNodes.push_back(CycleTerminator);
2379 }
while (CyclePad != SuccPad);
2380 Check(
false,
"EH pads can't handle each other's exceptions",
2384 if (!Visited.
insert(SuccPad).second)
2388 auto TermI = SiblingFuncletInfo.find(PredPad);
2389 if (TermI == SiblingFuncletInfo.end())
2402 void Verifier::visitFunction(
const Function &
F) {
2403 visitGlobalValue(
F);
2407 unsigned NumArgs =
F.arg_size();
2410 "Function context does not match Module context!", &
F);
2412 Check(!
F.hasCommonLinkage(),
"Functions may not have common linkage", &
F);
2414 "# formal arguments must match # of arguments for function type!", &
F,
2416 Check(
F.getReturnType()->isFirstClassType() ||
2417 F.getReturnType()->isVoidTy() ||
F.getReturnType()->isStructTy(),
2418 "Functions cannot return aggregate values!", &
F);
2420 Check(!
F.hasStructRetAttr() ||
F.getReturnType()->isVoidTy(),
2421 "Invalid struct return type!", &
F);
2426 "Attribute after last parameter!", &
F);
2428 bool IsIntrinsic =
F.isIntrinsic();
2431 verifyFunctionAttrs(FT,
Attrs, &
F, IsIntrinsic,
false);
2437 "Attribute 'builtin' can only be applied to a callsite.", &
F);
2439 Check(!
Attrs.hasAttrSomewhere(Attribute::ElementType),
2440 "Attribute 'elementtype' can only be applied to a callsite.", &
F);
2445 switch (
F.getCallingConv()) {
2450 Check(
F.arg_empty() ||
Attrs.hasParamAttr(0, Attribute::ByVal),
2451 "Calling convention parameter requires byval", &
F);
2456 Check(
F.getReturnType()->isVoidTy(),
2457 "Calling convention requires void return type", &
F);
2464 Check(!
F.hasStructRetAttr(),
"Calling convention does not allow sret", &
F);
2466 const unsigned StackAS =
DL.getAllocaAddrSpace();
2470 "Calling convention disallows byval", &
F);
2471 Check(!
Attrs.hasParamAttr(
i, Attribute::Preallocated),
2472 "Calling convention disallows preallocated", &
F);
2473 Check(!
Attrs.hasParamAttr(
i, Attribute::InAlloca),
2474 "Calling convention disallows inalloca", &
F);
2476 if (
Attrs.hasParamAttr(
i, Attribute::ByRef)) {
2479 Check(
Arg.getType()->getPointerAddressSpace() != StackAS,
2480 "Calling convention disallows stack byref", &
F);
2494 "Calling convention does not support varargs or "
2495 "perfect forwarding!",
2504 "Argument value does not match function argument type!", &
Arg,
2506 Check(
Arg.getType()->isFirstClassType(),
2507 "Function arguments must have first-class types!", &
Arg);
2509 Check(!
Arg.getType()->isMetadataTy(),
2510 "Function takes metadata but isn't an intrinsic", &
Arg, &
F);
2512 "Function takes token but isn't an intrinsic", &
Arg, &
F);
2513 Check(!
Arg.getType()->isX86_AMXTy(),
2514 "Function takes x86_amx but isn't an intrinsic", &
Arg, &
F);
2518 if (
Attrs.hasParamAttr(
i, Attribute::SwiftError)) {
2519 verifySwiftErrorValue(&
Arg);
2525 Check(!
F.getReturnType()->isTokenTy(),
2526 "Function returns a token but isn't an intrinsic", &
F);
2527 Check(!
F.getReturnType()->isX86_AMXTy(),
2528 "Function returns a x86_amx but isn't an intrinsic", &
F);
2533 F.getAllMetadata(MDs);
2534 assert(
F.hasMetadata() != MDs.empty() &&
"Bit out-of-sync");
2535 verifyFunctionMetadata(MDs);
2538 if (
F.hasPersonalityFn()) {
2539 auto *Per = dyn_cast<Function>(
F.getPersonalityFn()->stripPointerCasts());
2541 Check(Per->getParent() ==
F.getParent(),
2542 "Referencing personality function in another module!", &
F,
2543 F.getParent(), Per, Per->getParent());
2546 if (
F.isMaterializable()) {
2548 Check(MDs.empty(),
"unmaterialized function cannot have metadata", &
F,
2549 MDs.empty() ?
nullptr : MDs.front().second);
2550 }
else if (
F.isDeclaration()) {
2551 for (
const auto &
I : MDs) {
2553 CheckDI(
I.first != LLVMContext::MD_dbg ||
2554 !cast<DISubprogram>(
I.second)->isDistinct(),
2555 "function declaration may only have a unique !dbg attachment",
2557 Check(
I.first != LLVMContext::MD_prof,
2558 "function declaration may not have a !prof attachment", &
F);
2561 visitMDNode(*
I.second, AreDebugLocsAllowed::Yes);
2563 Check(!
F.hasPersonalityFn(),
2564 "Function declaration shouldn't have a personality routine", &
F);
2568 Check(!IsIntrinsic,
"llvm intrinsics cannot be defined!", &
F);
2573 "Entry block to function must not have predecessors!", Entry);
2576 if (Entry->hasAddressTaken()) {
2578 "blockaddress may not be used with the entry block!", Entry);
2581 unsigned NumDebugAttachments = 0, NumProfAttachments = 0;
2583 for (
const auto &
I : MDs) {
2585 auto AllowLocs = AreDebugLocsAllowed::No;
2589 case LLVMContext::MD_dbg: {
2590 ++NumDebugAttachments;
2591 CheckDI(NumDebugAttachments == 1,
2592 "function must have a single !dbg attachment", &
F,
I.second);
2593 CheckDI(isa<DISubprogram>(
I.second),
2594 "function !dbg attachment must be a subprogram", &
F,
I.second);
2595 CheckDI(cast<DISubprogram>(
I.second)->isDistinct(),
2596 "function definition may only have a distinct !dbg attachment",
2599 auto *SP = cast<DISubprogram>(
I.second);
2600 const Function *&AttachedTo = DISubprogramAttachments[SP];
2601 CheckDI(!AttachedTo || AttachedTo == &
F,
2602 "DISubprogram attached to more than one function", SP, &
F);
2604 AllowLocs = AreDebugLocsAllowed::Yes;
2607 case LLVMContext::MD_prof:
2608 ++NumProfAttachments;
2609 Check(NumProfAttachments == 1,
2610 "function must have a single !prof attachment", &
F,
I.second);
2615 visitMDNode(*
I.second, AllowLocs);
2623 if (
F.isIntrinsic() &&
F.getParent()->isMaterialized()) {
2625 if (
F.hasAddressTaken(&U,
false,
true,
false,
2627 Check(
false,
"Invalid user of intrinsic instruction!", U);
2631 switch (
F.getIntrinsicID()) {
2632 case Intrinsic::experimental_gc_get_pointer_base: {
2635 Check(isa<PointerType>(
F.getReturnType()),
2636 "gc.get.pointer.base must return a pointer",
F);
2638 "gc.get.pointer.base operand and result must be of the same type",
F);
2641 case Intrinsic::experimental_gc_get_pointer_offset: {
2645 "gc.get.pointer.offset operand must be a pointer",
F);
2646 Check(
F.getReturnType()->isIntegerTy(),
2647 "gc.get.pointer.offset must return integer",
F);
2652 auto *
N =
F.getSubprogram();
2653 HasDebugInfo = (
N !=
nullptr);
2665 const DILocation *
DL = dyn_cast_or_null<DILocation>(Node);
2672 CheckDI(Parent && isa<DILocalScope>(Parent),
2673 "DILocation's scope must be a DILocalScope",
N, &
F, &
I,
DL, Parent);
2685 if (SP && ((
Scope != SP) && !Seen.
insert(SP).second))
2689 "!dbg attachment points at wrong subprogram for function",
N, &
F,
2693 for (
auto &
I :
BB) {
2694 VisitDebugLoc(
I,
I.getDebugLoc().getAsMDNode());
2696 if (
auto MD =
I.getMetadata(LLVMContext::MD_loop))
2698 VisitDebugLoc(
I, dyn_cast_or_null<MDNode>(MD->
getOperand(
i)));
2699 if (BrokenDebugInfo)
2707 InstsInThisBlock.
clear();
2710 Check(
BB.getTerminator(),
"Basic Block does not have terminator!", &
BB);
2714 if (isa<PHINode>(
BB.front())) {
2719 Check(PN.getNumIncomingValues() == Preds.size(),
2720 "PHINode should have one entry for each predecessor of its "
2721 "parent basic block!",
2726 Values.
reserve(PN.getNumIncomingValues());
2727 for (
unsigned i = 0,
e = PN.getNumIncomingValues();
i !=
e; ++
i)
2729 std::make_pair(PN.getIncomingBlock(
i), PN.getIncomingValue(
i)));
2732 for (
unsigned i = 0,
e = Values.size();
i !=
e; ++
i) {
2737 Check(
i == 0 || Values[
i].first != Values[
i - 1].first ||
2738 Values[
i].second == Values[
i - 1].second,
2739 "PHI node has multiple entries for the same basic block with "
2740 "different incoming values!",
2741 &PN, Values[
i].first, Values[
i].second, Values[
i - 1].second);
2745 Check(Values[
i].first == Preds[
i],
2746 "PHI node entries do not match predecessors!", &PN,
2747 Values[
i].first, Preds[
i]);
2755 Check(
I.getParent() == &
BB,
"Instruction has bogus parent pointer!");
2761 Check(&
I ==
I.getParent()->getTerminator(),
2762 "Terminator found in the middle of a basic block!",
I.getParent());
2763 visitInstruction(
I);
2766 void Verifier::visitBranchInst(
BranchInst &BI) {
2769 "Branch condition is not 'i1' type!", &BI, BI.
getCondition());
2771 visitTerminator(BI);
2774 void Verifier::visitReturnInst(
ReturnInst &RI) {
2777 if (
F->getReturnType()->isVoidTy())
2779 "Found return instr that returns non-void in Function of void "
2781 &RI,
F->getReturnType());
2784 "Function return type does not match operand "
2785 "type of return inst!",
2786 &RI,
F->getReturnType());
2790 visitTerminator(RI);
2794 Check(
SI.getType()->isVoidTy(),
"Switch must have void result type!", &
SI);
2797 Type *SwitchTy =
SI.getCondition()->getType();
2799 for (
auto &Case :
SI.cases()) {
2800 Check(Case.getCaseValue()->getType() == SwitchTy,
2801 "Switch constants must all be same type as switch value!", &
SI);
2803 "Duplicate integer as switch case", &
SI, Case.getCaseValue());
2806 visitTerminator(
SI);
2811 "Indirectbr operand must have pointer type!", &BI);
2814 "Indirectbr destinations must all have pointer type!", &BI);
2816 visitTerminator(BI);
2819 void Verifier::visitCallBrInst(
CallBrInst &CBI) {
2820 Check(CBI.
isInlineAsm(),
"Callbr is currently only used for asm-goto!", &CBI);
2822 Check(!IA->
canThrow(),
"Unwinding from Callbr is not allowed");
2825 "Callbr successors must all have pointer type!", &CBI);
2828 "Using an unescaped label as a callbr argument!", &CBI);
2830 for (
unsigned j =
i + 1;
j !=
e; ++
j)
2832 "Duplicate callbr destination!", &CBI);
2837 if (
auto *BA = dyn_cast<BlockAddress>(V))
2838 ArgBBs.
insert(BA->getBasicBlock());
2840 Check(ArgBBs.
count(
BB),
"Indirect label missing from arglist.", &CBI);
2843 verifyInlineAsmCall(CBI);
2844 visitTerminator(CBI);
2850 "Invalid operands for select instruction!", &
SI);
2852 Check(
SI.getTrueValue()->getType() ==
SI.getType(),
2853 "Select values must have same type as select instruction!", &
SI);
2854 visitInstruction(
SI);
2861 Check(
false,
"User-defined operators should not live outside of a pass!", &
I);
2864 void Verifier::visitTruncInst(
TruncInst &
I) {
2866 Type *SrcTy =
I.getOperand(0)->getType();
2867 Type *DestTy =
I.getType();
2876 "trunc source and destination must both be a vector or neither", &
I);
2877 Check(SrcBitSize > DestBitSize,
"DestTy too big for Trunc", &
I);
2879 visitInstruction(
I);
2882 void Verifier::visitZExtInst(
ZExtInst &
I) {
2884 Type *SrcTy =
I.getOperand(0)->getType();
2885 Type *DestTy =
I.getType();
2891 "zext source and destination must both be a vector or neither", &
I);
2895 Check(SrcBitSize < DestBitSize,
"Type too small for ZExt", &
I);
2897 visitInstruction(
I);
2900 void Verifier::visitSExtInst(
SExtInst &
I) {
2902 Type *SrcTy =
I.getOperand(0)->getType();
2903 Type *DestTy =
I.getType();
2912 "sext source and destination must both be a vector or neither", &
I);
2913 Check(SrcBitSize < DestBitSize,
"Type too small for SExt", &
I);
2915 visitInstruction(
I);
2920 Type *SrcTy =
I.getOperand(0)->getType();
2921 Type *DestTy =
I.getType();
2929 "fptrunc source and destination must both be a vector or neither", &
I);
2930 Check(SrcBitSize > DestBitSize,
"DestTy too big for FPTrunc", &
I);
2932 visitInstruction(
I);
2935 void Verifier::visitFPExtInst(
FPExtInst &
I) {
2937 Type *SrcTy =
I.getOperand(0)->getType();
2938 Type *DestTy =
I.getType();
2947 "fpext source and destination must both be a vector or neither", &
I);
2948 Check(SrcBitSize < DestBitSize,
"DestTy too small for FPExt", &
I);
2950 visitInstruction(
I);
2955 Type *SrcTy =
I.getOperand(0)->getType();
2956 Type *DestTy =
I.getType();
2961 Check(SrcVec == DstVec,
2962 "UIToFP source and dest must both be vector or scalar", &
I);
2964 "UIToFP source must be integer or integer vector", &
I);
2968 if (SrcVec && DstVec)
2969 Check(cast<VectorType>(SrcTy)->getElementCount() ==
2970 cast<VectorType>(DestTy)->getElementCount(),
2971 "UIToFP source and dest vector length mismatch", &
I);
2973 visitInstruction(
I);
2978 Type *SrcTy =
I.getOperand(0)->getType();
2979 Type *DestTy =
I.getType();
2984 Check(SrcVec == DstVec,
2985 "SIToFP source and dest must both be vector or scalar", &
I);
2987 "SIToFP source must be integer or integer vector", &
I);
2991 if (SrcVec && DstVec)
2992 Check(cast<VectorType>(SrcTy)->getElementCount() ==
2993 cast<VectorType>(DestTy)->getElementCount(),
2994 "SIToFP source and dest vector length mismatch", &
I);
2996 visitInstruction(
I);
3001 Type *SrcTy =
I.getOperand(0)->getType();
3002 Type *DestTy =
I.getType();
3007 Check(SrcVec == DstVec,
3008 "FPToUI source and dest must both be vector or scalar", &
I);
3011 "FPToUI result must be integer or integer vector", &
I);
3013 if (SrcVec && DstVec)
3014 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3015 cast<VectorType>(DestTy)->getElementCount(),
3016 "FPToUI source and dest vector length mismatch", &
I);
3018 visitInstruction(
I);
3023 Type *SrcTy =
I.getOperand(0)->getType();
3024 Type *DestTy =
I.getType();
3029 Check(SrcVec == DstVec,
3030 "FPToSI source and dest must both be vector or scalar", &
I);
3033 "FPToSI result must be integer or integer vector", &
I);
3035 if (SrcVec && DstVec)
3036 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3037 cast<VectorType>(DestTy)->getElementCount(),
3038 "FPToSI source and dest vector length mismatch", &
I);
3040 visitInstruction(
I);
3045 Type *SrcTy =
I.getOperand(0)->getType();
3046 Type *DestTy =
I.getType();
3055 auto *VSrc = cast<VectorType>(SrcTy);
3056 auto *VDest = cast<VectorType>(DestTy);
3057 Check(VSrc->getElementCount() == VDest->getElementCount(),
3058 "PtrToInt Vector width mismatch", &
I);
3061 visitInstruction(
I);
3066 Type *SrcTy =
I.getOperand(0)->getType();
3067 Type *DestTy =
I.getType();
3075 auto *VSrc = cast<VectorType>(SrcTy);
3076 auto *VDest = cast<VectorType>(DestTy);
3077 Check(VSrc->getElementCount() == VDest->getElementCount(),
3078 "IntToPtr Vector width mismatch", &
I);
3080 visitInstruction(
I);
3086 "Invalid bitcast", &
I);
3087 visitInstruction(
I);
3091 Type *SrcTy =
I.getOperand(0)->getType();
3092 Type *DestTy =
I.getType();
3099 "AddrSpaceCast must be between different address spaces", &
I);
3100 if (
auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
3101 Check(SrcVTy->getElementCount() ==
3102 cast<VectorType>(DestTy)->getElementCount(),
3103 "AddrSpaceCast vector pointer number of elements mismatch", &
I);
3104 visitInstruction(
I);
3109 void Verifier::visitPHINode(
PHINode &PN) {
3116 "PHI nodes not grouped at top of basic block!", &PN, PN.
getParent());
3125 "PHI node operands are not the same type as the result!", &PN);
3130 visitInstruction(PN);
3133 void Verifier::visitCallBase(
CallBase &Call) {
3134 Check(
Call.getCalledOperand()->getType()->isPointerTy(),
3135 "Called function must be a pointer!", Call);
3136 PointerType *FPTy = cast<PointerType>(
Call.getCalledOperand()->getType());
3139 "Called function is not the same type as the call!", Call);
3146 "Called function requires more parameters than were provided!", Call);
3149 "Incorrect number of arguments passed to called function!", Call);
3154 "Call parameter type does not match function signature!",
3160 "Attribute after last parameter!", Call);
3162 auto VerifyTypeAlign = [&](
Type *Ty,
const Twine &Message) {
3165 Align ABIAlign =
DL.getABITypeAlign(Ty);
3166 Align MaxAlign(ParamMaxAlignment);
3167 Check(ABIAlign <= MaxAlign,
3168 "Incorrect alignment of " + Message +
" to called function!", Call);
3174 VerifyTypeAlign(Ty,
"argument passed");
3178 dyn_cast<Function>(
Call.getCalledOperand()->stripPointerCasts());
3182 "Intrinsic called with incompatible signature", Call);
3184 if (
Attrs.hasFnAttr(Attribute::Speculatable)) {
3188 "speculatable attribute may not apply to call sites", Call);
3191 if (
Attrs.hasFnAttr(Attribute::Preallocated)) {
3192 Check(
Call.getCalledFunction()->getIntrinsicID() ==
3193 Intrinsic::call_preallocated_arg,
3194 "preallocated as a call site attribute can only be on "
3195 "llvm.call.preallocated.arg");
3199 verifyFunctionAttrs(FTy,
Attrs, &Call, IsIntrinsic,
Call.isInlineAsm());
3204 if (
Call.hasInAllocaArgument()) {
3207 Check(AI->isUsedWithInAlloca(),
3208 "inalloca argument for call has mismatched alloca", AI, Call);
3215 if (
Call.paramHasAttr(
i, Attribute::SwiftError)) {
3216 Value *SwiftErrorArg =
Call.getArgOperand(
i);
3218 Check(AI->isSwiftError(),
3219 "swifterror argument for call has mismatched alloca", AI, Call);
3222 auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
3223 Check(ArgI,
"swifterror argument should come from an alloca or parameter",
3224 SwiftErrorArg, Call);
3225 Check(ArgI->hasSwiftErrorAttr(),
3226 "swifterror argument for call has mismatched parameter", ArgI,
3230 if (
Attrs.hasParamAttr(
i, Attribute::ImmArg)) {
3233 Check(Callee &&
Callee->hasParamAttribute(
i, Attribute::ImmArg),
3234 "immarg may not apply only to call sites",
Call.getArgOperand(
i),
3238 if (
Call.paramHasAttr(
i, Attribute::ImmArg)) {
3240 Check(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
3241 "immarg operand has non-immediate parameter", ArgVal, Call);
3244 if (
Call.paramHasAttr(
i, Attribute::Preallocated)) {
3248 bool isMustTail =
Call.isMustTailCall();
3249 Check(hasOB != isMustTail,
3250 "preallocated operand either requires a preallocated bundle or "
3251 "the call to be musttail (but not both)",
3258 bool SawNest =
false;
3259 bool SawReturned =
false;
3261 for (
unsigned Idx = 0; Idx < FTy->
getNumParams(); ++Idx) {
3262 if (
Attrs.hasParamAttr(Idx, Attribute::Nest))
3264 if (
Attrs.hasParamAttr(Idx, Attribute::Returned))
3270 Type *Ty =
Call.getArgOperand(Idx)->getType();
3272 verifyParameterAttrs(ArgAttrs, Ty, &Call);
3275 Check(!SawNest,
"More than one parameter has attribute nest!", Call);
3280 Check(!SawReturned,
"More than one parameter has attribute returned!",
3283 "Incompatible argument and return types for 'returned' "
3291 if (!
Call.getCalledFunction() ||
3292 Call.getCalledFunction()->getIntrinsicID() !=
3293 Intrinsic::experimental_gc_statepoint)
3295 "Attribute 'sret' cannot be used for vararg call arguments!",
3300 "inalloca isn't on the last argument!", Call);
3307 Check(!ParamTy->isMetadataTy(),
3308 "Function has metadata parameter but isn't an intrinsic", Call);
3309 Check(!ParamTy->isTokenTy(),
3310 "Function has token parameter but isn't an intrinsic", Call);
3315 if (!
Call.getCalledFunction()) {
3317 "Return type cannot be token for indirect call!");
3319 "Return type cannot be x86_amx for indirect call!");
3324 visitIntrinsicCall(
ID, Call);
3329 bool FoundDeoptBundle =
false, FoundFuncletBundle =
false,
3330 FoundGCTransitionBundle =
false, FoundCFGuardTargetBundle =
false,
3331 FoundPreallocatedBundle =
false, FoundGCLiveBundle =
false,
3332 FoundPtrauthBundle =
false,
3333 FoundAttachedCallBundle =
false;
3334 for (
unsigned i = 0,
e =
Call.getNumOperandBundles();
i <
e; ++
i) {
3338 Check(!FoundDeoptBundle,
"Multiple deopt operand bundles", Call);
3339 FoundDeoptBundle =
true;
3341 Check(!FoundGCTransitionBundle,
"Multiple gc-transition operand bundles",
3343 FoundGCTransitionBundle =
true;
3345 Check(!FoundFuncletBundle,
"Multiple funclet operand bundles", Call);
3346 FoundFuncletBundle =
true;
3348 "Expected exactly one funclet bundle operand", Call);
3350 "Funclet bundle operands should correspond to a FuncletPadInst",
3353 Check(!FoundCFGuardTargetBundle,
"Multiple CFGuardTarget operand bundles",
3355 FoundCFGuardTargetBundle =
true;
3357 "Expected exactly one cfguardtarget bundle operand", Call);
3359 Check(!FoundPtrauthBundle,
"Multiple ptrauth operand bundles", Call);
3360 FoundPtrauthBundle =
true;
3362 "Expected exactly two ptrauth bundle operands", Call);
3364 BU.
Inputs[0]->getType()->isIntegerTy(32),
3365 "Ptrauth bundle key operand must be an i32 constant", Call);
3367 "Ptrauth bundle discriminator operand must be an i64", Call);
3369 Check(!FoundPreallocatedBundle,
"Multiple preallocated operand bundles",
3371 FoundPreallocatedBundle =
true;
3373 "Expected exactly one preallocated bundle operand", Call);
3374 auto Input = dyn_cast<IntrinsicInst>(BU.
Inputs.front());
3376 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
3377 "\"preallocated\" argument must be a token from "
3378 "llvm.call.preallocated.setup",
3381 Check(!FoundGCLiveBundle,
"Multiple gc-live operand bundles", Call);
3382 FoundGCLiveBundle =
true;
3384 Check(!FoundAttachedCallBundle,
3385 "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
3386 FoundAttachedCallBundle =
true;
3387 verifyAttachedCallBundle(Call, BU);
3392 Check(!(
Call.getCalledFunction() && FoundPtrauthBundle),
3393 "Direct call cannot have a ptrauth bundle", Call);
3398 if (
Call.getFunction()->getSubprogram() &&
Call.getCalledFunction() &&
3399 Call.getCalledFunction()->getSubprogram())
3401 "inlinable function call in a function with "
3402 "debug info must have a !dbg location",
3405 if (
Call.isInlineAsm())
3406 verifyInlineAsmCall(Call);
3408 visitInstruction(Call);
3414 Twine(
"inalloca attribute not allowed in ") +
Context);
3417 Check(!
Attrs.contains(Attribute::SwiftError),
3418 Twine(
"swifterror attribute not allowed in ") +
Context);
3419 Check(!
Attrs.contains(Attribute::Preallocated),
3420 Twine(
"preallocated attribute not allowed in ") +
Context);
3439 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
3440 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
3441 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
3444 for (
auto AK : ABIAttrs) {
3447 Copy.addAttribute(Attr);
3451 if (
Attrs.hasParamAttr(
I, Attribute::Alignment) &&
3452 (
Attrs.hasParamAttr(
I, Attribute::ByVal) ||
3453 Attrs.hasParamAttr(
I, Attribute::ByRef)))
3458 void Verifier::verifyMustTailCall(
CallInst &CI) {
3465 "cannot guarantee tail call due to mismatched varargs", &CI);
3467 "cannot guarantee tail call due to mismatched return types", &CI);
3471 "cannot guarantee tail call due to mismatched calling conv", &CI);
3477 Value *RetVal = &CI;
3481 if (
BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
3483 "bitcast following musttail call must use the call", BI);
3490 Check(
Ret,
"musttail call must precede a ret with an optional bitcast", &CI);
3491 Check(!
Ret->getReturnValue() ||
Ret->getReturnValue() == RetVal ||
3492 isa<UndefValue>(
Ret->getReturnValue()),
3493 "musttail call result must be returned",
Ret);
3507 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
3512 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
3516 " tail call for varargs function");
3525 "cannot guarantee tail call due to mismatched parameter counts", &CI);
3529 "cannot guarantee tail call due to mismatched parameter types", &CI);
3538 Check(CallerABIAttrs == CalleeABIAttrs,
3539 "cannot guarantee tail call due to mismatched ABI impacting "
3540 "function attributes",
3545 void Verifier::visitCallInst(
CallInst &CI) {
3549 verifyMustTailCall(CI);
3552 void Verifier::visitInvokeInst(
InvokeInst &II) {
3559 "The unwind destination does not have an exception handling instruction!",
3562 visitTerminator(II);
3569 "Unary operators must have same type for"
3570 "operands and result!",
3576 case Instruction::FNeg:
3578 "FNeg operator only works with float types!", &U);
3584 visitInstruction(U);
3591 Check(
B.getOperand(0)->getType() ==
B.getOperand(1)->getType(),
3592 "Both operands to a binary operator are not of the same type!", &
B);
3594 switch (
B.getOpcode()) {
3598 case Instruction::Sub:
3600 case Instruction::SDiv:
3601 case Instruction::UDiv:
3602 case Instruction::SRem:
3603 case Instruction::URem:
3604 Check(
B.getType()->isIntOrIntVectorTy(),
3605 "Integer arithmetic operators only work with integral types!", &
B);
3606 Check(
B.getType() ==
B.getOperand(0)->getType(),
3607 "Integer arithmetic operators must have same type "
3608 "for operands and result!",
3613 case Instruction::FAdd:
3614 case Instruction::FSub:
3615 case Instruction::FMul:
3616 case Instruction::FDiv:
3617 case Instruction::FRem:
3618 Check(
B.getType()->isFPOrFPVectorTy(),
3619 "Floating-point arithmetic operators only work with "
3620 "floating-point types!",
3622 Check(
B.getType() ==
B.getOperand(0)->getType(),
3623 "Floating-point arithmetic operators must have same type "
3624 "for operands and result!",
3628 case Instruction::And:
3629 case Instruction::Or:
3630 case Instruction::Xor:
3631 Check(
B.getType()->isIntOrIntVectorTy(),
3632 "Logical operators only work with integral types!", &
B);
3633 Check(
B.getType() ==
B.getOperand(0)->getType(),
3634 "Logical operators must have same type for operands and result!", &
B);
3636 case Instruction::Shl:
3637 case Instruction::LShr:
3638 case Instruction::AShr:
3639 Check(
B.getType()->isIntOrIntVectorTy(),
3640 "Shifts only work with integral types!", &
B);
3641 Check(
B.getType() ==
B.getOperand(0)->getType(),
3642 "Shift return type must be same as operands!", &
B);
3648 visitInstruction(
B);
3651 void Verifier::visitICmpInst(
ICmpInst &IC) {
3655 Check(Op0Ty == Op1Ty,
3656 "Both operands to ICmp instruction are not of the same type!", &IC);
3659 "Invalid operand types for ICmp instruction", &IC);
3663 visitInstruction(IC);
3668 Type *Op0Ty =
FC.getOperand(0)->getType();
3669 Type *Op1Ty =
FC.getOperand(1)->getType();
3670 Check(Op0Ty == Op1Ty,
3671 "Both operands to FCmp instruction are not of the same type!", &
FC);
3676 Check(
FC.isFPPredicate(),
"Invalid predicate in FCmp instruction!", &
FC);
3678 visitInstruction(
FC);
3683 "Invalid extractelement operands!", &EI);
3684 visitInstruction(EI);
3690 "Invalid insertelement operands!", &
IE);
3691 visitInstruction(
IE);
3697 "Invalid shufflevector operands!", &SV);
3698 visitInstruction(SV);
3702 Type *TargetTy =
GEP.getPointerOperandType()->getScalarType();
3704 Check(isa<PointerType>(TargetTy),
3705 "GEP base pointer is not a vector or a vector of pointers", &
GEP);
3706 Check(
GEP.getSourceElementType()->isSized(),
"GEP into unsized type!", &
GEP);
3711 "GEP indexes must be integers", &
GEP);
3714 Check(ElTy,
"Invalid indices for GEP pointer type!", &
GEP);
3716 Check(
GEP.getType()->isPtrOrPtrVectorTy() &&
3717 GEP.getResultElementType() == ElTy,
3718 "GEP is not of right type for indices!", &
GEP, ElTy);
3720 if (
auto *GEPVTy = dyn_cast<VectorType>(
GEP.getType())) {
3723 if (
GEP.getPointerOperandType()->isVectorTy())
3726 cast<VectorType>(
GEP.getPointerOperandType())->getElementCount(),
3727 "Vector GEP result width doesn't match operand's", &
GEP);
3728 for (
Value *Idx : Idxs) {
3729 Type *IndexTy = Idx->getType();
3730 if (
auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
3732 Check(IndexWidth == GEPWidth,
"Invalid GEP index vector width", &
GEP);
3735 "All GEP indices should be of integer type");
3739 if (
auto *PTy = dyn_cast<PointerType>(
GEP.getType())) {
3741 "GEP address space doesn't match type", &
GEP);
3744 visitInstruction(
GEP);
3748 return A.getUpper() ==
B.getLower() || A.getLower() ==
B.getUpper();
3752 assert(Range && Range ==
I.getMetadata(LLVMContext::MD_range) &&
3753 "precondition violation");
3756 Check(NumOperands % 2 == 0,
"Unfinished range!", Range);
3757 unsigned NumRanges = NumOperands / 2;
3758 Check(NumRanges >= 1,
"It should have at least one range!", Range);
3761 for (
unsigned i = 0;
i < NumRanges; ++
i) {
3763 mdconst::dyn_extract<ConstantInt>(Range->
getOperand(2 *
i));
3764 Check(Low,
"The lower limit must be an integer!", Low);
3766 mdconst::dyn_extract<ConstantInt>(Range->
getOperand(2 *
i + 1));
3769 "Range types must match instruction type!", &
I);
3774 Check(!CurRange.isEmptySet() && !CurRange.isFullSet(),
3775 "Range must not be empty!", Range);
3777 Check(CurRange.intersectWith(LastRange).isEmptySet(),
3778 "Intervals are overlapping", Range);
3779 Check(LowV.
sgt(LastRange.getLower()),
"Intervals are not in order",
3786 if (NumRanges > 2) {
3788 mdconst::dyn_extract<ConstantInt>(Range->
getOperand(0))->getValue();
3790 mdconst::dyn_extract<ConstantInt>(Range->
getOperand(1))->getValue();
3792 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
3793 "Intervals are overlapping", Range);
3800 unsigned Size =
DL.getTypeSizeInBits(Ty);
3801 Check(Size >= 8,
"atomic memory access' size must be byte-sized", Ty,
I);
3802 Check(!(Size & (Size - 1)),
3803 "atomic memory access' operand must have a power-of-two size", Ty,
I);
3806 void Verifier::visitLoadInst(
LoadInst &LI) {
3808 Check(PTy,
"Load operand must be a pointer.", &LI);
3812 "huge alignment values are unsupported", &LI);
3814 Check(ElTy->
isSized(),
"loading unsized types is not allowed", &LI);
3818 "Load cannot have Release ordering", &LI);
3820 "atomic load operand must have integer, pointer, or floating point "
3823 checkAtomicMemAccessSize(ElTy, &LI);
3826 "Non-atomic load cannot have SynchronizationScope specified", &LI);
3829 visitInstruction(LI);
3833 PointerType *PTy = dyn_cast<PointerType>(
SI.getOperand(1)->getType());
3834 Check(PTy,
"Store operand must be a pointer.", &
SI);
3835 Type *ElTy =
SI.getOperand(0)->getType();
3837 "Stored value type does not match pointer operand type!", &
SI, ElTy);
3840 "huge alignment values are unsupported", &
SI);
3842 Check(ElTy->
isSized(),
"storing unsized types is not allowed", &
SI);
3843 if (
SI.isAtomic()) {
3846 "Store cannot have Acquire ordering", &
SI);
3848 "atomic store operand must have integer, pointer, or floating point "
3851 checkAtomicMemAccessSize(ElTy, &
SI);
3854 "Non-atomic store cannot have SynchronizationScope specified", &
SI);
3856 visitInstruction(
SI);
3860 void Verifier::verifySwiftErrorCall(
CallBase &Call,
3861 const Value *SwiftErrorVal) {
3863 if (
I.value() == SwiftErrorVal) {
3864 Check(
Call.paramHasAttr(
I.index(), Attribute::SwiftError),
3865 "swifterror value when used in a callsite should be marked "
3866 "with swifterror attribute",
3867 SwiftErrorVal, Call);
3872 void Verifier::verifySwiftErrorValue(
const Value *SwiftErrorVal) {
3875 for (
const User *U : SwiftErrorVal->
users()) {
3876 Check(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
3878 "swifterror value can only be loaded and stored from, or "
3879 "as a swifterror argument!",
3882 if (
auto StoreI = dyn_cast<StoreInst>(U))
3883 Check(StoreI->getOperand(1) == SwiftErrorVal,
3884 "swifterror value should be the second operand when used "
3887 if (
auto *Call = dyn_cast<CallBase>(U))
3888 verifySwiftErrorCall(*
const_cast<CallBase *
>(Call), SwiftErrorVal);
3892 void Verifier::visitAllocaInst(
AllocaInst &AI) {
3895 "Cannot allocate unsized type", &AI);
3897 "Alloca array size must have integer type", &AI);
3900 "huge alignment values are unsupported", &AI);
3905 "swifterror alloca must have pointer type", &AI);
3907 "swifterror alloca must not be array allocation", &AI);
3908 verifySwiftErrorValue(&AI);
3911 visitInstruction(AI);
3917 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
3918 checkAtomicMemAccessSize(ElTy, &CXI);
3919 visitInstruction(CXI);
3924 "atomicrmw instructions cannot be unordered.", &RMWI);
3930 " operand must have integer or floating point type!",
3935 " operand must have floating point type!",
3940 " operand must have integer type!",
3943 checkAtomicMemAccessSize(ElTy, &RMWI);
3945 "Invalid binary operation!", &RMWI);
3946 visitInstruction(RMWI);
3949 void Verifier::visitFenceInst(
FenceInst &FI) {
3955 "fence instructions may only have acquire, release, acq_rel, or "
3956 "seq_cst ordering.",
3958 visitInstruction(FI);
3964 "Invalid ExtractValueInst operands!", &EVI);
3966 visitInstruction(EVI);
3973 "Invalid InsertValueInst operands!", &IVI);
3975 visitInstruction(IVI);
3979 if (
auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
3980 return FPI->getParentPad();
3982 return cast<CatchSwitchInst>(EHPad)->getParentPad();
3985 void Verifier::visitEHPadPredecessors(
Instruction &
I) {
3991 Check(
BB != &
F->getEntryBlock(),
"EH pad cannot be in entry block.", &
I);
3993 if (
auto *LPI = dyn_cast<LandingPadInst>(&
I)) {
3998 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
3999 Check(II && II->getUnwindDest() ==
BB && II->getNormalDest() !=
BB,
4000 "Block containing LandingPadInst must be jumped to "
4001 "only by the unwind edge of an invoke.",
4006 if (
auto *CPI = dyn_cast<CatchPadInst>(&
I)) {
4008 Check(
BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
4009 "Block containg CatchPadInst must be jumped to "
4010 "only by its catchswitch.",
4012 Check(
BB != CPI->getCatchSwitch()->getUnwindDest(),
4013 "Catchswitch cannot unwind to one of its catchpads",
4014 CPI->getCatchSwitch(), CPI);
4025 if (
auto *II = dyn_cast<InvokeInst>(TI)) {
4026 Check(II->getUnwindDest() ==
BB && II->getNormalDest() !=
BB,
4027 "EH pad must be jumped to via an unwind edge", ToPad, II);
4029 FromPad = Bundle->Inputs[0];
4032 }
else if (
auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
4033 FromPad = CRI->getOperand(0);
4034 Check(FromPad != ToPadParent,
"A cleanupret must exit its cleanup", CRI);
4035 }
else if (
auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4038 Check(
false,
"EH pad must be jumped to via an unwind edge", ToPad, TI);
4044 Check(FromPad != ToPad,
4045 "EH pad cannot handle exceptions raised within it", FromPad, TI);
4046 if (FromPad == ToPadParent) {
4050 Check(!isa<ConstantTokenNone>(FromPad),
4051 "A single unwind edge may only enter one EH pad", TI);
4052 Check(Seen.
insert(FromPad).second,
"EH pad jumps through a cycle of pads",
4057 Check(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
4058 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
4067 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
4069 visitEHPadPredecessors(LPI);
4071 if (!LandingPadResultTy)
4072 LandingPadResultTy = LPI.
getType();
4075 "The landingpad instruction should have a consistent result type "
4076 "inside a function.",
4080 Check(
F->hasPersonalityFn(),
4081 "LandingPadInst needs to be in a function with a personality.", &LPI);
4086 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
4092 "Catch operand does not have pointer type!", &LPI);
4094 Check(LPI.
isFilter(
i),
"Clause is neither catch nor filter!", &LPI);
4096 "Filter operand is not an array of constants!", &LPI);
4100 visitInstruction(LPI);
4103 void Verifier::visitResumeInst(
ResumeInst &RI) {
4105 "ResumeInst needs to be in a function with a personality.", &RI);
4107 if (!LandingPadResultTy)
4111 "The resume instruction should have a consistent result type "
4112 "inside a function.",
4115 visitTerminator(RI);
4122 Check(
F->hasPersonalityFn(),
4123 "CatchPadInst needs to be in a function with a personality.", &CPI);
4126 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4131 Check(
BB->getFirstNonPHI() == &CPI,
4132 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
4134 visitEHPadPredecessors(CPI);
4135 visitFuncletPadInst(CPI);
4140 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
4143 visitTerminator(CatchReturn);
4150 Check(
F->hasPersonalityFn(),
4151 "CleanupPadInst needs to be in a function with a personality.", &CPI);
4155 Check(
BB->getFirstNonPHI() == &CPI,
4156 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
4159 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4160 "CleanupPadInst has an invalid parent.", &CPI);
4162 visitEHPadPredecessors(CPI);
4163 visitFuncletPadInst(CPI);
4167 User *FirstUser =
nullptr;
4168 Value *FirstUnwindPad =
nullptr;
4172 while (!Worklist.empty()) {
4175 "FuncletPadInst must not be nested within itself", CurrentPad);
4176 Value *UnresolvedAncestorPad =
nullptr;
4179 if (
auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
4180 UnwindDest = CRI->getUnwindDest();
4181 }
else if (
auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
4186 if (CSI->unwindsToCaller())
4188 UnwindDest = CSI->getUnwindDest();
4189 }
else if (
auto *II = dyn_cast<InvokeInst>(U)) {
4190 UnwindDest = II->getUnwindDest();
4191 }
else if (isa<CallInst>(U)) {
4196 }
else if (
auto *CPI = dyn_cast<CleanupPadInst>(U)) {
4200 Worklist.push_back(CPI);
4203 Check(isa<CatchReturnInst>(U),
"Bogus funclet pad use", U);
4211 if (!cast<Instruction>(UnwindPad)->isEHPad())
4215 if (UnwindParent == CurrentPad)
4221 Value *ExitedPad = CurrentPad;
4224 if (ExitedPad == &FPI) {
4229 UnresolvedAncestorPad = &FPI;
4233 if (ExitedParent == UnwindParent) {
4237 UnresolvedAncestorPad = ExitedParent;
4240 ExitedPad = ExitedParent;
4241 }
while (!isa<ConstantTokenNone>(ExitedPad));
4246 UnresolvedAncestorPad = &FPI;
4253 Check(UnwindPad == FirstUnwindPad,
4254 "Unwind edges out of a funclet "
4255 "pad must have the same unwind "
4257 &FPI, U, FirstUser);
4260 FirstUnwindPad = UnwindPad;
4262 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
4264 SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
4269 if (CurrentPad != &FPI)
4272 if (UnresolvedAncestorPad) {
4273 if (CurrentPad == UnresolvedAncestorPad) {
4277 assert(CurrentPad == &FPI);
4285 Value *ResolvedPad = CurrentPad;
4286 while (!Worklist.empty()) {
4287 Value *UnclePad = Worklist.back();
4291 while (ResolvedPad != AncestorPad) {
4293 if (ResolvedParent == UnresolvedAncestorPad) {
4296 ResolvedPad = ResolvedParent;
4300 if (ResolvedPad != AncestorPad)
4303 Worklist.pop_back();
4308 if (FirstUnwindPad) {
4309 if (
auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.
getParentPad())) {
4310 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
4311 Value *SwitchUnwindPad;
4312 if (SwitchUnwindDest)
4316 Check(SwitchUnwindPad == FirstUnwindPad,
4317 "Unwind edges out of a catch must have the same unwind dest as "
4318 "the parent catchswitch",
4319 &FPI, FirstUser, CatchSwitch);
4323 visitInstruction(FPI);
4330 Check(
F->hasPersonalityFn(),
4331 "CatchSwitchInst needs to be in a function with a personality.",
4336 Check(
BB->getFirstNonPHI() == &CatchSwitch,
4337 "CatchSwitchInst not the first non-PHI instruction in the block.",
4341 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4342 "CatchSwitchInst has an invalid parent.", ParentPad);
4346 Check(
I->isEHPad() && !isa<LandingPadInst>(
I),
4347 "CatchSwitchInst must unwind to an EH block which is not a "
4353 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
4357 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
4360 Check(isa<CatchPadInst>(Handler->getFirstNonPHI()),
4361 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
4364 visitEHPadPredecessors(CatchSwitch);
4365 visitTerminator(CatchSwitch);
4370 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
4375 Check(
I->isEHPad() && !isa<LandingPadInst>(
I),
4376 "CleanupReturnInst must unwind to an EH block which is not a "
4381 visitTerminator(CRI);
4384 void Verifier::verifyDominatesUse(
Instruction &
I,
unsigned i) {
4390 if (II->getNormalDest() == II->getUnwindDest())
4401 if (!isa<PHINode>(
I) && InstsInThisBlock.
count(
Op))
4404 const Use &U =
I.getOperandUse(
i);
4409 Check(
I.getType()->isPointerTy(),
4410 "dereferenceable, dereferenceable_or_null "
4411 "apply only to pointer types",
4413 Check((isa<LoadInst>(
I) || isa<IntToPtrInst>(
I)),
4414 "dereferenceable, dereferenceable_or_null apply only to load"
4415 " and inttoptr instructions, use attributes for calls or invokes",
4418 "dereferenceable, dereferenceable_or_null "
4419 "take one operand!",
4424 "dereferenceable_or_null metadata value must be an i64!",
4430 "!prof annotations should have no less than 2 operands", MD);
4433 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null", MD);
4435 "expected string with name of the !prof annotation", MD);
4440 if (ProfName.
equals(
"branch_weights")) {
4441 if (isa<InvokeInst>(&
I)) {
4443 "Wrong number of InvokeInst branch_weights operands", MD);
4445 unsigned ExpectedNumOperands = 0;
4449 ExpectedNumOperands =
SI->getNumSuccessors();
4450 else if (isa<CallInst>(&
I))
4451 ExpectedNumOperands = 1;
4453 ExpectedNumOperands = IBI->getNumDestinations();
4454 else if (isa<SelectInst>(&
I))
4455 ExpectedNumOperands = 2;
4457 CheckFailed(
"!prof branch_weights are not allowed for this instruction",
4461 "Wrong number of operands", MD);
4465 Check(MDO,
"second operand should not be null", MD);
4466 Check(mdconst::dyn_extract<ConstantInt>(MDO),
4467 "!prof brunch_weights operand is not a const int");
4472 void Verifier::visitAnnotationMetadata(
MDNode *Annotation) {
4473 Check(isa<MDTuple>(Annotation),
"annotation must be a tuple");
4475 "annotation must have at least one operand");
4477 Check(isa<MDString>(
Op.get()),
"operands must be strings");
4480 void Verifier::visitAliasScopeMetadata(
const MDNode *MD) {
4482 Check(NumOps >= 2 && NumOps <= 3,
"scope must have two or three operands",
4485 "first scope operand must be self-referential or string", MD);
4488 "third scope operand must be string (if used)", MD);
4491 Check(
Domain !=
nullptr,
"second scope operand must be MDNode", MD);
4493 unsigned NumDomainOps =
Domain->getNumOperands();
4494 Check(NumDomainOps >= 1 && NumDomainOps <= 2,
4495 "domain must have one or two operands",
Domain);
4497 isa<MDString>(
Domain->getOperand(0)),
4498 "first domain operand must be self-referential or string",
Domain);
4499 if (NumDomainOps == 2)
4501 "second domain operand must be string (if used)",
Domain);
4504 void Verifier::visitAliasScopeListMetadata(
const MDNode *MD) {
4506 const MDNode *OpMD = dyn_cast<MDNode>(
Op);
4507 Check(OpMD !=
nullptr,
"scope list must consist of MDNodes", MD);
4508 visitAliasScopeMetadata(OpMD);
4512 void Verifier::visitAccessGroupMetadata(
const MDNode *MD) {
4513 auto IsValidAccessScope = [](
const MDNode *MD) {
4518 if (IsValidAccessScope(MD))
4523 const MDNode *OpMD = dyn_cast<MDNode>(
Op);
4524 Check(OpMD !=
nullptr,
"Access scope list must consist of MDNodes", MD);
4525 Check(IsValidAccessScope(OpMD),
4526 "Access scope list contains invalid access scope", MD);
4534 Check(
BB,
"Instruction not embedded in basic block!", &
I);
4536 if (!isa<PHINode>(
I)) {
4537 for (
User *U :
I.users()) {
4539 "Only PHI nodes may reference their own value!", &
I);
4544 Check(!
I.getType()->isVoidTy() || !
I.hasName(),
4545 "Instruction has a name, but provides a void value!", &
I);
4549 Check(
I.getType()->isVoidTy() ||
I.getType()->isFirstClassType(),
4550 "Instruction returns a non-scalar type!", &
I);
4554 Check(!
I.getType()->isMetadataTy() || isa<CallInst>(
I) || isa<InvokeInst>(
I),
4555 "Invalid use of metadata!", &
I);
4560 for (
Use &U :
I.uses()) {
4563 "Instruction referencing"
4564 " instruction not embedded in a basic block!",
4567 CheckFailed(
"Use of instruction is not an instruction!", U);
4574 const CallBase *CBI = dyn_cast<CallBase>(&
I);
4576 for (
unsigned i = 0,
e =
I.getNumOperands();
i !=
e; ++
i) {
4577 Check(
I.getOperand(
i) !=
nullptr,
"Instruction has null operand!", &
I);
4581 if (!
I.getOperand(
i)->getType()->isFirstClassType()) {
4582 Check(
false,
"Instruction operands must be first-class values!", &
I);
4585 if (
Function *
F = dyn_cast<Function>(
I.getOperand(
i))) {
4590 return CBI && CBI->isOperandBundleOfType(
4598 Check((!
F->isIntrinsic() ||
4599 (CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(
i)) ||
4600 IsAttachedCallOperand(
F, CBI,
i)),
4601 "Cannot take the address of an intrinsic!", &
I);
4602 Check(!
F->isIntrinsic() || isa<CallInst>(
I) ||
4603 F->getIntrinsicID() == Intrinsic::donothing ||
4604 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
4605 F->getIntrinsicID() == Intrinsic::seh_try_end ||
4606 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
4607 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
4608 F->getIntrinsicID() == Intrinsic::coro_resume ||
4609 F->getIntrinsicID() == Intrinsic::coro_destroy ||
4610 F->getIntrinsicID() ==
4611 Intrinsic::experimental_patchpoint_void ||
4612 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
4613 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
4614 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
4615 IsAttachedCallOperand(
F, CBI,
i),
4616 "Cannot invoke an intrinsic other than donothing, patchpoint, "
4617 "statepoint, coro_resume, coro_destroy or clang.arc.attachedcall",
4619 Check(
F->getParent() == &M,
"Referencing function in another module!", &
I,
4620 &M,
F,
F->getParent());
4621 }
else if (
BasicBlock *OpBB = dyn_cast<BasicBlock>(
I.getOperand(
i))) {
4622 Check(OpBB->getParent() ==
BB->getParent(),
4623 "Referring to a basic block in another function!", &
I);
4624 }
else if (
Argument *OpArg = dyn_cast<Argument>(
I.getOperand(
i))) {
4625 Check(OpArg->getParent() ==
BB->getParent(),
4626 "Referring to an argument in another function!", &
I);
4627 }
else if (
GlobalValue *GV = dyn_cast<GlobalValue>(
I.getOperand(
i))) {
4628 Check(GV->
getParent() == &M,
"Referencing global in another module!", &
I,
4630 }
else if (isa<Instruction>(
I.getOperand(
i))) {
4631 verifyDominatesUse(
I,
i);
4632 }
else if (isa<InlineAsm>(
I.getOperand(
i))) {
4633 Check(CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(
i),
4634 "Cannot take the address of an inline asm!", &
I);
4635 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(
I.getOperand(
i))) {
4636 if (
CE->getType()->isPtrOrPtrVectorTy()) {
4639 visitConstantExprsRecursively(CE);
4644 if (
MDNode *MD =
I.getMetadata(LLVMContext::MD_fpmath)) {
4645 Check(
I.getType()->isFPOrFPVectorTy(),
4646 "fpmath requires a floating point result!", &
I);
4649 mdconst::dyn_extract_or_null<ConstantFP>(MD->
getOperand(0))) {
4650 const APFloat &Accuracy = CFP0->getValueAPF();
4652 "fpmath accuracy must have float type", &
I);
4654 "fpmath accuracy not a positive number!", &
I);
4656 Check(
false,
"invalid fpmath accuracy!", &
I);
4660 if (
MDNode *Range =
I.getMetadata(LLVMContext::MD_range)) {
4661 Check(isa<LoadInst>(
I) || isa<CallInst>(
I) || isa<InvokeInst>(
I),
4662 "Ranges are only for loads, calls and invokes!", &
I);
4663 visitRangeMetadata(
I, Range,
I.getType());
4666 if (
I.hasMetadata(LLVMContext::MD_invariant_group)) {
4667 Check(isa<LoadInst>(
I) || isa<StoreInst>(
I),
4668 "invariant.group metadata is only for loads and stores", &
I);
4671 if (
I.getMetadata(LLVMContext::MD_nonnull)) {
4672 Check(
I.getType()->isPointerTy(),
"nonnull applies only to pointer types",
4675 "nonnull applies only to load instructions, use attributes"
4676 " for calls or invokes",
4680 if (
MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable))
4681 visitDereferenceableMetadata(
I, MD);
4683 if (
MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
4684 visitDereferenceableMetadata(
I, MD);
4686 if (
MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa))
4689 if (
MDNode *MD =
I.getMetadata(LLVMContext::MD_noalias))
4690 visitAliasScopeListMetadata(MD);
4691 if (
MDNode *MD =
I.getMetadata(LLVMContext::MD_alias_scope))
4692 visitAliasScopeListMetadata(MD);
4694 if (
MDNode *MD =
I.getMetadata(LLVMContext::MD_access_group))
4695 visitAccessGroupMetadata(MD);
4697 if (
MDNode *AlignMD =
I.getMetadata(LLVMContext::MD_align)) {
4698 Check(
I.getType()->isPointerTy(),
"align applies only to pointer types",
4701 "align applies only to load instructions, "
4702 "use attributes for calls or invokes",
4704 Check(AlignMD->getNumOperands() == 1,
"align takes one operand!", &
I);
4705 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
4707 "align metadata value must be an i64!", &
I);
4712 "alignment is larger that implementation defined limit", &
I);
4715 if (
MDNode *MD =
I.getMetadata(LLVMContext::MD_prof))
4716 visitProfMetadata(
I, MD);
4718 if (
MDNode *Annotation =
I.getMetadata(LLVMContext::MD_annotation))
4719 visitAnnotationMetadata(Annotation);
4721 if (
MDNode *
N =
I.getDebugLoc().getAsMDNode()) {
4722 CheckDI(isa<DILocation>(
N),
"invalid !dbg metadata attachment", &
I,
N);
4723 visitMDNode(*
N, AreDebugLocsAllowed::Yes);
4726 if (
auto *DII = dyn_cast<DbgVariableIntrinsic>(&
I)) {
4727 verifyFragmentExpression(*DII);
4728 verifyNotEntryValue(*DII);
4732 I.getAllMetadata(MDs);
4733 for (
auto Attachment : MDs) {
4734 unsigned Kind = Attachment.first;
4736 (
Kind == LLVMContext::MD_dbg ||
Kind == LLVMContext::MD_loop)
4737 ? AreDebugLocsAllowed::Yes
4738 : AreDebugLocsAllowed::No;
4739 visitMDNode(*Attachment.second, AllowLocs);
4748 Check(
IF->isDeclaration(),
"Intrinsic functions should never be defined!",
4765 "Intrinsic has incorrect return type!",
IF);
4767 "Intrinsic has incorrect argument type!",
IF);
4772 "Intrinsic was not defined with variable arguments!",
IF);
4775 "Callsite was not defined with variable arguments!",
IF);
4784 const std::string ExpectedName =
4786 Check(ExpectedName ==
IF->getName(),
4787 "Intrinsic name not mangled correctly for type arguments! "
4795 if (
auto *MD = dyn_cast<MetadataAsValue>(V))
4796 visitMetadataAsValue(*MD,
Call.getCaller());
4797 if (
auto *Const = dyn_cast<Constant>(V))
4799 "const x86_amx is not allowed in argument!");
4805 case Intrinsic::assume: {
4806 for (
auto &Elem :
Call.bundle_op_infos()) {
4807 Check(Elem.Tag->getKey() ==
"ignore" ||
4809 "tags must be valid attribute names", Call);
4812 unsigned ArgCount = Elem.End - Elem.Begin;
4813 if (
Kind == Attribute::Alignment) {
4814 Check(ArgCount <= 3 && ArgCount >= 2,
4815 "alignment assumptions should have 2 or 3 arguments", Call);
4816 Check(
Call.getOperand(Elem.Begin)->getType()->isPointerTy(),
4817 "first argument should be a pointer", Call);
4818 Check(
Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(),
4819 "second argument should be an integer", Call);
4821 Check(
Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(),
4822 "third argument should be an integer if present", Call);
4825 Check(ArgCount <= 2,
"too many arguments", Call);
4829 Check(ArgCount == 2,
"this attribute should have 2 arguments", Call);
4830 Check(isa<ConstantInt>(
Call.getOperand(Elem.Begin + 1)),
4831 "the second argument should be a constant integral value", Call);
4833 Check((ArgCount) == 1,
"this attribute should have one argument", Call);
4835 Check((ArgCount) == 0,
"this attribute has no argument", Call);
4840 case Intrinsic::coro_id: {
4841 auto *InfoArg =
Call.getArgOperand(3)->stripPointerCasts();
4842 if (isa<ConstantPointerNull>(InfoArg))
4844 auto *GV = dyn_cast<GlobalVariable>(InfoArg);
4846 "info argument of llvm.coro.id must refer to an initialized "
4849 Check(isa<ConstantStruct>(
Init) || isa<ConstantArray>(
Init),
4850 "info argument of llvm.coro.id must refer to either a struct or "
4854 case Intrinsic::fptrunc_round: {
4857 auto *MAV = dyn_cast<MetadataAsValue>(
Call.getOperand(1));
4859 MD = MAV->getMetadata();
4861 Check(MD !=
nullptr,
"missing rounding mode argument", Call);