96#include "llvm/IR/IntrinsicsAArch64.h"
97#include "llvm/IR/IntrinsicsAMDGPU.h"
98#include "llvm/IR/IntrinsicsARM.h"
99#include "llvm/IR/IntrinsicsNVPTX.h"
100#include "llvm/IR/IntrinsicsWebAssembly.h"
138 cl::desc(
"Ensure that llvm.experimental.noalias.scope.decl for identical "
139 "scopes are not dominating"));
162 *
OS <<
"; ModuleID = '" << M->getModuleIdentifier() <<
"'\n";
175 V.printAsOperand(*
OS,
true,
MST);
180 void Write(
const DbgRecord *DR) {
196 *
OS <<
"declare_value";
217 template <
class T>
void Write(
const MDTupleTypedArrayWrapper<T> &MD) {
221 void Write(
const NamedMDNode *NMD) {
234 void Write(
const Comdat *
C) {
240 void Write(
const APInt *AI) {
246 void Write(
const unsigned i) { *
OS << i <<
'\n'; }
252 *
OS <<
A->getAsString() <<
'\n';
256 void Write(
const AttributeSet *AS) {
263 void Write(
const AttributeList *AL) {
269 void Write(Printable
P) { *
OS <<
P <<
'\n'; }
271 template <
typename T>
void Write(ArrayRef<T> Vs) {
272 for (
const T &V : Vs)
276 template <
typename T1,
typename... Ts>
277 void WriteTs(
const T1 &V1,
const Ts &... Vs) {
282 template <
typename... Ts>
void WriteTs() {}
291 *
OS << Message <<
'\n';
299 template <
typename T1,
typename... Ts>
309 *
OS << Message <<
'\n';
315 template <
typename T1,
typename... Ts>
347 Type *LandingPadResultTy;
354 bool HasDebugInfo =
false;
397 SawFrameEscape(
false), TBAAVerifyHelper(this) {
398 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
401 bool hasBrokenDebugInfo()
const {
return BrokenDebugInfo; }
403 bool verify(
const Function &
F) {
404 llvm::TimeTraceScope timeScope(
"Verifier");
406 "An instance of this class only works with a specific module!");
416 for (
const BasicBlock &BB :
F) {
417 if (!BB.empty() && BB.back().isTerminator())
421 *OS <<
"Basic Block in function '" <<
F.getName()
422 <<
"' does not have terminator!\n";
423 BB.printAsOperand(*OS,
true, MST);
431 DT.recalculate(
const_cast<Function &
>(
F));
433 auto FailureCB = [
this](
const Twine &Message) {
434 this->CheckFailed(Message);
436 ConvergenceVerifyHelper.initialize(OS, FailureCB,
F);
441 verifySiblingFuncletUnwinds();
443 if (ConvergenceVerifyHelper.sawTokens())
444 ConvergenceVerifyHelper.verify(DT);
446 InstsInThisBlock.clear();
448 LandingPadResultTy =
nullptr;
449 SawFrameEscape =
false;
450 SiblingFuncletInfo.clear();
451 verifyNoAliasScopeDecl();
452 NoAliasScopeDecls.clear();
462 for (
const Function &
F : M)
463 if (
F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
464 DeoptimizeDeclarations.push_back(&
F);
468 verifyFrameRecoverIndices();
469 for (
const GlobalVariable &GV :
M.globals())
470 visitGlobalVariable(GV);
472 for (
const GlobalAlias &GA :
M.aliases())
473 visitGlobalAlias(GA);
475 for (
const GlobalIFunc &GI :
M.ifuncs())
476 visitGlobalIFunc(GI);
478 for (
const NamedMDNode &NMD :
M.named_metadata())
479 visitNamedMDNode(NMD);
481 for (
const StringMapEntry<Comdat> &SMEC :
M.getComdatSymbolTable())
482 visitComdat(SMEC.getValue());
486 visitModuleCommandLines();
487 visitModuleErrnoTBAA();
489 verifyCompileUnits();
491 verifyDeoptimizeCallingConvs();
492 DISubprogramAttachments.clear();
498 enum class AreDebugLocsAllowed {
No,
Yes };
502 enum class RangeLikeMetadataKind {
509 void visitGlobalValue(
const GlobalValue &GV);
510 void visitGlobalVariable(
const GlobalVariable &GV);
511 void visitGlobalAlias(
const GlobalAlias &GA);
512 void visitGlobalIFunc(
const GlobalIFunc &GI);
513 void visitAliaseeSubExpr(
const GlobalAlias &
A,
const Constant &
C);
514 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
515 const GlobalAlias &
A,
const Constant &
C);
516 void visitNamedMDNode(
const NamedMDNode &NMD);
517 void visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs);
518 void visitMetadataAsValue(
const MetadataAsValue &MD, Function *
F);
519 void visitValueAsMetadata(
const ValueAsMetadata &MD, Function *
F);
520 void visitDIArgList(
const DIArgList &AL, Function *
F);
521 void visitComdat(
const Comdat &
C);
522 void visitModuleIdents();
523 void visitModuleCommandLines();
524 void visitModuleErrnoTBAA();
525 void visitModuleFlags();
526 void visitModuleFlag(
const MDNode *
Op,
527 DenseMap<const MDString *, const MDNode *> &SeenIDs,
528 SmallVectorImpl<const MDNode *> &Requirements);
529 void visitModuleFlagCGProfileEntry(
const MDOperand &MDO);
530 void visitFunction(
const Function &
F);
531 void visitBasicBlock(BasicBlock &BB);
532 void verifyRangeLikeMetadata(
const Value &V,
const MDNode *
Range,
Type *Ty,
533 RangeLikeMetadataKind Kind);
534 void visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
535 void visitNoFPClassMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
536 void visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
537 void visitDereferenceableMetadata(Instruction &
I, MDNode *MD);
538 void visitNofreeMetadata(Instruction &
I, MDNode *MD);
539 void visitProfMetadata(Instruction &
I, MDNode *MD);
540 void visitCallStackMetadata(MDNode *MD);
541 void visitMemProfMetadata(Instruction &
I, MDNode *MD);
542 void visitCallsiteMetadata(Instruction &
I, MDNode *MD);
543 void visitCalleeTypeMetadata(Instruction &
I, MDNode *MD);
544 void visitDIAssignIDMetadata(Instruction &
I, MDNode *MD);
545 void visitMMRAMetadata(Instruction &
I, MDNode *MD);
546 void visitAnnotationMetadata(MDNode *Annotation);
547 void visitAliasScopeMetadata(
const MDNode *MD);
548 void visitAliasScopeListMetadata(
const MDNode *MD);
549 void visitAccessGroupMetadata(
const MDNode *MD);
550 void visitCapturesMetadata(Instruction &
I,
const MDNode *Captures);
551 void visitAllocTokenMetadata(Instruction &
I, MDNode *MD);
553 template <
class Ty>
bool isValidMetadataArray(
const MDTuple &
N);
554#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
555#include "llvm/IR/Metadata.def"
556 void visitDIScope(
const DIScope &
N);
580 void checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V);
585 void visitPHINode(
PHINode &PN);
594 void visitVAArgInst(
VAArgInst &VAA) { visitInstruction(VAA); }
595 void visitCallInst(CallInst &CI);
596 void visitInvokeInst(InvokeInst &
II);
597 void visitGetElementPtrInst(GetElementPtrInst &
GEP);
598 void visitLoadInst(LoadInst &LI);
599 void visitStoreInst(StoreInst &SI);
600 void verifyDominatesUse(Instruction &
I,
unsigned i);
601 void visitInstruction(Instruction &
I);
602 void visitTerminator(Instruction &
I);
603 void visitCondBrInst(CondBrInst &BI);
604 void visitReturnInst(ReturnInst &RI);
605 void visitSwitchInst(SwitchInst &SI);
606 void visitIndirectBrInst(IndirectBrInst &BI);
607 void visitCallBrInst(CallBrInst &CBI);
608 void visitSelectInst(SelectInst &SI);
609 void visitUserOp1(Instruction &
I);
610 void visitUserOp2(Instruction &
I) { visitUserOp1(
I); }
612 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
613 void visitVPIntrinsic(VPIntrinsic &VPI);
614 void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
615 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
616 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
617 void visitFenceInst(FenceInst &FI);
618 void visitAllocaInst(AllocaInst &AI);
619 void visitExtractValueInst(ExtractValueInst &EVI);
620 void visitInsertValueInst(InsertValueInst &IVI);
621 void visitEHPadPredecessors(Instruction &
I);
622 void visitLandingPadInst(LandingPadInst &LPI);
623 void visitResumeInst(ResumeInst &RI);
624 void visitCatchPadInst(CatchPadInst &CPI);
625 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
626 void visitCleanupPadInst(CleanupPadInst &CPI);
627 void visitFuncletPadInst(FuncletPadInst &FPI);
628 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
629 void visitCleanupReturnInst(CleanupReturnInst &CRI);
631 void verifySwiftErrorCall(CallBase &
Call,
const Value *SwiftErrorVal);
632 void verifySwiftErrorValue(
const Value *SwiftErrorVal);
633 void verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs, StringRef
Context);
634 void verifyMustTailCall(CallInst &CI);
635 bool verifyAttributeCount(AttributeList Attrs,
unsigned Params);
636 void verifyAttributeTypes(AttributeSet Attrs,
const Value *V);
637 void verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
const Value *V);
638 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
640 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
641 const Value *V,
bool IsIntrinsic,
bool IsInlineAsm);
642 void verifyFunctionMetadata(
ArrayRef<std::pair<unsigned, MDNode *>> MDs);
643 void verifyUnknownProfileMetadata(MDNode *MD);
644 void visitConstantExprsRecursively(
const Constant *EntryC);
645 void visitConstantExpr(
const ConstantExpr *CE);
646 void visitConstantPtrAuth(
const ConstantPtrAuth *CPA);
647 void verifyInlineAsmCall(
const CallBase &
Call);
648 void verifyStatepoint(
const CallBase &
Call);
649 void verifyFrameRecoverIndices();
650 void verifySiblingFuncletUnwinds();
652 void verifyFragmentExpression(
const DbgVariableRecord &
I);
653 template <
typename ValueOrMetadata>
654 void verifyFragmentExpression(
const DIVariable &V,
656 ValueOrMetadata *
Desc);
657 void verifyFnArgs(
const DbgVariableRecord &DVR);
658 void verifyNotEntryValue(
const DbgVariableRecord &
I);
661 void verifyCompileUnits();
665 void verifyDeoptimizeCallingConvs();
667 void verifyAttachedCallBundle(
const CallBase &
Call,
668 const OperandBundleUse &BU);
671 void verifyNoAliasScopeDecl();
677#define Check(C, ...) \
680 CheckFailed(__VA_ARGS__); \
687#define CheckDI(C, ...) \
690 DebugInfoCheckFailed(__VA_ARGS__); \
698 CheckDI(
I.DebugMarker->MarkedInstr == &
I,
699 "Instruction has invalid DebugMarker", &
I);
701 "PHI Node must not have any attached DbgRecords", &
I);
704 "DbgRecord had invalid DebugMarker", &
I, &DR);
707 visitMDNode(*
Loc, AreDebugLocsAllowed::Yes);
712 verifyFragmentExpression(*DVR);
713 verifyNotEntryValue(*DVR);
720void Verifier::visit(Instruction &
I) {
722 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i)
723 Check(
I.getOperand(i) !=
nullptr,
"Operand is null", &
I);
735 while (!WorkList.
empty()) {
737 if (!Visited.
insert(Cur).second)
744void Verifier::visitGlobalValue(
const GlobalValue &GV) {
746 "Global is external, but doesn't have external or weak linkage!", &GV);
749 if (
const MDNode *Associated =
750 GO->getMetadata(LLVMContext::MD_associated)) {
751 Check(Associated->getNumOperands() == 1,
752 "associated metadata must have one operand", &GV, Associated);
753 const Metadata *
Op = Associated->getOperand(0).get();
754 Check(
Op,
"associated metadata must have a global value", GO, Associated);
757 Check(VM,
"associated metadata must be ValueAsMetadata", GO, Associated);
760 "associated value must be pointer typed", GV, Associated);
762 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
764 "associated metadata must point to a GlobalObject", GO, Stripped);
765 Check(Stripped != GO,
766 "global values should not associate to themselves", GO,
772 if (
const MDNode *AbsoluteSymbol =
773 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
774 verifyRangeLikeMetadata(*GO, AbsoluteSymbol,
775 DL.getIntPtrType(GO->getType()),
776 RangeLikeMetadataKind::AbsoluteSymbol);
779 if (GO->hasMetadata(LLVMContext::MD_implicit_ref)) {
780 Check(!GO->isDeclaration(),
781 "ref metadata must not be placed on a declaration", GO);
784 GO->getMetadata(LLVMContext::MD_implicit_ref, MDs);
785 for (
const MDNode *MD : MDs) {
786 Check(MD->getNumOperands() == 1,
"ref metadata must have one operand",
790 Check(VM,
"ref metadata must be ValueAsMetadata", GO, MD);
793 "ref value must be pointer typed", GV, MD);
797 "ref metadata must point to a GlobalObject", GO, Stripped);
798 Check(Stripped != GO,
"values should not reference themselves", GO,
806 "Only global variables can have appending linkage!", &GV);
811 "Only global arrays can have appending linkage!", GVar);
815 Check(!GV.
hasComdat(),
"Declaration may not be in a Comdat!", &GV);
819 "dllexport GlobalValue must have default or protected visibility",
824 "dllimport GlobalValue must have default visibility", &GV);
825 Check(!GV.
isDSOLocal(),
"GlobalValue with DLLImport Storage is dso_local!",
831 "Global is marked as dllimport, but not external", &GV);
836 "GlobalValue with local linkage or non-default "
837 "visibility must be dso_local!",
842 if (!
I->getParent() || !
I->getParent()->getParent())
843 CheckFailed(
"Global is referenced by parentless instruction!", &GV, &M,
845 else if (
I->getParent()->getParent()->getParent() != &M)
846 CheckFailed(
"Global is referenced in a different module!", &GV, &M,
I,
847 I->getParent()->getParent(),
848 I->getParent()->getParent()->getParent());
851 if (
F->getParent() != &M)
852 CheckFailed(
"Global is used by function in a different module", &GV, &M,
860void Verifier::visitGlobalVariable(
const GlobalVariable &GV) {
864 Check(
A->value() <= Value::MaximumAlignment,
865 "huge alignment values are unsupported", &GV);
870 "Global variable initializer type does not match global "
874 "Global variable initializer must be sized", &GV);
880 "'common' global must have a zero initializer!", &GV);
883 Check(!GV.
hasComdat(),
"'common' global may not be in a Comdat!", &GV);
888 GV.
getName() ==
"llvm.global_dtors")) {
890 "invalid linkage for intrinsic global variable", &GV);
892 "invalid uses of intrinsic global variable", &GV);
899 PointerType::get(
Context,
DL.getProgramAddressSpace());
903 "wrong type for intrinsic global variable", &GV);
905 "the third field of the element type is mandatory, "
906 "specify ptr null to migrate from the obsoleted 2-field form");
914 GV.
getName() ==
"llvm.compiler.used")) {
916 "invalid linkage for intrinsic global variable", &GV);
918 "invalid uses of intrinsic global variable", &GV);
922 Check(PTy,
"wrong type for intrinsic global variable", &GV);
926 Check(InitArray,
"wrong initializer for intrinsic global variable",
932 Twine(
"invalid ") + GV.
getName() +
" member", V);
934 Twine(
"members of ") + GV.
getName() +
" must be named", V);
943 for (
auto *MD : MDs) {
945 visitDIGlobalVariableExpression(*GVE);
947 CheckDI(
false,
"!dbg attachment of global variable must be a "
948 "DIGlobalVariableExpression");
958 "Global @" + GV.
getName() +
" has illegal target extension type",
967 "Global variable is too large to fit into the address space", &GV,
971 visitGlobalValue(GV);
978 visitGlobalValue(GV);
981void Verifier::visitAliaseeSubExpr(
const GlobalAlias &GA,
const Constant &
C) {
982 SmallPtrSet<const GlobalAlias*, 4> Visited;
984 visitAliaseeSubExpr(Visited, GA,
C);
987void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
988 const GlobalAlias &GA,
const Constant &
C) {
992 "available_externally alias must point to available_externally "
1003 Check(Visited.
insert(GA2).second,
"Aliases cannot form a cycle", &GA);
1005 Check(!GA2->isInterposable(),
1006 "Alias cannot point to an interposable alias", &GA);
1015 visitConstantExprsRecursively(CE);
1017 for (
const Use &U :
C.operands()) {
1020 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
1022 visitAliaseeSubExpr(Visited, GA, *C2);
1026void Verifier::visitGlobalAlias(
const GlobalAlias &GA) {
1028 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
1029 "weak_odr, external, or available_externally linkage!",
1032 Check(Aliasee,
"Aliasee cannot be NULL!", &GA);
1034 "Alias and aliasee types should match!", &GA);
1037 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
1039 visitAliaseeSubExpr(GA, *Aliasee);
1041 visitGlobalValue(GA);
1044void Verifier::visitGlobalIFunc(
const GlobalIFunc &GI) {
1045 visitGlobalValue(GI);
1049 for (
const auto &
I : MDs) {
1050 CheckDI(
I.first != LLVMContext::MD_dbg,
1051 "an ifunc may not have a !dbg attachment", &GI);
1052 Check(
I.first != LLVMContext::MD_prof,
1053 "an ifunc may not have a !prof attachment", &GI);
1054 visitMDNode(*
I.second, AreDebugLocsAllowed::No);
1058 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
1059 "weak_odr, or external linkage!",
1064 Check(Resolver,
"IFunc must have a Function resolver", &GI);
1066 "IFunc resolver must be a definition", &GI);
1073 "IFunc resolver must return a pointer", &GI);
1076 "IFunc resolver has incorrect type", &GI);
1079void Verifier::visitNamedMDNode(
const NamedMDNode &NMD) {
1084 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
1085 for (
const MDNode *MD : NMD.
operands()) {
1086 if (NMD.
getName() ==
"llvm.dbg.cu")
1092 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
1096void Verifier::visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
1099 if (!MDNodes.
insert(&MD).second)
1103 "MDNode context does not match Module context!", &MD);
1108 case Metadata::MDTupleKind:
1110#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
1111 case Metadata::CLASS##Kind: \
1112 visit##CLASS(cast<CLASS>(MD)); \
1114#include "llvm/IR/Metadata.def"
1123 "DILocation not allowed within this metadata node", &MD,
Op);
1125 visitMDNode(*
N, AllowLocs);
1129 visitValueAsMetadata(*V,
nullptr);
1141 "Expected second operand to be an integer constant of type i32 or "
1151void Verifier::visitValueAsMetadata(
const ValueAsMetadata &MD, Function *
F) {
1154 "Unexpected metadata round-trip through values", &MD, MD.
getValue());
1160 Check(
F,
"function-local metadata used outside a function", L);
1166 Check(
I->getParent(),
"function-local metadata not in basic block", L,
I);
1172 assert(ActualF &&
"Unimplemented function local metadata case!");
1174 Check(ActualF ==
F,
"function-local metadata used in wrong function", L);
1177void Verifier::visitDIArgList(
const DIArgList &AL, Function *
F) {
1178 for (
const ValueAsMetadata *VAM :
AL.getArgs())
1179 visitValueAsMetadata(*VAM,
F);
1182void Verifier::visitMetadataAsValue(
const MetadataAsValue &MDV, Function *
F) {
1185 visitMDNode(*
N, AreDebugLocsAllowed::No);
1191 if (!MDNodes.
insert(MD).second)
1195 visitValueAsMetadata(*V,
F);
1198 visitDIArgList(*AL,
F);
1206void Verifier::visitDILocation(
const DILocation &
N) {
1208 "location requires a valid scope", &
N,
N.getRawScope());
1209 if (
auto *IA =
N.getRawInlinedAt())
1212 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1215void Verifier::visitGenericDINode(
const GenericDINode &
N) {
1219void Verifier::visitDIScope(
const DIScope &
N) {
1220 if (
auto *
F =
N.getRawFile())
1224void Verifier::visitDISubrangeType(
const DISubrangeType &
N) {
1225 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1228 auto *LBound =
N.getRawLowerBound();
1232 "LowerBound must be signed constant or DIVariable or DIExpression or "
1235 auto *UBound =
N.getRawUpperBound();
1239 "UpperBound must be signed constant or DIVariable or DIExpression or "
1242 auto *Stride =
N.getRawStride();
1245 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1246 auto *Bias =
N.getRawBias();
1249 "Bias must be signed constant or DIVariable or DIExpression", &
N);
1251 auto *
Size =
N.getRawSizeInBits();
1253 "SizeInBits must be a constant");
1256void Verifier::visitDISubrange(
const DISubrange &
N) {
1257 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1258 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1259 "Subrange can have any one of count or upperBound", &
N);
1260 auto *CBound =
N.getRawCountNode();
1263 "Count must be signed constant or DIVariable or DIExpression", &
N);
1264 auto Count =
N.getCount();
1267 "invalid subrange count", &
N);
1268 auto *LBound =
N.getRawLowerBound();
1271 "LowerBound must be signed constant or DIVariable or DIExpression",
1273 auto *UBound =
N.getRawUpperBound();
1276 "UpperBound must be signed constant or DIVariable or DIExpression",
1278 auto *Stride =
N.getRawStride();
1281 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1284void Verifier::visitDIGenericSubrange(
const DIGenericSubrange &
N) {
1285 CheckDI(
N.getTag() == dwarf::DW_TAG_generic_subrange,
"invalid tag", &
N);
1286 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1287 "GenericSubrange can have any one of count or upperBound", &
N);
1288 auto *CBound =
N.getRawCountNode();
1290 "Count must be signed constant or DIVariable or DIExpression", &
N);
1291 auto *LBound =
N.getRawLowerBound();
1292 CheckDI(LBound,
"GenericSubrange must contain lowerBound", &
N);
1294 "LowerBound must be signed constant or DIVariable or DIExpression",
1296 auto *UBound =
N.getRawUpperBound();
1298 "UpperBound must be signed constant or DIVariable or DIExpression",
1300 auto *Stride =
N.getRawStride();
1301 CheckDI(Stride,
"GenericSubrange must contain stride", &
N);
1303 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1306void Verifier::visitDIEnumerator(
const DIEnumerator &
N) {
1307 CheckDI(
N.getTag() == dwarf::DW_TAG_enumerator,
"invalid tag", &
N);
1310void Verifier::visitDIBasicType(
const DIBasicType &
N) {
1311 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type ||
1312 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1313 N.getTag() == dwarf::DW_TAG_string_type,
1316 auto *
Size =
N.getRawSizeInBits();
1318 "SizeInBits must be a constant");
1321void Verifier::visitDIFixedPointType(
const DIFixedPointType &
N) {
1322 visitDIBasicType(
N);
1324 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type,
"invalid tag", &
N);
1325 CheckDI(
N.getEncoding() == dwarf::DW_ATE_signed_fixed ||
1326 N.getEncoding() == dwarf::DW_ATE_unsigned_fixed,
1327 "invalid encoding", &
N);
1331 "invalid kind", &
N);
1333 N.getFactorRaw() == 0,
1334 "factor should be 0 for rationals", &
N);
1336 (
N.getNumeratorRaw() == 0 &&
N.getDenominatorRaw() == 0),
1337 "numerator and denominator should be 0 for non-rationals", &
N);
1340void Verifier::visitDIStringType(
const DIStringType &
N) {
1341 CheckDI(
N.getTag() == dwarf::DW_TAG_string_type,
"invalid tag", &
N);
1342 CheckDI(!(
N.isBigEndian() &&
N.isLittleEndian()),
"has conflicting flags",
1346void Verifier::visitDIDerivedType(
const DIDerivedType &
N) {
1350 CheckDI(
N.getTag() == dwarf::DW_TAG_typedef ||
1351 N.getTag() == dwarf::DW_TAG_pointer_type ||
1352 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1353 N.getTag() == dwarf::DW_TAG_reference_type ||
1354 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1355 N.getTag() == dwarf::DW_TAG_const_type ||
1356 N.getTag() == dwarf::DW_TAG_immutable_type ||
1357 N.getTag() == dwarf::DW_TAG_volatile_type ||
1358 N.getTag() == dwarf::DW_TAG_restrict_type ||
1359 N.getTag() == dwarf::DW_TAG_atomic_type ||
1360 N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
1361 N.getTag() == dwarf::DW_TAG_member ||
1362 (
N.getTag() == dwarf::DW_TAG_variable &&
N.isStaticMember()) ||
1363 N.getTag() == dwarf::DW_TAG_inheritance ||
1364 N.getTag() == dwarf::DW_TAG_friend ||
1365 N.getTag() == dwarf::DW_TAG_set_type ||
1366 N.getTag() == dwarf::DW_TAG_template_alias,
1368 if (
N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1369 CheckDI(
isType(
N.getRawExtraData()),
"invalid pointer to member type", &
N,
1370 N.getRawExtraData());
1371 }
else if (
N.getTag() == dwarf::DW_TAG_template_alias) {
1373 N.getRawExtraData());
1374 }
else if (
N.getTag() == dwarf::DW_TAG_inheritance ||
1375 N.getTag() == dwarf::DW_TAG_member ||
1376 N.getTag() == dwarf::DW_TAG_variable) {
1377 auto *ExtraData =
N.getRawExtraData();
1378 auto IsValidExtraData = [&]() {
1379 if (ExtraData ==
nullptr)
1385 if (Tuple->getNumOperands() != 1)
1392 "extraData must be ConstantAsMetadata, MDString, DIObjCProperty, "
1393 "or MDTuple with single ConstantAsMetadata operand",
1397 if (
N.getTag() == dwarf::DW_TAG_set_type) {
1398 if (
auto *
T =
N.getRawBaseType()) {
1403 (Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1404 (Subrange &&
Subrange->getTag() == dwarf::DW_TAG_subrange_type) ||
1405 (
Basic && (
Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1406 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1407 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1408 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1409 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1410 "invalid set base type", &
N,
T);
1416 N.getRawBaseType());
1418 if (
N.getDWARFAddressSpace()) {
1419 CheckDI(
N.getTag() == dwarf::DW_TAG_pointer_type ||
1420 N.getTag() == dwarf::DW_TAG_reference_type ||
1421 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1422 "DWARF address space only applies to pointer or reference types",
1426 auto *
Size =
N.getRawSizeInBits();
1429 "SizeInBits must be a constant or DIVariable or DIExpression");
1434 return ((Flags & DINode::FlagLValueReference) &&
1435 (Flags & DINode::FlagRValueReference)) ||
1436 ((Flags & DINode::FlagTypePassByValue) &&
1437 (Flags & DINode::FlagTypePassByReference));
1440void Verifier::visitTemplateParams(
const MDNode &
N,
const Metadata &RawParams) {
1442 CheckDI(Params,
"invalid template params", &
N, &RawParams);
1449void Verifier::visitDICompositeType(
const DICompositeType &
N) {
1453 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type ||
1454 N.getTag() == dwarf::DW_TAG_structure_type ||
1455 N.getTag() == dwarf::DW_TAG_union_type ||
1456 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1457 N.getTag() == dwarf::DW_TAG_class_type ||
1458 N.getTag() == dwarf::DW_TAG_variant_part ||
1459 N.getTag() == dwarf::DW_TAG_variant ||
1460 N.getTag() == dwarf::DW_TAG_namelist,
1465 N.getRawBaseType());
1468 "invalid composite elements", &
N,
N.getRawElements());
1470 N.getRawVTableHolder());
1472 "invalid reference flags", &
N);
1473 unsigned DIBlockByRefStruct = 1 << 4;
1474 CheckDI((
N.getFlags() & DIBlockByRefStruct) == 0,
1475 "DIBlockByRefStruct on DICompositeType is no longer supported", &
N);
1477 "DISubprogram contains null entry in `elements` field", &
N);
1480 const DINodeArray
Elements =
N.getElements();
1482 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1483 "invalid vector, expected one element of type subrange", &
N);
1486 if (
auto *Params =
N.getRawTemplateParams())
1487 visitTemplateParams(
N, *Params);
1489 if (
auto *
D =
N.getRawDiscriminator()) {
1491 "discriminator can only appear on variant part");
1494 if (
N.getRawDataLocation()) {
1495 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1496 "dataLocation can only appear in array type");
1499 if (
N.getRawAssociated()) {
1500 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1501 "associated can only appear in array type");
1504 if (
N.getRawAllocated()) {
1505 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1506 "allocated can only appear in array type");
1509 if (
N.getRawRank()) {
1510 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1511 "rank can only appear in array type");
1514 if (
N.getTag() == dwarf::DW_TAG_array_type) {
1515 CheckDI(
N.getRawBaseType(),
"array types must have a base type", &
N);
1518 auto *
Size =
N.getRawSizeInBits();
1521 "SizeInBits must be a constant or DIVariable or DIExpression");
1524void Verifier::visitDISubroutineType(
const DISubroutineType &
N) {
1525 CheckDI(
N.getTag() == dwarf::DW_TAG_subroutine_type,
"invalid tag", &
N);
1526 if (
auto *Types =
N.getRawTypeArray()) {
1528 for (
Metadata *Ty :
N.getTypeArray()->operands()) {
1529 CheckDI(
isType(Ty),
"invalid subroutine type ref", &
N, Types, Ty);
1533 "invalid reference flags", &
N);
1536void Verifier::visitDIFile(
const DIFile &
N) {
1537 CheckDI(
N.getTag() == dwarf::DW_TAG_file_type,
"invalid tag", &
N);
1538 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum =
N.getChecksum();
1540 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1541 "invalid checksum kind", &
N);
1543 switch (Checksum->Kind) {
1554 CheckDI(Checksum->Value.size() ==
Size,
"invalid checksum length", &
N);
1556 "invalid checksum", &
N);
1560void Verifier::visitDICompileUnit(
const DICompileUnit &
N) {
1561 CheckDI(
N.isDistinct(),
"compile units must be distinct", &
N);
1562 CheckDI(
N.getTag() == dwarf::DW_TAG_compile_unit,
"invalid tag", &
N);
1568 CheckDI(!
N.getFile()->getFilename().empty(),
"invalid filename", &
N,
1572 "invalid emission kind", &
N);
1574 if (
auto *Array =
N.getRawEnumTypes()) {
1576 for (
Metadata *
Op :
N.getEnumTypes()->operands()) {
1578 CheckDI(Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1579 "invalid enum type", &
N,
N.getEnumTypes(),
Op);
1581 "function-local enum in a DICompileUnit's enum list", &
N,
1582 N.getEnumTypes(),
Op);
1585 if (
auto *Array =
N.getRawRetainedTypes()) {
1587 for (
Metadata *
Op :
N.getRetainedTypes()->operands()) {
1591 "invalid retained type", &
N,
Op);
1594 if (
auto *Array =
N.getRawGlobalVariables()) {
1596 for (
Metadata *
Op :
N.getGlobalVariables()->operands()) {
1598 "invalid global variable ref", &
N,
Op);
1601 if (
auto *Array =
N.getRawImportedEntities()) {
1603 for (
Metadata *
Op :
N.getImportedEntities()->operands()) {
1608 if (
auto *Array =
N.getRawMacros()) {
1617void Verifier::visitDISubprogram(
const DISubprogram &
N) {
1618 CheckDI(
N.getTag() == dwarf::DW_TAG_subprogram,
"invalid tag", &
N);
1620 if (
auto *
F =
N.getRawFile())
1623 CheckDI(
N.getLine() == 0,
"line specified with no file", &
N,
N.getLine());
1624 if (
auto *
T =
N.getRawType())
1626 CheckDI(
isType(
N.getRawContainingType()),
"invalid containing type", &
N,
1627 N.getRawContainingType());
1628 if (
auto *Params =
N.getRawTemplateParams())
1629 visitTemplateParams(
N, *Params);
1630 if (
auto *S =
N.getRawDeclaration())
1632 "invalid subprogram declaration", &
N, S);
1633 if (
auto *RawNode =
N.getRawRetainedNodes()) {
1635 CheckDI(Node,
"invalid retained nodes list", &
N, RawNode);
1637 DenseMap<unsigned, DILocalVariable *>
Args;
1639 CheckDI(
Op,
"nullptr in retained nodes", &
N, Node);
1641 auto True = [](
const Metadata *) {
return true; };
1642 auto False = [](
const Metadata *) {
return false; };
1643 bool IsTypeCorrect = DISubprogram::visitRetainedNode<bool>(
1644 Op, True, True, True, True, False);
1646 "invalid retained nodes, expected DILocalVariable, DILabel, "
1647 "DIImportedEntity or DIType",
1654 "invalid retained nodes, retained node is not local", &
N, Node,
1657 DISubprogram *RetainedNodeSP = RetainedNodeScope->getSubprogram();
1658 DICompileUnit *RetainedNodeUnit =
1659 RetainedNodeSP ? RetainedNodeSP->getUnit() :
nullptr;
1661 RetainedNodeSP == &
N,
1662 "invalid retained nodes, retained node does not belong to subprogram",
1663 &
N, Node, RetainedNode, RetainedNodeScope, RetainedNodeSP,
1669 if (
unsigned ArgNum = DV->getArg()) {
1671 CheckDI(Inserted || DV == ArgI->second,
1672 "invalid retained nodes, more than one local variable with the "
1673 "same argument index",
1674 &
N,
N.getUnit(), Node, RetainedNode, Args[ArgNum]);
1679 "invalid reference flags", &
N);
1681 auto *
Unit =
N.getRawUnit();
1682 if (
N.isDefinition()) {
1684 CheckDI(
N.isDistinct(),
"subprogram definitions must be distinct", &
N);
1685 CheckDI(Unit,
"subprogram definitions must have a compile unit", &
N);
1690 if (CT && CT->getRawIdentifier() &&
1691 M.getContext().isODRUniquingDebugTypes())
1693 "definition subprograms cannot be nested within DICompositeType "
1694 "when enabling ODR",
1698 CheckDI(!Unit,
"subprogram declarations must not have a compile unit", &
N);
1700 "subprogram declaration must not have a declaration field");
1703 if (
auto *RawThrownTypes =
N.getRawThrownTypes()) {
1705 CheckDI(ThrownTypes,
"invalid thrown types list", &
N, RawThrownTypes);
1711 if (
N.areAllCallsDescribed())
1713 "DIFlagAllCallsDescribed must be attached to a definition");
1716void Verifier::visitDILexicalBlockBase(
const DILexicalBlockBase &
N) {
1717 CheckDI(
N.getTag() == dwarf::DW_TAG_lexical_block,
"invalid tag", &
N);
1719 "invalid local scope", &
N,
N.getRawScope());
1721 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1724void Verifier::visitDILexicalBlock(
const DILexicalBlock &
N) {
1725 visitDILexicalBlockBase(
N);
1728 "cannot have column info without line info", &
N);
1731void Verifier::visitDILexicalBlockFile(
const DILexicalBlockFile &
N) {
1732 visitDILexicalBlockBase(
N);
1735void Verifier::visitDICommonBlock(
const DICommonBlock &
N) {
1736 CheckDI(
N.getTag() == dwarf::DW_TAG_common_block,
"invalid tag", &
N);
1737 if (
auto *S =
N.getRawScope())
1739 if (
auto *S =
N.getRawDecl())
1743void Verifier::visitDINamespace(
const DINamespace &
N) {
1744 CheckDI(
N.getTag() == dwarf::DW_TAG_namespace,
"invalid tag", &
N);
1745 if (
auto *S =
N.getRawScope())
1749void Verifier::visitDIMacro(
const DIMacro &
N) {
1752 "invalid macinfo type", &
N);
1753 CheckDI(!
N.getName().empty(),
"anonymous macro", &
N);
1754 if (!
N.getValue().empty()) {
1755 assert(
N.getValue().data()[0] !=
' ' &&
"Macro value has a space prefix");
1759void Verifier::visitDIMacroFile(
const DIMacroFile &
N) {
1761 "invalid macinfo type", &
N);
1762 if (
auto *
F =
N.getRawFile())
1765 if (
auto *Array =
N.getRawElements()) {
1767 for (
Metadata *
Op :
N.getElements()->operands()) {
1773void Verifier::visitDIModule(
const DIModule &
N) {
1774 CheckDI(
N.getTag() == dwarf::DW_TAG_module,
"invalid tag", &
N);
1775 CheckDI(!
N.getName().empty(),
"anonymous module", &
N);
1778void Verifier::visitDITemplateParameter(
const DITemplateParameter &
N) {
1782void Verifier::visitDITemplateTypeParameter(
const DITemplateTypeParameter &
N) {
1783 visitDITemplateParameter(
N);
1785 CheckDI(
N.getTag() == dwarf::DW_TAG_template_type_parameter,
"invalid tag",
1789void Verifier::visitDITemplateValueParameter(
1790 const DITemplateValueParameter &
N) {
1791 visitDITemplateParameter(
N);
1793 CheckDI(
N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1794 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1795 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1799void Verifier::visitDIVariable(
const DIVariable &
N) {
1800 if (
auto *S =
N.getRawScope())
1802 if (
auto *
F =
N.getRawFile())
1806void Verifier::visitDIGlobalVariable(
const DIGlobalVariable &
N) {
1810 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1813 if (
N.isDefinition())
1814 CheckDI(
N.getType(),
"missing global variable type", &
N);
1815 if (
auto *Member =
N.getRawStaticDataMemberDeclaration()) {
1817 "invalid static data member declaration", &
N, Member);
1821void Verifier::visitDILocalVariable(
const DILocalVariable &
N) {
1826 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1828 "local variable requires a valid scope", &
N,
N.getRawScope());
1829 if (
auto Ty =
N.getType())
1833void Verifier::visitDIAssignID(
const DIAssignID &
N) {
1834 CheckDI(!
N.getNumOperands(),
"DIAssignID has no arguments", &
N);
1835 CheckDI(
N.isDistinct(),
"DIAssignID must be distinct", &
N);
1838void Verifier::visitDILabel(
const DILabel &
N) {
1839 if (
auto *S =
N.getRawScope())
1841 if (
auto *
F =
N.getRawFile())
1844 CheckDI(
N.getTag() == dwarf::DW_TAG_label,
"invalid tag", &
N);
1846 "label requires a valid scope", &
N,
N.getRawScope());
1849void Verifier::visitDIExpression(
const DIExpression &
N) {
1850 CheckDI(
N.isValid(),
"invalid expression", &
N);
1853void Verifier::visitDIGlobalVariableExpression(
1854 const DIGlobalVariableExpression &GVE) {
1857 visitDIGlobalVariable(*Var);
1859 visitDIExpression(*Expr);
1860 if (
auto Fragment = Expr->getFragmentInfo())
1861 verifyFragmentExpression(*GVE.
getVariable(), *Fragment, &GVE);
1865void Verifier::visitDIObjCProperty(
const DIObjCProperty &
N) {
1866 CheckDI(
N.getTag() == dwarf::DW_TAG_APPLE_property,
"invalid tag", &
N);
1867 if (
auto *
T =
N.getRawType())
1869 if (
auto *
F =
N.getRawFile())
1873void Verifier::visitDIImportedEntity(
const DIImportedEntity &
N) {
1874 CheckDI(
N.getTag() == dwarf::DW_TAG_imported_module ||
1875 N.getTag() == dwarf::DW_TAG_imported_declaration,
1877 if (
auto *S =
N.getRawScope())
1883void Verifier::visitComdat(
const Comdat &
C) {
1886 if (
TT.isOSBinFormatCOFF())
1887 if (
const GlobalValue *GV =
M.getNamedValue(
C.getName()))
1892void Verifier::visitModuleIdents() {
1893 const NamedMDNode *Idents =
M.getNamedMetadata(
"llvm.ident");
1899 for (
const MDNode *
N : Idents->
operands()) {
1900 Check(
N->getNumOperands() == 1,
1901 "incorrect number of operands in llvm.ident metadata",
N);
1903 (
"invalid value for llvm.ident metadata entry operand"
1904 "(the operand should be a string)"),
1909void Verifier::visitModuleCommandLines() {
1910 const NamedMDNode *CommandLines =
M.getNamedMetadata(
"llvm.commandline");
1917 for (
const MDNode *
N : CommandLines->
operands()) {
1918 Check(
N->getNumOperands() == 1,
1919 "incorrect number of operands in llvm.commandline metadata",
N);
1921 (
"invalid value for llvm.commandline metadata entry operand"
1922 "(the operand should be a string)"),
1927void Verifier::visitModuleErrnoTBAA() {
1928 const NamedMDNode *ErrnoTBAA =
M.getNamedMetadata(
"llvm.errno.tbaa");
1933 "llvm.errno.tbaa must have at least one operand", ErrnoTBAA);
1935 for (
const MDNode *
N : ErrnoTBAA->
operands())
1939void Verifier::visitModuleFlags() {
1940 const NamedMDNode *
Flags =
M.getModuleFlagsMetadata();
1944 DenseMap<const MDString*, const MDNode*> SeenIDs;
1946 uint64_t PAuthABIPlatform = -1;
1947 uint64_t PAuthABIVersion = -1;
1948 for (
const MDNode *MDN :
Flags->operands()) {
1949 visitModuleFlag(MDN, SeenIDs, Requirements);
1950 if (MDN->getNumOperands() != 3)
1953 if (FlagName->getString() ==
"aarch64-elf-pauthabi-platform") {
1954 if (
const auto *PAP =
1956 PAuthABIPlatform = PAP->getZExtValue();
1957 }
else if (FlagName->getString() ==
"aarch64-elf-pauthabi-version") {
1958 if (
const auto *PAV =
1960 PAuthABIVersion = PAV->getZExtValue();
1965 if ((PAuthABIPlatform == uint64_t(-1)) != (PAuthABIVersion == uint64_t(-1)))
1966 CheckFailed(
"either both or no 'aarch64-elf-pauthabi-platform' and "
1967 "'aarch64-elf-pauthabi-version' module flags must be present");
1970 for (
const MDNode *Requirement : Requirements) {
1972 const Metadata *ReqValue = Requirement->getOperand(1);
1974 const MDNode *
Op = SeenIDs.
lookup(Flag);
1976 CheckFailed(
"invalid requirement on flag, flag is not present in module",
1981 if (
Op->getOperand(2) != ReqValue) {
1982 CheckFailed((
"invalid requirement on flag, "
1983 "flag does not have the required value"),
1991Verifier::visitModuleFlag(
const MDNode *
Op,
1992 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1993 SmallVectorImpl<const MDNode *> &Requirements) {
1997 "incorrect number of operands in module flag",
Op);
1998 Module::ModFlagBehavior MFB;
1999 if (!Module::isValidModFlagBehavior(
Op->getOperand(0), MFB)) {
2001 "invalid behavior operand in module flag (expected constant integer)",
2004 "invalid behavior operand in module flag (unexpected constant)",
2008 Check(
ID,
"invalid ID operand in module flag (expected metadata string)",
2014 case Module::Warning:
2015 case Module::Override:
2021 Check(V &&
V->getValue().isNonNegative(),
2022 "invalid value for 'min' module flag (expected constant non-negative "
2030 "invalid value for 'max' module flag (expected constant integer)",
2035 case Module::Require: {
2040 "invalid value for 'require' module flag (expected metadata pair)",
2043 (
"invalid value for 'require' module flag "
2044 "(first value operand should be a string)"),
2045 Value->getOperand(0));
2053 case Module::Append:
2054 case Module::AppendUnique: {
2057 "invalid value for 'append'-type module flag "
2058 "(expected a metadata node)",
2065 if (MFB != Module::Require) {
2068 "module flag identifiers must be unique (or of 'require' type)",
ID);
2071 if (
ID->getString() ==
"wchar_size") {
2074 Check(
Value,
"wchar_size metadata requires constant integer argument");
2077 if (
ID->getString() ==
"Linker Options") {
2081 Check(
M.getNamedMetadata(
"llvm.linker.options"),
2082 "'Linker Options' named metadata no longer supported");
2085 if (
ID->getString() ==
"SemanticInterposition") {
2086 ConstantInt *
Value =
2089 "SemanticInterposition metadata requires constant integer argument");
2092 if (
ID->getString() ==
"CG Profile") {
2093 for (
const MDOperand &MDO :
cast<MDNode>(
Op->getOperand(2))->operands())
2094 visitModuleFlagCGProfileEntry(MDO);
2098void Verifier::visitModuleFlagCGProfileEntry(
const MDOperand &MDO) {
2099 auto CheckFunction = [&](
const MDOperand &FuncMDO) {
2104 "expected a Function or null", FuncMDO);
2107 Check(Node &&
Node->getNumOperands() == 3,
"expected a MDNode triple", MDO);
2108 CheckFunction(
Node->getOperand(0));
2109 CheckFunction(
Node->getOperand(1));
2112 "expected an integer constant",
Node->getOperand(2));
2115void Verifier::verifyAttributeTypes(AttributeSet Attrs,
const Value *V) {
2118 if (
A.isStringAttribute()) {
2119#define GET_ATTR_NAMES
2120#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
2121#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
2122 if (A.getKindAsString() == #DISPLAY_NAME) { \
2123 auto V = A.getValueAsString(); \
2124 if (!(V.empty() || V == "true" || V == "false")) \
2125 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
2129#include "llvm/IR/Attributes.inc"
2133 if (
A.isIntAttribute() != Attribute::isIntAttrKind(
A.getKindAsEnum())) {
2134 CheckFailed(
"Attribute '" +
A.getAsString() +
"' should have an Argument",
2143void Verifier::verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
2145 if (!
Attrs.hasAttributes())
2148 verifyAttributeTypes(Attrs, V);
2151 Check(Attr.isStringAttribute() ||
2152 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
2153 "Attribute '" + Attr.getAsString() +
"' does not apply to parameters",
2156 if (
Attrs.hasAttribute(Attribute::ImmArg)) {
2157 unsigned AttrCount =
2158 Attrs.getNumAttributes() -
Attrs.hasAttribute(Attribute::Range);
2159 Check(AttrCount == 1,
2160 "Attribute 'immarg' is incompatible with other attributes except the "
2161 "'range' attribute",
2167 unsigned AttrCount = 0;
2168 AttrCount +=
Attrs.hasAttribute(Attribute::ByVal);
2169 AttrCount +=
Attrs.hasAttribute(Attribute::InAlloca);
2170 AttrCount +=
Attrs.hasAttribute(Attribute::Preallocated);
2171 AttrCount +=
Attrs.hasAttribute(Attribute::StructRet) ||
2172 Attrs.hasAttribute(Attribute::InReg);
2173 AttrCount +=
Attrs.hasAttribute(Attribute::Nest);
2174 AttrCount +=
Attrs.hasAttribute(Attribute::ByRef);
2175 Check(AttrCount <= 1,
2176 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
2177 "'byref', and 'sret' are incompatible!",
2180 Check(!(
Attrs.hasAttribute(Attribute::InAlloca) &&
2181 Attrs.hasAttribute(Attribute::ReadOnly)),
2183 "'inalloca and readonly' are incompatible!",
2186 Check(!(
Attrs.hasAttribute(Attribute::StructRet) &&
2187 Attrs.hasAttribute(Attribute::Returned)),
2189 "'sret and returned' are incompatible!",
2192 Check(!(
Attrs.hasAttribute(Attribute::ZExt) &&
2193 Attrs.hasAttribute(Attribute::SExt)),
2195 "'zeroext and signext' are incompatible!",
2198 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2199 Attrs.hasAttribute(Attribute::ReadOnly)),
2201 "'readnone and readonly' are incompatible!",
2204 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2205 Attrs.hasAttribute(Attribute::WriteOnly)),
2207 "'readnone and writeonly' are incompatible!",
2210 Check(!(
Attrs.hasAttribute(Attribute::ReadOnly) &&
2211 Attrs.hasAttribute(Attribute::WriteOnly)),
2213 "'readonly and writeonly' are incompatible!",
2216 Check(!(
Attrs.hasAttribute(Attribute::NoInline) &&
2217 Attrs.hasAttribute(Attribute::AlwaysInline)),
2219 "'noinline and alwaysinline' are incompatible!",
2222 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2223 Attrs.hasAttribute(Attribute::ReadNone)),
2224 "Attributes writable and readnone are incompatible!", V);
2226 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2227 Attrs.hasAttribute(Attribute::ReadOnly)),
2228 "Attributes writable and readonly are incompatible!", V);
2230 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty, Attrs);
2232 if (!Attr.isStringAttribute() &&
2233 IncompatibleAttrs.
contains(Attr.getKindAsEnum())) {
2234 CheckFailed(
"Attribute '" + Attr.getAsString() +
2235 "' applied to incompatible type!", V);
2241 if (
Attrs.hasAttribute(Attribute::Alignment)) {
2242 Align AttrAlign =
Attrs.getAlignment().valueOrOne();
2243 Check(AttrAlign.
value() <= Value::MaximumAlignment,
2244 "huge alignment values are unsupported", V);
2246 if (
Attrs.hasAttribute(Attribute::ByVal)) {
2248 SmallPtrSet<Type *, 4> Visited;
2250 "Attribute 'byval' does not support unsized types!", V);
2254 "'byval' argument has illegal target extension type", V);
2255 Check(
DL.getTypeAllocSize(ByValTy).getKnownMinValue() < (1ULL << 32),
2256 "huge 'byval' arguments are unsupported", V);
2258 if (
Attrs.hasAttribute(Attribute::ByRef)) {
2259 SmallPtrSet<Type *, 4> Visited;
2260 Check(
Attrs.getByRefType()->isSized(&Visited),
2261 "Attribute 'byref' does not support unsized types!", V);
2262 Check(
DL.getTypeAllocSize(
Attrs.getByRefType()).getKnownMinValue() <
2264 "huge 'byref' arguments are unsupported", V);
2266 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
2267 SmallPtrSet<Type *, 4> Visited;
2268 Check(
Attrs.getInAllocaType()->isSized(&Visited),
2269 "Attribute 'inalloca' does not support unsized types!", V);
2270 Check(
DL.getTypeAllocSize(
Attrs.getInAllocaType()).getKnownMinValue() <
2272 "huge 'inalloca' arguments are unsupported", V);
2274 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
2275 SmallPtrSet<Type *, 4> Visited;
2276 Check(
Attrs.getPreallocatedType()->isSized(&Visited),
2277 "Attribute 'preallocated' does not support unsized types!", V);
2279 DL.getTypeAllocSize(
Attrs.getPreallocatedType()).getKnownMinValue() <
2281 "huge 'preallocated' arguments are unsupported", V);
2285 if (
Attrs.hasAttribute(Attribute::Initializes)) {
2286 auto Inits =
Attrs.getAttribute(Attribute::Initializes).getInitializes();
2287 Check(!Inits.empty(),
"Attribute 'initializes' does not support empty list",
2290 "Attribute 'initializes' does not support unordered ranges", V);
2293 if (
Attrs.hasAttribute(Attribute::NoFPClass)) {
2294 uint64_t Val =
Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
2295 Check(Val != 0,
"Attribute 'nofpclass' must have at least one test bit set",
2298 "Invalid value for 'nofpclass' test mask", V);
2300 if (
Attrs.hasAttribute(Attribute::Range)) {
2301 const ConstantRange &CR =
2302 Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2304 "Range bit width must match type bit width!", V);
2308void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
2310 if (
Attrs.hasFnAttr(Attr)) {
2311 StringRef S =
Attrs.getFnAttr(Attr).getValueAsString();
2314 CheckFailed(
"\"" + Attr +
"\" takes an unsigned integer: " + S, V);
2320void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
2321 const Value *V,
bool IsIntrinsic,
2323 if (
Attrs.isEmpty())
2326 if (AttributeListsVisited.
insert(
Attrs.getRawPointer()).second) {
2328 "Attribute list does not match Module context!", &Attrs, V);
2329 for (
const auto &AttrSet : Attrs) {
2330 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(
Context),
2331 "Attribute set does not match Module context!", &AttrSet, V);
2332 for (
const auto &
A : AttrSet) {
2334 "Attribute does not match Module context!", &
A, V);
2339 bool SawNest =
false;
2340 bool SawReturned =
false;
2341 bool SawSRet =
false;
2342 bool SawSwiftSelf =
false;
2343 bool SawSwiftAsync =
false;
2344 bool SawSwiftError =
false;
2347 AttributeSet RetAttrs =
Attrs.getRetAttrs();
2350 Attribute::canUseAsRetAttr(
RetAttr.getKindAsEnum()),
2351 "Attribute '" +
RetAttr.getAsString() +
2352 "' does not apply to function return values",
2355 unsigned MaxParameterWidth = 0;
2356 auto GetMaxParameterWidth = [&MaxParameterWidth](
Type *Ty) {
2359 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2360 if (
Size > MaxParameterWidth)
2361 MaxParameterWidth =
Size;
2365 GetMaxParameterWidth(FT->getReturnType());
2366 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2369 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2370 Type *Ty = FT->getParamType(i);
2371 AttributeSet ArgAttrs =
Attrs.getParamAttrs(i);
2375 "immarg attribute only applies to intrinsics", V);
2378 "Attribute 'elementtype' can only be applied to intrinsics"
2383 verifyParameterAttrs(ArgAttrs, Ty, V);
2384 GetMaxParameterWidth(Ty);
2387 Check(!SawNest,
"More than one parameter has attribute nest!", V);
2392 Check(!SawReturned,
"More than one parameter has attribute returned!", V);
2394 "Incompatible argument and return types for 'returned' attribute",
2400 Check(!SawSRet,
"Cannot have multiple 'sret' parameters!", V);
2401 Check(i == 0 || i == 1,
2402 "Attribute 'sret' is not on first or second parameter!", V);
2407 Check(!SawSwiftSelf,
"Cannot have multiple 'swiftself' parameters!", V);
2408 SawSwiftSelf =
true;
2412 Check(!SawSwiftAsync,
"Cannot have multiple 'swiftasync' parameters!", V);
2413 SawSwiftAsync =
true;
2417 Check(!SawSwiftError,
"Cannot have multiple 'swifterror' parameters!", V);
2418 SawSwiftError =
true;
2422 Check(i == FT->getNumParams() - 1,
2423 "inalloca isn't on the last parameter!", V);
2427 if (!
Attrs.hasFnAttrs())
2430 verifyAttributeTypes(
Attrs.getFnAttrs(), V);
2433 Attribute::canUseAsFnAttr(
FnAttr.getKindAsEnum()),
2434 "Attribute '" +
FnAttr.getAsString() +
2435 "' does not apply to functions!",
2438 Check(!(
Attrs.hasFnAttr(Attribute::NoInline) &&
2439 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2440 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2442 if (
Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2444 "Attribute 'optnone' requires 'noinline'!", V);
2446 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2447 "Attributes 'optsize and optnone' are incompatible!", V);
2450 "Attributes 'minsize and optnone' are incompatible!", V);
2452 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
2453 "Attributes 'optdebug and optnone' are incompatible!", V);
2456 Check(!(
Attrs.hasFnAttr(Attribute::SanitizeRealtime) &&
2457 Attrs.hasFnAttr(Attribute::SanitizeRealtimeBlocking)),
2459 "'sanitize_realtime and sanitize_realtime_blocking' are incompatible!",
2462 if (
Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
2463 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2464 "Attributes 'optsize and optdebug' are incompatible!", V);
2467 "Attributes 'minsize and optdebug' are incompatible!", V);
2470 Check(!
Attrs.hasAttrSomewhere(Attribute::Writable) ||
2471 isModSet(
Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
2472 "Attribute writable and memory without argmem: write are incompatible!",
2475 if (
Attrs.hasFnAttr(
"aarch64_pstate_sm_enabled")) {
2476 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_sm_compatible"),
2477 "Attributes 'aarch64_pstate_sm_enabled and "
2478 "aarch64_pstate_sm_compatible' are incompatible!",
2482 Check((
Attrs.hasFnAttr(
"aarch64_new_za") +
Attrs.hasFnAttr(
"aarch64_in_za") +
2483 Attrs.hasFnAttr(
"aarch64_inout_za") +
2484 Attrs.hasFnAttr(
"aarch64_out_za") +
2485 Attrs.hasFnAttr(
"aarch64_preserves_za") +
2486 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2487 "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2488 "'aarch64_inout_za', 'aarch64_preserves_za' and "
2489 "'aarch64_za_state_agnostic' are mutually exclusive",
2493 Attrs.hasFnAttr(
"aarch64_in_zt0") +
2494 Attrs.hasFnAttr(
"aarch64_inout_zt0") +
2495 Attrs.hasFnAttr(
"aarch64_out_zt0") +
2496 Attrs.hasFnAttr(
"aarch64_preserves_zt0") +
2497 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2498 "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
2499 "'aarch64_inout_zt0', 'aarch64_preserves_zt0' and "
2500 "'aarch64_za_state_agnostic' are mutually exclusive",
2503 if (
Attrs.hasFnAttr(Attribute::JumpTable)) {
2506 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2509 if (
auto Args =
Attrs.getFnAttrs().getAllocSizeArgs()) {
2510 auto CheckParam = [&](StringRef
Name,
unsigned ParamNo) {
2511 if (ParamNo >= FT->getNumParams()) {
2512 CheckFailed(
"'allocsize' " + Name +
" argument is out of bounds", V);
2516 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2517 CheckFailed(
"'allocsize' " + Name +
2518 " argument must refer to an integer parameter",
2526 if (!CheckParam(
"element size",
Args->first))
2529 if (
Args->second && !CheckParam(
"number of elements", *
Args->second))
2533 if (
Attrs.hasFnAttr(Attribute::AllocKind)) {
2536 K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
2538 {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
2541 "'allockind()' requires exactly one of alloc, realloc, and free");
2542 if ((
Type == AllocFnKind::Free) &&
2543 ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
2544 AllocFnKind::Aligned)) != AllocFnKind::Unknown))
2545 CheckFailed(
"'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2546 "or aligned modifiers.");
2547 AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
2548 if ((K & ZeroedUninit) == ZeroedUninit)
2549 CheckFailed(
"'allockind()' can't be both zeroed and uninitialized");
2553 StringRef S =
A.getValueAsString();
2554 Check(!S.
empty(),
"'alloc-variant-zeroed' must not be empty");
2562 "'alloc-variant-zeroed' must name a function belonging to the "
2563 "same 'alloc-family'");
2566 (
Variant->getFnAttribute(Attribute::AllocKind).getAllocKind() &
2567 AllocFnKind::Zeroed) != AllocFnKind::Unknown,
2568 "'alloc-variant-zeroed' must name a function with "
2569 "'allockind(\"zeroed\")'");
2572 "'alloc-variant-zeroed' must name a function with the same "
2577 "'alloc-variant-zeroed' must name a function with the same "
2578 "calling convention");
2582 if (
Attrs.hasFnAttr(Attribute::VScaleRange)) {
2583 unsigned VScaleMin =
Attrs.getFnAttrs().getVScaleRangeMin();
2585 CheckFailed(
"'vscale_range' minimum must be greater than 0", V);
2587 CheckFailed(
"'vscale_range' minimum must be power-of-two value", V);
2588 std::optional<unsigned> VScaleMax =
Attrs.getFnAttrs().getVScaleRangeMax();
2589 if (VScaleMax && VScaleMin > VScaleMax)
2590 CheckFailed(
"'vscale_range' minimum cannot be greater than maximum", V);
2592 CheckFailed(
"'vscale_range' maximum must be power-of-two value", V);
2595 if (
Attribute FPAttr =
Attrs.getFnAttr(
"frame-pointer"); FPAttr.isValid()) {
2596 StringRef
FP = FPAttr.getValueAsString();
2597 if (
FP !=
"all" &&
FP !=
"non-leaf" &&
FP !=
"none" &&
FP !=
"reserved" &&
2598 FP !=
"non-leaf-no-reserve")
2599 CheckFailed(
"invalid value for 'frame-pointer' attribute: " +
FP, V);
2602 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-prefix", V);
2603 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-entry", V);
2604 if (
Attrs.hasFnAttr(
"patchable-function-entry-section"))
2605 Check(!
Attrs.getFnAttr(
"patchable-function-entry-section")
2608 "\"patchable-function-entry-section\" must not be empty");
2609 checkUnsignedBaseTenFuncAttr(Attrs,
"warn-stack-size", V);
2611 if (
auto A =
Attrs.getFnAttr(
"sign-return-address");
A.isValid()) {
2612 StringRef S =
A.getValueAsString();
2613 if (S !=
"none" && S !=
"all" && S !=
"non-leaf")
2614 CheckFailed(
"invalid value for 'sign-return-address' attribute: " + S, V);
2617 if (
auto A =
Attrs.getFnAttr(
"sign-return-address-key");
A.isValid()) {
2618 StringRef S =
A.getValueAsString();
2619 if (S !=
"a_key" && S !=
"b_key")
2620 CheckFailed(
"invalid value for 'sign-return-address-key' attribute: " + S,
2622 if (
auto AA =
Attrs.getFnAttr(
"sign-return-address"); !AA.isValid()) {
2624 "'sign-return-address-key' present without `sign-return-address`");
2628 if (
auto A =
Attrs.getFnAttr(
"branch-target-enforcement");
A.isValid()) {
2629 StringRef S =
A.getValueAsString();
2630 if (S !=
"" && S !=
"true" && S !=
"false")
2632 "invalid value for 'branch-target-enforcement' attribute: " + S, V);
2635 if (
auto A =
Attrs.getFnAttr(
"branch-protection-pauth-lr");
A.isValid()) {
2636 StringRef S =
A.getValueAsString();
2637 if (S !=
"" && S !=
"true" && S !=
"false")
2639 "invalid value for 'branch-protection-pauth-lr' attribute: " + S, V);
2642 if (
auto A =
Attrs.getFnAttr(
"guarded-control-stack");
A.isValid()) {
2643 StringRef S =
A.getValueAsString();
2644 if (S !=
"" && S !=
"true" && S !=
"false")
2645 CheckFailed(
"invalid value for 'guarded-control-stack' attribute: " + S,
2649 if (
auto A =
Attrs.getFnAttr(
"vector-function-abi-variant");
A.isValid()) {
2650 StringRef S =
A.getValueAsString();
2653 CheckFailed(
"invalid name for a VFABI variant: " + S, V);
2656 if (
auto A =
Attrs.getFnAttr(
"modular-format");
A.isValid()) {
2657 StringRef S =
A.getValueAsString();
2661 "modular-format attribute requires at least 5 arguments", V);
2662 unsigned FirstArgIdx;
2663 Check(!Args[2].getAsInteger(10, FirstArgIdx),
2664 "modular-format attribute first arg index is not an integer", V);
2665 unsigned UpperBound = FT->getNumParams() + (FT->isVarArg() ? 1 : 0);
2666 Check(FirstArgIdx > 0 && FirstArgIdx <= UpperBound,
2667 "modular-format attribute first arg index is out of bounds", V);
2670 if (
auto A =
Attrs.getFnAttr(
"target-features");
A.isValid()) {
2671 StringRef S =
A.getValueAsString();
2673 for (
auto FeatureFlag :
split(S,
',')) {
2674 if (FeatureFlag.empty())
2676 "target-features attribute should not contain an empty string");
2678 Check(FeatureFlag[0] ==
'+' || FeatureFlag[0] ==
'-',
2679 "target feature '" + FeatureFlag +
2680 "' must start with a '+' or '-'",
2686void Verifier::verifyUnknownProfileMetadata(MDNode *MD) {
2688 "'unknown' !prof should have a single additional operand", MD);
2691 "'unknown' !prof should have an additional operand of type "
2694 "the 'unknown' !prof operand should not be an empty string");
2697void Verifier::verifyFunctionMetadata(
2698 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2699 for (
const auto &Pair : MDs) {
2700 if (Pair.first == LLVMContext::MD_prof) {
2701 MDNode *MD = Pair.second;
2703 "!prof annotations should have no less than 2 operands", MD);
2708 verifyUnknownProfileMetadata(MD);
2713 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null",
2716 "expected string with name of the !prof annotation", MD);
2721 "first operand should be 'function_entry_count'"
2722 " or 'synthetic_function_entry_count'",
2726 Check(MD->
getOperand(1) !=
nullptr,
"second operand should not be null",
2729 "expected integer argument to function_entry_count", MD);
2730 }
else if (Pair.first == LLVMContext::MD_kcfi_type) {
2731 MDNode *MD = Pair.second;
2733 "!kcfi_type must have exactly one operand", MD);
2734 Check(MD->
getOperand(0) !=
nullptr,
"!kcfi_type operand must not be null",
2737 "expected a constant operand for !kcfi_type", MD);
2740 "expected a constant integer operand for !kcfi_type", MD);
2742 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2747void Verifier::visitConstantExprsRecursively(
const Constant *EntryC) {
2751 if (!ConstantExprVisited.
insert(EntryC).second)
2755 Stack.push_back(EntryC);
2757 while (!
Stack.empty()) {
2762 visitConstantExpr(CE);
2765 visitConstantPtrAuth(CPA);
2770 Check(GV->
getParent() == &M,
"Referencing global in another module!",
2776 for (
const Use &U :
C->operands()) {
2780 if (!ConstantExprVisited.
insert(OpC).second)
2782 Stack.push_back(OpC);
2787void Verifier::visitConstantExpr(
const ConstantExpr *CE) {
2788 if (
CE->getOpcode() == Instruction::BitCast)
2791 "Invalid bitcast", CE);
2792 else if (
CE->getOpcode() == Instruction::PtrToAddr)
2793 checkPtrToAddr(
CE->getOperand(0)->getType(),
CE->getType(), *CE);
2796void Verifier::visitConstantPtrAuth(
const ConstantPtrAuth *CPA) {
2798 "signed ptrauth constant base pointer must have pointer type");
2801 "signed ptrauth constant must have same type as its base pointer");
2804 "signed ptrauth constant key must be i32 constant integer");
2807 "signed ptrauth constant address discriminator must be a pointer");
2810 "signed ptrauth constant discriminator must be i64 constant integer");
2813 "signed ptrauth constant deactivation symbol must be a pointer");
2817 "signed ptrauth constant deactivation symbol must be a global value "
2821bool Verifier::verifyAttributeCount(AttributeList Attrs,
unsigned Params) {
2824 return Attrs.getNumAttrSets() <= Params + 2;
2827void Verifier::verifyInlineAsmCall(
const CallBase &
Call) {
2830 unsigned LabelNo = 0;
2831 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
2841 if (CI.isIndirect) {
2844 "Operand for indirect constraint must have pointer type", &
Call);
2847 "Operand for indirect constraint must have elementtype attribute",
2851 "Elementtype attribute can only be applied for indirect "
2860 Check(LabelNo == CallBr->getNumIndirectDests(),
2861 "Number of label constraints does not match number of callbr dests",
2864 Check(LabelNo == 0,
"Label constraints can only be used with callbr",
2870void Verifier::verifyStatepoint(
const CallBase &
Call) {
2875 "gc.statepoint must read and write all memory to preserve "
2876 "reordering restrictions required by safepoint semantics",
2879 const int64_t NumPatchBytes =
2882 Check(NumPatchBytes >= 0,
2883 "gc.statepoint number of patchable bytes must be "
2888 Check(TargetElemType,
2889 "gc.statepoint callee argument must have elementtype attribute",
Call);
2891 Check(TargetFuncType,
2892 "gc.statepoint callee elementtype must be function type",
Call);
2895 Check(NumCallArgs >= 0,
2896 "gc.statepoint number of arguments to underlying call "
2899 const int NumParams = (int)TargetFuncType->getNumParams();
2900 if (TargetFuncType->isVarArg()) {
2901 Check(NumCallArgs >= NumParams,
2902 "gc.statepoint mismatch in number of vararg call args",
Call);
2905 Check(TargetFuncType->getReturnType()->isVoidTy(),
2906 "gc.statepoint doesn't support wrapping non-void "
2907 "vararg functions yet",
2910 Check(NumCallArgs == NumParams,
2911 "gc.statepoint mismatch in number of call args",
Call);
2913 const uint64_t
Flags
2915 Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
2916 "unknown flag used in gc.statepoint flags argument",
Call);
2921 for (
int i = 0; i < NumParams; i++) {
2922 Type *ParamType = TargetFuncType->getParamType(i);
2924 Check(ArgType == ParamType,
2925 "gc.statepoint call argument does not match wrapped "
2929 if (TargetFuncType->isVarArg()) {
2930 AttributeSet ArgAttrs =
Attrs.getParamAttrs(5 + i);
2932 "Attribute 'sret' cannot be used for vararg call arguments!",
Call);
2936 const int EndCallArgsInx = 4 + NumCallArgs;
2940 "gc.statepoint number of transition arguments "
2941 "must be constant integer",
2943 const int NumTransitionArgs =
2945 Check(NumTransitionArgs == 0,
2946 "gc.statepoint w/inline transition bundle is deprecated",
Call);
2947 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2951 "gc.statepoint number of deoptimization arguments "
2952 "must be constant integer",
2955 Check(NumDeoptArgs == 0,
2956 "gc.statepoint w/inline deopt operands is deprecated",
Call);
2958 const int ExpectedNumArgs = 7 + NumCallArgs;
2960 "gc.statepoint too many arguments",
Call);
2967 Check(UserCall,
"illegal use of statepoint token",
Call, U);
2971 "gc.result or gc.relocate are the only value uses "
2972 "of a gc.statepoint",
2976 "gc.result connected to wrong gc.statepoint",
Call, UserCall);
2979 "gc.relocate connected to wrong gc.statepoint",
Call, UserCall);
2993void Verifier::verifyFrameRecoverIndices() {
2994 for (
auto &Counts : FrameEscapeInfo) {
2996 unsigned EscapedObjectCount = Counts.second.first;
2997 unsigned MaxRecoveredIndex = Counts.second.second;
2998 Check(MaxRecoveredIndex <= EscapedObjectCount,
2999 "all indices passed to llvm.localrecover must be less than the "
3000 "number of arguments passed to llvm.localescape in the parent "
3009 UnwindDest =
II->getUnwindDest();
3011 UnwindDest = CSI->getUnwindDest();
3017void Verifier::verifySiblingFuncletUnwinds() {
3018 llvm::TimeTraceScope timeScope(
"Verifier verify sibling funclet unwinds");
3019 SmallPtrSet<Instruction *, 8> Visited;
3020 SmallPtrSet<Instruction *, 8>
Active;
3021 for (
const auto &Pair : SiblingFuncletInfo) {
3023 if (Visited.
count(PredPad))
3029 if (
Active.count(SuccPad)) {
3032 SmallVector<Instruction *, 8> CycleNodes;
3035 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
3036 if (CycleTerminator != CyclePad)
3039 }
while (CyclePad != SuccPad);
3040 Check(
false,
"EH pads can't handle each other's exceptions",
3044 if (!Visited.
insert(SuccPad).second)
3048 auto TermI = SiblingFuncletInfo.find(PredPad);
3049 if (TermI == SiblingFuncletInfo.end())
3062void Verifier::visitFunction(
const Function &
F) {
3063 visitGlobalValue(
F);
3066 FunctionType *FT =
F.getFunctionType();
3067 unsigned NumArgs =
F.arg_size();
3070 "Function context does not match Module context!", &
F);
3072 Check(!
F.hasCommonLinkage(),
"Functions may not have common linkage", &
F);
3073 Check(FT->getNumParams() == NumArgs,
3074 "# formal arguments must match # of arguments for function type!", &
F,
3076 Check(
F.getReturnType()->isFirstClassType() ||
3077 F.getReturnType()->isVoidTy() ||
F.getReturnType()->isStructTy(),
3078 "Functions cannot return aggregate values!", &
F);
3080 Check(!
F.hasStructRetAttr() ||
F.getReturnType()->isVoidTy(),
3081 "Invalid struct return type!", &
F);
3083 if (MaybeAlign
A =
F.getAlign()) {
3084 Check(
A->value() <= Value::MaximumAlignment,
3085 "huge alignment values are unsupported", &
F);
3088 AttributeList
Attrs =
F.getAttributes();
3090 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
3091 "Attribute after last parameter!", &
F);
3093 bool IsIntrinsic =
F.isIntrinsic();
3096 verifyFunctionAttrs(FT, Attrs, &
F, IsIntrinsic,
false);
3102 "Attribute 'builtin' can only be applied to a callsite.", &
F);
3104 Check(!
Attrs.hasAttrSomewhere(Attribute::ElementType),
3105 "Attribute 'elementtype' can only be applied to a callsite.", &
F);
3108 "Attribute 'aarch64_zt0_undef' can only be applied to a callsite.");
3110 if (
Attrs.hasFnAttr(Attribute::Naked))
3111 for (
const Argument &Arg :
F.args())
3112 Check(Arg.use_empty(),
"cannot use argument of naked function", &Arg);
3117 switch (
F.getCallingConv()) {
3119 case CallingConv::C:
3121 case CallingConv::X86_INTR: {
3122 Check(
F.arg_empty() ||
Attrs.hasParamAttr(0, Attribute::ByVal),
3123 "Calling convention parameter requires byval", &
F);
3126 case CallingConv::AMDGPU_KERNEL:
3127 case CallingConv::SPIR_KERNEL:
3128 case CallingConv::AMDGPU_CS_Chain:
3129 case CallingConv::AMDGPU_CS_ChainPreserve:
3130 Check(
F.getReturnType()->isVoidTy(),
3131 "Calling convention requires void return type", &
F);
3133 case CallingConv::AMDGPU_VS:
3134 case CallingConv::AMDGPU_HS:
3135 case CallingConv::AMDGPU_GS:
3136 case CallingConv::AMDGPU_PS:
3137 case CallingConv::AMDGPU_CS:
3138 Check(!
F.hasStructRetAttr(),
"Calling convention does not allow sret", &
F);
3139 if (
F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3140 const unsigned StackAS =
DL.getAllocaAddrSpace();
3142 for (
const Argument &Arg :
F.args()) {
3143 Check(!
Attrs.hasParamAttr(i, Attribute::ByVal),
3144 "Calling convention disallows byval", &
F);
3145 Check(!
Attrs.hasParamAttr(i, Attribute::Preallocated),
3146 "Calling convention disallows preallocated", &
F);
3147 Check(!
Attrs.hasParamAttr(i, Attribute::InAlloca),
3148 "Calling convention disallows inalloca", &
F);
3150 if (
Attrs.hasParamAttr(i, Attribute::ByRef)) {
3153 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
3154 "Calling convention disallows stack byref", &
F);
3162 case CallingConv::Fast:
3163 case CallingConv::Cold:
3164 case CallingConv::Intel_OCL_BI:
3165 case CallingConv::PTX_Kernel:
3166 case CallingConv::PTX_Device:
3168 "Calling convention does not support varargs or "
3169 "perfect forwarding!",
3172 case CallingConv::AMDGPU_Gfx_WholeWave:
3173 Check(!
F.arg_empty() &&
F.arg_begin()->getType()->isIntegerTy(1),
3174 "Calling convention requires first argument to be i1", &
F);
3175 Check(!
F.arg_begin()->hasInRegAttr(),
3176 "Calling convention requires first argument to not be inreg", &
F);
3178 "Calling convention does not support varargs or "
3179 "perfect forwarding!",
3186 for (
const Argument &Arg :
F.args()) {
3187 Check(Arg.getType() == FT->getParamType(i),
3188 "Argument value does not match function argument type!", &Arg,
3189 FT->getParamType(i));
3190 Check(Arg.getType()->isFirstClassType(),
3191 "Function arguments must have first-class types!", &Arg);
3193 Check(!Arg.getType()->isMetadataTy(),
3194 "Function takes metadata but isn't an intrinsic", &Arg, &
F);
3195 Check(!Arg.getType()->isTokenLikeTy(),
3196 "Function takes token but isn't an intrinsic", &Arg, &
F);
3197 Check(!Arg.getType()->isX86_AMXTy(),
3198 "Function takes x86_amx but isn't an intrinsic", &Arg, &
F);
3202 if (
Attrs.hasParamAttr(i, Attribute::SwiftError)) {
3203 verifySwiftErrorValue(&Arg);
3209 Check(!
F.getReturnType()->isTokenLikeTy(),
3210 "Function returns a token but isn't an intrinsic", &
F);
3211 Check(!
F.getReturnType()->isX86_AMXTy(),
3212 "Function returns a x86_amx but isn't an intrinsic", &
F);
3217 F.getAllMetadata(MDs);
3218 assert(
F.hasMetadata() != MDs.
empty() &&
"Bit out-of-sync");
3219 verifyFunctionMetadata(MDs);
3222 if (
F.hasPersonalityFn()) {
3225 Check(Per->getParent() ==
F.getParent(),
3226 "Referencing personality function in another module!", &
F,
3227 F.getParent(), Per, Per->getParent());
3231 BlockEHFuncletColors.
clear();
3233 if (
F.isMaterializable()) {
3235 Check(MDs.
empty(),
"unmaterialized function cannot have metadata", &
F,
3237 }
else if (
F.isDeclaration()) {
3238 for (
const auto &
I : MDs) {
3240 CheckDI(
I.first != LLVMContext::MD_dbg ||
3242 "function declaration may only have a unique !dbg attachment",
3244 Check(
I.first != LLVMContext::MD_prof,
3245 "function declaration may not have a !prof attachment", &
F);
3248 visitMDNode(*
I.second, AreDebugLocsAllowed::Yes);
3250 Check(!
F.hasPersonalityFn(),
3251 "Function declaration shouldn't have a personality routine", &
F);
3255 Check(!IsIntrinsic,
"llvm intrinsics cannot be defined!", &
F);
3260 "Entry block to function must not have predecessors!", Entry);
3263 if (
Entry->hasAddressTaken()) {
3265 "blockaddress may not be used with the entry block!", Entry);
3268 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
3269 NumKCFIAttachments = 0;
3271 for (
const auto &
I : MDs) {
3273 auto AllowLocs = AreDebugLocsAllowed::No;
3277 case LLVMContext::MD_dbg: {
3278 ++NumDebugAttachments;
3279 CheckDI(NumDebugAttachments == 1,
3280 "function must have a single !dbg attachment", &
F,
I.second);
3282 "function !dbg attachment must be a subprogram", &
F,
I.second);
3284 "function definition may only have a distinct !dbg attachment",
3288 const Function *&AttachedTo = DISubprogramAttachments[
SP];
3289 CheckDI(!AttachedTo || AttachedTo == &
F,
3290 "DISubprogram attached to more than one function", SP, &
F);
3292 AllowLocs = AreDebugLocsAllowed::Yes;
3295 case LLVMContext::MD_prof:
3296 ++NumProfAttachments;
3297 Check(NumProfAttachments == 1,
3298 "function must have a single !prof attachment", &
F,
I.second);
3300 case LLVMContext::MD_kcfi_type:
3301 ++NumKCFIAttachments;
3302 Check(NumKCFIAttachments == 1,
3303 "function must have a single !kcfi_type attachment", &
F,
3309 visitMDNode(*
I.second, AllowLocs);
3317 if (
F.isIntrinsic() &&
F.getParent()->isMaterialized()) {
3319 if (
F.hasAddressTaken(&U,
false,
true,
false,
3321 Check(
false,
"Invalid user of intrinsic instruction!", U);
3325 switch (
F.getIntrinsicID()) {
3326 case Intrinsic::experimental_gc_get_pointer_base: {
3327 FunctionType *FT =
F.getFunctionType();
3328 Check(FT->getNumParams() == 1,
"wrong number of parameters",
F);
3330 "gc.get.pointer.base must return a pointer",
F);
3331 Check(FT->getParamType(0) ==
F.getReturnType(),
3332 "gc.get.pointer.base operand and result must be of the same type",
F);
3335 case Intrinsic::experimental_gc_get_pointer_offset: {
3336 FunctionType *FT =
F.getFunctionType();
3337 Check(FT->getNumParams() == 1,
"wrong number of parameters",
F);
3339 "gc.get.pointer.offset operand must be a pointer",
F);
3340 Check(
F.getReturnType()->isIntegerTy(),
3341 "gc.get.pointer.offset must return integer",
F);
3346 auto *
N =
F.getSubprogram();
3347 HasDebugInfo = (
N !=
nullptr);
3355 SmallPtrSet<const MDNode *, 32> Seen;
3367 "DILocation's scope must be a DILocalScope",
N, &
F, &
I,
DL, Parent);
3369 DILocalScope *
Scope =
DL->getInlinedAtScope();
3370 Check(Scope,
"Failed to find DILocalScope",
DL);
3372 if (!Seen.
insert(Scope).second)
3375 DISubprogram *
SP =
Scope->getSubprogram();
3379 if ((Scope != SP) && !Seen.
insert(SP).second)
3383 "!dbg attachment points at wrong subprogram for function",
N, &
F,
3387 for (
auto &
I : BB) {
3388 VisitDebugLoc(
I,
I.getDebugLoc().getAsMDNode());
3390 if (
auto MD =
I.getMetadata(LLVMContext::MD_loop))
3393 if (BrokenDebugInfo)
3400void Verifier::visitBasicBlock(BasicBlock &BB) {
3401 InstsInThisBlock.
clear();
3402 ConvergenceVerifyHelper.
visit(BB);
3413 for (
const PHINode &PN : BB.
phis()) {
3414 Check(PN.getNumIncomingValues() == Preds.size(),
3415 "PHINode should have one entry for each predecessor of its "
3416 "parent basic block!",
3421 Values.
reserve(PN.getNumIncomingValues());
3422 for (
unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3424 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3427 for (
unsigned i = 0, e = Values.
size(); i != e; ++i) {
3432 Check(i == 0 || Values[i].first != Values[i - 1].first ||
3433 Values[i].second == Values[i - 1].second,
3434 "PHI node has multiple entries for the same basic block with "
3435 "different incoming values!",
3436 &PN, Values[i].first, Values[i].second, Values[i - 1].second);
3440 Check(Values[i].first == Preds[i],
3441 "PHI node entries do not match predecessors!", &PN,
3442 Values[i].first, Preds[i]);
3450 Check(
I.getParent() == &BB,
"Instruction has bogus parent pointer!");
3454 CheckDI(!BB.getTrailingDbgRecords(),
"Basic Block has trailing DbgRecords!",
3458void Verifier::visitTerminator(Instruction &
I) {
3460 Check(&
I ==
I.getParent()->getTerminator(),
3461 "Terminator found in the middle of a basic block!",
I.getParent());
3462 visitInstruction(
I);
3465void Verifier::visitCondBrInst(CondBrInst &BI) {
3467 "Branch condition is not 'i1' type!", &BI, BI.
getCondition());
3468 visitTerminator(BI);
3471void Verifier::visitReturnInst(ReturnInst &RI) {
3474 if (
F->getReturnType()->isVoidTy())
3476 "Found return instr that returns non-void in Function of void "
3478 &RI,
F->getReturnType());
3481 "Function return type does not match operand "
3482 "type of return inst!",
3483 &RI,
F->getReturnType());
3487 visitTerminator(RI);
3490void Verifier::visitSwitchInst(SwitchInst &SI) {
3491 Check(
SI.getType()->isVoidTy(),
"Switch must have void result type!", &SI);
3494 Type *SwitchTy =
SI.getCondition()->getType();
3495 SmallPtrSet<ConstantInt*, 32>
Constants;
3496 for (
auto &Case :
SI.cases()) {
3498 "Case value is not a constant integer.", &SI);
3499 Check(Case.getCaseValue()->getType() == SwitchTy,
3500 "Switch constants must all be same type as switch value!", &SI);
3502 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3505 visitTerminator(SI);
3508void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
3510 "Indirectbr operand must have pointer type!", &BI);
3513 "Indirectbr destinations must all have pointer type!", &BI);
3515 visitTerminator(BI);
3518void Verifier::visitCallBrInst(CallBrInst &CBI) {
3521 "Callbr: indirect function / invalid signature");
3523 "Callbr for intrinsics currently doesn't support operand bundles");
3526 case Intrinsic::amdgcn_kill: {
3528 "Callbr amdgcn_kill only supports one indirect dest");
3532 Intrinsic::amdgcn_unreachable),
3533 "Callbr amdgcn_kill indirect dest needs to be unreachable");
3538 "Callbr currently only supports asm-goto and selected intrinsics");
3543 Check(!
IA->canThrow(),
"Unwinding from Callbr is not allowed");
3545 verifyInlineAsmCall(CBI);
3547 visitTerminator(CBI);
3550void Verifier::visitSelectInst(SelectInst &SI) {
3553 "Invalid operands for select instruction!", &SI);
3555 Check(
SI.getTrueValue()->getType() ==
SI.getType(),
3556 "Select values must have same type as select instruction!", &SI);
3557 visitInstruction(SI);
3563void Verifier::visitUserOp1(Instruction &
I) {
3564 Check(
false,
"User-defined operators should not live outside of a pass!", &
I);
3567void Verifier::visitTruncInst(TruncInst &
I) {
3569 Type *SrcTy =
I.getOperand(0)->getType();
3570 Type *DestTy =
I.getType();
3579 "trunc source and destination must both be a vector or neither", &
I);
3580 Check(SrcBitSize > DestBitSize,
"DestTy too big for Trunc", &
I);
3582 visitInstruction(
I);
3585void Verifier::visitZExtInst(ZExtInst &
I) {
3587 Type *SrcTy =
I.getOperand(0)->getType();
3588 Type *DestTy =
I.getType();
3594 "zext source and destination must both be a vector or neither", &
I);
3598 Check(SrcBitSize < DestBitSize,
"Type too small for ZExt", &
I);
3600 visitInstruction(
I);
3603void Verifier::visitSExtInst(SExtInst &
I) {
3605 Type *SrcTy =
I.getOperand(0)->getType();
3606 Type *DestTy =
I.getType();
3615 "sext source and destination must both be a vector or neither", &
I);
3616 Check(SrcBitSize < DestBitSize,
"Type too small for SExt", &
I);
3618 visitInstruction(
I);
3621void Verifier::visitFPTruncInst(FPTruncInst &
I) {
3623 Type *SrcTy =
I.getOperand(0)->getType();
3624 Type *DestTy =
I.getType();
3632 "fptrunc source and destination must both be a vector or neither", &
I);
3633 Check(SrcBitSize > DestBitSize,
"DestTy too big for FPTrunc", &
I);
3635 visitInstruction(
I);
3638void Verifier::visitFPExtInst(FPExtInst &
I) {
3640 Type *SrcTy =
I.getOperand(0)->getType();
3641 Type *DestTy =
I.getType();
3650 "fpext source and destination must both be a vector or neither", &
I);
3651 Check(SrcBitSize < DestBitSize,
"DestTy too small for FPExt", &
I);
3653 visitInstruction(
I);
3656void Verifier::visitUIToFPInst(UIToFPInst &
I) {
3658 Type *SrcTy =
I.getOperand(0)->getType();
3659 Type *DestTy =
I.getType();
3664 Check(SrcVec == DstVec,
3665 "UIToFP source and dest must both be vector or scalar", &
I);
3667 "UIToFP source must be integer or integer vector", &
I);
3671 if (SrcVec && DstVec)
3674 "UIToFP source and dest vector length mismatch", &
I);
3676 visitInstruction(
I);
3679void Verifier::visitSIToFPInst(SIToFPInst &
I) {
3681 Type *SrcTy =
I.getOperand(0)->getType();
3682 Type *DestTy =
I.getType();
3687 Check(SrcVec == DstVec,
3688 "SIToFP source and dest must both be vector or scalar", &
I);
3690 "SIToFP source must be integer or integer vector", &
I);
3694 if (SrcVec && DstVec)
3697 "SIToFP source and dest vector length mismatch", &
I);
3699 visitInstruction(
I);
3702void Verifier::visitFPToUIInst(FPToUIInst &
I) {
3704 Type *SrcTy =
I.getOperand(0)->getType();
3705 Type *DestTy =
I.getType();
3710 Check(SrcVec == DstVec,
3711 "FPToUI source and dest must both be vector or scalar", &
I);
3714 "FPToUI result must be integer or integer vector", &
I);
3716 if (SrcVec && DstVec)
3719 "FPToUI source and dest vector length mismatch", &
I);
3721 visitInstruction(
I);
3724void Verifier::visitFPToSIInst(FPToSIInst &
I) {
3726 Type *SrcTy =
I.getOperand(0)->getType();
3727 Type *DestTy =
I.getType();
3732 Check(SrcVec == DstVec,
3733 "FPToSI source and dest must both be vector or scalar", &
I);
3736 "FPToSI result must be integer or integer vector", &
I);
3738 if (SrcVec && DstVec)
3741 "FPToSI source and dest vector length mismatch", &
I);
3743 visitInstruction(
I);
3746void Verifier::checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V) {
3755 Check(VSrc->getElementCount() == VDest->getElementCount(),
3756 "PtrToAddr vector length mismatch", V);
3759 Type *AddrTy =
DL.getAddressType(SrcTy);
3760 Check(AddrTy == DestTy,
"PtrToAddr result must be address width", V);
3763void Verifier::visitPtrToAddrInst(PtrToAddrInst &
I) {
3764 checkPtrToAddr(
I.getOperand(0)->getType(),
I.getType(),
I);
3765 visitInstruction(
I);
3768void Verifier::visitPtrToIntInst(PtrToIntInst &
I) {
3770 Type *SrcTy =
I.getOperand(0)->getType();
3771 Type *DestTy =
I.getType();
3782 Check(VSrc->getElementCount() == VDest->getElementCount(),
3783 "PtrToInt Vector length mismatch", &
I);
3786 visitInstruction(
I);
3789void Verifier::visitIntToPtrInst(IntToPtrInst &
I) {
3791 Type *SrcTy =
I.getOperand(0)->getType();
3792 Type *DestTy =
I.getType();
3802 Check(VSrc->getElementCount() == VDest->getElementCount(),
3803 "IntToPtr Vector length mismatch", &
I);
3805 visitInstruction(
I);
3808void Verifier::visitBitCastInst(BitCastInst &
I) {
3811 "Invalid bitcast", &
I);
3812 visitInstruction(
I);
3815void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &
I) {
3816 Type *SrcTy =
I.getOperand(0)->getType();
3817 Type *DestTy =
I.getType();
3824 "AddrSpaceCast must be between different address spaces", &
I);
3826 Check(SrcVTy->getElementCount() ==
3828 "AddrSpaceCast vector pointer number of elements mismatch", &
I);
3829 visitInstruction(
I);
3834void Verifier::visitPHINode(PHINode &PN) {
3841 "PHI nodes not grouped at top of basic block!", &PN, PN.
getParent());
3850 "PHI node operands are not the same type as the result!", &PN);
3855 visitInstruction(PN);
3858void Verifier::visitCallBase(CallBase &
Call) {
3860 "Called function must be a pointer!",
Call);
3864 if (FTy->isVarArg())
3866 "Called function requires more parameters than were provided!",
Call);
3869 "Incorrect number of arguments passed to called function!",
Call);
3872 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3874 "Call parameter type does not match function signature!",
3880 "Attribute after last parameter!",
Call);
3887 "Intrinsic called with incompatible signature",
Call);
3891 "calling convention does not permit calls",
Call);
3897 auto VerifyTypeAlign = [&](
Type *Ty,
const Twine &Message) {
3900 Align ABIAlign =
DL.getABITypeAlign(Ty);
3901 Check(ABIAlign.
value() <= Value::MaximumAlignment,
3902 "Incorrect alignment of " + Message +
" to called function!",
Call);
3906 VerifyTypeAlign(FTy->getReturnType(),
"return type");
3907 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3908 Type *Ty = FTy->getParamType(i);
3909 VerifyTypeAlign(Ty,
"argument passed");
3913 if (
Attrs.hasFnAttr(Attribute::Speculatable)) {
3917 "speculatable attribute may not apply to call sites",
Call);
3920 if (
Attrs.hasFnAttr(Attribute::Preallocated)) {
3922 "preallocated as a call site attribute can only be on "
3923 "llvm.call.preallocated.arg");
3926 Check(!
Attrs.hasFnAttr(Attribute::DenormalFPEnv),
3927 "denormal_fpenv attribute may not apply to call sites",
Call);
3938 Check(AI->isUsedWithInAlloca(),
3939 "inalloca argument for call has mismatched alloca", AI,
Call);
3945 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3949 Check(AI->isSwiftError(),
3950 "swifterror argument for call has mismatched alloca", AI,
Call);
3954 Check(ArgI,
"swifterror argument should come from an alloca or parameter",
3955 SwiftErrorArg,
Call);
3956 Check(ArgI->hasSwiftErrorAttr(),
3957 "swifterror argument for call has mismatched parameter", ArgI,
3961 if (
Attrs.hasParamAttr(i, Attribute::ImmArg)) {
3964 Check(Callee &&
Callee->hasParamAttribute(i, Attribute::ImmArg),
3972 "immarg operand has non-immediate parameter", ArgVal,
Call);
3978 const ConstantRange &CR =
3981 "immarg value " + Twine(CI->getValue().getSExtValue()) +
3994 Check(hasOB != isMustTail,
3995 "preallocated operand either requires a preallocated bundle or "
3996 "the call to be musttail (but not both)",
4001 if (FTy->isVarArg()) {
4003 bool SawNest =
false;
4004 bool SawReturned =
false;
4006 for (
unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
4007 if (
Attrs.hasParamAttr(Idx, Attribute::Nest))
4009 if (
Attrs.hasParamAttr(Idx, Attribute::Returned))
4014 for (
unsigned Idx = FTy->getNumParams(); Idx <
Call.
arg_size(); ++Idx) {
4016 AttributeSet ArgAttrs =
Attrs.getParamAttrs(Idx);
4017 verifyParameterAttrs(ArgAttrs, Ty, &
Call);
4020 Check(!SawNest,
"More than one parameter has attribute nest!",
Call);
4025 Check(!SawReturned,
"More than one parameter has attribute returned!",
4028 "Incompatible argument and return types for 'returned' "
4038 "Attribute 'sret' cannot be used for vararg call arguments!",
4043 "inalloca isn't on the last argument!",
Call);
4049 for (
Type *ParamTy : FTy->params()) {
4050 Check(!ParamTy->isMetadataTy(),
4051 "Function has metadata parameter but isn't an intrinsic",
Call);
4052 Check(!ParamTy->isTokenLikeTy(),
4053 "Function has token parameter but isn't an intrinsic",
Call);
4059 Check(!FTy->getReturnType()->isTokenLikeTy(),
4060 "Return type cannot be token for indirect call!");
4061 Check(!FTy->getReturnType()->isX86_AMXTy(),
4062 "Return type cannot be x86_amx for indirect call!");
4066 visitIntrinsicCall(
ID,
Call);
4071 bool FoundDeoptBundle =
false, FoundFuncletBundle =
false,
4072 FoundGCTransitionBundle =
false, FoundCFGuardTargetBundle =
false,
4073 FoundPreallocatedBundle =
false, FoundGCLiveBundle =
false,
4074 FoundPtrauthBundle =
false, FoundKCFIBundle =
false,
4075 FoundAttachedCallBundle =
false;
4080 Check(!FoundDeoptBundle,
"Multiple deopt operand bundles",
Call);
4081 FoundDeoptBundle =
true;
4083 Check(!FoundGCTransitionBundle,
"Multiple gc-transition operand bundles",
4085 FoundGCTransitionBundle =
true;
4087 Check(!FoundFuncletBundle,
"Multiple funclet operand bundles",
Call);
4088 FoundFuncletBundle =
true;
4090 "Expected exactly one funclet bundle operand",
Call);
4092 "Funclet bundle operands should correspond to a FuncletPadInst",
4095 Check(!FoundCFGuardTargetBundle,
"Multiple CFGuardTarget operand bundles",
4097 FoundCFGuardTargetBundle =
true;
4099 "Expected exactly one cfguardtarget bundle operand",
Call);
4101 Check(!FoundPtrauthBundle,
"Multiple ptrauth operand bundles",
Call);
4102 FoundPtrauthBundle =
true;
4104 "Expected exactly two ptrauth bundle operands",
Call);
4106 BU.
Inputs[0]->getType()->isIntegerTy(32),
4107 "Ptrauth bundle key operand must be an i32 constant",
Call);
4109 "Ptrauth bundle discriminator operand must be an i64",
Call);
4111 Check(!FoundKCFIBundle,
"Multiple kcfi operand bundles",
Call);
4112 FoundKCFIBundle =
true;
4113 Check(BU.
Inputs.size() == 1,
"Expected exactly one kcfi bundle operand",
4116 BU.
Inputs[0]->getType()->isIntegerTy(32),
4117 "Kcfi bundle operand must be an i32 constant",
Call);
4119 Check(!FoundPreallocatedBundle,
"Multiple preallocated operand bundles",
4121 FoundPreallocatedBundle =
true;
4123 "Expected exactly one preallocated bundle operand",
Call);
4126 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
4127 "\"preallocated\" argument must be a token from "
4128 "llvm.call.preallocated.setup",
4131 Check(!FoundGCLiveBundle,
"Multiple gc-live operand bundles",
Call);
4132 FoundGCLiveBundle =
true;
4134 Check(!FoundAttachedCallBundle,
4135 "Multiple \"clang.arc.attachedcall\" operand bundles",
Call);
4136 FoundAttachedCallBundle =
true;
4137 verifyAttachedCallBundle(
Call, BU);
4143 "Direct call cannot have a ptrauth bundle",
Call);
4155 "inlinable function call in a function with "
4156 "debug info must have a !dbg location",
4160 verifyInlineAsmCall(
Call);
4164 visitInstruction(
Call);
4167void Verifier::verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs,
4170 Twine(
"inalloca attribute not allowed in ") +
Context);
4172 Twine(
"inreg attribute not allowed in ") +
Context);
4173 Check(!
Attrs.contains(Attribute::SwiftError),
4174 Twine(
"swifterror attribute not allowed in ") +
Context);
4175 Check(!
Attrs.contains(Attribute::Preallocated),
4176 Twine(
"preallocated attribute not allowed in ") +
Context);
4178 Twine(
"byref attribute not allowed in ") +
Context);
4190 return PL->getAddressSpace() == PR->getAddressSpace();
4195 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
4196 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
4197 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
4199 AttrBuilder Copy(
C);
4200 for (
auto AK : ABIAttrs) {
4201 Attribute Attr = Attrs.getParamAttrs(
I).getAttribute(AK);
4203 Copy.addAttribute(Attr);
4207 if (Attrs.hasParamAttr(
I, Attribute::Alignment) &&
4208 (Attrs.hasParamAttr(
I, Attribute::ByVal) ||
4209 Attrs.hasParamAttr(
I, Attribute::ByRef)))
4210 Copy.addAlignmentAttr(Attrs.getParamAlignment(
I));
4214void Verifier::verifyMustTailCall(CallInst &CI) {
4218 FunctionType *CallerTy =
F->getFunctionType();
4220 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
4221 "cannot guarantee tail call due to mismatched varargs", &CI);
4223 "cannot guarantee tail call due to mismatched return types", &CI);
4227 "cannot guarantee tail call due to mismatched calling conv", &CI);
4233 Value *RetVal = &CI;
4239 "bitcast following musttail call must use the call", BI);
4246 Check(Ret,
"musttail call must precede a ret with an optional bitcast", &CI);
4249 "musttail call result must be returned", Ret);
4251 AttributeList CallerAttrs =
F->getAttributes();
4256 CI.
getCallingConv() == CallingConv::Tail ?
"tailcc" :
"swifttailcc";
4260 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4262 SmallString<32>
Context{CCName, StringRef(
" musttail caller")};
4263 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4265 for (
unsigned I = 0,
E = CalleeTy->getNumParams();
I !=
E; ++
I) {
4267 SmallString<32>
Context{CCName, StringRef(
" musttail callee")};
4268 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4271 Check(!CallerTy->isVarArg(), Twine(
"cannot guarantee ") + CCName +
4272 " tail call for varargs function");
4280 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
4281 "cannot guarantee tail call due to mismatched parameter counts", &CI);
4282 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4285 "cannot guarantee tail call due to mismatched parameter types", &CI);
4291 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4294 Check(CallerABIAttrs == CalleeABIAttrs,
4295 "cannot guarantee tail call due to mismatched ABI impacting "
4296 "function attributes",
4301void Verifier::visitCallInst(CallInst &CI) {
4305 verifyMustTailCall(CI);
4308void Verifier::visitInvokeInst(InvokeInst &
II) {
4314 II.getUnwindDest()->isEHPad(),
4315 "The unwind destination does not have an exception handling instruction!",
4318 visitTerminator(
II);
4323void Verifier::visitUnaryOperator(UnaryOperator &U) {
4324 Check(
U.getType() ==
U.getOperand(0)->getType(),
4325 "Unary operators must have same type for"
4326 "operands and result!",
4329 switch (
U.getOpcode()) {
4332 case Instruction::FNeg:
4333 Check(
U.getType()->isFPOrFPVectorTy(),
4334 "FNeg operator only works with float types!", &U);
4340 visitInstruction(U);
4346void Verifier::visitBinaryOperator(BinaryOperator &
B) {
4347 Check(
B.getOperand(0)->getType() ==
B.getOperand(1)->getType(),
4348 "Both operands to a binary operator are not of the same type!", &
B);
4350 switch (
B.getOpcode()) {
4353 case Instruction::Add:
4354 case Instruction::Sub:
4355 case Instruction::Mul:
4356 case Instruction::SDiv:
4357 case Instruction::UDiv:
4358 case Instruction::SRem:
4359 case Instruction::URem:
4360 Check(
B.getType()->isIntOrIntVectorTy(),
4361 "Integer arithmetic operators only work with integral types!", &
B);
4362 Check(
B.getType() ==
B.getOperand(0)->getType(),
4363 "Integer arithmetic operators must have same type "
4364 "for operands and result!",
4369 case Instruction::FAdd:
4370 case Instruction::FSub:
4371 case Instruction::FMul:
4372 case Instruction::FDiv:
4373 case Instruction::FRem:
4374 Check(
B.getType()->isFPOrFPVectorTy(),
4375 "Floating-point arithmetic operators only work with "
4376 "floating-point types!",
4378 Check(
B.getType() ==
B.getOperand(0)->getType(),
4379 "Floating-point arithmetic operators must have same type "
4380 "for operands and result!",
4384 case Instruction::And:
4385 case Instruction::Or:
4386 case Instruction::Xor:
4387 Check(
B.getType()->isIntOrIntVectorTy(),
4388 "Logical operators only work with integral types!", &
B);
4389 Check(
B.getType() ==
B.getOperand(0)->getType(),
4390 "Logical operators must have same type for operands and result!", &
B);
4392 case Instruction::Shl:
4393 case Instruction::LShr:
4394 case Instruction::AShr:
4395 Check(
B.getType()->isIntOrIntVectorTy(),
4396 "Shifts only work with integral types!", &
B);
4397 Check(
B.getType() ==
B.getOperand(0)->getType(),
4398 "Shift return type must be same as operands!", &
B);
4404 visitInstruction(
B);
4407void Verifier::visitICmpInst(ICmpInst &IC) {
4411 Check(Op0Ty == Op1Ty,
4412 "Both operands to ICmp instruction are not of the same type!", &IC);
4415 "Invalid operand types for ICmp instruction", &IC);
4419 visitInstruction(IC);
4422void Verifier::visitFCmpInst(FCmpInst &FC) {
4424 Type *Op0Ty =
FC.getOperand(0)->getType();
4425 Type *Op1Ty =
FC.getOperand(1)->getType();
4426 Check(Op0Ty == Op1Ty,
4427 "Both operands to FCmp instruction are not of the same type!", &FC);
4432 Check(
FC.isFPPredicate(),
"Invalid predicate in FCmp instruction!", &FC);
4434 visitInstruction(FC);
4437void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
4439 "Invalid extractelement operands!", &EI);
4440 visitInstruction(EI);
4443void Verifier::visitInsertElementInst(InsertElementInst &IE) {
4446 "Invalid insertelement operands!", &IE);
4447 visitInstruction(IE);
4450void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
4453 "Invalid shufflevector operands!", &SV);
4454 visitInstruction(SV);
4457void Verifier::visitGetElementPtrInst(GetElementPtrInst &
GEP) {
4458 Type *TargetTy =
GEP.getPointerOperandType()->getScalarType();
4461 "GEP base pointer is not a vector or a vector of pointers", &
GEP);
4462 Check(
GEP.getSourceElementType()->isSized(),
"GEP into unsized type!", &
GEP);
4466 "getelementptr cannot target structure that contains scalable vector"
4471 SmallVector<Value *, 16> Idxs(
GEP.indices());
4473 all_of(Idxs, [](
Value *V) {
return V->getType()->isIntOrIntVectorTy(); }),
4474 "GEP indexes must be integers", &
GEP);
4477 Check(ElTy,
"Invalid indices for GEP pointer type!", &
GEP);
4481 Check(PtrTy &&
GEP.getResultElementType() == ElTy,
4482 "GEP is not of right type for indices!", &
GEP, ElTy);
4486 ElementCount GEPWidth = GEPVTy->getElementCount();
4487 if (
GEP.getPointerOperandType()->isVectorTy())
4491 "Vector GEP result width doesn't match operand's", &
GEP);
4492 for (
Value *Idx : Idxs) {
4493 Type *IndexTy = Idx->getType();
4495 ElementCount IndexWidth = IndexVTy->getElementCount();
4496 Check(IndexWidth == GEPWidth,
"Invalid GEP index vector width", &
GEP);
4499 "All GEP indices should be of integer type");
4506 GTI != GTE; ++GTI) {
4507 if (GTI.isVector()) {
4508 Type *ElemTy = GTI.getIndexedType();
4509 Check(
DL.typeSizeEqualsStoreSize(ElemTy),
4510 "GEP into vector with non-byte-addressable element type", &
GEP);
4514 Check(
GEP.getAddressSpace() == PtrTy->getAddressSpace(),
4515 "GEP address space doesn't match type", &
GEP);
4517 visitInstruction(
GEP);
4521 return A.getUpper() ==
B.getLower() ||
A.getLower() ==
B.getUpper();
4526void Verifier::verifyRangeLikeMetadata(
const Value &
I,
const MDNode *
Range,
4527 Type *Ty, RangeLikeMetadataKind Kind) {
4528 unsigned NumOperands =
Range->getNumOperands();
4529 Check(NumOperands % 2 == 0,
"Unfinished range!",
Range);
4530 unsigned NumRanges = NumOperands / 2;
4531 Check(NumRanges >= 1,
"It should have at least one range!",
Range);
4533 ConstantRange LastRange(1,
true);
4534 for (
unsigned i = 0; i < NumRanges; ++i) {
4537 Check(
Low,
"The lower limit must be an integer!",
Low);
4542 Check(
High->getType() ==
Low->getType(),
"Range pair types must match!",
4545 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4547 "noalias.addrspace type must be i32!", &
I);
4550 "Range types must match instruction type!", &
I);
4553 APInt HighV =
High->getValue();
4554 APInt LowV =
Low->getValue();
4559 "The upper and lower limits cannot be the same value", &
I);
4561 ConstantRange CurRange(LowV, HighV);
4562 Check(!CurRange.isEmptySet() &&
4563 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
4564 !CurRange.isFullSet()),
4565 "Range must not be empty!",
Range);
4567 Check(CurRange.intersectWith(LastRange).isEmptySet(),
4568 "Intervals are overlapping",
Range);
4569 Check(LowV.
sgt(LastRange.getLower()),
"Intervals are not in order",
4574 LastRange = ConstantRange(LowV, HighV);
4576 if (NumRanges > 2) {
4581 ConstantRange FirstRange(FirstLow, FirstHigh);
4582 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
4583 "Intervals are overlapping",
Range);
4589void Verifier::visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty) {
4591 "precondition violation");
4592 verifyRangeLikeMetadata(
I,
Range, Ty, RangeLikeMetadataKind::Range);
4595void Verifier::visitNoFPClassMetadata(Instruction &
I, MDNode *NoFPClass,
4597 Check(AttributeFuncs::isNoFPClassCompatibleType(Ty),
4598 "nofpclass only applies to floating-point typed loads",
I);
4601 "nofpclass must have exactly one entry", NoFPClass);
4602 ConstantInt *MaskVal =
4605 "nofpclass entry must be a constant i32", NoFPClass);
4607 Check(Val != 0,
"'nofpclass' must have at least one test bit set", NoFPClass,
4611 "Invalid value for 'nofpclass' test mask", NoFPClass,
I);
4614void Verifier::visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
4617 "precondition violation");
4618 verifyRangeLikeMetadata(
I,
Range, Ty,
4619 RangeLikeMetadataKind::NoaliasAddrspace);
4622void Verifier::checkAtomicMemAccessSize(
Type *Ty,
const Instruction *
I) {
4623 unsigned Size =
DL.getTypeSizeInBits(Ty).getFixedValue();
4624 Check(
Size >= 8,
"atomic memory access' size must be byte-sized", Ty,
I);
4626 "atomic memory access' operand must have a power-of-two size", Ty,
I);
4629void Verifier::visitLoadInst(LoadInst &LI) {
4631 Check(PTy,
"Load operand must be a pointer.", &LI);
4634 Check(
A->value() <= Value::MaximumAlignment,
4635 "huge alignment values are unsupported", &LI);
4637 Check(ElTy->
isSized(),
"loading unsized types is not allowed", &LI);
4640 LI.
getOrdering() != AtomicOrdering::AcquireRelease,
4641 "Load cannot have Release ordering", &LI);
4645 "atomic load operand must have integer, byte, pointer, floating "
4646 "point, or vector type!",
4649 checkAtomicMemAccessSize(ElTy, &LI);
4652 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4655 visitInstruction(LI);
4658void Verifier::visitStoreInst(StoreInst &SI) {
4660 Check(PTy,
"Store operand must be a pointer.", &SI);
4661 Type *ElTy =
SI.getOperand(0)->getType();
4662 if (MaybeAlign
A =
SI.getAlign()) {
4663 Check(
A->value() <= Value::MaximumAlignment,
4664 "huge alignment values are unsupported", &SI);
4666 Check(ElTy->
isSized(),
"storing unsized types is not allowed", &SI);
4667 if (
SI.isAtomic()) {
4668 Check(
SI.getOrdering() != AtomicOrdering::Acquire &&
4669 SI.getOrdering() != AtomicOrdering::AcquireRelease,
4670 "Store cannot have Acquire ordering", &SI);
4674 "atomic store operand must have integer, byte, pointer, floating "
4675 "point, or vector type!",
4677 checkAtomicMemAccessSize(ElTy, &SI);
4680 "Non-atomic store cannot have SynchronizationScope specified", &SI);
4682 visitInstruction(SI);
4686void Verifier::verifySwiftErrorCall(CallBase &
Call,
4687 const Value *SwiftErrorVal) {
4689 if (
I.value() == SwiftErrorVal) {
4691 "swifterror value when used in a callsite should be marked "
4692 "with swifterror attribute",
4693 SwiftErrorVal,
Call);
4698void Verifier::verifySwiftErrorValue(
const Value *SwiftErrorVal) {
4701 for (
const User *U : SwiftErrorVal->
users()) {
4704 "swifterror value can only be loaded and stored from, or "
4705 "as a swifterror argument!",
4709 Check(StoreI->getOperand(1) == SwiftErrorVal,
4710 "swifterror value should be the second operand when used "
4714 verifySwiftErrorCall(*
const_cast<CallBase *
>(
Call), SwiftErrorVal);
4718void Verifier::visitAllocaInst(AllocaInst &AI) {
4720 SmallPtrSet<Type*, 4> Visited;
4721 Check(Ty->
isSized(&Visited),
"Cannot allocate unsized type", &AI);
4725 "Alloca has illegal target extension type", &AI);
4727 "Alloca array size must have integer type", &AI);
4729 Check(
A->value() <= Value::MaximumAlignment,
4730 "huge alignment values are unsupported", &AI);
4736 "swifterror alloca must not be array allocation", &AI);
4737 verifySwiftErrorValue(&AI);
4740 if (
TT.isAMDGPU()) {
4742 "alloca on amdgpu must be in addrspace(5)", &AI);
4745 visitInstruction(AI);
4748void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4751 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4752 checkAtomicMemAccessSize(ElTy, &CXI);
4753 visitInstruction(CXI);
4756void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
4758 "atomicrmw instructions cannot be unordered.", &RMWI);
4765 " operand must have integer or floating point type!",
4770 " operand must have floating-point or fixed vector of floating-point "
4776 " operand must have integer type!",
4779 checkAtomicMemAccessSize(ElTy, &RMWI);
4781 "Invalid binary operation!", &RMWI);
4782 visitInstruction(RMWI);
4785void Verifier::visitFenceInst(FenceInst &FI) {
4787 Check(Ordering == AtomicOrdering::Acquire ||
4788 Ordering == AtomicOrdering::Release ||
4789 Ordering == AtomicOrdering::AcquireRelease ||
4790 Ordering == AtomicOrdering::SequentiallyConsistent,
4791 "fence instructions may only have acquire, release, acq_rel, or "
4792 "seq_cst ordering.",
4794 visitInstruction(FI);
4797void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
4800 "Invalid ExtractValueInst operands!", &EVI);
4802 visitInstruction(EVI);
4805void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
4809 "Invalid InsertValueInst operands!", &IVI);
4811 visitInstruction(IVI);
4816 return FPI->getParentPad();
4821void Verifier::visitEHPadPredecessors(Instruction &
I) {
4827 Check(BB != &
F->getEntryBlock(),
"EH pad cannot be in entry block.", &
I);
4835 Check(
II &&
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4836 "Block containing LandingPadInst must be jumped to "
4837 "only by the unwind edge of an invoke.",
4845 "Block containg CatchPadInst must be jumped to "
4846 "only by its catchswitch.",
4848 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4849 "Catchswitch cannot unwind to one of its catchpads",
4850 CPI->getCatchSwitch(), CPI);
4862 Check(
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4863 "EH pad must be jumped to via an unwind edge", ToPad,
II);
4866 if (CalledFn && CalledFn->isIntrinsic() &&
II->doesNotThrow() &&
4870 FromPad = Bundle->Inputs[0];
4874 FromPad = CRI->getOperand(0);
4875 Check(FromPad != ToPadParent,
"A cleanupret must exit its cleanup", CRI);
4879 Check(
false,
"EH pad must be jumped to via an unwind edge", ToPad, TI);
4883 SmallPtrSet<Value *, 8> Seen;
4885 Check(FromPad != ToPad,
4886 "EH pad cannot handle exceptions raised within it", FromPad, TI);
4887 if (FromPad == ToPadParent) {
4892 "A single unwind edge may only enter one EH pad", TI);
4893 Check(Seen.
insert(FromPad).second,
"EH pad jumps through a cycle of pads",
4899 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
4904void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
4908 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
4910 visitEHPadPredecessors(LPI);
4912 if (!LandingPadResultTy)
4913 LandingPadResultTy = LPI.
getType();
4916 "The landingpad instruction should have a consistent result type "
4917 "inside a function.",
4921 Check(
F->hasPersonalityFn(),
4922 "LandingPadInst needs to be in a function with a personality.", &LPI);
4927 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
4933 "Catch operand does not have pointer type!", &LPI);
4935 Check(LPI.
isFilter(i),
"Clause is neither catch nor filter!", &LPI);
4937 "Filter operand is not an array of constants!", &LPI);
4941 visitInstruction(LPI);
4944void Verifier::visitResumeInst(ResumeInst &RI) {
4946 "ResumeInst needs to be in a function with a personality.", &RI);
4948 if (!LandingPadResultTy)
4952 "The resume instruction should have a consistent result type "
4953 "inside a function.",
4956 visitTerminator(RI);
4959void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
4963 Check(
F->hasPersonalityFn(),
4964 "CatchPadInst needs to be in a function with a personality.", &CPI);
4967 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4973 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
4975 visitEHPadPredecessors(CPI);
4976 visitFuncletPadInst(CPI);
4979void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
4981 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
4984 visitTerminator(CatchReturn);
4987void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
4991 Check(
F->hasPersonalityFn(),
4992 "CleanupPadInst needs to be in a function with a personality.", &CPI);
4997 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
5001 "CleanupPadInst has an invalid parent.", &CPI);
5003 visitEHPadPredecessors(CPI);
5004 visitFuncletPadInst(CPI);
5007void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
5008 User *FirstUser =
nullptr;
5009 Value *FirstUnwindPad =
nullptr;
5011 SmallPtrSet<FuncletPadInst *, 8> Seen;
5013 while (!Worklist.empty()) {
5014 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
5016 "FuncletPadInst must not be nested within itself", CurrentPad);
5017 Value *UnresolvedAncestorPad =
nullptr;
5018 for (User *U : CurrentPad->
users()) {
5021 UnwindDest = CRI->getUnwindDest();
5027 if (CSI->unwindsToCaller())
5029 UnwindDest = CSI->getUnwindDest();
5031 UnwindDest =
II->getUnwindDest();
5041 Worklist.push_back(CPI);
5056 if (UnwindParent == CurrentPad)
5062 Value *ExitedPad = CurrentPad;
5065 if (ExitedPad == &FPI) {
5070 UnresolvedAncestorPad = &FPI;
5074 if (ExitedParent == UnwindParent) {
5078 UnresolvedAncestorPad = ExitedParent;
5081 ExitedPad = ExitedParent;
5087 UnresolvedAncestorPad = &FPI;
5094 Check(UnwindPad == FirstUnwindPad,
5095 "Unwind edges out of a funclet "
5096 "pad must have the same unwind "
5098 &FPI, U, FirstUser);
5101 FirstUnwindPad = UnwindPad;
5110 if (CurrentPad != &FPI)
5113 if (UnresolvedAncestorPad) {
5114 if (CurrentPad == UnresolvedAncestorPad) {
5118 assert(CurrentPad == &FPI);
5126 Value *ResolvedPad = CurrentPad;
5127 while (!Worklist.empty()) {
5128 Value *UnclePad = Worklist.back();
5132 while (ResolvedPad != AncestorPad) {
5134 if (ResolvedParent == UnresolvedAncestorPad) {
5137 ResolvedPad = ResolvedParent;
5141 if (ResolvedPad != AncestorPad)
5144 Worklist.pop_back();
5149 if (FirstUnwindPad) {
5151 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
5152 Value *SwitchUnwindPad;
5153 if (SwitchUnwindDest)
5157 Check(SwitchUnwindPad == FirstUnwindPad,
5158 "Unwind edges out of a catch must have the same unwind dest as "
5159 "the parent catchswitch",
5160 &FPI, FirstUser, CatchSwitch);
5164 visitInstruction(FPI);
5167void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
5171 Check(
F->hasPersonalityFn(),
5172 "CatchSwitchInst needs to be in a function with a personality.",
5178 "CatchSwitchInst not the first non-PHI instruction in the block.",
5183 "CatchSwitchInst has an invalid parent.", ParentPad);
5188 "CatchSwitchInst must unwind to an EH block which is not a "
5194 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
5198 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
5200 for (BasicBlock *Handler : CatchSwitch.
handlers()) {
5202 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
5205 visitEHPadPredecessors(CatchSwitch);
5206 visitTerminator(CatchSwitch);
5209void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
5211 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
5217 "CleanupReturnInst must unwind to an EH block which is not a "
5222 visitTerminator(CRI);
5225void Verifier::verifyDominatesUse(Instruction &
I,
unsigned i) {
5231 if (
II->getNormalDest() ==
II->getUnwindDest())
5245 const Use &
U =
I.getOperandUse(i);
5246 Check(DT.dominates(
Op, U),
"Instruction does not dominate all uses!",
Op, &
I);
5249void Verifier::visitDereferenceableMetadata(Instruction&
I, MDNode* MD) {
5250 Check(
I.getType()->isPointerTy(),
5251 "dereferenceable, dereferenceable_or_null "
5252 "apply only to pointer types",
5255 "dereferenceable, dereferenceable_or_null apply only to load"
5256 " and inttoptr instructions, use attributes for calls or invokes",
5259 "dereferenceable, dereferenceable_or_null "
5260 "take one operand!",
5265 "dereferenceable_or_null metadata value must be an i64!",
5269void Verifier::visitNofreeMetadata(Instruction &
I, MDNode *MD) {
5270 Check(
I.getType()->isPointerTy(),
"nofree applies only to pointer types", &
I);
5276void Verifier::visitProfMetadata(Instruction &
I, MDNode *MD) {
5277 auto GetBranchingTerminatorNumOperands = [&]() {
5278 unsigned ExpectedNumOperands = 0;
5282 ExpectedNumOperands =
SI->getNumSuccessors();
5284 ExpectedNumOperands = 1;
5286 ExpectedNumOperands = IBI->getNumDestinations();
5288 ExpectedNumOperands = 2;
5291 return ExpectedNumOperands;
5294 "!prof annotations should have at least 1 operand", MD);
5296 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null", MD);
5298 "expected string with name of the !prof annotation", MD);
5304 "'unknown' !prof should only appear on instructions on which "
5305 "'branch_weights' would",
5307 verifyUnknownProfileMetadata(MD);
5312 "!prof annotations should have no less than 2 operands", MD);
5318 Check(NumBranchWeights == 1 || NumBranchWeights == 2,
5319 "Wrong number of InvokeInst branch_weights operands", MD);
5321 const unsigned ExpectedNumOperands = GetBranchingTerminatorNumOperands();
5322 if (ExpectedNumOperands == 0)
5323 CheckFailed(
"!prof branch_weights are not allowed for this instruction",
5326 Check(NumBranchWeights == ExpectedNumOperands,
"Wrong number of operands",
5332 Check(MDO,
"second operand should not be null", MD);
5334 "!prof brunch_weights operand is not a const int");
5339 Check(KindInt,
"VP !prof missing kind argument", MD);
5342 Check(Kind >= InstrProfValueKind::IPVK_First &&
5343 Kind <= InstrProfValueKind::IPVK_Last,
5344 "Invalid VP !prof kind", MD);
5346 "VP !prof should have an even number "
5347 "of arguments after 'VP'",
5349 if (Kind == InstrProfValueKind::IPVK_IndirectCallTarget ||
5350 Kind == InstrProfValueKind::IPVK_MemOPSize)
5352 "VP !prof indirect call or memop size expected to be applied to "
5353 "CallBase instructions only",
5356 CheckFailed(
"expected either branch_weights or VP profile name", MD);
5360void Verifier::visitDIAssignIDMetadata(Instruction &
I, MDNode *MD) {
5361 assert(
I.hasMetadata(LLVMContext::MD_DIAssignID));
5366 bool ExpectedInstTy =
5368 CheckDI(ExpectedInstTy,
"!DIAssignID attached to unexpected instruction kind",
5373 for (
auto *User : AsValue->users()) {
5375 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
5379 CheckDI(DAI->getFunction() ==
I.getFunction(),
5380 "dbg.assign not in same function as inst", DAI, &
I);
5383 for (DbgVariableRecord *DVR :
5386 "!DIAssignID should only be used by Assign DVRs.", MD, DVR);
5387 CheckDI(DVR->getFunction() ==
I.getFunction(),
5388 "DVRAssign not in same function as inst", DVR, &
I);
5392void Verifier::visitMMRAMetadata(Instruction &
I, MDNode *MD) {
5394 "!mmra metadata attached to unexpected instruction kind",
I, MD);
5405 for (
const MDOperand &MDOp : MD->
operands())
5407 "!mmra metadata tuple operand is not an MMRA tag",
I, MDOp.get());
5410void Verifier::visitCallStackMetadata(MDNode *MD) {
5414 "call stack metadata should have at least 1 operand", MD);
5418 "call stack metadata operand should be constant integer",
Op);
5421void Verifier::visitMemProfMetadata(Instruction &
I, MDNode *MD) {
5424 "!memprof annotations should have at least 1 metadata operand "
5429 for (
auto &MIBOp : MD->
operands()) {
5435 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
5439 "!memprof MemInfoBlock first operand should not be null", MIB);
5441 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
5443 visitCallStackMetadata(StackMD);
5447 "!memprof MemInfoBlock second operand should be an MDString", MIB);
5452 Check(OpNode,
"Not all !memprof MemInfoBlock operands 2 to N are MDNode",
5455 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with 2 "
5460 [](
const MDOperand &
Op) {
5461 return mdconst::hasa<ConstantInt>(Op);
5463 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with "
5464 "ConstantInt operands",
5470void Verifier::visitCallsiteMetadata(Instruction &
I, MDNode *MD) {
5474 visitCallStackMetadata(MD);
5483void Verifier::visitCalleeTypeMetadata(Instruction &
I, MDNode *MD) {
5488 "The callee_type metadata must be a list of type metadata nodes",
Op);
5490 Check(TypeMD->getNumOperands() == 2,
5491 "Well-formed generalized type metadata must contain exactly two "
5496 "The first operand of type metadata for functions must be zero",
Op);
5497 Check(TypeMD->hasGeneralizedMDString(),
5498 "Only generalized type metadata can be part of the callee_type "
5504void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
5507 "annotation must have at least one operand");
5509 bool TupleOfStrings =
5515 "operands must be a string or a tuple of strings");
5519void Verifier::visitAliasScopeMetadata(
const MDNode *MD) {
5524 "first scope operand must be self-referential or string", MD);
5527 "third scope operand must be string (if used)", MD);
5530 Check(
Domain !=
nullptr,
"second scope operand must be MDNode", MD);
5532 unsigned NumDomainOps =
Domain->getNumOperands();
5533 Check(NumDomainOps >= 1 && NumDomainOps <= 2,
5534 "domain must have one or two operands",
Domain);
5537 "first domain operand must be self-referential or string",
Domain);
5538 if (NumDomainOps == 2)
5540 "second domain operand must be string (if used)",
Domain);
5543void Verifier::visitAliasScopeListMetadata(
const MDNode *MD) {
5546 Check(OpMD !=
nullptr,
"scope list must consist of MDNodes", MD);
5547 visitAliasScopeMetadata(OpMD);
5551void Verifier::visitAccessGroupMetadata(
const MDNode *MD) {
5552 auto IsValidAccessScope = [](
const MDNode *MD) {
5557 if (IsValidAccessScope(MD))
5563 Check(OpMD !=
nullptr,
"Access scope list must consist of MDNodes", MD);
5564 Check(IsValidAccessScope(OpMD),
5565 "Access scope list contains invalid access scope", MD);
5569void Verifier::visitCapturesMetadata(Instruction &
I,
const MDNode *Captures) {
5570 static const char *ValidArgs[] = {
"address_is_null",
"address",
5571 "read_provenance",
"provenance"};
5574 Check(SI,
"!captures metadata can only be applied to store instructions", &
I);
5575 Check(
SI->getValueOperand()->getType()->isPointerTy(),
5576 "!captures metadata can only be applied to store with value operand of "
5584 Check(Str,
"!captures metadata must be a list of strings", &
I);
5586 "invalid entry in !captures metadata", &
I, Str);
5590void Verifier::visitAllocTokenMetadata(Instruction &
I, MDNode *MD) {
5595 "expected integer constant", MD);
5600void Verifier::visitInstruction(Instruction &
I) {
5602 Check(BB,
"Instruction not embedded in basic block!", &
I);
5605 for (User *U :
I.users()) {
5606 Check(U != (User *)&
I || !DT.isReachableFromEntry(BB),
5607 "Only PHI nodes may reference their own value!", &
I);
5612 Check(!
I.getType()->isVoidTy() || !
I.hasName(),
5613 "Instruction has a name, but provides a void value!", &
I);
5617 Check(
I.getType()->isVoidTy() ||
I.getType()->isFirstClassType(),
5618 "Instruction returns a non-scalar type!", &
I);
5623 "Invalid use of metadata!", &
I);
5628 for (Use &U :
I.uses()) {
5631 "Instruction referencing"
5632 " instruction not embedded in a basic block!",
5635 CheckFailed(
"Use of instruction is not an instruction!", U);
5644 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i) {
5645 Check(
I.getOperand(i) !=
nullptr,
"Instruction has null operand!", &
I);
5649 if (!
I.getOperand(i)->getType()->isFirstClassType()) {
5650 Check(
false,
"Instruction operands must be first-class values!", &
I);
5656 auto IsAttachedCallOperand = [](
Function *
F,
const CallBase *CBI,
5658 return CBI && CBI->isOperandBundleOfType(
5666 Check((!
F->isIntrinsic() ||
5667 (CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i)) ||
5668 IsAttachedCallOperand(
F, CBI, i)),
5669 "Cannot take the address of an intrinsic!", &
I);
5671 F->getIntrinsicID() == Intrinsic::donothing ||
5672 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
5673 F->getIntrinsicID() == Intrinsic::seh_try_end ||
5674 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
5675 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
5676 F->getIntrinsicID() == Intrinsic::coro_resume ||
5677 F->getIntrinsicID() == Intrinsic::coro_destroy ||
5678 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
5679 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
5680 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
5681 F->getIntrinsicID() ==
5682 Intrinsic::experimental_patchpoint_void ||
5683 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
5684 F->getIntrinsicID() == Intrinsic::fake_use ||
5685 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
5686 F->getIntrinsicID() == Intrinsic::wasm_throw ||
5687 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
5688 IsAttachedCallOperand(
F, CBI, i),
5689 "Cannot invoke an intrinsic other than donothing, patchpoint, "
5690 "statepoint, coro_resume, coro_destroy, clang.arc.attachedcall or "
5693 Check(
F->getParent() == &M,
"Referencing function in another module!", &
I,
5694 &M,
F,
F->getParent());
5697 "Referring to a basic block in another function!", &
I);
5700 "Referring to an argument in another function!", &
I);
5702 Check(GV->
getParent() == &M,
"Referencing global in another module!", &
I,
5706 "Referring to an instruction in another function!", &
I);
5707 verifyDominatesUse(
I, i);
5709 Check(CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i),
5710 "Cannot take the address of an inline asm!", &
I);
5712 visitConstantExprsRecursively(
C);
5716 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_fpmath)) {
5717 Check(
I.getType()->isFPOrFPVectorTy(),
5718 "fpmath requires a floating point result!", &
I);
5720 if (ConstantFP *CFP0 =
5722 const APFloat &Accuracy = CFP0->getValueAPF();
5724 "fpmath accuracy must have float type", &
I);
5726 "fpmath accuracy not a positive number!", &
I);
5728 Check(
false,
"invalid fpmath accuracy!", &
I);
5732 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_range)) {
5734 "Ranges are only for loads, calls and invokes!", &
I);
5735 visitRangeMetadata(
I,
Range,
I.getType());
5738 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofpclass)) {
5740 visitNoFPClassMetadata(
I, MD,
I.getType());
5743 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_noalias_addrspace)) {
5746 "noalias.addrspace are only for memory operations!", &
I);
5747 visitNoaliasAddrspaceMetadata(
I,
Range,
I.getType());
5750 if (
I.hasMetadata(LLVMContext::MD_invariant_group)) {
5752 "invariant.group metadata is only for loads and stores", &
I);
5755 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nonnull)) {
5756 Check(
I.getType()->isPointerTy(),
"nonnull applies only to pointer types",
5759 "nonnull applies only to load instructions, use attributes"
5760 " for calls or invokes",
5765 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable))
5766 visitDereferenceableMetadata(
I, MD);
5768 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
5769 visitDereferenceableMetadata(
I, MD);
5771 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofree))
5772 visitNofreeMetadata(
I, MD);
5774 if (MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa))
5777 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noalias))
5778 visitAliasScopeListMetadata(MD);
5779 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alias_scope))
5780 visitAliasScopeListMetadata(MD);
5782 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_access_group))
5783 visitAccessGroupMetadata(MD);
5785 if (MDNode *AlignMD =
I.getMetadata(LLVMContext::MD_align)) {
5786 Check(
I.getType()->isPointerTy(),
"align applies only to pointer types",
5789 "align applies only to load instructions, "
5790 "use attributes for calls or invokes",
5792 Check(AlignMD->getNumOperands() == 1,
"align takes one operand!", &
I);
5795 "align metadata value must be an i64!", &
I);
5799 Check(Align <= Value::MaximumAlignment,
5800 "alignment is larger that implementation defined limit", &
I);
5803 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_prof))
5804 visitProfMetadata(
I, MD);
5806 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_memprof))
5807 visitMemProfMetadata(
I, MD);
5809 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callsite))
5810 visitCallsiteMetadata(
I, MD);
5812 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callee_type))
5813 visitCalleeTypeMetadata(
I, MD);
5815 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_DIAssignID))
5816 visitDIAssignIDMetadata(
I, MD);
5818 if (MDNode *MMRA =
I.getMetadata(LLVMContext::MD_mmra))
5819 visitMMRAMetadata(
I, MMRA);
5821 if (MDNode *Annotation =
I.getMetadata(LLVMContext::MD_annotation))
5822 visitAnnotationMetadata(Annotation);
5824 if (MDNode *Captures =
I.getMetadata(LLVMContext::MD_captures))
5825 visitCapturesMetadata(
I, Captures);
5827 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alloc_token))
5828 visitAllocTokenMetadata(
I, MD);
5830 if (MDNode *
N =
I.getDebugLoc().getAsMDNode()) {
5832 visitMDNode(*
N, AreDebugLocsAllowed::Yes);
5835 if (
DL->getAtomGroup()) {
5836 CheckDI(
DL->getScope()->getSubprogram()->getKeyInstructionsEnabled(),
5837 "DbgLoc uses atomGroup but DISubprogram doesn't have Key "
5838 "Instructions enabled",
5839 DL,
DL->getScope()->getSubprogram());
5845 I.getAllMetadata(MDs);
5846 for (
auto Attachment : MDs) {
5847 unsigned Kind = Attachment.first;
5849 (
Kind == LLVMContext::MD_dbg ||
Kind == LLVMContext::MD_loop)
5850 ? AreDebugLocsAllowed::Yes
5851 : AreDebugLocsAllowed::
No;
5852 visitMDNode(*Attachment.second, AllowLocs);
5867 bool IsVarArg = IFTy->isVarArg();
5878 "Intrinsic has incorrect return type!", IF);
5880 "Intrinsic has incorrect argument type!", IF);
5885 "Intrinsic was not defined with variable arguments!", IF);
5888 "Callsite was not defined with variable arguments!", IF);
5897 const std::string ExpectedName =
5900 "Intrinsic name not mangled correctly for type arguments! "
5912 "const x86_amx is not allowed in argument!");
5918 case Intrinsic::assume: {
5922 "assume with operand bundles must have i1 true condition",
Call);
5925 unsigned ArgCount = Elem.End - Elem.Begin;
5928 if (Elem.Tag->getKey() ==
"separate_storage") {
5929 Check(ArgCount == 2,
5930 "separate_storage assumptions should have 2 arguments",
Call);
5933 "arguments to separate_storage assumptions should be pointers",
5937 Check(Elem.Tag->getKey() ==
"ignore" ||
5938 Attribute::isExistingAttribute(Elem.Tag->getKey()),
5939 "tags must be valid attribute names",
Call);
5940 Attribute::AttrKind
Kind =
5941 Attribute::getAttrKindFromName(Elem.Tag->getKey());
5942 if (Kind == Attribute::Alignment) {
5943 Check(ArgCount <= 3 && ArgCount >= 2,
5944 "alignment assumptions should have 2 or 3 arguments",
Call);
5946 "first argument should be a pointer",
Call);
5948 "second argument should be an integer",
Call);
5951 "third argument should be an integer if present",
Call);
5954 if (Kind == Attribute::Dereferenceable) {
5955 Check(ArgCount == 2,
5956 "dereferenceable assumptions should have 2 arguments",
Call);
5958 "first argument should be a pointer",
Call);
5960 "second argument should be an integer",
Call);
5963 Check(ArgCount <= 2,
"too many arguments",
Call);
5964 if (Kind == Attribute::None)
5966 if (Attribute::isIntAttrKind(Kind)) {
5967 Check(ArgCount == 2,
"this attribute should have 2 arguments",
Call);
5969 "the second argument should be a constant integral value",
Call);
5970 }
else if (Attribute::canUseAsParamAttr(Kind)) {
5971 Check((ArgCount) == 1,
"this attribute should have one argument",
Call);
5972 }
else if (Attribute::canUseAsFnAttr(Kind)) {
5973 Check((ArgCount) == 0,
"this attribute has no argument",
Call);
5978 case Intrinsic::ucmp:
5979 case Intrinsic::scmp: {
5984 "result type must be at least 2 bits wide",
Call);
5986 bool IsDestTypeVector = DestTy->
isVectorTy();
5988 "ucmp/scmp argument and result types must both be either vector or "
5991 if (IsDestTypeVector) {
5994 Check(SrcVecLen == DestVecLen,
5995 "return type and arguments must have the same number of "
6001 case Intrinsic::coro_id: {
6007 "info argument of llvm.coro.id must refer to an initialized "
6011 "info argument of llvm.coro.id must refer to either a struct or "
6015 case Intrinsic::is_fpclass: {
6018 "unsupported bits for llvm.is.fpclass test mask");
6021 case Intrinsic::fptrunc_round: {
6026 MD = MAV->getMetadata();
6028 Check(MD !=
nullptr,
"missing rounding mode argument",
Call);
6031 (
"invalid value for llvm.fptrunc.round metadata operand"
6032 " (the operand should be a string)"),
6035 std::optional<RoundingMode> RoundMode =
6037 Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
6038 "unsupported rounding mode argument",
Call);
6041 case Intrinsic::convert_to_arbitrary_fp: {
6049 "if floating-point operand is a vector, integer operand must also "
6052 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6053 "floating-point and integer vector operands must have the same "
6060 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6062 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6063 StringRef Interp = InterpStr->getString();
6065 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6070 "unsupported interpretation metadata string",
Call);
6074 Check(RoundingMAV,
"missing rounding mode metadata operand",
Call);
6076 Check(RoundingStr,
"rounding mode metadata operand must be a string",
Call);
6078 std::optional<RoundingMode>
RM =
6080 Check(RM && *RM != RoundingMode::Dynamic,
6081 "unsupported rounding mode argument",
Call);
6084 case Intrinsic::convert_from_arbitrary_fp: {
6092 "if floating-point operand is a vector, integer operand must also "
6095 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6096 "floating-point and integer vector operands must have the same "
6103 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6105 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6106 StringRef Interp = InterpStr->getString();
6108 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6113 "unsupported interpretation metadata string",
Call);
6116#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6117#include "llvm/IR/VPIntrinsics.def"
6118#undef BEGIN_REGISTER_VP_INTRINSIC
6121#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
6122 case Intrinsic::INTRINSIC:
6123#include "llvm/IR/ConstrainedOps.def"
6127 case Intrinsic::dbg_declare:
6128 case Intrinsic::dbg_value:
6129 case Intrinsic::dbg_assign:
6130 case Intrinsic::dbg_label:
6137 case Intrinsic::memcpy:
6138 case Intrinsic::memcpy_inline:
6139 case Intrinsic::memmove:
6140 case Intrinsic::memset:
6141 case Intrinsic::memset_inline:
6143 case Intrinsic::experimental_memset_pattern: {
6145 Check(Memset->getValue()->getType()->isSized(),
6146 "unsized types cannot be used as memset patterns",
Call);
6149 case Intrinsic::memcpy_element_unordered_atomic:
6150 case Intrinsic::memmove_element_unordered_atomic:
6151 case Intrinsic::memset_element_unordered_atomic: {
6154 ConstantInt *ElementSizeCI =
6156 const APInt &ElementSizeVal = ElementSizeCI->
getValue();
6158 "element size of the element-wise atomic memory intrinsic "
6159 "must be a power of 2",
6162 auto IsValidAlignment = [&](MaybeAlign Alignment) {
6163 return Alignment && ElementSizeVal.
ule(Alignment->value());
6165 Check(IsValidAlignment(AMI->getDestAlign()),
6166 "incorrect alignment of the destination argument",
Call);
6168 Check(IsValidAlignment(AMT->getSourceAlign()),
6169 "incorrect alignment of the source argument",
Call);
6173 case Intrinsic::call_preallocated_setup: {
6175 bool FoundCall =
false;
6178 Check(UseCall !=
nullptr,
6179 "Uses of llvm.call.preallocated.setup must be calls");
6181 if (IID == Intrinsic::call_preallocated_arg) {
6183 Check(AllocArgIndex !=
nullptr,
6184 "llvm.call.preallocated.alloc arg index must be a constant");
6185 auto AllocArgIndexInt = AllocArgIndex->getValue();
6186 Check(AllocArgIndexInt.sge(0) &&
6187 AllocArgIndexInt.slt(NumArgs->getValue()),
6188 "llvm.call.preallocated.alloc arg index must be between 0 and "
6190 "llvm.call.preallocated.setup's argument count");
6191 }
else if (IID == Intrinsic::call_preallocated_teardown) {
6194 Check(!FoundCall,
"Can have at most one call corresponding to a "
6195 "llvm.call.preallocated.setup");
6197 size_t NumPreallocatedArgs = 0;
6198 for (
unsigned i = 0; i < UseCall->arg_size(); i++) {
6199 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
6200 ++NumPreallocatedArgs;
6203 Check(NumPreallocatedArgs != 0,
6204 "cannot use preallocated intrinsics on a call without "
6205 "preallocated arguments");
6206 Check(NumArgs->equalsInt(NumPreallocatedArgs),
6207 "llvm.call.preallocated.setup arg size must be equal to number "
6208 "of preallocated arguments "
6218 auto PreallocatedBundle =
6220 Check(PreallocatedBundle,
6221 "Use of llvm.call.preallocated.setup outside intrinsics "
6222 "must be in \"preallocated\" operand bundle");
6223 Check(PreallocatedBundle->Inputs.front().get() == &
Call,
6224 "preallocated bundle must have token from corresponding "
6225 "llvm.call.preallocated.setup");
6230 case Intrinsic::call_preallocated_arg: {
6233 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6234 "llvm.call.preallocated.arg token argument must be a "
6235 "llvm.call.preallocated.setup");
6237 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
6238 "call site attribute");
6241 case Intrinsic::call_preallocated_teardown: {
6244 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6245 "llvm.call.preallocated.teardown token argument must be a "
6246 "llvm.call.preallocated.setup");
6249 case Intrinsic::gcroot:
6250 case Intrinsic::gcwrite:
6251 case Intrinsic::gcread:
6252 if (
ID == Intrinsic::gcroot) {
6255 Check(AI,
"llvm.gcroot parameter #1 must be an alloca.",
Call);
6257 "llvm.gcroot parameter #2 must be a constant.",
Call);
6260 "llvm.gcroot parameter #1 must either be a pointer alloca, "
6261 "or argument #2 must be a non-null constant.",
6267 "Enclosing function does not use GC.",
Call);
6269 case Intrinsic::init_trampoline:
6271 "llvm.init_trampoline parameter #2 must resolve to a function.",
6274 case Intrinsic::prefetch:
6276 "rw argument to llvm.prefetch must be 0-1",
Call);
6278 "locality argument to llvm.prefetch must be 0-3",
Call);
6280 "cache type argument to llvm.prefetch must be 0-1",
Call);
6282 case Intrinsic::reloc_none: {
6285 "llvm.reloc.none argument must be a metadata string", &
Call);
6288 case Intrinsic::stackprotector:
6290 "llvm.stackprotector parameter #2 must resolve to an alloca.",
Call);
6292 case Intrinsic::localescape: {
6296 Check(!SawFrameEscape,
"multiple calls to llvm.localescape in one function",
6303 "llvm.localescape only accepts static allocas",
Call);
6306 SawFrameEscape =
true;
6309 case Intrinsic::localrecover: {
6313 "llvm.localrecover first "
6314 "argument must be function defined in this module",
6317 auto &
Entry = FrameEscapeInfo[Fn];
6318 Entry.second = unsigned(
6319 std::max(uint64_t(
Entry.second), IdxArg->getLimitedValue(~0U) + 1));
6323 case Intrinsic::experimental_gc_statepoint:
6325 Check(!CI->isInlineAsm(),
6326 "gc.statepoint support for inline assembly unimplemented", CI);
6328 "Enclosing function does not use GC.",
Call);
6330 verifyStatepoint(
Call);
6332 case Intrinsic::experimental_gc_result: {
6334 "Enclosing function does not use GC.",
Call);
6342 Check(StatepointCall && StatepointCall->getIntrinsicID() ==
6343 Intrinsic::experimental_gc_statepoint,
6344 "gc.result operand #1 must be from a statepoint",
Call,
6348 auto *TargetFuncType =
6351 "gc.result result type does not match wrapped callee",
Call);
6354 case Intrinsic::experimental_gc_relocate: {
6358 "gc.relocate must return a pointer or a vector of pointers",
Call);
6363 if (LandingPadInst *LandingPad =
6367 LandingPad->getParent()->getUniquePredecessor();
6371 Check(InvokeBB,
"safepoints should have unique landingpads",
6372 LandingPad->getParent());
6376 "gc relocate should be linked to a statepoint", InvokeBB);
6383 "gc relocate is incorrectly tied to the statepoint",
Call, Token);
6392 "gc.relocate operand #2 must be integer offset",
Call);
6396 "gc.relocate operand #3 must be integer offset",
Call);
6406 Check(BaseIndex < Opt->Inputs.size(),
6407 "gc.relocate: statepoint base index out of bounds",
Call);
6408 Check(DerivedIndex < Opt->Inputs.size(),
6409 "gc.relocate: statepoint derived index out of bounds",
Call);
6422 "gc.relocate: relocated value must be a pointer",
Call);
6423 Check(DerivedType->isPtrOrPtrVectorTy(),
6424 "gc.relocate: relocated value must be a pointer",
Call);
6426 Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
6427 "gc.relocate: vector relocates to vector and pointer to pointer",
6430 ResultType->getPointerAddressSpace() ==
6431 DerivedType->getPointerAddressSpace(),
6432 "gc.relocate: relocating a pointer shouldn't change its address space",
6436 Check(GC,
"gc.relocate: calling function must have GCStrategy",
6439 auto isGCPtr = [&
GC](
Type *PTy) {
6440 return GC->isGCManagedPointer(PTy->getScalarType()).value_or(
true);
6442 Check(isGCPtr(ResultType),
"gc.relocate: must return gc pointer",
Call);
6444 "gc.relocate: relocated value must be a gc pointer",
Call);
6445 Check(isGCPtr(DerivedType),
6446 "gc.relocate: relocated value must be a gc pointer",
Call);
6450 case Intrinsic::experimental_patchpoint: {
6453 "patchpoint: invalid return type used with anyregcc",
Call);
6457 case Intrinsic::eh_exceptioncode:
6458 case Intrinsic::eh_exceptionpointer: {
6460 "eh.exceptionpointer argument must be a catchpad",
Call);
6463 case Intrinsic::get_active_lane_mask: {
6465 "get_active_lane_mask: must return a "
6469 Check(ElemTy->isIntegerTy(1),
6470 "get_active_lane_mask: element type is not "
6475 case Intrinsic::experimental_get_vector_length: {
6478 "get_vector_length: VF must be positive",
Call);
6481 case Intrinsic::masked_load: {
6487 Check(
Mask->getType()->isVectorTy(),
"masked_load: mask must be vector",
6490 "masked_load: pass through and return type must match",
Call);
6493 "masked_load: vector mask must be same length as return",
Call);
6496 case Intrinsic::masked_store: {
6499 Check(
Mask->getType()->isVectorTy(),
"masked_store: mask must be vector",
6503 "masked_store: vector mask must be same length as value",
Call);
6507 case Intrinsic::experimental_guard: {
6510 "experimental_guard must have exactly one "
6511 "\"deopt\" operand bundle");
6515 case Intrinsic::experimental_deoptimize: {
6519 "experimental_deoptimize must have exactly one "
6520 "\"deopt\" operand bundle");
6522 "experimental_deoptimize return type must match caller return type");
6527 "calls to experimental_deoptimize must be followed by a return");
6531 "calls to experimental_deoptimize must be followed by a return "
6532 "of the value computed by experimental_deoptimize");
6537 case Intrinsic::vastart: {
6539 "va_start called in a non-varargs function");
6542 case Intrinsic::get_dynamic_area_offset: {
6544 Check(IntTy &&
DL.getPointerSizeInBits(
DL.getAllocaAddrSpace()) ==
6545 IntTy->getBitWidth(),
6546 "get_dynamic_area_offset result type must be scalar integer matching "
6547 "alloca address space width",
6551 case Intrinsic::vector_reduce_and:
6552 case Intrinsic::vector_reduce_or:
6553 case Intrinsic::vector_reduce_xor:
6554 case Intrinsic::vector_reduce_add:
6555 case Intrinsic::vector_reduce_mul:
6556 case Intrinsic::vector_reduce_smax:
6557 case Intrinsic::vector_reduce_smin:
6558 case Intrinsic::vector_reduce_umax:
6559 case Intrinsic::vector_reduce_umin: {
6562 "Intrinsic has incorrect argument type!");
6565 case Intrinsic::vector_reduce_fmax:
6566 case Intrinsic::vector_reduce_fmin: {
6569 "Intrinsic has incorrect argument type!");
6572 case Intrinsic::vector_reduce_fadd:
6573 case Intrinsic::vector_reduce_fmul: {
6578 "Intrinsic has incorrect argument type!");
6581 case Intrinsic::smul_fix:
6582 case Intrinsic::smul_fix_sat:
6583 case Intrinsic::umul_fix:
6584 case Intrinsic::umul_fix_sat:
6585 case Intrinsic::sdiv_fix:
6586 case Intrinsic::sdiv_fix_sat:
6587 case Intrinsic::udiv_fix:
6588 case Intrinsic::udiv_fix_sat: {
6592 "first operand of [us][mul|div]_fix[_sat] must be an int type or "
6595 "second operand of [us][mul|div]_fix[_sat] must be an int type or "
6599 Check(Op3->getType()->isIntegerTy(),
6600 "third operand of [us][mul|div]_fix[_sat] must be an int type");
6601 Check(Op3->getBitWidth() <= 32,
6602 "third operand of [us][mul|div]_fix[_sat] must fit within 32 bits");
6604 if (
ID == Intrinsic::smul_fix ||
ID == Intrinsic::smul_fix_sat ||
6605 ID == Intrinsic::sdiv_fix ||
ID == Intrinsic::sdiv_fix_sat) {
6607 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
6611 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
6612 "to the width of the operands");
6616 case Intrinsic::lrint:
6617 case Intrinsic::llrint:
6618 case Intrinsic::lround:
6619 case Intrinsic::llround: {
6625 ExpectedName +
": argument must be floating-point or vector "
6626 "of floating-points, and result must be integer or "
6627 "vector of integers",
6630 ExpectedName +
": argument and result disagree on vector use", &
Call);
6632 Check(VTy->getElementCount() == RTy->getElementCount(),
6633 ExpectedName +
": argument must be same length as result", &
Call);
6637 case Intrinsic::bswap: {
6640 Check(
Size % 16 == 0,
"bswap must be an even number of bytes", &
Call);
6643 case Intrinsic::invariant_start: {
6645 Check(InvariantSize &&
6647 "invariant_start parameter must be -1, 0 or a positive number",
6651 case Intrinsic::matrix_multiply:
6652 case Intrinsic::matrix_transpose:
6653 case Intrinsic::matrix_column_major_load:
6654 case Intrinsic::matrix_column_major_store: {
6656 ConstantInt *Stride =
nullptr;
6657 ConstantInt *NumRows;
6658 ConstantInt *NumColumns;
6660 Type *Op0ElemTy =
nullptr;
6661 Type *Op1ElemTy =
nullptr;
6663 case Intrinsic::matrix_multiply: {
6668 ->getNumElements() ==
6670 "First argument of a matrix operation does not match specified "
6673 ->getNumElements() ==
6675 "Second argument of a matrix operation does not match specified "
6685 case Intrinsic::matrix_transpose:
6692 case Intrinsic::matrix_column_major_load: {
6699 case Intrinsic::matrix_column_major_store: {
6712 Check(ResultTy->getElementType()->isIntegerTy() ||
6713 ResultTy->getElementType()->isFloatingPointTy(),
6714 "Result type must be an integer or floating-point type!", IF);
6717 Check(ResultTy->getElementType() == Op0ElemTy,
6718 "Vector element type mismatch of the result and first operand "
6723 Check(ResultTy->getElementType() == Op1ElemTy,
6724 "Vector element type mismatch of the result and second operand "
6730 "Result of a matrix operation does not fit in the returned vector!");
6736 "Stride must be greater or equal than the number of rows!", IF);
6741 case Intrinsic::stepvector: {
6743 Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
6744 VecTy->getScalarSizeInBits() >= 8,
6745 "stepvector only supported for vectors of integers "
6746 "with a bitwidth of at least 8.",
6750 case Intrinsic::experimental_vector_match: {
6759 Check(Op1Ty && Op2Ty && MaskTy,
"Operands must be vectors.", &
Call);
6761 "Second operand must be a fixed length vector.", &
Call);
6762 Check(Op1Ty->getElementType()->isIntegerTy(),
6763 "First operand must be a vector of integers.", &
Call);
6764 Check(Op1Ty->getElementType() == Op2Ty->getElementType(),
6765 "First two operands must have the same element type.", &
Call);
6766 Check(Op1Ty->getElementCount() == MaskTy->getElementCount(),
6767 "First operand and mask must have the same number of elements.",
6769 Check(MaskTy->getElementType()->isIntegerTy(1),
6770 "Mask must be a vector of i1's.", &
Call);
6775 case Intrinsic::vector_insert: {
6784 ElementCount VecEC = VecTy->getElementCount();
6785 ElementCount SubVecEC = SubVecTy->getElementCount();
6786 Check(VecTy->getElementType() == SubVecTy->getElementType(),
6787 "vector_insert parameters must have the same element "
6791 "vector_insert index must be a constant multiple of "
6792 "the subvector's known minimum vector length.");
6800 "subvector operand of vector_insert would overrun the "
6801 "vector being inserted into.");
6805 case Intrinsic::vector_extract: {
6813 ElementCount VecEC = VecTy->getElementCount();
6814 ElementCount ResultEC = ResultTy->getElementCount();
6816 Check(ResultTy->getElementType() == VecTy->getElementType(),
6817 "vector_extract result must have the same element "
6818 "type as the input vector.",
6821 "vector_extract index must be a constant multiple of "
6822 "the result type's known minimum vector length.");
6830 "vector_extract would overrun.");
6834 case Intrinsic::vector_partial_reduce_fadd:
6835 case Intrinsic::vector_partial_reduce_add: {
6839 unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
6840 unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
6842 Check((VecWidth % AccWidth) == 0,
6843 "Invalid vector widths for partial "
6844 "reduction. The width of the input vector "
6845 "must be a positive integer multiple of "
6846 "the width of the accumulator vector.");
6849 case Intrinsic::experimental_noalias_scope_decl: {
6853 case Intrinsic::preserve_array_access_index:
6854 case Intrinsic::preserve_struct_access_index:
6855 case Intrinsic::aarch64_ldaxr:
6856 case Intrinsic::aarch64_ldxr:
6857 case Intrinsic::arm_ldaex:
6858 case Intrinsic::arm_ldrex: {
6860 Check(ElemTy,
"Intrinsic requires elementtype attribute on first argument.",
6864 case Intrinsic::aarch64_stlxr:
6865 case Intrinsic::aarch64_stxr:
6866 case Intrinsic::arm_stlex:
6867 case Intrinsic::arm_strex: {
6870 "Intrinsic requires elementtype attribute on second argument.",
6874 case Intrinsic::aarch64_prefetch: {
6876 "write argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6878 "target argument to llvm.aarch64.prefetch must be 0-3",
Call);
6880 "stream argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6882 "isdata argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6885 case Intrinsic::aarch64_range_prefetch: {
6887 "write argument to llvm.aarch64.range.prefetch must be 0 or 1",
Call);
6889 "stream argument to llvm.aarch64.range.prefetch must be 0 or 1",
6893 case Intrinsic::aarch64_stshh_atomic_store: {
6895 Check(Order ==
static_cast<uint64_t
>(AtomicOrderingCABI::relaxed) ||
6896 Order ==
static_cast<uint64_t
>(AtomicOrderingCABI::release) ||
6897 Order ==
static_cast<uint64_t
>(AtomicOrderingCABI::seq_cst),
6898 "order argument to llvm.aarch64.stshh.atomic.store must be 0, 3 or 5",
6902 "policy argument to llvm.aarch64.stshh.atomic.store must be 0 or 1",
6907 "size argument to llvm.aarch64.stshh.atomic.store must be 8, 16, "
6912 case Intrinsic::callbr_landingpad: {
6914 Check(CBR,
"intrinstic requires callbr operand", &
Call);
6921 CheckFailed(
"Intrinsic in block must have 1 unique predecessor", &
Call);
6925 CheckFailed(
"Intrinsic must have corresponding callbr in predecessor",
6930 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
6931 "block in indirect destination list",
6934 Check(&
First == &
Call,
"No other instructions may proceed intrinsic",
6938 case Intrinsic::structured_gep: {
6944 "Intrinsic first parameter is missing an ElementType attribute",
6952 "Index operand type must be an integer", &
Call);
6955 T = AT->getElementType();
6957 Check(CI,
"Indexing into a struct requires a constant int", &
Call);
6959 "Indexing in a struct should be inbounds", &
Call);
6962 T = VT->getElementType();
6964 CheckFailed(
"Reached a non-composite type with more indices to process",
6970 case Intrinsic::amdgcn_cs_chain: {
6973 case CallingConv::AMDGPU_CS:
6974 case CallingConv::AMDGPU_CS_Chain:
6975 case CallingConv::AMDGPU_CS_ChainPreserve:
6976 case CallingConv::AMDGPU_ES:
6977 case CallingConv::AMDGPU_GS:
6978 case CallingConv::AMDGPU_HS:
6979 case CallingConv::AMDGPU_LS:
6980 case CallingConv::AMDGPU_VS:
6983 CheckFailed(
"Intrinsic cannot be called from functions with this "
6984 "calling convention",
6990 "SGPR arguments must have the `inreg` attribute", &
Call);
6992 "VGPR arguments must not have the `inreg` attribute", &
Call);
6997 Intrinsic::amdgcn_unreachable;
6999 "llvm.amdgcn.cs.chain must be followed by unreachable", &
Call);
7002 case Intrinsic::amdgcn_init_exec_from_input: {
7005 "only inreg arguments to the parent function are valid as inputs to "
7010 case Intrinsic::amdgcn_set_inactive_chain_arg: {
7013 case CallingConv::AMDGPU_CS_Chain:
7014 case CallingConv::AMDGPU_CS_ChainPreserve:
7017 CheckFailed(
"Intrinsic can only be used from functions with the "
7018 "amdgpu_cs_chain or amdgpu_cs_chain_preserve "
7019 "calling conventions",
7024 unsigned InactiveIdx = 1;
7026 "Value for inactive lanes must not have the `inreg` attribute",
7029 "Value for inactive lanes must be a function argument", &
Call);
7031 "Value for inactive lanes must be a VGPR function argument", &
Call);
7034 case Intrinsic::amdgcn_call_whole_wave: {
7036 Check(
F,
"Indirect whole wave calls are not allowed", &
Call);
7038 CallingConv::ID CC =
F->getCallingConv();
7039 Check(CC == CallingConv::AMDGPU_Gfx_WholeWave,
7040 "Callee must have the amdgpu_gfx_whole_wave calling convention",
7043 Check(!
F->isVarArg(),
"Variadic whole wave calls are not allowed", &
Call);
7046 "Call argument count must match callee argument count", &
Call);
7050 Check(
F->arg_begin()->getType()->isIntegerTy(1),
7051 "Callee must have i1 as its first argument", &
Call);
7052 for (
auto [CallArg, FuncArg] :
7054 Check(CallArg->getType() == FuncArg.getType(),
7055 "Argument types must match", &
Call);
7059 FuncArg.hasInRegAttr(),
7060 "Argument inreg attributes must match", &
Call);
7064 case Intrinsic::amdgcn_s_prefetch_data: {
7068 "llvm.amdgcn.s.prefetch.data only supports global or constant memory");
7071 case Intrinsic::amdgcn_mfma_scale_f32_16x16x128_f8f6f4:
7072 case Intrinsic::amdgcn_mfma_scale_f32_32x32x64_f8f6f4: {
7078 Check(CBSZ <= 4,
"invalid value for cbsz format",
Call,
7080 Check(BLGP <= 4,
"invalid value for blgp format",
Call,
7084 auto getFormatNumRegs = [](
unsigned FormatVal) {
7085 switch (FormatVal) {
7099 auto isValidSrcASrcBVector = [](FixedVectorType *Ty) {
7100 if (!Ty || !Ty->getElementType()->
isIntegerTy(32))
7102 unsigned NumElts = Ty->getNumElements();
7103 return NumElts == 4 || NumElts == 6 || NumElts == 8;
7108 Check(isValidSrcASrcBVector(Src0Ty),
7109 "operand 0 must be 4, 6 or 8 element i32 vector", &
Call, Src0);
7110 Check(isValidSrcASrcBVector(Src1Ty),
7111 "operand 1 must be 4, 6 or 8 element i32 vector", &
Call, Src1);
7114 Check(Src0Ty->getNumElements() >= getFormatNumRegs(CBSZ),
7116 Check(Src1Ty->getNumElements() >= getFormatNumRegs(BLGP),
7120 case Intrinsic::amdgcn_wmma_f32_16x16x128_f8f6f4:
7121 case Intrinsic::amdgcn_wmma_scale_f32_16x16x128_f8f6f4:
7122 case Intrinsic::amdgcn_wmma_scale16_f32_16x16x128_f8f6f4: {
7128 Check(FmtA <= 4,
"invalid value for matrix format",
Call,
7130 Check(FmtB <= 4,
"invalid value for matrix format",
Call,
7134 auto getFormatNumRegs = [](
unsigned FormatVal) {
7135 switch (FormatVal) {
7149 auto isValidSrcASrcBVector = [](FixedVectorType *Ty) {
7150 if (!Ty || !Ty->getElementType()->
isIntegerTy(32))
7152 unsigned NumElts = Ty->getNumElements();
7153 return NumElts == 16 || NumElts == 12 || NumElts == 8;
7158 Check(isValidSrcASrcBVector(Src0Ty),
7159 "operand 1 must be 8, 12 or 16 element i32 vector", &
Call, Src0);
7160 Check(isValidSrcASrcBVector(Src1Ty),
7161 "operand 3 must be 8, 12 or 16 element i32 vector", &
Call, Src1);
7164 Check(Src0Ty->getNumElements() >= getFormatNumRegs(FmtA),
7166 Check(Src1Ty->getNumElements() >= getFormatNumRegs(FmtB),
7170 case Intrinsic::amdgcn_cooperative_atomic_load_32x4B:
7171 case Intrinsic::amdgcn_cooperative_atomic_load_16x8B:
7172 case Intrinsic::amdgcn_cooperative_atomic_load_8x16B:
7173 case Intrinsic::amdgcn_cooperative_atomic_store_32x4B:
7174 case Intrinsic::amdgcn_cooperative_atomic_store_16x8B:
7175 case Intrinsic::amdgcn_cooperative_atomic_store_8x16B: {
7180 "cooperative atomic intrinsics require a generic or global pointer",
7187 "cooperative atomic intrinsics require that the last argument is a "
7192 case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
7193 case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
7196 Check(RegCount % 8 == 0,
7197 "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
7200 case Intrinsic::experimental_convergence_entry:
7201 case Intrinsic::experimental_convergence_anchor:
7203 case Intrinsic::experimental_convergence_loop:
7205 case Intrinsic::ptrmask: {
7209 "llvm.ptrmask intrinsic first argument must be pointer or vector "
7214 "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
7219 "llvm.ptrmask intrinsic arguments must have the same number of "
7223 "llvm.ptrmask intrinsic second argument bitwidth must match "
7224 "pointer index type size of first argument",
7228 case Intrinsic::thread_pointer: {
7230 DL.getDefaultGlobalsAddressSpace(),
7231 "llvm.thread.pointer intrinsic return type must be for the globals "
7236 case Intrinsic::threadlocal_address: {
7239 "llvm.threadlocal.address first argument must be a GlobalValue");
7241 "llvm.threadlocal.address operand isThreadLocal() must be true");
7244 case Intrinsic::lifetime_start:
7245 case Intrinsic::lifetime_end: {
7248 "llvm.lifetime.start/end can only be used on alloca or poison",
7252 case Intrinsic::sponentry: {
7253 const unsigned StackAS =
DL.getAllocaAddrSpace();
7256 "llvm.sponentry must return a pointer to the stack", &
Call);
7264 if (
F->hasPersonalityFn() &&
7268 if (BlockEHFuncletColors.
empty())
7272 bool InEHFunclet =
false;
7276 for (BasicBlock *ColorFirstBB : CV)
7277 if (
auto It = ColorFirstBB->getFirstNonPHIIt();
7278 It != ColorFirstBB->end())
7283 bool HasToken =
false;
7290 Check(HasToken,
"Missing funclet token on intrinsic call", &
Call);
7314void Verifier::visit(DbgLabelRecord &DLR) {
7316 "invalid #dbg_label intrinsic variable", &DLR, DLR.
getRawLabel());
7329 CheckDI(Loc,
"#dbg_label record requires a !dbg attachment", &DLR, BB,
F);
7333 if (!LabelSP || !LocSP)
7337 "mismatched subprogram between #dbg_label label and !dbg attachment",
7338 &DLR, BB,
F, Label,
Label->getScope()->getSubprogram(), Loc,
7339 Loc->getScope()->getSubprogram());
7342void Verifier::visit(DbgVariableRecord &DVR) {
7346 CheckDI(DVR.
getType() == DbgVariableRecord::LocationType::Value ||
7347 DVR.
getType() == DbgVariableRecord::LocationType::Declare ||
7348 DVR.
getType() == DbgVariableRecord::LocationType::DeclareValue ||
7349 DVR.
getType() == DbgVariableRecord::LocationType::Assign,
7350 "invalid #dbg record type", &DVR, DVR.
getType(), BB,
F);
7358 "invalid #dbg record address/value", &DVR, MD, BB,
F);
7360 visitValueAsMetadata(*VAM,
F);
7363 Type *Ty = VAM->getValue()->getType();
7365 "location of #dbg_declare must be a pointer or int", &DVR, MD, BB,
7369 visitDIArgList(*AL,
F);
7383 "invalid #dbg_assign DIAssignID", &DVR, DVR.
getRawAssignID(), BB,
7386 AreDebugLocsAllowed::No);
7395 "invalid #dbg_assign address", &DVR, DVR.
getRawAddress(), BB,
F);
7397 visitValueAsMetadata(*VAM,
F);
7400 "invalid #dbg_assign address expression", &DVR,
7407 "inst not in same function as #dbg_assign",
I, &DVR, BB,
F);
7417 &DVR, DLNode, BB,
F);
7423 if (!VarSP || !LocSP)
7427 "mismatched subprogram between #dbg record variable and DILocation",
7429 Loc->getScope()->getSubprogram(), BB,
F);
7434void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
7438 Check(RetTy->getElementCount() == ValTy->getElementCount(),
7439 "VP cast intrinsic first argument and result vector lengths must be "
7443 switch (VPCast->getIntrinsicID()) {
7446 case Intrinsic::vp_trunc:
7448 "llvm.vp.trunc intrinsic first argument and result element type "
7452 "llvm.vp.trunc intrinsic the bit size of first argument must be "
7453 "larger than the bit size of the return type",
7456 case Intrinsic::vp_zext:
7457 case Intrinsic::vp_sext:
7459 "llvm.vp.zext or llvm.vp.sext intrinsic first argument and result "
7460 "element type must be integer",
7463 "llvm.vp.zext or llvm.vp.sext intrinsic the bit size of first "
7464 "argument must be smaller than the bit size of the return type",
7467 case Intrinsic::vp_fptoui:
7468 case Intrinsic::vp_fptosi:
7469 case Intrinsic::vp_lrint:
7470 case Intrinsic::vp_llrint:
7473 "llvm.vp.fptoui, llvm.vp.fptosi, llvm.vp.lrint or llvm.vp.llrint" "intrinsic first argument element "
7474 "type must be floating-point and result element type must be integer",
7477 case Intrinsic::vp_uitofp:
7478 case Intrinsic::vp_sitofp:
7481 "llvm.vp.uitofp or llvm.vp.sitofp intrinsic first argument element "
7482 "type must be integer and result element type must be floating-point",
7485 case Intrinsic::vp_fptrunc:
7487 "llvm.vp.fptrunc intrinsic first argument and result element type "
7488 "must be floating-point",
7491 "llvm.vp.fptrunc intrinsic the bit size of first argument must be "
7492 "larger than the bit size of the return type",
7495 case Intrinsic::vp_fpext:
7497 "llvm.vp.fpext intrinsic first argument and result element type "
7498 "must be floating-point",
7501 "llvm.vp.fpext intrinsic the bit size of first argument must be "
7502 "smaller than the bit size of the return type",
7505 case Intrinsic::vp_ptrtoint:
7507 "llvm.vp.ptrtoint intrinsic first argument element type must be "
7508 "pointer and result element type must be integer",
7511 case Intrinsic::vp_inttoptr:
7513 "llvm.vp.inttoptr intrinsic first argument element type must be "
7514 "integer and result element type must be pointer",
7521 case Intrinsic::vp_fcmp: {
7524 "invalid predicate for VP FP comparison intrinsic", &VPI);
7527 case Intrinsic::vp_icmp: {
7530 "invalid predicate for VP integer comparison intrinsic", &VPI);
7533 case Intrinsic::vp_is_fpclass: {
7536 "unsupported bits for llvm.vp.is.fpclass test mask");
7539 case Intrinsic::experimental_vp_splice: {
7542 int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
7544 AttributeList
Attrs = VPI.
getParent()->getParent()->getAttributes();
7545 if (
Attrs.hasFnAttr(Attribute::VScaleRange))
7546 KnownMinNumElements *=
Attrs.getFnAttrs().getVScaleRangeMin();
7548 Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
7549 (Idx >= 0 && Idx < KnownMinNumElements),
7550 "The splice index exceeds the range [-VL, VL-1] where VL is the "
7551 "known minimum number of elements in the vector. For scalable "
7552 "vectors the minimum number of elements is determined from "
7560void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
7562 bool HasRoundingMD =
7566 NumOperands += (1 + HasRoundingMD);
7572 "invalid arguments for constrained FP intrinsic", &FPI);
7575 case Intrinsic::experimental_constrained_lrint:
7576 case Intrinsic::experimental_constrained_llrint: {
7580 "Intrinsic does not support vectors", &FPI);
7584 case Intrinsic::experimental_constrained_lround:
7585 case Intrinsic::experimental_constrained_llround: {
7589 "Intrinsic does not support vectors", &FPI);
7593 case Intrinsic::experimental_constrained_fcmp:
7594 case Intrinsic::experimental_constrained_fcmps: {
7597 "invalid predicate for constrained FP comparison intrinsic", &FPI);
7601 case Intrinsic::experimental_constrained_fptosi:
7602 case Intrinsic::experimental_constrained_fptoui: {
7606 "Intrinsic first argument must be floating point", &FPI);
7613 "Intrinsic first argument and result disagree on vector use", &FPI);
7615 "Intrinsic result must be an integer", &FPI);
7618 "Intrinsic first argument and result vector lengths must be equal",
7624 case Intrinsic::experimental_constrained_sitofp:
7625 case Intrinsic::experimental_constrained_uitofp: {
7629 "Intrinsic first argument must be integer", &FPI);
7636 "Intrinsic first argument and result disagree on vector use", &FPI);
7638 "Intrinsic result must be a floating point", &FPI);
7641 "Intrinsic first argument and result vector lengths must be equal",
7647 case Intrinsic::experimental_constrained_fptrunc:
7648 case Intrinsic::experimental_constrained_fpext: {
7654 "Intrinsic first argument must be FP or FP vector", &FPI);
7656 "Intrinsic result must be FP or FP vector", &FPI);
7658 "Intrinsic first argument and result disagree on vector use", &FPI);
7662 "Intrinsic first argument and result vector lengths must be equal",
7665 if (FPI.
getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
7667 "Intrinsic first argument's type must be larger than result type",
7671 "Intrinsic first argument's type must be smaller than result type",
7687 "invalid exception behavior argument", &FPI);
7688 if (HasRoundingMD) {
7694void Verifier::verifyFragmentExpression(
const DbgVariableRecord &DVR) {
7699 if (!V || !
E || !
E->isValid())
7703 auto Fragment =
E->getFragmentInfo();
7713 if (
V->isArtificial())
7716 verifyFragmentExpression(*V, *Fragment, &DVR);
7719template <
typename ValueOrMetadata>
7720void Verifier::verifyFragmentExpression(
const DIVariable &V,
7722 ValueOrMetadata *
Desc) {
7725 auto VarSize =
V.getSizeInBits();
7731 CheckDI(FragSize + FragOffset <= *VarSize,
7732 "fragment is larger than or outside of variable",
Desc, &V);
7733 CheckDI(FragSize != *VarSize,
"fragment covers entire variable",
Desc, &V);
7736void Verifier::verifyFnArgs(
const DbgVariableRecord &DVR) {
7748 CheckDI(Var,
"#dbg record without variable");
7750 unsigned ArgNo = Var->
getArg();
7756 if (DebugFnArgs.
size() < ArgNo)
7757 DebugFnArgs.
resize(ArgNo,
nullptr);
7759 auto *Prev = DebugFnArgs[ArgNo - 1];
7760 DebugFnArgs[ArgNo - 1] = Var;
7761 CheckDI(!Prev || (Prev == Var),
"conflicting debug info for argument", &DVR,
7765void Verifier::verifyNotEntryValue(
const DbgVariableRecord &DVR) {
7769 if (!
E || !
E->isValid())
7779 ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
7784 "Entry values are only allowed in MIR unless they target a "
7785 "swiftasync Argument",
7789void Verifier::verifyCompileUnits() {
7793 if (
M.getContext().isODRUniquingDebugTypes())
7795 auto *CUs =
M.getNamedMetadata(
"llvm.dbg.cu");
7796 SmallPtrSet<const Metadata *, 2> Listed;
7799 for (
const auto *CU : CUVisited)
7800 CheckDI(Listed.
count(CU),
"DICompileUnit not listed in llvm.dbg.cu", CU);
7804void Verifier::verifyDeoptimizeCallingConvs() {
7805 if (DeoptimizeDeclarations.
empty())
7809 for (
const auto *
F :
ArrayRef(DeoptimizeDeclarations).slice(1)) {
7810 Check(
First->getCallingConv() ==
F->getCallingConv(),
7811 "All llvm.experimental.deoptimize declarations must have the same "
7812 "calling convention",
7817void Verifier::verifyAttachedCallBundle(
const CallBase &
Call,
7818 const OperandBundleUse &BU) {
7821 Check((FTy->getReturnType()->isPointerTy() ||
7823 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
7824 "function returning a pointer or a non-returning function that has a "
7829 "operand bundle \"clang.arc.attachedcall\" requires one function as "
7837 Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
7838 IID == Intrinsic::objc_claimAutoreleasedReturnValue ||
7839 IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
7840 "invalid function argument",
Call);
7842 StringRef FnName = Fn->
getName();
7843 Check((FnName ==
"objc_retainAutoreleasedReturnValue" ||
7844 FnName ==
"objc_claimAutoreleasedReturnValue" ||
7845 FnName ==
"objc_unsafeClaimAutoreleasedReturnValue"),
7846 "invalid function argument",
Call);
7850void Verifier::verifyNoAliasScopeDecl() {
7851 if (NoAliasScopeDecls.
empty())
7855 for (
auto *
II : NoAliasScopeDecls) {
7856 assert(
II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
7857 "Not a llvm.experimental.noalias.scope.decl ?");
7860 Check(ScopeListMV !=
nullptr,
7861 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
7866 Check(ScopeListMD !=
nullptr,
"!id.scope.list must point to an MDNode",
II);
7867 Check(ScopeListMD->getNumOperands() == 1,
7868 "!id.scope.list must point to a list with a single scope",
II);
7869 visitAliasScopeListMetadata(ScopeListMD);
7879 auto GetScope = [](IntrinsicInst *
II) {
7882 return &
cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
7887 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
7888 return GetScope(Lhs) < GetScope(Rhs);
7895 auto ItCurrent = NoAliasScopeDecls.begin();
7896 while (ItCurrent != NoAliasScopeDecls.end()) {
7897 auto CurScope = GetScope(*ItCurrent);
7898 auto ItNext = ItCurrent;
7901 }
while (ItNext != NoAliasScopeDecls.end() &&
7902 GetScope(*ItNext) == CurScope);
7907 if (ItNext - ItCurrent < 32)
7911 Check(!DT.dominates(
I, J),
7912 "llvm.experimental.noalias.scope.decl dominates another one "
7913 "with the same scope",
7927 Verifier V(OS,
true, *f.getParent());
7931 return !V.verify(
F);
7935 bool *BrokenDebugInfo) {
7937 Verifier V(OS, !BrokenDebugInfo, M);
7939 bool Broken =
false;
7941 Broken |= !V.verify(
F);
7943 Broken |= !V.verify();
7944 if (BrokenDebugInfo)
7945 *BrokenDebugInfo = V.hasBrokenDebugInfo();
7956 std::unique_ptr<Verifier> V;
7957 bool FatalErrors =
true;
7960 explicit VerifierLegacyPass(
bool FatalErrors)
7961 : FunctionPass(
ID), FatalErrors(FatalErrors) {}
7963 bool doInitialization(
Module &M)
override {
7964 V = std::make_unique<Verifier>(
7970 if (!
V->verify(
F) && FatalErrors) {
7971 errs() <<
"in function " <<
F.getName() <<
'\n';
7977 bool doFinalization(
Module &M)
override {
7978 bool HasErrors =
false;
7979 for (Function &
F : M)
7980 if (
F.isDeclaration())
7981 HasErrors |= !
V->verify(
F);
7983 HasErrors |= !
V->verify();
7984 if (FatalErrors && (HasErrors ||
V->hasBrokenDebugInfo()))
7989 void getAnalysisUsage(AnalysisUsage &AU)
const override {
7997template <
typename... Tys>
void TBAAVerifier::CheckFailed(Tys &&... Args) {
7999 return Diagnostic->CheckFailed(
Args...);
8002#define CheckTBAA(C, ...) \
8005 CheckFailed(__VA_ARGS__); \
8013TBAAVerifier::TBAABaseNodeSummary
8017 CheckFailed(
"Base nodes must have at least two operands",
I, BaseNode);
8021 auto Itr = TBAABaseNodes.find(BaseNode);
8022 if (Itr != TBAABaseNodes.end())
8025 auto Result = verifyTBAABaseNodeImpl(
I, BaseNode, IsNewFormat);
8026 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
8028 assert(InsertResult.second &&
"We just checked!");
8032TBAAVerifier::TBAABaseNodeSummary
8033TBAAVerifier::verifyTBAABaseNodeImpl(
const Instruction *
I,
8034 const MDNode *BaseNode,
bool IsNewFormat) {
8035 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {
true, ~0
u};
8039 return isValidScalarTBAANode(BaseNode)
8040 ? TBAAVerifier::TBAABaseNodeSummary({
false, 0})
8046 CheckFailed(
"Access tag nodes must have the number of operands that is a "
8047 "multiple of 3!", BaseNode);
8052 CheckFailed(
"Struct tag nodes must have an odd number of operands!",
8062 if (!TypeSizeNode) {
8063 CheckFailed(
"Type size nodes must be constants!",
I, BaseNode);
8070 CheckFailed(
"Struct tag nodes have a string as their first operand",
8077 std::optional<APInt> PrevOffset;
8082 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8083 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8084 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
8085 Idx += NumOpsPerField) {
8086 const MDOperand &FieldTy = BaseNode->
getOperand(Idx);
8087 const MDOperand &FieldOffset = BaseNode->
getOperand(Idx + 1);
8089 CheckFailed(
"Incorrect field entry in struct type node!",
I, BaseNode);
8094 auto *OffsetEntryCI =
8096 if (!OffsetEntryCI) {
8097 CheckFailed(
"Offset entries must be constants!",
I, BaseNode);
8103 BitWidth = OffsetEntryCI->getBitWidth();
8105 if (OffsetEntryCI->getBitWidth() !=
BitWidth) {
8107 "Bitwidth between the offsets and struct type entries must match",
I,
8119 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
8122 CheckFailed(
"Offsets must be increasing!",
I, BaseNode);
8126 PrevOffset = OffsetEntryCI->getValue();
8131 if (!MemberSizeNode) {
8132 CheckFailed(
"Member size entries must be constants!",
I, BaseNode);
8139 return Failed ? InvalidNode
8140 : TBAAVerifier::TBAABaseNodeSummary(
false,
BitWidth);
8162 return Parent && Visited.
insert(Parent).second &&
8166bool TBAAVerifier::isValidScalarTBAANode(
const MDNode *MD) {
8167 auto ResultIt = TBAAScalarNodes.find(MD);
8168 if (ResultIt != TBAAScalarNodes.end())
8169 return ResultIt->second;
8171 SmallPtrSet<const MDNode *, 4> Visited;
8173 auto InsertResult = TBAAScalarNodes.insert({MD,
Result});
8175 assert(InsertResult.second &&
"Just checked!");
8184MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(
const Instruction *
I,
8185 const MDNode *BaseNode,
8196 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8197 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8198 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
8199 Idx += NumOpsPerField) {
8200 auto *OffsetEntryCI =
8202 if (OffsetEntryCI->getValue().ugt(
Offset)) {
8203 if (Idx == FirstFieldOpNo) {
8204 CheckFailed(
"Could not find TBAA parent in struct type node",
I,
8209 unsigned PrevIdx = Idx - NumOpsPerField;
8210 auto *PrevOffsetEntryCI =
8212 Offset -= PrevOffsetEntryCI->getValue();
8220 Offset -= LastOffsetEntryCI->getValue();
8225 if (!
Type ||
Type->getNumOperands() < 3)
8241 "This instruction shall not have a TBAA access tag!",
I);
8243 bool IsStructPathTBAA =
8247 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
8257 "Access tag metadata must have either 4 or 5 operands",
I, MD);
8260 "Struct tag metadata must have either 3 or 4 operands",
I, MD);
8267 CheckTBAA(AccessSizeNode,
"Access size field must be a constant",
I, MD);
8271 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
8276 "Immutability tag on struct tag metadata must be a constant",
I,
8279 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
8280 "Immutability part of the struct tag metadata must be either 0 or 1",
I,
8285 "Malformed struct tag metadata: base and access-type "
8286 "should be non-null and point to Metadata nodes",
8287 I, MD, BaseNode, AccessType);
8290 CheckTBAA(isValidScalarTBAANode(AccessType),
8291 "Access type node must be a valid scalar type",
I, MD,
8296 CheckTBAA(OffsetCI,
"Offset must be constant integer",
I, MD);
8299 bool SeenAccessTypeInPath =
false;
8305 getFieldNodeFromTBAABaseNode(
I, BaseNode,
Offset, IsNewFormat)) {
8306 if (!StructPath.
insert(BaseNode).second) {
8307 CheckFailed(
"Cycle detected in struct path",
I, MD);
8312 unsigned BaseNodeBitWidth;
8313 std::tie(
Invalid, BaseNodeBitWidth) =
8314 verifyTBAABaseNode(
I, BaseNode, IsNewFormat);
8321 SeenAccessTypeInPath |= BaseNode == AccessType;
8323 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
8328 (BaseNodeBitWidth == 0 &&
Offset == 0) ||
8329 (IsNewFormat && BaseNodeBitWidth == ~0u),
8330 "Access bit-width not the same as description bit-width",
I, MD,
8331 BaseNodeBitWidth,
Offset.getBitWidth());
8333 if (IsNewFormat && SeenAccessTypeInPath)
8337 CheckTBAA(SeenAccessTypeInPath,
"Did not see access type in access path!",
I,
8342char VerifierLegacyPass::ID = 0;
8343INITIALIZE_PASS(VerifierLegacyPass,
"verify",
"Module Verifier",
false,
false)
8346 return new VerifierLegacyPass(FatalErrors);
8364 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
8372 if (res.IRBroken && FatalErrors)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU address space definition.
ArrayRef< TableEntry > TableRef
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericConvergenceVerifier template.
static DISubprogram * getSubprogram(bool IsDistinct, Ts &&...Args)
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
static bool runOnFunction(Function &F, bool PostInlining)
This file contains the declarations of entities that describe floating point environment and related ...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
static unsigned getNumElements(Type *Ty)
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
verify safepoint Safepoint IR Verifier
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static bool IsScalarTBAANodeImpl(const MDNode *MD, SmallPtrSetImpl< const MDNode * > &Visited)
static bool isType(const Metadata *MD)
static Instruction * getSuccPad(Instruction *Terminator)
static bool isMDTuple(const Metadata *MD)
static bool isNewFormatTBAATypeNode(llvm::MDNode *Type)
#define CheckDI(C,...)
We know that a debug info condition should be true, if not print an error message.
static void forEachUser(const Value *User, SmallPtrSet< const Value *, 32 > &Visited, llvm::function_ref< bool(const Value *)> Callback)
static bool isDINode(const Metadata *MD)
static bool isScope(const Metadata *MD)
static cl::opt< bool > VerifyNoAliasScopeDomination("verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false), cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical " "scopes are not dominating"))
static bool isTypeCongruent(Type *L, Type *R)
Two types are "congruent" if they are identical, or if they are both pointer types with different poi...
static bool isConstantIntMetadataOperand(const Metadata *MD)
static bool IsRootTBAANode(const MDNode *MD)
static Value * getParentPad(Value *EHPad)
static bool hasConflictingReferenceFlags(unsigned Flags)
Detect mutually exclusive flags.
static AttrBuilder getParameterABIAttributes(LLVMContext &C, unsigned I, AttributeList Attrs)
static const char PassName[]
static LLVM_ABI bool isValidArbitraryFPFormat(StringRef Format)
Returns true if the given string is a valid arbitrary floating-point format interpretation for llvm....
bool isFiniteNonZero() const
const fltSemantics & getSemantics() const
Class for arbitrary precision integers.
bool sgt(const APInt &RHS) const
Signed greater than comparison.
bool isMinValue() const
Determine if this is the smallest unsigned value.
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
int64_t getSExtValue() const
Get sign extended value.
bool isMaxValue() const
Determine if this is the largest unsigned value.
This class represents a conversion between pointers from one address space to another.
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
unsigned getAddressSpace() const
Return the address space for the allocation.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
const Value * getArraySize() const
Get the number of elements allocated.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVM_ABI bool hasInRegAttr() const
Return true if this argument has the inreg attribute.
bool empty() const
empty - Check if the array is empty.
static bool isFPOperation(BinOp Op)
BinOp getOperation() const
static LLVM_ABI StringRef getOperationName(BinOp Op)
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
LLVM_ABI std::string getAsString(bool InAttrGrp=false) const
Functions, function parameters, and return types can have attributes to indicate how they should be t...
LLVM_ABI const ConstantRange & getValueAsConstantRange() const
Return the attribute's value as a ConstantRange.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
bool isValid() const
Return true if the attribute is any kind of attribute.
LLVM_ABI Type * getValueAsType() const
Return the attribute's value as a Type.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
const Instruction & front() const
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
This class represents a no-op cast from one type to another.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isInlineAsm() const
Check if this call is an inline asm statement.
bool hasInAllocaArgument() const
Determine if there are is an inalloca argument.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool doesNotAccessMemory(unsigned OpNo) const
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Get the attribute of a given kind from a given arg.
iterator_range< bundle_op_iterator > bundle_op_infos()
Return the range [bundle_op_info_begin, bundle_op_info_end).
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Type * getParamElementType(unsigned ArgNo) const
Extract the elementtype type for a parameter.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
bool doesNotReturn() const
Determine if the call cannot return.
LLVM_ABI bool onlyAccessesArgMemory() const
Determine if the call can access memmory only using pointers based on its arguments.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
BasicBlock * getIndirectDest(unsigned i) const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
bool isMustTailCall() const
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
unsigned getNumHandlers() const
return the number of 'handlers' in this catchswitch instruction, except the default handler
Value * getParentPad() const
BasicBlock * getUnwindDest() const
handler_range handlers()
iteration adapter for range-for loops.
BasicBlock * getUnwindDest() const
bool isFPPredicate() const
bool isIntPredicate() const
static bool isIntPredicate(Predicate P)
Value * getCondition() const
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
const APInt & getValue() const
Return the constant as an APInt value reference.
Constant * getAddrDiscriminator() const
The address discriminator if any, or the null constant.
Constant * getPointer() const
The pointer that is signed in this ptrauth signed pointer.
ConstantInt * getKey() const
The Key ID, an i32 constant.
Constant * getDeactivationSymbol() const
ConstantInt * getDiscriminator() const
The integer discriminator, an i64 constant, or 0.
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
LLVM_ABI bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI std::optional< RoundingMode > getRoundingMode() const
LLVM_ABI unsigned getNonMetadataArgCount() const
DbgVariableFragmentInfo FragmentInfo
@ FixedPointBinary
Scale factor 2^Factor.
@ FixedPointDecimal
Scale factor 10^Factor.
@ FixedPointRational
Arbitrary rational scale factor.
DIGlobalVariable * getVariable() const
DIExpression * getExpression() const
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
DILocalScope * getScope() const
Get the local scope for this variable.
Metadata * getRawScope() const
Base class for scope-like contexts.
Subprogram description. Uses SubclassData1.
static const DIScope * getRawRetainedNodeScope(const MDNode *N)
Base class for template parameters.
Base class for variables.
Metadata * getRawType() const
Metadata * getRawScope() const
uint64_t getNumOperands() const
A parsed version of the target data layout string in and methods for querying it.
Records a position in IR for a source label (DILabel).
MDNode * getRawLabel() const
DILabel * getLabel() const
Base class for non-instruction debug metadata records that have positions within IR.
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
DebugLoc getDebugLoc() const
LLVM_ABI const BasicBlock * getParent() const
LLVM_ABI Function * getFunction()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LocationType getType() const
MDNode * getRawExpression() const
MDNode * getRawAddressExpression() const
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
DIExpression * getExpression() const
Metadata * getRawAssignID() const
MDNode * getRawVariable() const
DILocalVariable * getVariable() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
bool isDbgDeclare() const
Metadata * getRawAddress() const
@ End
Marks the end of the concrete types.
@ Any
To indicate all LocationTypes in searches.
DIExpression * getAddressExpression() const
MDNode * getAsMDNode() const
Return this as a bar MDNode.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
This instruction compares its operands according to the predicate given to the constructor.
This class represents an extension of floating point types.
This class represents a cast from floating point to signed integer.
This class represents a cast from floating point to unsigned integer.
This class represents a truncation of floating point types.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
Value * getParentPad() const
Convenience accessors.
FunctionPass class - This class is used to implement most global optimizations.
Type * getReturnType() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
DISubprogram * getSubprogram() const
Get the attached subprogram.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
bool hasPersonalityFn() const
Check whether this function has a personality function.
const Function & getFunction() const
const std::string & getGC() const
Type * getReturnType() const
Returns the type of the ret val.
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
LLVM_ABI Value * getBasePtr() const
LLVM_ABI Value * getDerivedPtr() const
void visit(const BlockT &BB)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
const Constant * getAliasee() const
LLVM_ABI const Function * getResolverFunction() const
static bool isValidLinkage(LinkageTypes L)
const Constant * getResolver() const
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
bool hasExternalLinkage() const
bool isImplicitDSOLocal() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
bool hasValidDeclarationLinkage() const
LinkageTypes getLinkage() const
bool hasDefaultVisibility() const
bool hasPrivateLinkage() const
bool hasHiddenVisibility() const
bool hasExternalWeakLinkage() const
bool hasDLLImportStorageClass() const
bool hasDLLExportStorageClass() const
bool isDeclarationForLinker() const
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
LLVM_ABI bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
bool hasCommonLinkage() const
bool hasGlobalUnnamedAddr() const
bool hasAppendingLinkage() const
bool hasAvailableExternallyLinkage() const
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
BasicBlock * getDestination(unsigned i)
Return the specified destination.
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
unsigned getNumSuccessors() const
This instruction inserts a single (scalar) element into a VectorType value.
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
Value * getAggregateOperand()
ArrayRef< unsigned > getIndices() const
Base class for instruction visitors.
void visit(Iterator Start, Iterator End)
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
This class represents a cast from an integer to a pointer.
static LLVM_ABI bool mayLowerToFunctionCall(Intrinsic::ID IID)
Check if the intrinsic might lower into a regular function call in the course of IR transformations.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
@ OB_clang_arc_attachedcall
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
Align getAlign() const
Return the alignment of the access that is being performed.
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
unsigned getNumOperands() const
Return number of MDNode operands.
bool isResolved() const
Check if node is fully resolved.
LLVMContext & getContext() const
bool equalsStr(StringRef Str) const
LLVM_ABI StringRef getString() const
This class implements a map that also provides access to all stored values in a deterministic order.
Manage lifetime of a slot tracker for printing IR.
A Module instance is used to store all the information related to an LLVM module.
LLVM_ABI StringRef getName() const
LLVM_ABI void print(raw_ostream &ROS, bool IsForDebug=false) const
LLVM_ABI unsigned getNumOperands() const
iterator_range< op_iterator > operands()
op_range incoming_values()
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
This class represents a cast from a pointer to an address (non-capturing ptrtoint).
This class represents a cast from a pointer to an integer.
Value * getValue() const
Convenience accessor.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents a sign extension of integer types.
This class represents a cast from signed integer to floating point.
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
This instruction constructs a fixed permutation of two input vectors.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void reserve(size_type N)
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
static constexpr size_t npos
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
empty - Check if the string is empty.
unsigned getNumElements() const
Random access to the elements.
LLVM_ABI Type * getTypeAtIndex(const Value *V) const
Given an index value into the type, return the type of the element.
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Verify that the TBAA Metadatas are valid.
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
Triple - Helper class for working with autoconf configuration names.
This class represents a truncation of integer types.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
bool isByteTy() const
True if this is an instance of ByteType.
bool isVectorTy() const
True if this is an instance of VectorType.
LLVM_ABI bool containsNonGlobalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a global...
bool isArrayTy() const
True if this is an instance of ArrayType.
LLVM_ABI bool containsNonLocalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a local.
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
LLVM_ABI bool isTokenLikeTy() const
Returns true if this is 'token' or a token-like target type.s.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
LLVM_ABI bool canLosslesslyBitCastTo(Type *Ty) const
Return true if this type could be converted with a lossless BitCast to type 'Ty'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
This class represents a cast unsigned integer to floating point.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
iterator_range< user_iterator > materialized_users()
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
iterator_range< user_iterator > users()
bool materialized_use_empty() const
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Check a module for errors, and report separate error states for IR and debug info errors.
LLVM_ABI Result run(Module &M, ModuleAnalysisManager &)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
This class represents zero extension of integer types.
constexpr bool isNonZero() const
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
This class implements an extremely fast bulk output stream that can only output to a stream.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ FLAT_ADDRESS
Address space for flat memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
@ PRIVATE_ADDRESS
Address space for private memory.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
bool isFlatGlobalAddrSpace(unsigned AS)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
@ BasicBlock
Various leaf nodes.
LLVM_ABI MatchIntrinsicTypesResult matchIntrinsicSignature(FunctionType *FTy, ArrayRef< IITDescriptor > &Infos, SmallVectorImpl< Type * > &ArgTys)
Match the specified function type with the type constraints specified by the .td file.
LLVM_ABI void getIntrinsicInfoTableEntries(ID id, SmallVectorImpl< IITDescriptor > &T)
Return the IIT table descriptor for the specified intrinsic into an array of IITDescriptors.
MatchIntrinsicTypesResult
@ MatchIntrinsicTypes_NoMatchRet
@ MatchIntrinsicTypes_NoMatchArg
LLVM_ABI bool hasConstrainedFPRoundingModeOperand(ID QID)
Returns true if the intrinsic ID is for one of the "ConstrainedFloating-Point Intrinsics" that take r...
LLVM_ABI StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
static const int NoAliasScopeDeclScopeArg
LLVM_ABI bool matchIntrinsicVarArg(bool isVarArg, ArrayRef< IITDescriptor > &Infos)
Verify if the intrinsic has variable arguments.
std::variant< std::monostate, Loc::Single, Loc::Multi, Loc::MMI, Loc::EntryValue > Variant
Alias for the std::variant specialization base class of DbgVariable.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
LLVM_ABI std::optional< VFInfo > tryDemangleForVFABI(StringRef MangledName, const FunctionType *FTy)
Function to construct a VFInfo out of a mangled names in the following format:
@ CE
Windows NT (Windows on ARM)
LLVM_ABI AssignmentInstRange getAssignmentInsts(DIAssignID *ID)
Return a range of instructions (typically just one) that have ID as an attachment.
initializer< Ty > init(const Ty &Val)
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
NodeAddr< NodeBase * > Node
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
FunctionAddr VTableAddr Value
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool canInstructionHaveMMRAs(const Instruction &I)
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
testing::Matcher< const detail::ErrorHolder & > Failed()
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
LLVM_ABI DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
gep_type_iterator gep_type_end(const User *GEP)
bool isa_and_nonnull(const Y &Val)
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
auto dyn_cast_or_null(const Y &Val)
GenericConvergenceVerifier< SSAContext > ConvergenceVerifier
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
bool isModSet(const ModRefInfo MRI)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
generic_gep_type_iterator<> gep_type_iterator
FunctionAddr VTableAddr Count
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI bool isValueProfileMD(const MDNode *ProfileData)
Checks if an MDNode contains value profiling Metadata.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI unsigned getNumBranchWeights(const MDNode &ProfileData)
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
LLVM_ABI FunctionPass * createVerifierPass(bool FatalErrors=true)
FunctionAddr VTableAddr Next
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
TinyPtrVector< BasicBlock * > ColorVector
LLVM_ABI const char * LLVMLoopEstimatedTripCount
Profile-based loop metadata that should be accessed only by using llvm::getLoopEstimatedTripCount and...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI std::optional< RoundingMode > convertStrToRoundingMode(StringRef)
Returns a valid RoundingMode enumerator when given a string that is valid as input in constrained int...
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI std::unique_ptr< GCStrategy > getGCStrategy(const StringRef Name)
Lookup the GCStrategy object associated with the given gc name.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
bool pred_empty(const BasicBlock *BB)
bool isHexDigit(char C)
Checks if character C is a hexadecimal numeric character.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
constexpr bool isCallableCC(CallingConv::ID CC)
LLVM_ABI bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
A special type used by analysis passes to provide an address that identifies that particular analysis...
static LLVM_ABI const char * SyntheticFunctionEntryCount
static LLVM_ABI const char * UnknownBranchWeightsMarker
static LLVM_ABI const char * ValueProfile
static LLVM_ABI const char * FunctionEntryCount
static LLVM_ABI const char * BranchWeights
uint32_t getTagID() const
Return the tag of this operand bundle as an integer.
void DebugInfoCheckFailed(const Twine &Message)
A debug info check failed.
VerifierSupport(raw_ostream *OS, const Module &M)
bool Broken
Track the brokenness of the module while recursively visiting.
void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs)
A check failed (with values to print).
bool BrokenDebugInfo
Broken debug info can be "recovered" from by stripping the debug info.
bool TreatBrokenDebugInfoAsError
Whether to treat broken debug info as an error.
void CheckFailed(const Twine &Message)
A check failed, so printout out the condition and the message.
void DebugInfoCheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs)
A debug info check failed (with values to print).