99#include "llvm/IR/IntrinsicsAArch64.h"
100#include "llvm/IR/IntrinsicsARM.h"
101#include "llvm/IR/IntrinsicsNVPTX.h"
102#include "llvm/IR/IntrinsicsRISCV.h"
103#include "llvm/IR/IntrinsicsWebAssembly.h"
147 cl::desc(
"Ensure that llvm.experimental.noalias.scope.decl for identical "
148 "scopes are not dominating"));
173 Type *LandingPadResultTy;
180 bool HasDebugInfo =
false;
223 SawFrameEscape(
false), TBAAVerifyHelper(this) {
224 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
227 bool hasBrokenDebugInfo()
const {
return BrokenDebugInfo; }
230 llvm::TimeTraceScope timeScope(
"Verifier");
232 "An instance of this class only works with a specific module!");
242 for (
const BasicBlock &BB :
F) {
243 if (!BB.empty() && BB.back().isTerminator())
247 *OS <<
"Basic Block in function '" <<
F.getName()
248 <<
"' does not have terminator!\n";
249 BB.printAsOperand(*OS,
true, MST);
257 DT.recalculate(
const_cast<Function &
>(
F));
259 auto FailureCB = [
this](
const Twine &Message) {
260 this->CheckFailed(Message);
262 ConvergenceVerifyHelper.initialize(OS, FailureCB,
F);
267 verifySiblingFuncletUnwinds();
269 if (ConvergenceVerifyHelper.sawTokens())
270 ConvergenceVerifyHelper.verify(DT);
272 InstsInThisBlock.clear();
274 LandingPadResultTy =
nullptr;
275 SawFrameEscape =
false;
276 SiblingFuncletInfo.clear();
277 verifyNoAliasScopeDecl();
278 NoAliasScopeDecls.clear();
289 if (
F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
290 DeoptimizeDeclarations.push_back(&
F);
294 verifyFrameRecoverIndices();
295 for (
const GlobalVariable &GV :
M.globals())
296 visitGlobalVariable(GV);
298 for (
const GlobalAlias &GA :
M.aliases())
299 visitGlobalAlias(GA);
301 for (
const GlobalIFunc &GI :
M.ifuncs())
302 visitGlobalIFunc(GI);
304 for (
const NamedMDNode &NMD :
M.named_metadata())
305 visitNamedMDNode(NMD);
307 for (
const StringMapEntry<Comdat> &SMEC :
M.getComdatSymbolTable())
308 visitComdat(SMEC.getValue());
312 visitModuleCommandLines();
313 visitModuleErrnoTBAA();
315 verifyCompileUnits();
317 verifyDeoptimizeCallingConvs();
318 DISubprogramAttachments.clear();
324 enum class AreDebugLocsAllowed {
No,
Yes };
328 enum class RangeLikeMetadataKind {
335 void visitGlobalValue(
const GlobalValue &GV);
336 void visitGlobalVariable(
const GlobalVariable &GV);
337 void visitGlobalAlias(
const GlobalAlias &GA);
338 void visitGlobalIFunc(
const GlobalIFunc &GI);
339 void visitAliaseeSubExpr(
const GlobalAlias &
A,
const Constant &
C);
340 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
341 const GlobalAlias &
A,
const Constant &
C);
342 void visitNamedMDNode(
const NamedMDNode &NMD);
343 void visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs);
344 void visitMetadataAsValue(
const MetadataAsValue &MD,
Function *
F);
345 void visitValueAsMetadata(
const ValueAsMetadata &MD,
Function *
F);
346 void visitDIArgList(
const DIArgList &AL,
Function *
F);
347 void visitComdat(
const Comdat &
C);
348 void visitModuleIdents();
349 void visitModuleCommandLines();
350 void visitModuleErrnoTBAA();
351 void visitModuleFlags();
352 void visitModuleFlag(
const MDNode *
Op,
353 DenseMap<const MDString *, const MDNode *> &SeenIDs,
354 SmallVectorImpl<const MDNode *> &Requirements);
355 void visitModuleFlagCGProfileEntry(
const MDOperand &MDO);
357 void visitBasicBlock(BasicBlock &BB);
358 void verifyRangeLikeMetadata(
const Value &V,
const MDNode *
Range,
Type *Ty,
359 RangeLikeMetadataKind Kind);
360 void visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
361 void visitNoFPClassMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
362 void visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
363 void visitDereferenceableMetadata(Instruction &
I, MDNode *MD);
364 void visitNoFreeObjMetadata(Instruction &
I, MDNode *MD);
365 void visitProfMetadata(Instruction &
I, MDNode *MD);
366 void visitCallStackMetadata(MDNode *MD);
367 void visitMemProfMetadata(Instruction &
I, MDNode *MD);
368 void visitCallsiteMetadata(Instruction &
I, MDNode *MD);
369 void visitCalleeTypeMetadata(Instruction &
I, MDNode *MD);
370 void visitDIAssignIDMetadata(Instruction &
I, MDNode *MD);
371 void visitMMRAMetadata(Instruction &
I, MDNode *MD);
372 void visitAnnotationMetadata(MDNode *Annotation);
373 void visitAliasScopeMetadata(
const MDNode *MD);
374 void visitAliasScopeListMetadata(
const MDNode *MD);
375 void visitAccessGroupMetadata(
const MDNode *MD);
376 void visitCapturesMetadata(Instruction &
I,
const MDNode *Captures);
377 void visitAllocTokenMetadata(Instruction &
I, MDNode *MD);
378 void visitInlineHistoryMetadata(Instruction &
I, MDNode *MD);
379 void visitMemCacheHintMetadata(Instruction &
I, MDNode *MD);
381#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
382#include "llvm/IR/Metadata.def"
383 void visitDIType(
const DIType &
N);
384 void visitDIScope(
const DIScope &
N);
408 void checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V);
413 void visitPHINode(
PHINode &PN);
422 void visitVAArgInst(
VAArgInst &VAA) { visitInstruction(VAA); }
423 void visitCallInst(CallInst &CI);
424 void visitInvokeInst(InvokeInst &
II);
425 void visitGetElementPtrInst(GetElementPtrInst &
GEP);
426 void visitLoadInst(LoadInst &LI);
427 void visitStoreInst(StoreInst &SI);
428 void verifyDominatesUse(Instruction &
I,
unsigned i);
429 void visitInstruction(Instruction &
I);
430 void visitTerminator(Instruction &
I);
431 void visitCondBrInst(CondBrInst &BI);
432 void visitReturnInst(ReturnInst &RI);
433 void visitSwitchInst(SwitchInst &SI);
434 void visitIndirectBrInst(IndirectBrInst &BI);
435 void visitCallBrInst(CallBrInst &CBI);
436 void visitSelectInst(SelectInst &SI);
437 void visitUserOp1(Instruction &
I);
438 void visitUserOp2(Instruction &
I) { visitUserOp1(
I); }
440 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
441 void visitVPIntrinsic(VPIntrinsic &VPI);
442 void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
443 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
444 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
445 void visitFenceInst(FenceInst &FI);
446 void visitAllocaInst(AllocaInst &AI);
447 void visitExtractValueInst(ExtractValueInst &EVI);
448 void visitInsertValueInst(InsertValueInst &IVI);
449 void visitEHPadPredecessors(Instruction &
I);
450 void visitLandingPadInst(LandingPadInst &LPI);
451 void visitResumeInst(ResumeInst &RI);
452 void visitCatchPadInst(CatchPadInst &CPI);
453 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
454 void visitCleanupPadInst(CleanupPadInst &CPI);
455 void visitFuncletPadInst(FuncletPadInst &FPI);
456 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
457 void visitCleanupReturnInst(CleanupReturnInst &CRI);
459 void verifySwiftErrorCall(CallBase &
Call,
const Value *SwiftErrorVal);
460 void verifySwiftErrorValue(
const Value *SwiftErrorVal);
461 void verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs, StringRef
Context);
462 void verifyMustTailCall(CallInst &CI);
463 bool verifyAttributeCount(AttributeList Attrs,
unsigned Params);
464 void verifyAttributeTypes(AttributeSet Attrs,
const Value *V);
465 void verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
const Value *V);
466 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
468 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
469 const Value *V,
bool IsIntrinsic,
bool IsInlineAsm);
470 void verifyFunctionMetadata(
ArrayRef<std::pair<unsigned, MDNode *>> MDs);
471 void verifyUnknownProfileMetadata(MDNode *MD);
472 void visitConstantExprsRecursively(
const Constant *EntryC);
473 void visitConstantExpr(
const ConstantExpr *CE);
474 void visitConstantPtrAuth(
const ConstantPtrAuth *CPA);
475 void verifyInlineAsmCall(
const CallBase &
Call);
476 void verifyStatepoint(
const CallBase &
Call);
477 void verifyFrameRecoverIndices();
478 void verifySiblingFuncletUnwinds();
480 void verifyFragmentExpression(
const DbgVariableRecord &
I);
481 template <
typename ValueOrMetadata>
482 void verifyFragmentExpression(
const DIVariable &V,
484 ValueOrMetadata *
Desc);
485 void verifyFnArgs(
const DbgVariableRecord &DVR);
486 void verifyNotEntryValue(
const DbgVariableRecord &
I);
489 void verifyCompileUnits();
493 void verifyDeoptimizeCallingConvs();
495 void verifyAttachedCallBundle(
const CallBase &
Call,
496 const OperandBundleUse &BU);
499 void verifyNoAliasScopeDecl();
505#define Check(C, ...) \
508 CheckFailed(__VA_ARGS__); \
515#define CheckDI(C, ...) \
518 DebugInfoCheckFailed(__VA_ARGS__); \
526 CheckDI(
I.DebugMarker->MarkedInstr == &
I,
527 "Instruction has invalid DebugMarker", &
I);
529 "PHI Node must not have any attached DbgRecords", &
I);
531 CheckDI(DR.getMarker() ==
I.DebugMarker,
532 "DbgRecord had invalid DebugMarker", &
I, &DR);
535 visitMDNode(*
Loc, AreDebugLocsAllowed::Yes);
540 verifyFragmentExpression(*DVR);
541 verifyNotEntryValue(*DVR);
548void Verifier::visit(Instruction &
I) {
550 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i)
551 Check(
I.getOperand(i) !=
nullptr,
"Operand is null", &
I);
563 while (!WorkList.
empty()) {
565 if (!Visited.
insert(Cur).second)
572void Verifier::visitGlobalValue(
const GlobalValue &GV) {
574 "Global is external, but doesn't have external or weak linkage!", &GV);
577 if (
const MDNode *Associated =
578 GO->getMetadata(LLVMContext::MD_associated)) {
579 Check(Associated->getNumOperands() == 1,
580 "associated metadata must have one operand", &GV, Associated);
581 const Metadata *
Op = Associated->getOperand(0).get();
582 Check(
Op,
"associated metadata must have a global value", GO, Associated);
585 Check(VM,
"associated metadata must be ValueAsMetadata", GO, Associated);
588 "associated value must be pointer typed", GV, Associated);
590 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
592 "associated metadata must point to a GlobalObject", GO, Stripped);
593 Check(Stripped != GO,
594 "global values should not associate to themselves", GO,
600 if (
const MDNode *AbsoluteSymbol =
601 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
602 verifyRangeLikeMetadata(*GO, AbsoluteSymbol,
603 DL.getIntPtrType(GO->getType()),
604 RangeLikeMetadataKind::AbsoluteSymbol);
607 if (GO->hasMetadata(LLVMContext::MD_implicit_ref)) {
608 Check(!GO->isDeclaration(),
609 "ref metadata must not be placed on a declaration", GO);
612 GO->getMetadata(LLVMContext::MD_implicit_ref, MDs);
613 for (
const MDNode *MD : MDs) {
614 Check(MD->getNumOperands() == 1,
"ref metadata must have one operand",
618 Check(VM,
"ref metadata must be ValueAsMetadata", GO, MD);
621 "ref value must be pointer typed", GV, MD);
625 "ref metadata must point to a GlobalObject", GO, Stripped);
626 Check(Stripped != GO,
"values should not reference themselves", GO,
632 if (
auto *Props = GO->getMetadata(LLVMContext::MD_elf_section_properties)) {
633 Check(Props->getNumOperands() == 2,
634 "elf_section_properties metadata must have two operands", GO,
636 if (Props->getNumOperands() == 2) {
638 Check(
Type,
"type field must be ConstantAsMetadata", GO, Props);
640 Check(TypeInt,
"type field must be ConstantInt", GO, Props);
643 Check(Entsize,
"entsize field must be ConstantAsMetadata", GO, Props);
645 Check(EntsizeInt,
"entsize field must be ConstantInt", GO, Props);
651 "Only global variables can have appending linkage!", &GV);
655 Check(GVar && GVar->getValueType()->isArrayTy(),
656 "Only global arrays can have appending linkage!", GVar);
660 Check(!GV.
hasComdat(),
"Declaration may not be in a Comdat!", &GV);
664 "dllexport GlobalValue must have default or protected visibility",
669 "dllimport GlobalValue must have default visibility", &GV);
670 Check(!GV.
isDSOLocal(),
"GlobalValue with DLLImport Storage is dso_local!",
676 "Global is marked as dllimport, but not external", &GV);
681 "GlobalValue with local linkage or non-default "
682 "visibility must be dso_local!",
687 if (!
I->getParent() || !
I->getParent()->getParent())
688 CheckFailed(
"Global is referenced by parentless instruction!", &GV, &M,
690 else if (
I->getParent()->getParent()->getParent() != &M)
691 CheckFailed(
"Global is referenced in a different module!", &GV, &M,
I,
692 I->getParent()->getParent(),
693 I->getParent()->getParent()->getParent());
696 if (
F->getParent() != &M)
697 CheckFailed(
"Global is used by function in a different module", &GV, &M,
705void Verifier::visitGlobalVariable(
const GlobalVariable &GV) {
709 Check(
A->value() <= Value::MaximumAlignment,
710 "huge alignment values are unsupported", &GV);
715 "Global variable initializer type does not match global "
719 "Global variable initializer must be sized", &GV);
725 "'common' global must have a zero initializer!", &GV);
728 Check(!GV.
hasComdat(),
"'common' global may not be in a Comdat!", &GV);
733 GV.
getName() ==
"llvm.global_dtors")) {
735 "invalid linkage for intrinsic global variable", &GV);
737 "invalid uses of intrinsic global variable", &GV);
744 PointerType::get(
Context,
DL.getProgramAddressSpace());
745 Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
746 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
747 STy->getTypeAtIndex(1) == FuncPtrTy,
748 "wrong type for intrinsic global variable", &GV);
749 Check(STy->getNumElements() == 3,
750 "the third field of the element type is mandatory, "
751 "specify ptr null to migrate from the obsoleted 2-field form");
752 Type *ETy = STy->getTypeAtIndex(2);
761 for (
const Use &U : Init->operands()) {
763 if (!Structor || Structor->getNumOperands() != 3)
766 "signing of ctors/dtors should be requested via module flags");
772 GV.
getName() ==
"llvm.compiler.used")) {
774 "invalid linkage for intrinsic global variable", &GV);
776 "invalid uses of intrinsic global variable", &GV);
780 Check(PTy,
"wrong type for intrinsic global variable", &GV);
784 Check(InitArray,
"wrong initializer for intrinsic global variable",
786 for (
Value *
Op : InitArray->operands()) {
790 Twine(
"invalid ") + GV.
getName() +
" member", V);
792 Twine(
"members of ") + GV.
getName() +
" must be named", V);
801 for (MDNode *MD : MDs) {
803 visitDIGlobalVariableExpression(*GVE);
805 CheckDI(
false,
"!dbg attachment of global variable must be a "
806 "DIGlobalVariableExpression");
816 "Global @" + GV.
getName() +
" has illegal target extension type",
825 "Global variable is too large to fit into the address space", &GV,
829 visitGlobalValue(GV);
836 visitGlobalValue(GV);
839void Verifier::visitAliaseeSubExpr(
const GlobalAlias &GA,
const Constant &
C) {
840 SmallPtrSet<const GlobalAlias*, 4> Visited;
842 visitAliaseeSubExpr(Visited, GA,
C);
845void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
846 const GlobalAlias &GA,
const Constant &
C) {
850 "available_externally alias must point to available_externally "
861 Check(Visited.
insert(GA2).second,
"Aliases cannot form a cycle", &GA);
863 Check(!GA2->isInterposable(),
864 "Alias cannot point to an interposable alias", &GA);
873 visitConstantExprsRecursively(CE);
875 for (
const Use &U :
C.operands()) {
878 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
880 visitAliaseeSubExpr(Visited, GA, *C2);
884void Verifier::visitGlobalAlias(
const GlobalAlias &GA) {
886 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
887 "weak_odr, external, or available_externally linkage!",
890 Check(Aliasee,
"Aliasee cannot be NULL!", &GA);
892 "Alias and aliasee types should match!", &GA);
895 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
897 visitAliaseeSubExpr(GA, *Aliasee);
899 visitGlobalValue(GA);
902void Verifier::visitGlobalIFunc(
const GlobalIFunc &GI) {
903 visitGlobalValue(GI);
907 for (
const auto &
I : MDs) {
908 CheckDI(
I.first != LLVMContext::MD_dbg,
909 "an ifunc may not have a !dbg attachment", &GI);
910 Check(
I.first != LLVMContext::MD_prof,
911 "an ifunc may not have a !prof attachment", &GI);
912 visitMDNode(*
I.second, AreDebugLocsAllowed::No);
916 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
917 "weak_odr, or external linkage!",
922 Check(Resolver,
"IFunc must have a Function resolver", &GI);
924 "IFunc resolver must be a definition", &GI);
931 "IFunc resolver must return a pointer", &GI);
934 "IFunc resolver has incorrect type", &GI);
937void Verifier::visitNamedMDNode(
const NamedMDNode &NMD) {
942 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
943 for (
const MDNode *MD : NMD.
operands()) {
944 if (NMD.
getName() ==
"llvm.dbg.cu")
950 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
954void Verifier::visitMDNode(
const MDNode &BaseMD,
955 AreDebugLocsAllowed AllowLocs) {
958 if (!MDNodes.
insert(&BaseMD).second)
961 std::queue<const MDNode *> Worklist;
962 Worklist.push(&BaseMD);
964 while (!Worklist.empty()) {
965 const MDNode *CurrentMD = Worklist.front();
968 "MDNode context does not match Module context!", CurrentMD);
973 case Metadata::MDTupleKind:
975#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
976 case Metadata::CLASS##Kind: \
977 visit##CLASS(cast<CLASS>(*CurrentMD)); \
979#include "llvm/IR/Metadata.def"
988 "DILocation not allowed within this metadata node", CurrentMD,
996 visitValueAsMetadata(*V,
nullptr);
1010 "Expected second operand to be an integer constant of type i32 or "
1022 "Expecting only the metadata name", CurrentMD);
1027 Check(CurrentMD->
isResolved(),
"All nodes should be resolved!", CurrentMD);
1031void Verifier::visitValueAsMetadata(
const ValueAsMetadata &MD,
Function *
F) {
1034 "Unexpected metadata round-trip through values", &MD, MD.
getValue());
1040 Check(
F,
"function-local metadata used outside a function", L);
1046 Check(
I->getParent(),
"function-local metadata not in basic block", L,
I);
1053 assert(ActualF &&
"Unimplemented function local metadata case!");
1055 Check(ActualF ==
F,
"function-local metadata used in wrong function", L);
1058void Verifier::visitDIArgList(
const DIArgList &AL,
Function *
F) {
1059 for (
const ValueAsMetadata *VAM :
AL.getArgs())
1060 visitValueAsMetadata(*VAM,
F);
1063void Verifier::visitMetadataAsValue(
const MetadataAsValue &MDV,
Function *
F) {
1066 visitMDNode(*
N, AreDebugLocsAllowed::No);
1072 if (!MDNodes.
insert(MD).second)
1076 visitValueAsMetadata(*V,
F);
1079 visitDIArgList(*AL,
F);
1087void Verifier::visitDILocation(
const DILocation &
N) {
1089 "location requires a valid scope", &
N,
N.getRawScope());
1090 if (
auto *IA =
N.getRawInlinedAt())
1093 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1096void Verifier::visitGenericDINode(
const GenericDINode &
N) {
1100void Verifier::visitDIScope(
const DIScope &
N) {
1101 if (
auto *
F =
N.getRawFile())
1105void Verifier::visitDIType(
const DIType &
N) {
1108 CheckDI(
N.getRawFile() ||
N.getLine() == 0,
"line specified with no file", &
N,
1112void Verifier::visitDISubrangeType(
const DISubrangeType &
N) {
1115 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1118 auto *LBound =
N.getRawLowerBound();
1122 "LowerBound must be signed constant or DIVariable or DIExpression or "
1125 auto *UBound =
N.getRawUpperBound();
1129 "UpperBound must be signed constant or DIVariable or DIExpression or "
1132 auto *Stride =
N.getRawStride();
1135 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1136 auto *Bias =
N.getRawBias();
1139 "Bias must be signed constant or DIVariable or DIExpression", &
N);
1141 auto *
Size =
N.getRawSizeInBits();
1143 "SizeInBits must be a constant");
1146void Verifier::visitDISubrange(
const DISubrange &
N) {
1147 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1148 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1149 "Subrange can have any one of count or upperBound", &
N);
1150 auto *CBound =
N.getRawCountNode();
1153 "Count must be signed constant or DIVariable or DIExpression", &
N);
1154 auto Count =
N.getCount();
1157 "invalid subrange count", &
N);
1158 auto *LBound =
N.getRawLowerBound();
1161 "LowerBound must be signed constant or DIVariable or DIExpression",
1163 auto *UBound =
N.getRawUpperBound();
1166 "UpperBound must be signed constant or DIVariable or DIExpression",
1168 auto *Stride =
N.getRawStride();
1171 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1174void Verifier::visitDIGenericSubrange(
const DIGenericSubrange &
N) {
1175 CheckDI(
N.getTag() == dwarf::DW_TAG_generic_subrange,
"invalid tag", &
N);
1176 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1177 "GenericSubrange can have any one of count or upperBound", &
N);
1178 auto *CBound =
N.getRawCountNode();
1180 "Count must be signed constant or DIVariable or DIExpression", &
N);
1181 auto *LBound =
N.getRawLowerBound();
1182 CheckDI(LBound,
"GenericSubrange must contain lowerBound", &
N);
1184 "LowerBound must be signed constant or DIVariable or DIExpression",
1186 auto *UBound =
N.getRawUpperBound();
1188 "UpperBound must be signed constant or DIVariable or DIExpression",
1190 auto *Stride =
N.getRawStride();
1191 CheckDI(Stride,
"GenericSubrange must contain stride", &
N);
1193 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1196void Verifier::visitDIEnumerator(
const DIEnumerator &
N) {
1197 CheckDI(
N.getTag() == dwarf::DW_TAG_enumerator,
"invalid tag", &
N);
1200void Verifier::visitDIBasicType(
const DIBasicType &
N) {
1203 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type ||
1204 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1205 N.getTag() == dwarf::DW_TAG_string_type,
1208 auto *
Size =
N.getRawSizeInBits();
1210 "SizeInBits must be a constant");
1213void Verifier::visitDIFixedPointType(
const DIFixedPointType &
N) {
1214 visitDIBasicType(
N);
1216 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type,
"invalid tag", &
N);
1217 CheckDI(
N.getEncoding() == dwarf::DW_ATE_signed_fixed ||
1218 N.getEncoding() == dwarf::DW_ATE_unsigned_fixed,
1219 "invalid encoding", &
N);
1223 "invalid kind", &
N);
1225 N.getFactorRaw() == 0,
1226 "factor should be 0 for rationals", &
N);
1228 (
N.getNumeratorRaw() == 0 &&
N.getDenominatorRaw() == 0),
1229 "numerator and denominator should be 0 for non-rationals", &
N);
1232void Verifier::visitDIStringType(
const DIStringType &
N) {
1235 CheckDI(
N.getTag() == dwarf::DW_TAG_string_type,
"invalid tag", &
N);
1236 CheckDI(!(
N.isBigEndian() &&
N.isLittleEndian()),
"has conflicting flags",
1240void Verifier::visitDIDerivedType(
const DIDerivedType &
N) {
1244 CheckDI(
N.getTag() == dwarf::DW_TAG_typedef ||
1245 N.getTag() == dwarf::DW_TAG_pointer_type ||
1246 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1247 N.getTag() == dwarf::DW_TAG_reference_type ||
1248 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1249 N.getTag() == dwarf::DW_TAG_const_type ||
1250 N.getTag() == dwarf::DW_TAG_immutable_type ||
1251 N.getTag() == dwarf::DW_TAG_volatile_type ||
1252 N.getTag() == dwarf::DW_TAG_restrict_type ||
1253 N.getTag() == dwarf::DW_TAG_atomic_type ||
1254 N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
1255 N.getTag() == dwarf::DW_TAG_member ||
1256 (
N.getTag() == dwarf::DW_TAG_variable &&
N.isStaticMember()) ||
1257 N.getTag() == dwarf::DW_TAG_inheritance ||
1258 N.getTag() == dwarf::DW_TAG_friend ||
1259 N.getTag() == dwarf::DW_TAG_set_type ||
1260 N.getTag() == dwarf::DW_TAG_template_alias,
1262 if (
N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1263 CheckDI(
isType(
N.getRawExtraData()),
"invalid pointer to member type", &
N,
1264 N.getRawExtraData());
1265 }
else if (
N.getTag() == dwarf::DW_TAG_template_alias) {
1267 N.getRawExtraData());
1268 }
else if (
N.getTag() == dwarf::DW_TAG_inheritance ||
1269 N.getTag() == dwarf::DW_TAG_member ||
1270 N.getTag() == dwarf::DW_TAG_variable) {
1271 auto *ExtraData =
N.getRawExtraData();
1272 auto IsValidExtraData = [&]() {
1273 if (ExtraData ==
nullptr)
1279 if (Tuple->getNumOperands() != 1)
1286 "extraData must be ConstantAsMetadata, MDString, DIObjCProperty, "
1287 "or MDTuple with single ConstantAsMetadata operand",
1291 if (
N.getTag() == dwarf::DW_TAG_set_type) {
1292 if (
auto *
T =
N.getRawBaseType()) {
1297 (Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1298 (Subrange &&
Subrange->getTag() == dwarf::DW_TAG_subrange_type) ||
1299 (
Basic && (
Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1300 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1301 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1302 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1303 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1304 "invalid set base type", &
N,
T);
1309 N.getRawBaseType());
1311 if (
N.getDWARFAddressSpace()) {
1312 CheckDI(
N.getTag() == dwarf::DW_TAG_pointer_type ||
1313 N.getTag() == dwarf::DW_TAG_reference_type ||
1314 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1315 "DWARF address space only applies to pointer or reference types",
1319 auto *
Size =
N.getRawSizeInBits();
1322 "SizeInBits must be a constant or DIVariable or DIExpression");
1327 return ((Flags & DINode::FlagLValueReference) &&
1328 (Flags & DINode::FlagRValueReference)) ||
1329 ((Flags & DINode::FlagTypePassByValue) &&
1330 (Flags & DINode::FlagTypePassByReference));
1333void Verifier::visitTemplateParams(
const MDNode &
N,
const Metadata &RawParams) {
1335 CheckDI(Params,
"invalid template params", &
N, &RawParams);
1342void Verifier::visitDICompositeType(
const DICompositeType &
N) {
1346 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type ||
1347 N.getTag() == dwarf::DW_TAG_structure_type ||
1348 N.getTag() == dwarf::DW_TAG_union_type ||
1349 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1350 N.getTag() == dwarf::DW_TAG_class_type ||
1351 N.getTag() == dwarf::DW_TAG_variant_part ||
1352 N.getTag() == dwarf::DW_TAG_variant ||
1353 N.getTag() == dwarf::DW_TAG_namelist,
1357 N.getRawBaseType());
1360 "invalid composite elements", &
N,
N.getRawElements());
1362 N.getRawVTableHolder());
1364 "invalid reference flags", &
N);
1365 unsigned DIBlockByRefStruct = 1 << 4;
1366 CheckDI((
N.getFlags() & DIBlockByRefStruct) == 0,
1367 "DIBlockByRefStruct on DICompositeType is no longer supported", &
N);
1369 "DISubprogram contains null entry in `elements` field", &
N);
1372 const DINodeArray
Elements =
N.getElements();
1374 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1375 "invalid vector, expected one element of type subrange", &
N);
1378 if (
auto *Params =
N.getRawTemplateParams())
1379 visitTemplateParams(
N, *Params);
1381 if (
auto *
D =
N.getRawDiscriminator()) {
1383 "discriminator can only appear on variant part");
1386 if (
N.getRawDataLocation()) {
1387 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1388 "dataLocation can only appear in array type");
1391 if (
N.getRawAssociated()) {
1392 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1393 "associated can only appear in array type");
1396 if (
N.getRawAllocated()) {
1397 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1398 "allocated can only appear in array type");
1401 if (
N.getRawRank()) {
1402 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1403 "rank can only appear in array type");
1406 if (
N.getTag() == dwarf::DW_TAG_array_type) {
1407 CheckDI(
N.getRawBaseType(),
"array types must have a base type", &
N);
1410 auto *
Size =
N.getRawSizeInBits();
1413 "SizeInBits must be a constant or DIVariable or DIExpression");
1416void Verifier::visitDISubroutineType(
const DISubroutineType &
N) {
1418 CheckDI(
N.getTag() == dwarf::DW_TAG_subroutine_type,
"invalid tag", &
N);
1419 if (
auto *Types =
N.getRawTypeArray()) {
1421 for (
Metadata *Ty :
N.getTypeArray()->operands()) {
1422 CheckDI(
isType(Ty),
"invalid subroutine type ref", &
N, Types, Ty);
1426 "invalid reference flags", &
N);
1429void Verifier::visitDIFile(
const DIFile &
N) {
1430 CheckDI(
N.getTag() == dwarf::DW_TAG_file_type,
"invalid tag", &
N);
1431 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum =
N.getChecksum();
1433 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1434 "invalid checksum kind", &
N);
1436 switch (Checksum->Kind) {
1447 CheckDI(Checksum->Value.size() ==
Size,
"invalid checksum length", &
N);
1449 "invalid checksum", &
N);
1453void Verifier::visitDICompileUnit(
const DICompileUnit &
N) {
1454 CheckDI(
N.isDistinct(),
"compile units must be distinct", &
N);
1455 CheckDI(
N.getTag() == dwarf::DW_TAG_compile_unit,
"invalid tag", &
N);
1461 CheckDI(!
N.getFile()->getFilename().empty(),
"invalid filename", &
N,
1465 "invalid emission kind", &
N);
1468 "invalid language dialect", &
N);
1470 if (
auto *Array =
N.getRawEnumTypes()) {
1472 for (
Metadata *
Op :
N.getEnumTypes()->operands()) {
1474 CheckDI(Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1475 "invalid enum type", &
N,
N.getEnumTypes(),
Op);
1477 "function-local enum in a DICompileUnit's enum list", &
N,
1478 N.getEnumTypes(),
Op);
1481 if (
auto *Array =
N.getRawRetainedTypes()) {
1483 for (
Metadata *
Op :
N.getRetainedTypes()->operands()) {
1487 "invalid retained type", &
N,
Op);
1490 if (
auto *Array =
N.getRawGlobalVariables()) {
1492 for (
Metadata *
Op :
N.getGlobalVariables()->operands()) {
1494 CheckDI(GVE,
"invalid global variable ref", &
N,
Op);
1496 "function-local variables are not allowed in a DICompileUnit's "
1497 "global variables list",
1501 if (
auto *Array =
N.getRawImportedEntities()) {
1503 for (
Metadata *
Op :
N.getImportedEntities()->operands()) {
1505 CheckDI(IE,
"invalid imported entity ref", &
N,
Op);
1507 "function-local imports are not allowed in a DICompileUnit's "
1508 "imported entities list",
1512 if (
auto *Array =
N.getRawMacros()) {
1521void Verifier::visitDISubprogram(
const DISubprogram &
N) {
1522 CheckDI(
N.getTag() == dwarf::DW_TAG_subprogram,
"invalid tag", &
N);
1524 if (
auto *
F =
N.getRawFile())
1527 CheckDI(
N.getLine() == 0,
"line specified with no file", &
N,
N.getLine());
1528 auto *
T =
N.getRawType();
1529 CheckDI(
T,
"DISubprogram requires a non-null type", &
N);
1531 CheckDI(
isType(
N.getRawContainingType()),
"invalid containing type", &
N,
1532 N.getRawContainingType());
1533 if (
auto *Params =
N.getRawTemplateParams())
1534 visitTemplateParams(
N, *Params);
1535 if (
auto *S =
N.getRawDeclaration())
1537 "invalid subprogram declaration", &
N, S);
1538 if (
auto *RawNode =
N.getRawRetainedNodes()) {
1540 CheckDI(Node,
"invalid retained nodes list", &
N, RawNode);
1542 DenseMap<unsigned, DILocalVariable *>
Args;
1544 CheckDI(
Op,
"nullptr in retained nodes", &
N, Node);
1546 auto True = [](
const Metadata *) {
return true; };
1547 auto False = [](
const Metadata *) {
return false; };
1548 bool IsTypeCorrect = DISubprogram::visitRetainedNode<bool>(
1549 Op, True, True, True, True, True, False);
1551 "invalid retained nodes, expected DILocalVariable, DILabel, "
1552 "DIImportedEntity, DIType or DIGlobalVariableExpression",
1559 "invalid retained nodes, retained node is not local", &
N, Node,
1562 DISubprogram *RetainedNodeSP = RetainedNodeScope->getSubprogram();
1563 DICompileUnit *RetainedNodeUnit =
1564 RetainedNodeSP ? RetainedNodeSP->getUnit() :
nullptr;
1566 RetainedNodeSP == &
N,
1567 "invalid retained nodes, retained node does not belong to subprogram",
1568 &
N, Node, RetainedNode, RetainedNodeScope, RetainedNodeSP,
1574 if (
unsigned ArgNum = DV->getArg()) {
1576 CheckDI(Inserted || DV == ArgI->second,
1577 "invalid retained nodes, more than one local variable with the "
1578 "same argument index",
1579 &
N,
N.getUnit(), Node, RetainedNode, Args[ArgNum]);
1584 "invalid reference flags", &
N);
1586 auto *
Unit =
N.getRawUnit();
1587 if (
N.isDefinition()) {
1589 CheckDI(
N.isDistinct(),
"subprogram definitions must be distinct", &
N);
1590 CheckDI(Unit,
"subprogram definitions must have a compile unit", &
N);
1595 if (CT && CT->getRawIdentifier() &&
1596 M.getContext().isODRUniquingDebugTypes())
1598 "definition subprograms cannot be nested within DICompositeType "
1599 "when enabling ODR",
1603 CheckDI(!Unit,
"subprogram declarations must not have a compile unit", &
N);
1605 "subprogram declaration must not have a declaration field");
1608 if (
auto *RawThrownTypes =
N.getRawThrownTypes()) {
1610 CheckDI(ThrownTypes,
"invalid thrown types list", &
N, RawThrownTypes);
1616 if (
N.areAllCallsDescribed())
1618 "DIFlagAllCallsDescribed must be attached to a definition");
1621void Verifier::visitDILexicalBlockBase(
const DILexicalBlockBase &
N) {
1622 CheckDI(
N.getTag() == dwarf::DW_TAG_lexical_block,
"invalid tag", &
N);
1624 "invalid local scope", &
N,
N.getRawScope());
1626 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1629void Verifier::visitDILexicalBlock(
const DILexicalBlock &
N) {
1630 visitDILexicalBlockBase(
N);
1633 "cannot have column info without line info", &
N);
1636void Verifier::visitDILexicalBlockFile(
const DILexicalBlockFile &
N) {
1637 visitDILexicalBlockBase(
N);
1640void Verifier::visitDICommonBlock(
const DICommonBlock &
N) {
1641 CheckDI(
N.getTag() == dwarf::DW_TAG_common_block,
"invalid tag", &
N);
1642 if (
auto *S =
N.getRawScope())
1644 if (
auto *S =
N.getRawDecl())
1648void Verifier::visitDINamespace(
const DINamespace &
N) {
1649 CheckDI(
N.getTag() == dwarf::DW_TAG_namespace,
"invalid tag", &
N);
1650 if (
auto *S =
N.getRawScope())
1654void Verifier::visitDIMacro(
const DIMacro &
N) {
1657 "invalid macinfo type", &
N);
1658 CheckDI(!
N.getName().empty(),
"anonymous macro", &
N);
1659 if (!
N.getValue().empty()) {
1660 assert(
N.getValue().data()[0] !=
' ' &&
"Macro value has a space prefix");
1664void Verifier::visitDIMacroFile(
const DIMacroFile &
N) {
1666 "invalid macinfo type", &
N);
1667 if (
auto *
F =
N.getRawFile())
1670 if (
auto *Array =
N.getRawElements()) {
1672 for (
Metadata *
Op :
N.getElements()->operands()) {
1678void Verifier::visitDIModule(
const DIModule &
N) {
1679 CheckDI(
N.getTag() == dwarf::DW_TAG_module,
"invalid tag", &
N);
1680 CheckDI(!
N.getName().empty(),
"anonymous module", &
N);
1683void Verifier::visitDITemplateParameter(
const DITemplateParameter &
N) {
1687void Verifier::visitDITemplateTypeParameter(
const DITemplateTypeParameter &
N) {
1688 visitDITemplateParameter(
N);
1690 CheckDI(
N.getTag() == dwarf::DW_TAG_template_type_parameter,
"invalid tag",
1694void Verifier::visitDITemplateValueParameter(
1695 const DITemplateValueParameter &
N) {
1696 visitDITemplateParameter(
N);
1698 CheckDI(
N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1699 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1700 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1704void Verifier::visitDIVariable(
const DIVariable &
N) {
1705 if (
auto *S =
N.getRawScope())
1707 if (
auto *
F =
N.getRawFile())
1711void Verifier::visitDIGlobalVariable(
const DIGlobalVariable &
N) {
1715 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1718 if (
N.isDefinition())
1719 CheckDI(
N.getType(),
"missing global variable type", &
N);
1720 if (
auto *Member =
N.getRawStaticDataMemberDeclaration()) {
1722 "invalid static data member declaration", &
N, Member);
1726void Verifier::visitDILocalVariable(
const DILocalVariable &
N) {
1731 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1733 "local variable requires a valid scope", &
N,
N.getRawScope());
1734 if (
auto Ty =
N.getType())
1738void Verifier::visitDIAssignID(
const DIAssignID &
N) {
1739 CheckDI(!
N.getNumOperands(),
"DIAssignID has no arguments", &
N);
1740 CheckDI(
N.isDistinct(),
"DIAssignID must be distinct", &
N);
1743void Verifier::visitDILabel(
const DILabel &
N) {
1744 if (
auto *S =
N.getRawScope())
1746 if (
auto *
F =
N.getRawFile())
1749 CheckDI(
N.getTag() == dwarf::DW_TAG_label,
"invalid tag", &
N);
1751 "label requires a valid scope", &
N,
N.getRawScope());
1754void Verifier::visitDIExpression(
const DIExpression &
N) {
1755 CheckDI(
N.isValid(),
"invalid expression", &
N);
1758void Verifier::visitDIGlobalVariableExpression(
1759 const DIGlobalVariableExpression &GVE) {
1762 visitDIGlobalVariable(*Var);
1764 visitDIExpression(*Expr);
1765 if (
auto Fragment = Expr->getFragmentInfo())
1766 verifyFragmentExpression(*GVE.
getVariable(), *Fragment, &GVE);
1770void Verifier::visitDIObjCProperty(
const DIObjCProperty &
N) {
1771 CheckDI(
N.getTag() == dwarf::DW_TAG_APPLE_property,
"invalid tag", &
N);
1772 if (
auto *
T =
N.getRawType())
1774 if (
auto *
F =
N.getRawFile())
1778void Verifier::visitDIProperty(
const DIProperty &
N) {
1779 CheckDI(
N.getTag() == dwarf::DW_TAG_property,
"invalid tag", &
N);
1780 if (
auto *
T =
N.getRawType())
1782 if (
auto *
F =
N.getRawFile())
1786 if (DINode *BackingStorage =
N.getBackingStorage()) {
1788 CheckDI(DT && DT->getTag() == dwarf::DW_TAG_member,
1789 "property backing storage must be a member", &
N, BackingStorage);
1793void Verifier::visitDIImportedEntity(
const DIImportedEntity &
N) {
1794 CheckDI(
N.getTag() == dwarf::DW_TAG_imported_module ||
1795 N.getTag() == dwarf::DW_TAG_imported_declaration,
1797 if (
auto *S =
N.getRawScope())
1803void Verifier::visitComdat(
const Comdat &
C) {
1806 if (
TT.isOSBinFormatCOFF())
1807 if (
const GlobalValue *GV =
M.getNamedValue(
C.getName()))
1812void Verifier::visitModuleIdents() {
1813 const NamedMDNode *Idents =
M.getNamedMetadata(
"llvm.ident");
1819 for (
const MDNode *
N : Idents->
operands()) {
1820 Check(
N->getNumOperands() == 1,
1821 "incorrect number of operands in llvm.ident metadata",
N);
1823 (
"invalid value for llvm.ident metadata entry operand"
1824 "(the operand should be a string)"),
1829void Verifier::visitModuleCommandLines() {
1830 const NamedMDNode *CommandLines =
M.getNamedMetadata(
"llvm.commandline");
1837 for (
const MDNode *
N : CommandLines->
operands()) {
1838 Check(
N->getNumOperands() == 1,
1839 "incorrect number of operands in llvm.commandline metadata",
N);
1841 (
"invalid value for llvm.commandline metadata entry operand"
1842 "(the operand should be a string)"),
1847void Verifier::visitModuleErrnoTBAA() {
1848 const NamedMDNode *ErrnoTBAA =
M.getNamedMetadata(
"llvm.errno.tbaa");
1853 "llvm.errno.tbaa must have at least one operand", ErrnoTBAA);
1855 for (
const MDNode *
N : ErrnoTBAA->
operands())
1859void Verifier::visitModuleFlags() {
1860 const NamedMDNode *
Flags =
M.getModuleFlagsMetadata();
1864 DenseMap<const MDString*, const MDNode*> SeenIDs;
1868 std::optional<uint64_t> PAuthABIPlatform;
1869 std::optional<uint64_t> PAuthABIVersion;
1872 uint64_t HasPtrauthInitFiniAddr = 0;
1874 for (
const MDNode *MDN :
Flags->operands()) {
1875 visitModuleFlag(MDN, SeenIDs, Requirements);
1876 if (MDN->getNumOperands() != 3)
1880 auto GetFlagNamed = [&](StringRef
Name) -> std::optional<uint64_t> {
1881 if (FlagName->getString() != Name)
1882 return std::nullopt;
1883 if (
const auto *FlagValue =
1885 return FlagValue->getZExtValue();
1887 CheckFailed(Name +
": module flag expects integer value");
1888 return std::nullopt;
1891 if (
auto Value = GetFlagNamed(
"aarch64-elf-pauthabi-platform"))
1892 PAuthABIPlatform = *
Value;
1893 else if (
auto Value = GetFlagNamed(
"aarch64-elf-pauthabi-version"))
1894 PAuthABIVersion = *
Value;
1895 else if (
auto Value = GetFlagNamed(
"ptrauth-init-fini"))
1896 HasPtrauthInitFini = *
Value;
1897 else if (
auto Value =
1898 GetFlagNamed(
"ptrauth-init-fini-address-discrimination"))
1899 HasPtrauthInitFiniAddr = *
Value;
1904 "ptrauth-init-fini must be 0 or 1");
1906 "ptrauth-init-fini-address-discrimination must be 0 or 1, if set");
1907 if (HasPtrauthInitFiniAddr)
1908 Check(HasPtrauthInitFini,
"ptrauth-init-fini-address-discrimination module "
1909 "flag requires ptrauth-init-fini");
1911 if (PAuthABIPlatform.has_value() != PAuthABIVersion.has_value())
1912 CheckFailed(
"either both or no 'aarch64-elf-pauthabi-platform' and "
1913 "'aarch64-elf-pauthabi-version' module flags must be present");
1916 for (
const MDNode *Requirement : Requirements) {
1918 const Metadata *ReqValue = Requirement->getOperand(1);
1920 const MDNode *
Op = SeenIDs.
lookup(Flag);
1922 CheckFailed(
"invalid requirement on flag, flag is not present in module",
1927 if (
Op->getOperand(2) != ReqValue) {
1928 CheckFailed((
"invalid requirement on flag, "
1929 "flag does not have the required value"),
1937Verifier::visitModuleFlag(
const MDNode *
Op,
1938 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1939 SmallVectorImpl<const MDNode *> &Requirements) {
1943 "incorrect number of operands in module flag",
Op);
1944 Module::ModFlagBehavior MFB;
1945 if (!Module::isValidModFlagBehavior(
Op->getOperand(0), MFB)) {
1947 "invalid behavior operand in module flag (expected constant integer)",
1950 "invalid behavior operand in module flag (unexpected constant)",
1954 Check(ID,
"invalid ID operand in module flag (expected metadata string)",
1960 case Module::Warning:
1961 case Module::Override:
1967 Check(V &&
V->getValue().isNonNegative(),
1968 "invalid value for 'min' module flag (expected constant non-negative "
1976 "invalid value for 'max' module flag (expected constant integer)",
1981 case Module::Require: {
1986 "invalid value for 'require' module flag (expected metadata pair)",
1989 (
"invalid value for 'require' module flag "
1990 "(first value operand should be a string)"),
1991 Value->getOperand(0));
1999 case Module::Append:
2000 case Module::AppendUnique: {
2003 "invalid value for 'append'-type module flag "
2004 "(expected a metadata node)",
2011 if (MFB != Module::Require) {
2014 "module flag identifiers must be unique (or of 'require' type)", ID);
2017 if (
ID->getString() ==
"wchar_size") {
2020 Check(
Value,
"wchar_size metadata requires constant integer argument");
2023 if (
ID->getString() ==
"long-double-type") {
2024 Check(MFB == Module::Error,
2025 "long-double-type module flag must use 'error' merge behavior",
Op);
2027 Check(
Value,
"long-double-type metadata requires a string argument");
2030 "invalid long-double-type metadata value",
Op);
2033 if (
ID->getString() ==
"float-abi") {
2034 Check(MFB == Module::Error,
2035 "float-abi module flag must use 'error' merge behavior",
Op);
2037 Check(
Value,
"float-abi metadata requires a string argument");
2040 "invalid float-abi metadata value",
Op);
2043 if (
ID->getString() ==
"target-abi") {
2046 "target-abi metadata requires a non-empty string argument",
Op);
2049 if (
ID->getString() ==
"Linker Options") {
2053 Check(
M.getNamedMetadata(
"llvm.linker.options"),
2054 "'Linker Options' named metadata no longer supported");
2057 if (
ID->getString() ==
"SemanticInterposition") {
2058 ConstantInt *
Value =
2061 "SemanticInterposition metadata requires constant integer argument");
2064 if (
ID->getString() ==
"CG Profile") {
2065 for (
const MDOperand &MDO :
cast<MDNode>(
Op->getOperand(2))->operands())
2066 visitModuleFlagCGProfileEntry(MDO);
2073void Verifier::visitModuleFlagCGProfileEntry(
const MDOperand &MDO) {
2074 auto CheckFunction = [&](
const MDOperand &FuncMDO) {
2079 "expected a Function or null", FuncMDO);
2082 Check(Node &&
Node->getNumOperands() == 3,
"expected a MDNode triple", MDO);
2083 CheckFunction(
Node->getOperand(0));
2084 CheckFunction(
Node->getOperand(1));
2087 "expected an integer constant",
Node->getOperand(2));
2090void Verifier::verifyAttributeTypes(AttributeSet Attrs,
const Value *V) {
2093 if (
A.isStringAttribute()) {
2094#define GET_ATTR_NAMES
2095#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
2096#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
2097 if (A.getKindAsString() == #DISPLAY_NAME) { \
2098 auto V = A.getValueAsString(); \
2099 if (!(V.empty() || V == "true" || V == "false")) \
2100 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
2104#include "llvm/IR/Attributes.inc"
2108 if (
A.isIntAttribute() != Attribute::isIntAttrKind(
A.getKindAsEnum())) {
2109 CheckFailed(
"Attribute '" +
A.getAsString() +
"' should have an Argument",
2118void Verifier::verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
2120 if (!
Attrs.hasAttributes())
2123 verifyAttributeTypes(Attrs, V);
2126 Check(Attr.isStringAttribute() ||
2127 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
2128 "Attribute '" + Attr.getAsString() +
"' does not apply to parameters",
2131 if (
Attrs.hasAttribute(Attribute::ImmArg)) {
2132 unsigned AttrCount =
2133 Attrs.getNumAttributes() -
Attrs.hasAttribute(Attribute::Range);
2134 Check(AttrCount == 1,
2135 "Attribute 'immarg' is incompatible with other attributes except the "
2136 "'range' attribute",
2142 unsigned AttrCount = 0;
2143 AttrCount +=
Attrs.hasAttribute(Attribute::ByVal);
2144 AttrCount +=
Attrs.hasAttribute(Attribute::InAlloca);
2145 AttrCount +=
Attrs.hasAttribute(Attribute::Preallocated);
2146 AttrCount +=
Attrs.hasAttribute(Attribute::StructRet) ||
2147 Attrs.hasAttribute(Attribute::InReg);
2148 AttrCount +=
Attrs.hasAttribute(Attribute::Nest);
2149 AttrCount +=
Attrs.hasAttribute(Attribute::ByRef);
2150 Check(AttrCount <= 1,
2151 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
2152 "'byref', and 'sret' are incompatible!",
2155 Check(!(
Attrs.hasAttribute(Attribute::InAlloca) &&
2156 Attrs.hasAttribute(Attribute::ReadOnly)),
2158 "'inalloca and readonly' are incompatible!",
2161 Check(!(
Attrs.hasAttribute(Attribute::StructRet) &&
2162 Attrs.hasAttribute(Attribute::Returned)),
2164 "'sret and returned' are incompatible!",
2167 Check(!(
Attrs.hasAttribute(Attribute::ZExt) &&
2168 Attrs.hasAttribute(Attribute::SExt)),
2170 "'zeroext and signext' are incompatible!",
2173 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2174 Attrs.hasAttribute(Attribute::ReadOnly)),
2176 "'readnone and readonly' are incompatible!",
2179 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2180 Attrs.hasAttribute(Attribute::WriteOnly)),
2182 "'readnone and writeonly' are incompatible!",
2185 Check(!(
Attrs.hasAttribute(Attribute::ReadOnly) &&
2186 Attrs.hasAttribute(Attribute::WriteOnly)),
2188 "'readonly and writeonly' are incompatible!",
2191 Check(!(
Attrs.hasAttribute(Attribute::NoInline) &&
2192 Attrs.hasAttribute(Attribute::AlwaysInline)),
2194 "'noinline and alwaysinline' are incompatible!",
2197 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2198 Attrs.hasAttribute(Attribute::ReadNone)),
2199 "Attributes writable and readnone are incompatible!", V);
2201 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2202 Attrs.hasAttribute(Attribute::ReadOnly)),
2203 "Attributes writable and readonly are incompatible!", V);
2205 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty, Attrs);
2207 if (!Attr.isStringAttribute() &&
2208 IncompatibleAttrs.
contains(Attr.getKindAsEnum())) {
2209 CheckFailed(
"Attribute '" + Attr.getAsString() +
2210 "' applied to incompatible type!", V);
2216 if (
Attrs.hasAttribute(Attribute::Alignment)) {
2217 Align AttrAlign =
Attrs.getAlignment().valueOrOne();
2218 Check(AttrAlign.
value() <= Value::MaximumAlignment,
2219 "huge alignment values are unsupported", V);
2221 if (
Attrs.hasAttribute(Attribute::ByVal)) {
2223 SmallPtrSet<Type *, 4> Visited;
2225 "Attribute 'byval' does not support unsized types!", V);
2229 "'byval' argument has illegal target extension type", V);
2230 Check(
DL.getTypeAllocSize(ByValTy).getKnownMinValue() < (1ULL << 32),
2231 "huge 'byval' arguments are unsupported", V);
2233 if (
Attrs.hasAttribute(Attribute::ByRef)) {
2234 SmallPtrSet<Type *, 4> Visited;
2235 Check(
Attrs.getByRefType()->isSized(&Visited),
2236 "Attribute 'byref' does not support unsized types!", V);
2237 Check(
DL.getTypeAllocSize(
Attrs.getByRefType()).getKnownMinValue() <
2239 "huge 'byref' arguments are unsupported", V);
2241 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
2242 SmallPtrSet<Type *, 4> Visited;
2243 Check(
Attrs.getInAllocaType()->isSized(&Visited),
2244 "Attribute 'inalloca' does not support unsized types!", V);
2245 Check(
DL.getTypeAllocSize(
Attrs.getInAllocaType()).getKnownMinValue() <
2247 "huge 'inalloca' arguments are unsupported", V);
2249 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
2250 SmallPtrSet<Type *, 4> Visited;
2251 Check(
Attrs.getPreallocatedType()->isSized(&Visited),
2252 "Attribute 'preallocated' does not support unsized types!", V);
2254 DL.getTypeAllocSize(
Attrs.getPreallocatedType()).getKnownMinValue() <
2256 "huge 'preallocated' arguments are unsupported", V);
2260 if (
Attrs.hasAttribute(Attribute::Initializes)) {
2261 auto Inits =
Attrs.getAttribute(Attribute::Initializes).getInitializes();
2262 Check(!Inits.empty(),
"Attribute 'initializes' does not support empty list",
2265 "Attribute 'initializes' does not support unordered ranges", V);
2268 if (
Attrs.hasAttribute(Attribute::NoFPClass)) {
2269 uint64_t Val =
Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
2270 Check(Val != 0,
"Attribute 'nofpclass' must have at least one test bit set",
2273 "Invalid value for 'nofpclass' test mask", V);
2275 if (
Attrs.hasAttribute(Attribute::Range)) {
2276 const ConstantRange &CR =
2277 Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2279 "Range bit width must match type bit width!", V);
2283void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
2285 if (
Attrs.hasFnAttr(Attr)) {
2286 StringRef S =
Attrs.getFnAttr(Attr).getValueAsString();
2289 CheckFailed(
"\"" + Attr +
"\" takes an unsigned integer: " + S, V);
2295void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
2296 const Value *V,
bool IsIntrinsic,
2298 if (
Attrs.isEmpty())
2301 if (AttributeListsVisited.
insert(
Attrs.getRawPointer()).second) {
2303 "Attribute list does not match Module context!", &Attrs, V);
2304 for (
const auto &AttrSet : Attrs) {
2305 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(
Context),
2306 "Attribute set does not match Module context!", &AttrSet, V);
2307 for (
const auto &
A : AttrSet) {
2309 "Attribute does not match Module context!", &
A, V);
2314 bool SawNest =
false;
2315 bool SawReturned =
false;
2316 bool SawSRet =
false;
2317 bool SawSwiftSelf =
false;
2318 bool SawSwiftAsync =
false;
2319 bool SawSwiftError =
false;
2322 AttributeSet RetAttrs =
Attrs.getRetAttrs();
2325 Attribute::canUseAsRetAttr(
RetAttr.getKindAsEnum()),
2326 "Attribute '" +
RetAttr.getAsString() +
2327 "' does not apply to function return values",
2330 unsigned MaxParameterWidth = 0;
2331 auto GetMaxParameterWidth = [&MaxParameterWidth](
Type *Ty) {
2334 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2335 if (
Size > MaxParameterWidth)
2336 MaxParameterWidth =
Size;
2340 GetMaxParameterWidth(FT->getReturnType());
2341 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2344 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2345 Type *Ty = FT->getParamType(i);
2346 AttributeSet ArgAttrs =
Attrs.getParamAttrs(i);
2350 "immarg attribute only applies to intrinsics", V);
2353 "Attribute 'elementtype' can only be applied to intrinsics"
2358 verifyParameterAttrs(ArgAttrs, Ty, V);
2359 GetMaxParameterWidth(Ty);
2362 Check(!SawNest,
"More than one parameter has attribute nest!", V);
2367 Check(!SawReturned,
"More than one parameter has attribute returned!", V);
2369 "Incompatible argument and return types for 'returned' attribute",
2375 Check(!SawSRet,
"Cannot have multiple 'sret' parameters!", V);
2376 Check(i == 0 || i == 1,
2377 "Attribute 'sret' is not on first or second parameter!", V);
2382 Check(!SawSwiftSelf,
"Cannot have multiple 'swiftself' parameters!", V);
2383 SawSwiftSelf =
true;
2387 Check(!SawSwiftAsync,
"Cannot have multiple 'swiftasync' parameters!", V);
2388 SawSwiftAsync =
true;
2392 Check(!SawSwiftError,
"Cannot have multiple 'swifterror' parameters!", V);
2393 SawSwiftError =
true;
2397 Check(i == FT->getNumParams() - 1,
2398 "inalloca isn't on the last parameter!", V);
2402 if (!
Attrs.hasFnAttrs())
2405 verifyAttributeTypes(
Attrs.getFnAttrs(), V);
2408 Attribute::canUseAsFnAttr(
FnAttr.getKindAsEnum()),
2409 "Attribute '" +
FnAttr.getAsString() +
2410 "' does not apply to functions!",
2413 Check(!(
Attrs.hasFnAttr(Attribute::NoInline) &&
2414 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2415 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2417 if (
Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2419 "Attribute 'optnone' requires 'noinline'!", V);
2421 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2422 "Attributes 'optsize and optnone' are incompatible!", V);
2425 "Attributes 'minsize and optnone' are incompatible!", V);
2427 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
2428 "Attributes 'optdebug and optnone' are incompatible!", V);
2431 Check(!(
Attrs.hasFnAttr(Attribute::SanitizeRealtime) &&
2432 Attrs.hasFnAttr(Attribute::SanitizeRealtimeBlocking)),
2434 "'sanitize_realtime and sanitize_realtime_blocking' are incompatible!",
2437 if (
Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
2438 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2439 "Attributes 'optsize and optdebug' are incompatible!", V);
2442 "Attributes 'minsize and optdebug' are incompatible!", V);
2445 Check(!
Attrs.hasAttrSomewhere(Attribute::Writable) ||
2446 isModSet(
Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
2447 "Attribute writable and memory without argmem: write are incompatible!",
2450 if (
Attrs.hasFnAttr(
"aarch64_pstate_sm_enabled")) {
2451 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_sm_compatible"),
2452 "Attributes 'aarch64_pstate_sm_enabled and "
2453 "aarch64_pstate_sm_compatible' are incompatible!",
2457 Check((
Attrs.hasFnAttr(
"aarch64_new_za") +
Attrs.hasFnAttr(
"aarch64_in_za") +
2458 Attrs.hasFnAttr(
"aarch64_inout_za") +
2459 Attrs.hasFnAttr(
"aarch64_out_za") +
2460 Attrs.hasFnAttr(
"aarch64_preserves_za") +
2461 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2462 "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2463 "'aarch64_inout_za', 'aarch64_preserves_za' and "
2464 "'aarch64_za_state_agnostic' are mutually exclusive",
2468 Attrs.hasFnAttr(
"aarch64_in_zt0") +
2469 Attrs.hasFnAttr(
"aarch64_inout_zt0") +
2470 Attrs.hasFnAttr(
"aarch64_out_zt0") +
2471 Attrs.hasFnAttr(
"aarch64_preserves_zt0") +
2472 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2473 "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
2474 "'aarch64_inout_zt0', 'aarch64_preserves_zt0' and "
2475 "'aarch64_za_state_agnostic' are mutually exclusive",
2478 if (
Attrs.hasFnAttr(Attribute::JumpTable)) {
2481 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2484 if (
auto Args =
Attrs.getFnAttrs().getAllocSizeArgs()) {
2485 auto CheckParam = [&](StringRef
Name,
unsigned ParamNo) {
2486 if (ParamNo >= FT->getNumParams()) {
2487 CheckFailed(
"'allocsize' " + Name +
" argument is out of bounds", V);
2491 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2492 CheckFailed(
"'allocsize' " + Name +
2493 " argument must refer to an integer parameter",
2501 if (!CheckParam(
"element size",
Args->first))
2504 if (
Args->second && !CheckParam(
"number of elements", *
Args->second))
2508 if (
Attrs.hasFnAttr(Attribute::AllocKind)) {
2511 K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
2513 {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
2516 "'allockind()' requires exactly one of alloc, realloc, and free");
2517 if ((
Type == AllocFnKind::Free) &&
2518 ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
2519 AllocFnKind::Aligned)) != AllocFnKind::Unknown))
2520 CheckFailed(
"'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2521 "or aligned modifiers.");
2522 AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
2523 if ((K & ZeroedUninit) == ZeroedUninit)
2524 CheckFailed(
"'allockind()' can't be both zeroed and uninitialized");
2528 StringRef S =
A.getValueAsString();
2529 Check(!S.
empty(),
"'alloc-variant-zeroed' must not be empty");
2537 "'alloc-variant-zeroed' must name a function belonging to the "
2538 "same 'alloc-family'");
2541 (
Variant->getFnAttribute(Attribute::AllocKind).getAllocKind() &
2542 AllocFnKind::Zeroed) != AllocFnKind::Unknown,
2543 "'alloc-variant-zeroed' must name a function with "
2544 "'allockind(\"zeroed\")'");
2547 "'alloc-variant-zeroed' must name a function with the same "
2552 "'alloc-variant-zeroed' must name a function with the same "
2553 "calling convention");
2557 if (
Attrs.hasFnAttr(Attribute::VScaleRange)) {
2558 unsigned VScaleMin =
Attrs.getFnAttrs().getVScaleRangeMin();
2560 CheckFailed(
"'vscale_range' minimum must be greater than 0", V);
2562 CheckFailed(
"'vscale_range' minimum must be power-of-two value", V);
2563 std::optional<unsigned> VScaleMax =
Attrs.getFnAttrs().getVScaleRangeMax();
2564 if (VScaleMax && VScaleMin > VScaleMax)
2565 CheckFailed(
"'vscale_range' minimum cannot be greater than maximum", V);
2567 CheckFailed(
"'vscale_range' maximum must be power-of-two value", V);
2570 if (
Attribute FPAttr =
Attrs.getFnAttr(
"frame-pointer"); FPAttr.isValid()) {
2571 StringRef
FP = FPAttr.getValueAsString();
2572 if (
FP !=
"all" &&
FP !=
"non-leaf" &&
FP !=
"none" &&
FP !=
"reserved" &&
2573 FP !=
"non-leaf-no-reserve")
2574 CheckFailed(
"invalid value for 'frame-pointer' attribute: " +
FP, V);
2577 checkUnsignedBaseTenFuncAttr(Attrs,
"tail-pad-to-size", V);
2578 checkUnsignedBaseTenFuncAttr(Attrs,
"tail-pad-value", V);
2579 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-prefix", V);
2580 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-entry", V);
2581 if (
Attrs.hasFnAttr(
"patchable-function-entry-section"))
2582 Check(!
Attrs.getFnAttr(
"patchable-function-entry-section")
2585 "\"patchable-function-entry-section\" must not be empty");
2586 checkUnsignedBaseTenFuncAttr(Attrs,
"warn-stack-size", V);
2588 if (
auto A =
Attrs.getFnAttr(
"sign-return-address");
A.isValid()) {
2589 StringRef S =
A.getValueAsString();
2590 if (S !=
"none" && S !=
"all" && S !=
"non-leaf")
2591 CheckFailed(
"invalid value for 'sign-return-address' attribute: " + S, V);
2594 if (
auto A =
Attrs.getFnAttr(
"sign-return-address-key");
A.isValid()) {
2595 StringRef S =
A.getValueAsString();
2596 if (S !=
"a_key" && S !=
"b_key")
2597 CheckFailed(
"invalid value for 'sign-return-address-key' attribute: " + S,
2599 if (
auto AA =
Attrs.getFnAttr(
"sign-return-address"); !AA.isValid()) {
2601 "'sign-return-address-key' present without `sign-return-address`");
2605 if (
auto A =
Attrs.getFnAttr(
"branch-target-enforcement");
A.isValid()) {
2606 StringRef S =
A.getValueAsString();
2607 if (S !=
"" && S !=
"true" && S !=
"false")
2609 "invalid value for 'branch-target-enforcement' attribute: " + S, V);
2612 if (
auto A =
Attrs.getFnAttr(
"branch-protection-pauth-lr");
A.isValid()) {
2613 StringRef S =
A.getValueAsString();
2614 if (S !=
"" && S !=
"true" && S !=
"false")
2616 "invalid value for 'branch-protection-pauth-lr' attribute: " + S, V);
2619 if (
auto A =
Attrs.getFnAttr(
"guarded-control-stack");
A.isValid()) {
2620 StringRef S =
A.getValueAsString();
2621 if (S !=
"" && S !=
"true" && S !=
"false")
2622 CheckFailed(
"invalid value for 'guarded-control-stack' attribute: " + S,
2626 if (
auto A =
Attrs.getFnAttr(
"vector-function-abi-variant");
A.isValid()) {
2627 StringRef S =
A.getValueAsString();
2630 CheckFailed(
"invalid name for a VFABI variant: " + S, V);
2633 if (
auto A =
Attrs.getFnAttr(
"modular-format");
A.isValid()) {
2634 StringRef S =
A.getValueAsString();
2638 "modular-format attribute requires at least 5 arguments", V);
2639 unsigned UpperBound = FT->getNumParams() + (FT->isVarArg() ? 1 : 0);
2641 Check(!Args[1].getAsInteger(10, FormatIdx),
2642 "modular-format attribute format string index is not an integer", V);
2643 Check(FormatIdx > 0,
2644 "modular-format attribute format string index must be greater than 0",
2646 Check(FormatIdx <= UpperBound,
2647 "modular-format attribute format string index is out of bounds", V);
2648 unsigned FirstArgIdx;
2649 Check(!Args[2].getAsInteger(10, FirstArgIdx),
2650 "modular-format attribute first arg index is not an integer", V);
2651 Check(FirstArgIdx <= UpperBound,
2652 "modular-format attribute first arg index is out of bounds", V);
2654 "modular-format attribute modular implementation function name "
2658 "modular-format attribute implementation name cannot be empty", V);
2661 if (
auto A =
Attrs.getFnAttr(
"target-features");
A.isValid()) {
2662 StringRef S =
A.getValueAsString();
2664 for (
auto FeatureFlag :
split(S,
',')) {
2665 if (FeatureFlag.empty())
2667 "target-features attribute should not contain an empty string");
2669 Check(FeatureFlag[0] ==
'+' || FeatureFlag[0] ==
'-',
2670 "target feature '" + FeatureFlag +
2671 "' must start with a '+' or '-'",
2677void Verifier::verifyUnknownProfileMetadata(MDNode *MD) {
2679 "'unknown' !prof should have a single additional operand", MD);
2682 "'unknown' !prof should have an additional operand of type "
2685 "the 'unknown' !prof operand should not be an empty string");
2688void Verifier::verifyFunctionMetadata(
2689 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2690 for (
const auto &Pair : MDs) {
2691 if (Pair.first == LLVMContext::MD_prof) {
2692 MDNode *MD = Pair.second;
2694 "!prof annotations should have no less than 2 operands", MD);
2699 verifyUnknownProfileMetadata(MD);
2704 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null",
2707 "expected string with name of the !prof annotation", MD);
2712 "first operand should be 'function_entry_count'"
2713 " or 'synthetic_function_entry_count'",
2717 Check(MD->
getOperand(1) !=
nullptr,
"second operand should not be null",
2720 "expected integer argument to function_entry_count", MD);
2721 }
else if (Pair.first == LLVMContext::MD_kcfi_type) {
2722 MDNode *MD = Pair.second;
2724 "!kcfi_type must have exactly one operand", MD);
2725 Check(MD->
getOperand(0) !=
nullptr,
"!kcfi_type operand must not be null",
2728 "expected a constant operand for !kcfi_type", MD);
2731 "expected a constant integer operand for !kcfi_type", MD);
2733 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2734 }
else if (Pair.first ==
Context.getMDKindID(
"reqd_work_group_size")) {
2735 MDNode *MD = Pair.second;
2737 "reqd_work_group_size must have exactly three operands", MD);
2742 for (
unsigned I = 0;
I != 3; ++
I) {
2744 Check(
C,
"reqd_work_group_size operands must be integer constants", MD);
2748 const APInt &
Value =
C->getValue();
2750 "reqd_work_group_size operands must fit in 64 bits", MD);
2751 if (
Value.getActiveBits() > 64)
2755 Check(Dim == 0 || Product <= std::numeric_limits<uint64_t>::max() / Dim,
2756 "reqd_work_group_size product must fit in 64 bits", MD);
2757 if (Dim != 0 && Product > std::numeric_limits<uint64_t>::max() / Dim)
2765void Verifier::visitConstantExprsRecursively(
const Constant *EntryC) {
2769 if (!ConstantExprVisited.
insert(EntryC).second)
2773 Stack.push_back(EntryC);
2775 while (!
Stack.empty()) {
2780 visitConstantExpr(CE);
2783 visitConstantPtrAuth(CPA);
2788 Check(GV->
getParent() == &M,
"Referencing global in another module!",
2794 for (
const Use &U :
C->operands()) {
2798 if (!ConstantExprVisited.
insert(OpC).second)
2800 Stack.push_back(OpC);
2805void Verifier::visitConstantExpr(
const ConstantExpr *CE) {
2806 if (
CE->getOpcode() == Instruction::BitCast)
2809 "Invalid bitcast", CE);
2810 else if (
CE->getOpcode() == Instruction::PtrToAddr)
2811 checkPtrToAddr(
CE->getOperand(0)->getType(),
CE->getType(), *CE);
2814void Verifier::visitConstantPtrAuth(
const ConstantPtrAuth *CPA) {
2816 "signed ptrauth constant base pointer must have pointer type");
2819 "signed ptrauth constant must have same type as its base pointer");
2822 "signed ptrauth constant key must be i32 constant integer");
2825 "signed ptrauth constant address discriminator must be a pointer");
2828 "signed ptrauth constant discriminator must be i64 constant integer");
2831 "signed ptrauth constant deactivation symbol must be a pointer");
2835 "signed ptrauth constant deactivation symbol must be a global value "
2839bool Verifier::verifyAttributeCount(AttributeList Attrs,
unsigned Params) {
2842 return Attrs.getNumAttrSets() <= Params + 2;
2845void Verifier::verifyInlineAsmCall(
const CallBase &
Call) {
2848 unsigned LabelNo = 0;
2849 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
2859 if (CI.isIndirect) {
2862 "Operand for indirect constraint must have pointer type", &
Call);
2865 "Operand for indirect constraint must have elementtype attribute",
2869 "Elementtype attribute can only be applied for indirect "
2878 Check(LabelNo == CallBr->getNumIndirectDests(),
2879 "Number of label constraints does not match number of callbr dests",
2882 Check(LabelNo == 0,
"Label constraints can only be used with callbr",
2888void Verifier::verifyStatepoint(
const CallBase &
Call) {
2893 "gc.statepoint must read and write all memory to preserve "
2894 "reordering restrictions required by safepoint semantics",
2897 const int64_t NumPatchBytes =
2900 Check(NumPatchBytes >= 0,
2901 "gc.statepoint number of patchable bytes must be "
2906 Check(TargetElemType,
2907 "gc.statepoint callee argument must have elementtype attribute",
Call);
2909 Check(TargetFuncType,
2910 "gc.statepoint callee elementtype must be function type",
Call);
2913 Check(NumCallArgs >= 0,
2914 "gc.statepoint number of arguments to underlying call "
2917 const int NumParams = (int)TargetFuncType->getNumParams();
2918 if (TargetFuncType->isVarArg()) {
2919 Check(NumCallArgs >= NumParams,
2920 "gc.statepoint mismatch in number of vararg call args",
Call);
2923 Check(TargetFuncType->getReturnType()->isVoidTy(),
2924 "gc.statepoint doesn't support wrapping non-void "
2925 "vararg functions yet",
2928 Check(NumCallArgs == NumParams,
2929 "gc.statepoint mismatch in number of call args",
Call);
2934 "unknown flag used in gc.statepoint flags argument",
Call);
2939 for (
int i = 0; i < NumParams; i++) {
2940 Type *ParamType = TargetFuncType->getParamType(i);
2942 Check(ArgType == ParamType,
2943 "gc.statepoint call argument does not match wrapped "
2947 if (TargetFuncType->isVarArg()) {
2948 AttributeSet ArgAttrs =
Attrs.getParamAttrs(5 + i);
2950 "Attribute 'sret' cannot be used for vararg call arguments!",
Call);
2954 const int EndCallArgsInx = 4 + NumCallArgs;
2958 "gc.statepoint number of transition arguments "
2959 "must be constant integer",
2961 const int NumTransitionArgs =
2963 Check(NumTransitionArgs == 0,
2964 "gc.statepoint w/inline transition bundle is deprecated",
Call);
2965 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2969 "gc.statepoint number of deoptimization arguments "
2970 "must be constant integer",
2973 Check(NumDeoptArgs == 0,
2974 "gc.statepoint w/inline deopt operands is deprecated",
Call);
2976 const int ExpectedNumArgs = 7 + NumCallArgs;
2978 "gc.statepoint too many arguments",
Call);
2985 Check(UserCall,
"illegal use of statepoint token",
Call, U);
2989 "gc.result or gc.relocate are the only value uses "
2990 "of a gc.statepoint",
2993 Check(UserCall->getArgOperand(0) == &
Call,
2994 "gc.result connected to wrong gc.statepoint",
Call, UserCall);
2996 Check(UserCall->getArgOperand(0) == &
Call,
2997 "gc.relocate connected to wrong gc.statepoint",
Call, UserCall);
3011void Verifier::verifyFrameRecoverIndices() {
3012 for (
auto &Counts : FrameEscapeInfo) {
3014 unsigned EscapedObjectCount = Counts.second.first;
3015 unsigned MaxRecoveredIndex = Counts.second.second;
3016 Check(MaxRecoveredIndex <= EscapedObjectCount,
3017 "all indices passed to llvm.localrecover must be less than the "
3018 "number of arguments passed to llvm.localescape in the parent "
3027 UnwindDest =
II->getUnwindDest();
3029 UnwindDest = CSI->getUnwindDest();
3035void Verifier::verifySiblingFuncletUnwinds() {
3036 llvm::TimeTraceScope timeScope(
"Verifier verify sibling funclet unwinds");
3037 SmallPtrSet<Instruction *, 8> Visited;
3038 SmallPtrSet<Instruction *, 8>
Active;
3039 for (
const auto &Pair : SiblingFuncletInfo) {
3041 if (Visited.
count(PredPad))
3047 if (
Active.count(SuccPad)) {
3050 SmallVector<Instruction *, 8> CycleNodes;
3053 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
3054 if (CycleTerminator != CyclePad)
3057 }
while (CyclePad != SuccPad);
3058 Check(
false,
"EH pads can't handle each other's exceptions",
3062 if (!Visited.
insert(SuccPad).second)
3066 auto TermI = SiblingFuncletInfo.find(PredPad);
3067 if (TermI == SiblingFuncletInfo.end())
3080void Verifier::visitFunction(
const Function &
F) {
3081 visitGlobalValue(
F);
3084 FunctionType *FT =
F.getFunctionType();
3085 unsigned NumArgs =
F.arg_size();
3088 "Function context does not match Module context!", &
F);
3090 Check(!
F.hasCommonLinkage(),
"Functions may not have common linkage", &
F);
3091 Check(FT->getNumParams() == NumArgs,
3092 "# formal arguments must match # of arguments for function type!", &
F,
3094 Check(
F.getReturnType()->isFirstClassType() ||
3095 F.getReturnType()->isVoidTy() ||
F.getReturnType()->isStructTy(),
3096 "Functions cannot return aggregate values!", &
F);
3098 Check(!
F.hasStructRetAttr() ||
F.getReturnType()->isVoidTy(),
3099 "Invalid struct return type!", &
F);
3101 if (MaybeAlign
A =
F.getAlign()) {
3102 Check(
A->value() <= Value::MaximumAlignment,
3103 "huge alignment values are unsupported", &
F);
3106 AttributeList
Attrs =
F.getAttributes();
3108 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
3109 "Attribute after last parameter!", &
F);
3111 bool IsIntrinsic =
F.isIntrinsic();
3114 verifyFunctionAttrs(FT, Attrs, &
F, IsIntrinsic,
false);
3120 "Attribute 'builtin' can only be applied to a callsite.", &
F);
3122 Check(!
Attrs.hasAttrSomewhere(Attribute::ElementType),
3123 "Attribute 'elementtype' can only be applied to a callsite.", &
F);
3125 if (
Attrs.hasFnAttr(Attribute::Naked))
3126 for (
const Argument &Arg :
F.args())
3127 Check(Arg.use_empty(),
"cannot use argument of naked function", &Arg);
3132 switch (
F.getCallingConv()) {
3134 case CallingConv::C:
3136 case CallingConv::X86_INTR: {
3137 Check(
F.arg_empty() ||
Attrs.hasParamAttr(0, Attribute::ByVal),
3138 "Calling convention parameter requires byval", &
F);
3141 case CallingConv::AMDGPU_KERNEL:
3142 case CallingConv::SPIR_KERNEL:
3143 case CallingConv::AMDGPU_CS_Chain:
3144 case CallingConv::AMDGPU_CS_ChainPreserve:
3145 Check(
F.getReturnType()->isVoidTy(),
3146 "Calling convention requires void return type", &
F);
3148 case CallingConv::AMDGPU_VS:
3149 case CallingConv::AMDGPU_HS:
3150 case CallingConv::AMDGPU_GS:
3151 case CallingConv::AMDGPU_PS:
3152 case CallingConv::AMDGPU_CS:
3153 Check(!
F.hasStructRetAttr(),
"Calling convention does not allow sret", &
F);
3154 if (
F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3155 const unsigned StackAS =
DL.getAllocaAddrSpace();
3157 for (
const Argument &Arg :
F.args()) {
3158 Check(!
Attrs.hasParamAttr(i, Attribute::ByVal),
3159 "Calling convention disallows byval", &
F);
3160 Check(!
Attrs.hasParamAttr(i, Attribute::Preallocated),
3161 "Calling convention disallows preallocated", &
F);
3162 Check(!
Attrs.hasParamAttr(i, Attribute::InAlloca),
3163 "Calling convention disallows inalloca", &
F);
3165 if (
Attrs.hasParamAttr(i, Attribute::ByRef)) {
3168 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
3169 "Calling convention disallows stack byref", &
F);
3177 case CallingConv::Fast:
3178 case CallingConv::Cold:
3179 case CallingConv::Intel_OCL_BI:
3180 case CallingConv::PTX_Kernel:
3181 case CallingConv::PTX_Device:
3183 "Calling convention does not support varargs or "
3184 "perfect forwarding!",
3187 case CallingConv::AMDGPU_Gfx_WholeWave:
3188 Check(!
F.arg_empty() &&
F.arg_begin()->getType()->isIntegerTy(1),
3189 "Calling convention requires first argument to be i1", &
F);
3190 Check(!
F.arg_begin()->hasInRegAttr(),
3191 "Calling convention requires first argument to not be inreg", &
F);
3193 "Calling convention does not support varargs or "
3194 "perfect forwarding!",
3201 for (
const Argument &Arg :
F.args()) {
3202 Check(Arg.getType() == FT->getParamType(i),
3203 "Argument value does not match function argument type!", &Arg,
3204 FT->getParamType(i));
3205 Check(Arg.getType()->isFirstClassType(),
3206 "Function arguments must have first-class types!", &Arg);
3208 Check(!Arg.getType()->isMetadataTy(),
3209 "Function takes metadata but isn't an intrinsic", &Arg, &
F);
3210 Check(!Arg.getType()->isTokenLikeTy(),
3211 "Function takes token but isn't an intrinsic", &Arg, &
F);
3212 Check(!Arg.getType()->isX86_AMXTy(),
3213 "Function takes x86_amx but isn't an intrinsic", &Arg, &
F);
3217 if (
Attrs.hasParamAttr(i, Attribute::SwiftError)) {
3218 verifySwiftErrorValue(&Arg);
3224 Check(!
F.getReturnType()->isTokenLikeTy(),
3225 "Function returns a token but isn't an intrinsic", &
F);
3226 Check(!
F.getReturnType()->isX86_AMXTy(),
3227 "Function returns a x86_amx but isn't an intrinsic", &
F);
3232 F.getAllMetadata(MDs);
3233 assert(
F.hasMetadata() != MDs.
empty() &&
"Bit out-of-sync");
3234 verifyFunctionMetadata(MDs);
3240 if (
F.hasPersonalityFn()) {
3243 Check(Per->getParent() ==
F.getParent(),
3244 "Referencing personality function in another module!", &
F,
3245 F.getParent(), Per, Per->getParent());
3249 BlockEHFuncletColors.
clear();
3251 if (
F.isMaterializable()) {
3253 Check(MDs.
empty(),
"unmaterialized function cannot have metadata", &
F,
3255 }
else if (
F.isDeclaration()) {
3256 for (
const auto &
I : MDs) {
3258 CheckDI(
I.first != LLVMContext::MD_dbg ||
3260 "function declaration may only have a unique !dbg attachment",
3262 Check(
I.first != LLVMContext::MD_prof,
3263 "function declaration may not have a !prof attachment", &
F);
3266 visitMDNode(*
I.second, AreDebugLocsAllowed::Yes);
3268 Check(!
F.hasPersonalityFn(),
3269 "Function declaration shouldn't have a personality routine", &
F);
3273 Check(!IsIntrinsic,
"llvm intrinsics cannot be defined!", &
F);
3278 "Entry block to function must not have predecessors!", Entry);
3281 if (
Entry->hasAddressTaken()) {
3283 "blockaddress may not be used with the entry block!", Entry);
3286 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
3287 NumKCFIAttachments = 0;
3289 for (
const auto &
I : MDs) {
3291 auto AllowLocs = AreDebugLocsAllowed::No;
3295 case LLVMContext::MD_dbg: {
3296 ++NumDebugAttachments;
3297 CheckDI(NumDebugAttachments == 1,
3298 "function must have a single !dbg attachment", &
F,
I.second);
3300 "function !dbg attachment must be a subprogram", &
F,
I.second);
3302 "function definition may only have a distinct !dbg attachment",
3306 const Function *&AttachedTo = DISubprogramAttachments[
SP];
3307 CheckDI(!AttachedTo || AttachedTo == &
F,
3308 "DISubprogram attached to more than one function", SP, &
F);
3310 AllowLocs = AreDebugLocsAllowed::Yes;
3313 case LLVMContext::MD_prof:
3314 ++NumProfAttachments;
3315 Check(NumProfAttachments == 1,
3316 "function must have a single !prof attachment", &
F,
I.second);
3318 case LLVMContext::MD_kcfi_type:
3319 ++NumKCFIAttachments;
3320 Check(NumKCFIAttachments == 1,
3321 "function must have a single !kcfi_type attachment", &
F,
3327 visitMDNode(*
I.second, AllowLocs);
3335 bool isMaterialized =
F.getParent()->isMaterialized();
3336 if (
F.isIntrinsic() && isMaterialized) {
3338 if (
F.hasAddressTaken(&U,
false,
true,
false,
3340 Check(
false,
"Invalid user of intrinsic instruction!", U);
3347 if (IID && (isMaterialized || !
F.materialized_use_empty())) {
3351 raw_string_ostream ErrOS(ErrMsg);
3354 Printable PrintDecl([&
F](raw_ostream &OS) {
F.print(OS); });
3355 Check(IsValid, ErrMsg, PrintDecl);
3362 IID, OverloadTys,
const_cast<Module *
>(
F.getParent()), FT);
3363 Check(ExpectedName ==
F.getName(),
3364 "Intrinsic name not mangled correctly for type arguments! "
3370 auto *
N =
F.getSubprogram();
3371 HasDebugInfo = (
N !=
nullptr);
3379 SmallPtrSet<const MDNode *, 32> Seen;
3391 "DILocation's scope must be a DILocalScope",
N, &
F, &
I,
DL, Parent);
3393 DILocalScope *
Scope =
DL->getInlinedAtScope();
3394 Check(Scope,
"Failed to find DILocalScope",
DL);
3396 if (!Seen.
insert(Scope).second)
3399 DISubprogram *
SP =
Scope->getSubprogram();
3403 if ((Scope != SP) && !Seen.
insert(SP).second)
3407 "!dbg attachment points at wrong subprogram for function",
N, &
F,
3411 for (
auto &
I : BB) {
3412 VisitDebugLoc(
I,
I.getDebugLoc().getAsMDNode());
3414 if (
auto MD =
I.getMetadata(LLVMContext::MD_loop))
3417 if (BrokenDebugInfo)
3424void Verifier::visitBasicBlock(BasicBlock &BB) {
3425 InstsInThisBlock.
clear();
3426 ConvergenceVerifyHelper.
visit(BB);
3437 for (
const PHINode &PN : BB.
phis()) {
3438 Check(PN.getNumIncomingValues() == Preds.size(),
3439 "PHINode should have one entry for each predecessor of its "
3440 "parent basic block!",
3445 Values.reserve(PN.getNumIncomingValues());
3446 for (
unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3448 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3451 for (
unsigned i = 0, e =
Values.size(); i != e; ++i) {
3458 "PHI node has multiple entries for the same basic block with "
3459 "different incoming values!",
3465 "PHI node entries do not match predecessors!", &PN,
3466 Values[i].first, Preds[i]);
3474 Check(
I.getParent() == &BB,
"Instruction has bogus parent pointer!");
3478 CheckDI(!BB.getTrailingDbgRecords(),
"Basic Block has trailing DbgRecords!",
3482void Verifier::visitTerminator(Instruction &
I) {
3484 Check(&
I ==
I.getParent()->getTerminator(),
3485 "Terminator found in the middle of a basic block!",
I.getParent());
3486 visitInstruction(
I);
3489void Verifier::visitCondBrInst(CondBrInst &BI) {
3491 "Branch condition is not 'i1' type!", &BI, BI.
getCondition());
3492 visitTerminator(BI);
3495void Verifier::visitReturnInst(ReturnInst &RI) {
3498 if (
F->getReturnType()->isVoidTy())
3500 "Found return instr that returns non-void in Function of void "
3502 &RI,
F->getReturnType());
3505 "Function return type does not match operand "
3506 "type of return inst!",
3507 &RI,
F->getReturnType());
3511 visitTerminator(RI);
3514void Verifier::visitSwitchInst(SwitchInst &SI) {
3515 Check(
SI.getType()->isVoidTy(),
"Switch must have void result type!", &SI);
3518 Type *SwitchTy =
SI.getCondition()->getType();
3519 SmallPtrSet<ConstantInt*, 32>
Constants;
3520 for (
auto &Case :
SI.cases()) {
3522 "Case value is not a constant integer.", &SI);
3523 Check(Case.getCaseValue()->getType() == SwitchTy,
3524 "Switch constants must all be same type as switch value!", &SI);
3526 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3529 visitTerminator(SI);
3532void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
3534 "Indirectbr operand must have pointer type!", &BI);
3537 "Indirectbr destinations must all have pointer type!", &BI);
3539 visitTerminator(BI);
3548void Verifier::visitCallBrInst(CallBrInst &CBI) {
3551 "callbr: indirect function / invalid signature");
3553 "callbr for intrinsics currently doesn't support operand bundles");
3557 "callbr currently only supports asm-goto and selected intrinsics");
3562 Check(!
IA->canThrow(),
"Unwinding from Callbr is not allowed");
3564 verifyInlineAsmCall(CBI);
3566 visitTerminator(CBI);
3569void Verifier::visitSelectInst(SelectInst &SI) {
3572 "Invalid operands for select instruction!", &SI);
3574 Check(
SI.getTrueValue()->getType() ==
SI.getType(),
3575 "Select values must have same type as select instruction!", &SI);
3576 visitInstruction(SI);
3582void Verifier::visitUserOp1(Instruction &
I) {
3583 Check(
false,
"User-defined operators should not live outside of a pass!", &
I);
3586void Verifier::visitTruncInst(TruncInst &
I) {
3588 Type *SrcTy =
I.getOperand(0)->getType();
3589 Type *DestTy =
I.getType();
3598 "trunc source and destination must both be a vector or neither", &
I);
3599 Check(SrcBitSize > DestBitSize,
"DestTy too big for Trunc", &
I);
3601 visitInstruction(
I);
3604void Verifier::visitZExtInst(ZExtInst &
I) {
3606 Type *SrcTy =
I.getOperand(0)->getType();
3607 Type *DestTy =
I.getType();
3613 "zext source and destination must both be a vector or neither", &
I);
3617 Check(SrcBitSize < DestBitSize,
"Type too small for ZExt", &
I);
3619 visitInstruction(
I);
3622void Verifier::visitSExtInst(SExtInst &
I) {
3624 Type *SrcTy =
I.getOperand(0)->getType();
3625 Type *DestTy =
I.getType();
3634 "sext source and destination must both be a vector or neither", &
I);
3635 Check(SrcBitSize < DestBitSize,
"Type too small for SExt", &
I);
3637 visitInstruction(
I);
3640void Verifier::visitFPTruncInst(FPTruncInst &
I) {
3642 Type *SrcTy =
I.getOperand(0)->getType();
3643 Type *DestTy =
I.getType();
3651 "fptrunc source and destination must both be a vector or neither", &
I);
3652 Check(SrcBitSize > DestBitSize,
"DestTy too big for FPTrunc", &
I);
3654 visitInstruction(
I);
3657void Verifier::visitFPExtInst(FPExtInst &
I) {
3659 Type *SrcTy =
I.getOperand(0)->getType();
3660 Type *DestTy =
I.getType();
3669 "fpext source and destination must both be a vector or neither", &
I);
3670 Check(SrcBitSize < DestBitSize,
"DestTy too small for FPExt", &
I);
3672 visitInstruction(
I);
3675void Verifier::visitUIToFPInst(UIToFPInst &
I) {
3677 Type *SrcTy =
I.getOperand(0)->getType();
3678 Type *DestTy =
I.getType();
3683 Check(SrcVec == DstVec,
3684 "UIToFP source and dest must both be vector or scalar", &
I);
3686 "UIToFP source must be integer or integer vector", &
I);
3690 if (SrcVec && DstVec)
3693 "UIToFP source and dest vector length mismatch", &
I);
3695 visitInstruction(
I);
3698void Verifier::visitSIToFPInst(SIToFPInst &
I) {
3700 Type *SrcTy =
I.getOperand(0)->getType();
3701 Type *DestTy =
I.getType();
3706 Check(SrcVec == DstVec,
3707 "SIToFP source and dest must both be vector or scalar", &
I);
3709 "SIToFP source must be integer or integer vector", &
I);
3713 if (SrcVec && DstVec)
3716 "SIToFP source and dest vector length mismatch", &
I);
3718 visitInstruction(
I);
3721void Verifier::visitFPToUIInst(FPToUIInst &
I) {
3723 Type *SrcTy =
I.getOperand(0)->getType();
3724 Type *DestTy =
I.getType();
3729 Check(SrcVec == DstVec,
3730 "FPToUI source and dest must both be vector or scalar", &
I);
3733 "FPToUI result must be integer or integer vector", &
I);
3735 if (SrcVec && DstVec)
3738 "FPToUI source and dest vector length mismatch", &
I);
3740 visitInstruction(
I);
3743void Verifier::visitFPToSIInst(FPToSIInst &
I) {
3745 Type *SrcTy =
I.getOperand(0)->getType();
3746 Type *DestTy =
I.getType();
3751 Check(SrcVec == DstVec,
3752 "FPToSI source and dest must both be vector or scalar", &
I);
3755 "FPToSI result must be integer or integer vector", &
I);
3757 if (SrcVec && DstVec)
3760 "FPToSI source and dest vector length mismatch", &
I);
3762 visitInstruction(
I);
3765void Verifier::checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V) {
3774 Check(VSrc->getElementCount() == VDest->getElementCount(),
3775 "PtrToAddr vector length mismatch", V);
3778 Type *AddrTy =
DL.getAddressType(SrcTy);
3779 Check(AddrTy == DestTy,
"PtrToAddr result must be address width", V);
3782void Verifier::visitPtrToAddrInst(PtrToAddrInst &
I) {
3783 checkPtrToAddr(
I.getOperand(0)->getType(),
I.getType(),
I);
3784 visitInstruction(
I);
3787void Verifier::visitPtrToIntInst(PtrToIntInst &
I) {
3789 Type *SrcTy =
I.getOperand(0)->getType();
3790 Type *DestTy =
I.getType();
3801 Check(VSrc->getElementCount() == VDest->getElementCount(),
3802 "PtrToInt Vector length mismatch", &
I);
3805 visitInstruction(
I);
3808void Verifier::visitIntToPtrInst(IntToPtrInst &
I) {
3810 Type *SrcTy =
I.getOperand(0)->getType();
3811 Type *DestTy =
I.getType();
3821 Check(VSrc->getElementCount() == VDest->getElementCount(),
3822 "IntToPtr Vector length mismatch", &
I);
3824 visitInstruction(
I);
3827void Verifier::visitBitCastInst(BitCastInst &
I) {
3830 "Invalid bitcast", &
I);
3831 visitInstruction(
I);
3834void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &
I) {
3835 Type *SrcTy =
I.getOperand(0)->getType();
3836 Type *DestTy =
I.getType();
3843 "AddrSpaceCast must be between different address spaces", &
I);
3845 Check(SrcVTy->getElementCount() ==
3847 "AddrSpaceCast vector pointer number of elements mismatch", &
I);
3848 visitInstruction(
I);
3853void Verifier::visitPHINode(PHINode &PN) {
3860 "PHI nodes not grouped at top of basic block!", &PN, PN.
getParent());
3869 "PHI node operands are not the same type as the result!", &PN);
3874 visitInstruction(PN);
3877void Verifier::visitCallBase(CallBase &
Call) {
3879 "Called function must be a pointer!",
Call);
3883 if (FTy->isVarArg())
3885 "Called function requires more parameters than were provided!",
Call);
3888 "Incorrect number of arguments passed to called function!",
Call);
3891 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3893 "Call parameter type does not match function signature!",
3899 "Attribute after last parameter!",
Call);
3906 "Intrinsic called with incompatible signature",
Call);
3910 "calling convention does not permit calls",
Call);
3916 auto VerifyTypeAlign = [&](
Type *Ty,
const Twine &Message) {
3919 Align ABIAlign =
DL.getABITypeAlign(Ty);
3920 Check(ABIAlign.
value() <= Value::MaximumAlignment,
3921 "Incorrect alignment of " + Message +
" to called function!",
Call);
3925 VerifyTypeAlign(FTy->getReturnType(),
"return type");
3926 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3927 Type *Ty = FTy->getParamType(i);
3928 VerifyTypeAlign(Ty,
"argument passed");
3932 if (
Attrs.hasFnAttr(Attribute::Speculatable)) {
3936 "speculatable attribute may not apply to call sites",
Call);
3939 if (
Attrs.hasFnAttr(Attribute::Preallocated)) {
3941 "preallocated as a call site attribute can only be on "
3942 "llvm.call.preallocated.arg");
3945 Check(!
Attrs.hasFnAttr(Attribute::DenormalFPEnv),
3946 "denormal_fpenv attribute may not apply to call sites",
Call);
3957 Check(AI->isUsedWithInAlloca(),
3958 "inalloca argument for call has mismatched alloca", AI,
Call);
3964 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3968 Check(AI->isSwiftError(),
3969 "swifterror argument for call has mismatched alloca", AI,
Call);
3973 Check(ArgI,
"swifterror argument should come from an alloca or parameter",
3974 SwiftErrorArg,
Call);
3975 Check(ArgI->hasSwiftErrorAttr(),
3976 "swifterror argument for call has mismatched parameter", ArgI,
3980 if (
Attrs.hasParamAttr(i, Attribute::ImmArg)) {
3983 Check(Callee &&
Callee->hasParamAttribute(i, Attribute::ImmArg),
3992 "immarg operand has non-immediate parameter", ArgVal,
Call);
3998 const ConstantRange &CR =
4001 formatv(
"immarg value {} for arg {} out of range {}",
4002 CI->getValue(), i, CR),
4009 formatv(
"immarg value {} for arg {} out of range set",
4019 Check(hasOB != isMustTail,
4020 "preallocated operand either requires a preallocated bundle or "
4021 "the call to be musttail (but not both)",
4026 if (FTy->isVarArg()) {
4028 bool SawNest =
false;
4029 bool SawReturned =
false;
4031 for (
unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
4032 if (
Attrs.hasParamAttr(Idx, Attribute::Nest))
4034 if (
Attrs.hasParamAttr(Idx, Attribute::Returned))
4039 for (
unsigned Idx = FTy->getNumParams(); Idx <
Call.
arg_size(); ++Idx) {
4041 AttributeSet ArgAttrs =
Attrs.getParamAttrs(Idx);
4042 verifyParameterAttrs(ArgAttrs, Ty, &
Call);
4045 Check(!SawNest,
"More than one parameter has attribute nest!",
Call);
4050 Check(!SawReturned,
"More than one parameter has attribute returned!",
4053 "Incompatible argument and return types for 'returned' "
4063 "Attribute 'sret' cannot be used for vararg call arguments!",
4068 "inalloca isn't on the last argument!",
Call);
4074 for (
Type *ParamTy : FTy->params()) {
4075 Check(!ParamTy->isMetadataTy(),
4076 "Function has metadata parameter but isn't an intrinsic",
Call);
4077 Check(!ParamTy->isTokenLikeTy(),
4078 "Function has token parameter but isn't an intrinsic",
Call);
4084 Check(!FTy->getReturnType()->isTokenLikeTy(),
4085 "Return type cannot be token for indirect call!");
4086 Check(!FTy->getReturnType()->isX86_AMXTy(),
4087 "Return type cannot be x86_amx for indirect call!");
4091 visitIntrinsicCall(ID,
Call);
4096 bool FoundDeoptBundle =
false, FoundFuncletBundle =
false,
4097 FoundGCTransitionBundle =
false, FoundCFGuardTargetBundle =
false,
4098 FoundPreallocatedBundle =
false, FoundGCLiveBundle =
false,
4099 FoundPtrauthBundle =
false, FoundKCFIBundle =
false,
4100 FoundAttachedCallBundle =
false;
4105 Check(!FoundDeoptBundle,
"Multiple deopt operand bundles",
Call);
4106 FoundDeoptBundle =
true;
4108 Check(!FoundGCTransitionBundle,
"Multiple gc-transition operand bundles",
4110 FoundGCTransitionBundle =
true;
4112 Check(!FoundFuncletBundle,
"Multiple funclet operand bundles",
Call);
4113 FoundFuncletBundle =
true;
4115 "Expected exactly one funclet bundle operand",
Call);
4117 "Funclet bundle operands should correspond to a FuncletPadInst",
4120 Check(!FoundCFGuardTargetBundle,
"Multiple CFGuardTarget operand bundles",
4122 FoundCFGuardTargetBundle =
true;
4124 "Expected exactly one cfguardtarget bundle operand",
Call);
4126 Check(!FoundPtrauthBundle,
"Multiple ptrauth operand bundles",
Call);
4127 FoundPtrauthBundle =
true;
4129 "Expected exactly two ptrauth bundle operands",
Call);
4131 BU.
Inputs[0]->getType()->isIntegerTy(32),
4132 "Ptrauth bundle key operand must be an i32 constant",
Call);
4134 "Ptrauth bundle discriminator operand must be an i64",
Call);
4136 Check(!FoundKCFIBundle,
"Multiple kcfi operand bundles",
Call);
4137 FoundKCFIBundle =
true;
4138 Check(BU.
Inputs.size() == 1,
"Expected exactly one kcfi bundle operand",
4141 BU.
Inputs[0]->getType()->isIntegerTy(32),
4142 "Kcfi bundle operand must be an i32 constant",
Call);
4144 Check(!FoundPreallocatedBundle,
"Multiple preallocated operand bundles",
4146 FoundPreallocatedBundle =
true;
4148 "Expected exactly one preallocated bundle operand",
Call);
4151 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
4152 "\"preallocated\" argument must be a token from "
4153 "llvm.call.preallocated.setup",
4156 Check(!FoundGCLiveBundle,
"Multiple gc-live operand bundles",
Call);
4157 FoundGCLiveBundle =
true;
4159 Check(!FoundAttachedCallBundle,
4160 "Multiple \"clang.arc.attachedcall\" operand bundles",
Call);
4161 FoundAttachedCallBundle =
true;
4162 verifyAttachedCallBundle(
Call, BU);
4168 "Direct call cannot have a ptrauth bundle",
Call);
4180 "inlinable function call in a function with "
4181 "debug info must have a !dbg location",
4185 verifyInlineAsmCall(
Call);
4189 visitInstruction(
Call);
4192void Verifier::verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs,
4195 Twine(
"inalloca attribute not allowed in ") +
Context);
4197 Twine(
"inreg attribute not allowed in ") +
Context);
4198 Check(!
Attrs.contains(Attribute::SwiftError),
4199 Twine(
"swifterror attribute not allowed in ") +
Context);
4200 Check(!
Attrs.contains(Attribute::Preallocated),
4201 Twine(
"preallocated attribute not allowed in ") +
Context);
4203 Twine(
"byref attribute not allowed in ") +
Context);
4208 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
4209 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
4210 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
4212 AttrBuilder Copy(
C);
4213 for (
auto AK : ABIAttrs) {
4214 Attribute Attr = Attrs.getParamAttrs(
I).getAttribute(AK);
4216 Copy.addAttribute(Attr);
4220 if (Attrs.hasParamAttr(
I, Attribute::Alignment) &&
4221 (Attrs.hasParamAttr(
I, Attribute::ByVal) ||
4222 Attrs.hasParamAttr(
I, Attribute::ByRef)))
4223 Copy.addAlignmentAttr(Attrs.getParamAlignment(
I));
4227void Verifier::verifyMustTailCall(CallInst &CI) {
4231 FunctionType *CallerTy =
F->getFunctionType();
4233 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
4234 "cannot guarantee tail call due to mismatched varargs", &CI);
4235 Check(CallerTy->getReturnType() == CalleeTy->getReturnType(),
4236 "cannot guarantee tail call due to mismatched return types", &CI);
4240 "cannot guarantee tail call due to mismatched calling conv", &CI);
4248 Check(Ret,
"musttail call must precede a ret", &CI);
4251 "musttail call result must be returned", Ret);
4253 AttributeList CallerAttrs =
F->getAttributes();
4258 CI.
getCallingConv() == CallingConv::Tail ?
"tailcc" :
"swifttailcc";
4262 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4264 SmallString<32>
Context{CCName, StringRef(
" musttail caller")};
4265 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4267 for (
unsigned I = 0,
E = CalleeTy->getNumParams();
I !=
E; ++
I) {
4269 SmallString<32>
Context{CCName, StringRef(
" musttail callee")};
4270 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4273 Check(!CallerTy->isVarArg(), Twine(
"cannot guarantee ") + CCName +
4274 " 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) {
4283 Check(CallerTy->getParamType(
I) == CalleeTy->getParamType(
I),
4284 "cannot guarantee tail call due to mismatched parameter types",
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) {
4459 GEP.getModule()->getModuleFlag(
"require-logical-pointer")))
4460 Check(!MD->getZExtValue(),
4461 "Non-logical getelementptr disallowed for this module.");
4463 Type *TargetTy =
GEP.getPointerOperandType()->getScalarType();
4466 "GEP base pointer is not a vector or a vector of pointers", &
GEP);
4467 Check(
GEP.getSourceElementType()->isSized(),
"GEP into unsized type!", &
GEP);
4470 Check(!STy->isScalableTy(),
4471 "getelementptr cannot target structure that contains scalable vector"
4476 SmallVector<Value *, 16> Idxs(
GEP.indices());
4478 all_of(Idxs, [](
Value *V) {
return V->getType()->isIntOrIntVectorTy(); }),
4479 "GEP indexes must be integers", &
GEP);
4482 Check(ElTy,
"Invalid indices for GEP pointer type!", &
GEP);
4486 Check(PtrTy &&
GEP.getResultElementType() == ElTy,
4487 "GEP is not of right type for indices!", &
GEP, ElTy);
4491 ElementCount GEPWidth = GEPVTy->getElementCount();
4492 if (
GEP.getPointerOperandType()->isVectorTy())
4496 "Vector GEP result width doesn't match operand's", &
GEP);
4497 for (
Value *Idx : Idxs) {
4498 Type *IndexTy = Idx->getType();
4500 ElementCount IndexWidth = IndexVTy->getElementCount();
4501 Check(IndexWidth == GEPWidth,
"Invalid GEP index vector width", &
GEP);
4504 "All GEP indices should be of integer type");
4511 GTI != GTE; ++GTI) {
4512 if (GTI.isVector()) {
4513 Type *ElemTy = GTI.getIndexedType();
4514 Check(
DL.typeSizeEqualsStoreSize(ElemTy),
4515 "GEP into vector with non-byte-addressable element type", &
GEP);
4519 Check(
GEP.getAddressSpace() == PtrTy->getAddressSpace(),
4520 "GEP address space doesn't match type", &
GEP);
4522 visitInstruction(
GEP);
4526 return A.getUpper() ==
B.getLower() ||
A.getLower() ==
B.getUpper();
4531void Verifier::verifyRangeLikeMetadata(
const Value &
I,
const MDNode *
Range,
4532 Type *Ty, RangeLikeMetadataKind Kind) {
4533 unsigned NumOperands =
Range->getNumOperands();
4534 Check(NumOperands % 2 == 0,
"Unfinished range!",
Range);
4535 unsigned NumRanges = NumOperands / 2;
4536 Check(NumRanges >= 1,
"It should have at least one range!",
Range);
4538 ConstantRange LastRange(1,
true);
4539 for (
unsigned i = 0; i < NumRanges; ++i) {
4542 Check(
Low,
"The lower limit must be an integer!",
Low);
4547 Check(
High->getType() ==
Low->getType(),
"Range pair types must match!",
4550 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4552 "noalias.addrspace type must be i32!", &
I);
4555 "Range types must match instruction type!", &
I);
4558 APInt HighV =
High->getValue();
4559 APInt LowV =
Low->getValue();
4564 "The upper and lower limits cannot be the same value", &
I);
4566 ConstantRange CurRange(LowV, HighV);
4567 Check(!CurRange.isEmptySet() &&
4568 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
4569 !CurRange.isFullSet()),
4570 "Range must not be empty!",
Range);
4572 Check(CurRange.intersectWith(LastRange).isEmptySet(),
4573 "Intervals are overlapping",
Range);
4574 Check(LowV.
sgt(LastRange.getLower()),
"Intervals are not in order",
4579 LastRange = ConstantRange(LowV, HighV);
4581 if (NumRanges > 2) {
4586 ConstantRange FirstRange(FirstLow, FirstHigh);
4587 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
4588 "Intervals are overlapping",
Range);
4594void Verifier::visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty) {
4596 "precondition violation");
4597 verifyRangeLikeMetadata(
I,
Range, Ty, RangeLikeMetadataKind::Range);
4600void Verifier::visitNoFPClassMetadata(Instruction &
I, MDNode *NoFPClass,
4602 Check(AttributeFuncs::isNoFPClassCompatibleType(Ty),
4603 "nofpclass only applies to floating-point typed loads",
I);
4606 "nofpclass must have exactly one entry", NoFPClass);
4607 ConstantInt *MaskVal =
4610 "nofpclass entry must be a constant i32", NoFPClass);
4612 Check(Val != 0,
"'nofpclass' must have at least one test bit set", NoFPClass,
4616 "Invalid value for 'nofpclass' test mask", NoFPClass,
I);
4619void Verifier::visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
4622 "precondition violation");
4623 verifyRangeLikeMetadata(
I,
Range, Ty,
4624 RangeLikeMetadataKind::NoaliasAddrspace);
4627void Verifier::checkAtomicMemAccessSize(
Type *Ty,
const Instruction *
I) {
4628 unsigned Size =
DL.getTypeSizeInBits(Ty).getFixedValue();
4629 Check(
Size >= 8,
"atomic memory access' size must be byte-sized", Ty,
I);
4631 "atomic memory access' operand must have a power-of-two size", Ty,
I);
4634void Verifier::visitLoadInst(LoadInst &LI) {
4636 Check(PTy,
"Load operand must be a pointer.", &LI);
4639 Check(
A->value() <= Value::MaximumAlignment,
4640 "huge alignment values are unsupported", &LI);
4642 Check(ElTy->
isSized(),
"loading unsized types is not allowed", &LI);
4645 LI.
getOrdering() != AtomicOrdering::AcquireRelease,
4646 "Load cannot have Release ordering", &LI);
4650 "atomic elementwise load cannot be sequentially consistent.", &LI);
4653 "atomic elementwise load operand must have fixed vector type!", &LI,
4656 checkAtomicMemAccessSize(VecTy->getElementType(), &LI);
4662 "atomic load operand must have integer, byte, pointer, floating "
4663 "point, or vector type!",
4666 checkAtomicMemAccessSize(ElTy, &LI);
4670 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4673 visitInstruction(LI);
4676void Verifier::visitStoreInst(StoreInst &SI) {
4678 Check(PTy,
"Store operand must be a pointer.", &SI);
4679 Type *ElTy =
SI.getOperand(0)->getType();
4680 if (MaybeAlign
A =
SI.getAlign()) {
4681 Check(
A->value() <= Value::MaximumAlignment,
4682 "huge alignment values are unsupported", &SI);
4684 Check(ElTy->
isSized(),
"storing unsized types is not allowed", &SI);
4685 if (
SI.isAtomic()) {
4686 Check(
SI.getOrdering() != AtomicOrdering::Acquire &&
4687 SI.getOrdering() != AtomicOrdering::AcquireRelease,
4688 "Store cannot have Acquire ordering", &SI);
4690 if (
SI.isElementwise()) {
4691 Check(
SI.getOrdering() != AtomicOrdering::SequentiallyConsistent,
4692 "atomic elementwise store cannot be sequentially consistent.", &SI);
4696 "atomic elementwise store operand must have fixed vector type!",
4699 checkAtomicMemAccessSize(VecTy->getElementType(), &SI);
4705 "atomic store operand must have integer, byte, pointer, floating "
4706 "point, or vector type!",
4708 checkAtomicMemAccessSize(ElTy, &SI);
4710 Check(!
SI.isElementwise(),
"non-atomic store cannot be elementwise", &SI);
4712 "Non-atomic store cannot have SynchronizationScope specified", &SI);
4714 visitInstruction(SI);
4718void Verifier::verifySwiftErrorCall(CallBase &
Call,
4719 const Value *SwiftErrorVal) {
4721 if (
I.value() == SwiftErrorVal) {
4723 "swifterror value when used in a callsite should be marked "
4724 "with swifterror attribute",
4725 SwiftErrorVal,
Call);
4730void Verifier::verifySwiftErrorValue(
const Value *SwiftErrorVal) {
4733 for (
const User *U : SwiftErrorVal->
users()) {
4736 "swifterror value can only be loaded and stored from, or "
4737 "as a swifterror argument!",
4741 Check(StoreI->getOperand(1) == SwiftErrorVal,
4742 "swifterror value should be the second operand when used "
4746 verifySwiftErrorCall(*
const_cast<CallBase *
>(
Call), SwiftErrorVal);
4750void Verifier::visitAllocaInst(AllocaInst &AI) {
4753 Check(!MD->getZExtValue(),
4754 "Non-logical alloca disallowed for this module.");
4757 SmallPtrSet<Type*, 4> Visited;
4758 Check(Ty->
isSized(&Visited),
"Cannot allocate unsized type", &AI);
4762 "Alloca has illegal target extension type", &AI);
4764 "Alloca array size must have integer type", &AI);
4766 Check(
A->value() <= Value::MaximumAlignment,
4767 "huge alignment values are unsupported", &AI);
4773 "swifterror alloca must not be array allocation", &AI);
4774 verifySwiftErrorValue(&AI);
4777 visitInstruction(AI);
4783void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4786 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4787 checkAtomicMemAccessSize(ElTy, &CXI);
4788 visitInstruction(CXI);
4791void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
4793 "atomicrmw instructions cannot be unordered.", &RMWI);
4799 "atomicrmw elementwise cannot be sequentially consistent.", &RMWI);
4801 Check(VecTy,
"atomicrmw elementwise operand must have fixed vector type!",
4804 checkAtomicMemAccessSize(VecTy->getElementType(), &RMWI);
4811 " operand must be an integer type, a floating-point type, a "
4812 "pointer type, or a fixed vector of any of these types!",
4817 " operand must have floating-point or fixed vector of "
4824 " operand must have integer or fixed vector of integer type!",
4827 checkAtomicMemAccessSize(ElTy, &RMWI);
4829 "Invalid binary operation!", &RMWI);
4830 visitInstruction(RMWI);
4833void Verifier::visitFenceInst(FenceInst &FI) {
4835 Check(Ordering == AtomicOrdering::Acquire ||
4836 Ordering == AtomicOrdering::Release ||
4837 Ordering == AtomicOrdering::AcquireRelease ||
4838 Ordering == AtomicOrdering::SequentiallyConsistent,
4839 "fence instructions may only have acquire, release, acq_rel, or "
4840 "seq_cst ordering.",
4842 visitInstruction(FI);
4845void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
4848 "Invalid ExtractValueInst operands!", &EVI);
4850 visitInstruction(EVI);
4853void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
4857 "Invalid InsertValueInst operands!", &IVI);
4859 visitInstruction(IVI);
4864 return FPI->getParentPad();
4869void Verifier::visitEHPadPredecessors(Instruction &
I) {
4875 Check(BB != &
F->getEntryBlock(),
"EH pad cannot be in entry block.", &
I);
4883 Check(
II &&
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4884 "Block containing LandingPadInst must be jumped to "
4885 "only by the unwind edge of an invoke.",
4893 "Block containg CatchPadInst must be jumped to "
4894 "only by its catchswitch.",
4896 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4897 "Catchswitch cannot unwind to one of its catchpads",
4898 CPI->getCatchSwitch(), CPI);
4910 Check(
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4911 "EH pad must be jumped to via an unwind edge", ToPad,
II);
4914 if (CalledFn && CalledFn->isIntrinsic() &&
II->doesNotThrow() &&
4918 FromPad = Bundle->Inputs[0];
4922 FromPad = CRI->getOperand(0);
4923 Check(FromPad != ToPadParent,
"A cleanupret must exit its cleanup", CRI);
4927 Check(
false,
"EH pad must be jumped to via an unwind edge", ToPad, TI);
4931 SmallPtrSet<Value *, 8> Seen;
4933 Check(FromPad != ToPad,
4934 "EH pad cannot handle exceptions raised within it", FromPad, TI);
4935 if (FromPad == ToPadParent) {
4940 "A single unwind edge may only enter one EH pad", TI);
4941 Check(Seen.
insert(FromPad).second,
"EH pad jumps through a cycle of pads",
4947 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
4952void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
4956 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
4958 visitEHPadPredecessors(LPI);
4960 if (!LandingPadResultTy)
4961 LandingPadResultTy = LPI.
getType();
4964 "The landingpad instruction should have a consistent result type "
4965 "inside a function.",
4969 Check(
F->hasPersonalityFn(),
4970 "LandingPadInst needs to be in a function with a personality.", &LPI);
4975 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
4981 "Catch operand does not have pointer type!", &LPI);
4983 Check(LPI.
isFilter(i),
"Clause is neither catch nor filter!", &LPI);
4985 "Filter operand is not an array of constants!", &LPI);
4989 visitInstruction(LPI);
4992void Verifier::visitResumeInst(ResumeInst &RI) {
4994 "ResumeInst needs to be in a function with a personality.", &RI);
4996 if (!LandingPadResultTy)
5000 "The resume instruction should have a consistent result type "
5001 "inside a function.",
5004 visitTerminator(RI);
5007void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
5011 Check(
F->hasPersonalityFn(),
5012 "CatchPadInst needs to be in a function with a personality.", &CPI);
5015 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
5021 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
5026 return isa<Constant>(V) || isa<AllocaInst>(V);
5028 "Argument operand must be alloca or constant.", &CPI);
5030 visitEHPadPredecessors(CPI);
5031 visitFuncletPadInst(CPI);
5034void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
5036 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
5039 visitTerminator(CatchReturn);
5042void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
5046 Check(
F->hasPersonalityFn(),
5047 "CleanupPadInst needs to be in a function with a personality.", &CPI);
5052 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
5056 "CleanupPadInst has an invalid parent.", &CPI);
5058 visitEHPadPredecessors(CPI);
5059 visitFuncletPadInst(CPI);
5062void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
5063 User *FirstUser =
nullptr;
5064 Value *FirstUnwindPad =
nullptr;
5066 SmallPtrSet<FuncletPadInst *, 8> Seen;
5068 while (!Worklist.empty()) {
5069 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
5071 "FuncletPadInst must not be nested within itself", CurrentPad);
5072 Value *UnresolvedAncestorPad =
nullptr;
5073 for (User *U : CurrentPad->
users()) {
5076 UnwindDest = CRI->getUnwindDest();
5082 if (CSI->unwindsToCaller())
5084 UnwindDest = CSI->getUnwindDest();
5086 UnwindDest =
II->getUnwindDest();
5096 Worklist.push_back(CPI);
5111 if (UnwindParent == CurrentPad)
5117 Value *ExitedPad = CurrentPad;
5120 if (ExitedPad == &FPI) {
5125 UnresolvedAncestorPad = &FPI;
5129 if (ExitedParent == UnwindParent) {
5133 UnresolvedAncestorPad = ExitedParent;
5136 ExitedPad = ExitedParent;
5142 UnresolvedAncestorPad = &FPI;
5149 Check(UnwindPad == FirstUnwindPad,
5150 "Unwind edges out of a funclet "
5151 "pad must have the same unwind "
5153 &FPI, U, FirstUser);
5156 FirstUnwindPad = UnwindPad;
5165 if (CurrentPad != &FPI)
5168 if (UnresolvedAncestorPad) {
5169 if (CurrentPad == UnresolvedAncestorPad) {
5173 assert(CurrentPad == &FPI);
5181 Value *ResolvedPad = CurrentPad;
5182 while (!Worklist.empty()) {
5183 Value *UnclePad = Worklist.back();
5187 while (ResolvedPad != AncestorPad) {
5189 if (ResolvedParent == UnresolvedAncestorPad) {
5192 ResolvedPad = ResolvedParent;
5196 if (ResolvedPad != AncestorPad)
5199 Worklist.pop_back();
5204 if (FirstUnwindPad) {
5206 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
5207 Value *SwitchUnwindPad;
5208 if (SwitchUnwindDest)
5212 Check(SwitchUnwindPad == FirstUnwindPad,
5213 "Unwind edges out of a catch must have the same unwind dest as "
5214 "the parent catchswitch",
5215 &FPI, FirstUser, CatchSwitch);
5219 visitInstruction(FPI);
5222void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
5226 Check(
F->hasPersonalityFn(),
5227 "CatchSwitchInst needs to be in a function with a personality.",
5233 "CatchSwitchInst not the first non-PHI instruction in the block.",
5238 "CatchSwitchInst has an invalid parent.", ParentPad);
5243 "CatchSwitchInst must unwind to an EH block which is not a "
5249 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
5253 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
5255 for (BasicBlock *Handler : CatchSwitch.
handlers()) {
5257 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
5260 visitEHPadPredecessors(CatchSwitch);
5261 visitTerminator(CatchSwitch);
5264void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
5266 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
5272 "CleanupReturnInst must unwind to an EH block which is not a "
5277 visitTerminator(CRI);
5280void Verifier::verifyDominatesUse(Instruction &
I,
unsigned i) {
5286 if (
II->getNormalDest() ==
II->getUnwindDest())
5300 const Use &
U =
I.getOperandUse(i);
5301 Check(DT.dominates(
Op, U),
"Instruction does not dominate all uses!",
Op, &
I);
5304void Verifier::visitDereferenceableMetadata(Instruction&
I, MDNode* MD) {
5305 Check(
I.getType()->isPointerTy(),
5306 "dereferenceable, dereferenceable_or_null "
5307 "apply only to pointer types",
5310 "dereferenceable, dereferenceable_or_null apply only to load"
5311 " and inttoptr instructions, use attributes for calls or invokes",
5314 "dereferenceable, dereferenceable_or_null "
5315 "take one operand!",
5320 "dereferenceable_or_null metadata value must be an i64!",
5324void Verifier::visitNoFreeObjMetadata(Instruction &
I, MDNode *MD) {
5325 Check(
I.getType()->isPointerTy(),
"nofreeobj applies only to pointer types",
5328 "nofreeobj applies only to inttoptr instruction", &
I);
5332void Verifier::visitProfMetadata(Instruction &
I, MDNode *MD) {
5333 auto GetBranchingTerminatorNumOperands = [&]() {
5334 unsigned ExpectedNumOperands = 0;
5338 ExpectedNumOperands =
SI->getNumSuccessors();
5340 ExpectedNumOperands = 1;
5342 ExpectedNumOperands = IBI->getNumDestinations();
5344 ExpectedNumOperands = 2;
5347 return ExpectedNumOperands;
5350 "!prof annotations should have at least 1 operand", MD);
5352 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null", MD);
5354 "expected string with name of the !prof annotation", MD);
5360 "'unknown' !prof should only appear on instructions on which "
5361 "'branch_weights' would",
5363 verifyUnknownProfileMetadata(MD);
5368 "!prof annotations should have no less than 2 operands", MD);
5374 Check(NumBranchWeights == 1 || NumBranchWeights == 2,
5375 "Wrong number of InvokeInst branch_weights operands", MD);
5377 const unsigned ExpectedNumOperands = GetBranchingTerminatorNumOperands();
5378 if (ExpectedNumOperands == 0)
5379 CheckFailed(
"!prof branch_weights are not allowed for this instruction",
5382 Check(NumBranchWeights == ExpectedNumOperands,
"Wrong number of operands",
5388 Check(MDO,
"second operand should not be null", MD);
5390 "!prof brunch_weights operand is not a const int");
5395 Check(KindInt,
"VP !prof missing kind argument", MD);
5398 Check(Kind >= InstrProfValueKind::IPVK_First &&
5399 Kind <= InstrProfValueKind::IPVK_Last,
5400 "Invalid VP !prof kind", MD);
5402 "VP !prof should have an even number "
5403 "of arguments after 'VP'",
5405 if (Kind == InstrProfValueKind::IPVK_IndirectCallTarget ||
5406 Kind == InstrProfValueKind::IPVK_MemOPSize)
5408 "VP !prof indirect call or memop size expected to be applied to "
5409 "CallBase instructions only",
5412 DenseSet<uint64_t> ProfileValues;
5414 ConstantInt *ProfileValue =
5416 Check(ProfileValue,
"VP !prof value operand is not a const int", MD);
5418 auto [ValueIt,
Inserted] = ProfileValues.
insert(ProfileValueInt);
5419 Check(Inserted,
"VP !prof should not have duplicate profile values", MD);
5422 CheckFailed(
"expected either branch_weights or VP profile name", MD);
5426void Verifier::visitDIAssignIDMetadata(Instruction &
I, MDNode *MD) {
5427 assert(
I.hasMetadata(LLVMContext::MD_DIAssignID));
5432 bool ExpectedInstTy =
5434 CheckDI(ExpectedInstTy,
"!DIAssignID attached to unexpected instruction kind",
5439 for (
auto *User : AsValue->users()) {
5441 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
5445 CheckDI(DAI->getFunction() ==
I.getFunction(),
5446 "dbg.assign not in same function as inst", DAI, &
I);
5449 for (DbgVariableRecord *DVR :
5452 "!DIAssignID should only be used by Assign DVRs.", MD, DVR);
5453 CheckDI(DVR->getFunction() ==
I.getFunction(),
5454 "DVRAssign not in same function as inst", DVR, &
I);
5458void Verifier::visitMMRAMetadata(Instruction &
I, MDNode *MD) {
5460 "!mmra metadata attached to unexpected instruction kind",
I, MD);
5471 for (
const MDOperand &MDOp : MD->
operands())
5473 "!mmra metadata tuple operand is not an MMRA tag",
I, MDOp.get());
5476void Verifier::visitCallStackMetadata(MDNode *MD) {
5480 "call stack metadata should have at least 1 operand", MD);
5484 "call stack metadata operand should be constant integer",
Op);
5487void Verifier::visitMemProfMetadata(Instruction &
I, MDNode *MD) {
5490 Check(
I.hasMetadata(LLVMContext::MD_callsite),
5491 "!memprof metadata requires !callsite metadata", &
I, MD);
5493 "!memprof annotations should have at least 1 metadata operand "
5498 for (
auto &MIBOp : MD->
operands()) {
5503 Check(MIB->getNumOperands() >= 2,
5504 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
5507 Check(MIB->getOperand(0) !=
nullptr,
5508 "!memprof MemInfoBlock first operand should not be null", MIB);
5510 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
5512 visitCallStackMetadata(StackMD);
5516 "!memprof MemInfoBlock second operand should be an MDString", MIB);
5519 for (
unsigned I = 2;
I < MIB->getNumOperands(); ++
I) {
5521 Check(OpNode,
"Not all !memprof MemInfoBlock operands 2 to N are MDNode",
5523 Check(OpNode->getNumOperands() == 2,
5524 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with 2 "
5529 [](
const MDOperand &
Op) {
5530 return mdconst::hasa<ConstantInt>(Op);
5532 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with "
5533 "ConstantInt operands",
5539void Verifier::visitCallsiteMetadata(Instruction &
I, MDNode *MD) {
5543 visitCallStackMetadata(MD);
5546void Verifier::visitCalleeTypeMetadata(Instruction &
I, MDNode *MD) {
5551 "The callee_type metadata must be a list of callgraph metadata nodes",
5554 Check(CallgraphMD->getNumOperands() == 1,
5555 "Well-formed callgraph metadata must contain exactly one "
5559 "The operand of callgraph metadata for functions must be an MDString",
5564void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
5567 "annotation must have at least one operand");
5569 bool TupleOfStrings =
5575 "operands must be a string or a tuple of strings");
5579void Verifier::visitAliasScopeMetadata(
const MDNode *MD) {
5584 "first scope operand must be self-referential or string", MD);
5587 "third scope operand must be string (if used)", MD);
5590 Check(
Domain !=
nullptr,
"second scope operand must be MDNode", MD);
5592 unsigned NumDomainOps =
Domain->getNumOperands();
5593 Check(NumDomainOps >= 1 && NumDomainOps <= 2,
5594 "domain must have one or two operands",
Domain);
5597 "first domain operand must be self-referential or string",
Domain);
5598 if (NumDomainOps == 2)
5600 "second domain operand must be string (if used)",
Domain);
5603void Verifier::visitAliasScopeListMetadata(
const MDNode *MD) {
5606 Check(OpMD !=
nullptr,
"scope list must consist of MDNodes", MD);
5607 visitAliasScopeMetadata(OpMD);
5611void Verifier::visitAccessGroupMetadata(
const MDNode *MD) {
5612 auto IsValidAccessScope = [](
const MDNode *MD) {
5627 Check(OpMD !=
nullptr,
"Access scope list must consist of MDNodes", MD);
5628 Check(IsValidAccessScope(OpMD),
5629 "Access scope list contains invalid access scope", MD);
5633void Verifier::visitCapturesMetadata(Instruction &
I,
const MDNode *Captures) {
5634 static const char *ValidArgs[] = {
"address_is_null",
"address",
5635 "read_provenance",
"provenance"};
5638 Check(SI,
"!captures metadata can only be applied to store instructions", &
I);
5639 Check(
SI->getValueOperand()->getType()->isPointerTy(),
5640 "!captures metadata can only be applied to store with value operand of "
5648 Check(Str,
"!captures metadata must be a list of strings", &
I);
5650 "invalid entry in !captures metadata", &
I, Str);
5654void Verifier::visitAllocTokenMetadata(Instruction &
I, MDNode *MD) {
5659 "expected integer constant", MD);
5662void Verifier::visitInlineHistoryMetadata(Instruction &
I, MDNode *MD) {
5671 ->stripPointerCastsAndAliases()),
5672 "!inline_history operands must be functions or null", MD);
5676void Verifier::visitMemCacheHintMetadata(Instruction &
I, MDNode *MD) {
5677 Check(
I.mayReadOrWriteMemory(),
5678 "!mem.cache_hint is only valid on memory operations", &
I);
5681 "!mem.cache_hint must have even number of operands "
5682 "(operand_no, hint_node pairs)",
5688 "!mem.cache_hint is not supported on non-intrinsic calls", &
I);
5690 unsigned NumOperands = CB ? CB->arg_size() :
I.getNumOperands();
5692 SmallDenseSet<unsigned, 4> SeenOperandNos;
5693 std::optional<uint64_t> LastOperandNo;
5699 "!mem.cache_hint must alternate between i32 operand numbers and "
5700 "metadata hint nodes",
5703 Check(OpNoCI->getValue().isNonNegative(),
5704 "!mem.cache_hint operand number must be non-negative", MD);
5706 uint64_t OperandNo = OpNoCI->getZExtValue();
5707 Check(OperandNo < NumOperands,
5708 "!mem.cache_hint operand number is out of range", &
I);
5711 CB ? CB->getArgOperand(OperandNo) :
I.getOperand(OperandNo);
5713 "!mem.cache_hint operand number must refer to a pointer operand", &
I);
5716 Check(Inserted,
"!mem.cache_hint contains duplicate operand number", MD);
5718 Check(!Inserted || !LastOperandNo || OperandNo > *LastOperandNo,
5719 "!mem.cache_hint operand numbers must be in increasing order", MD);
5720 LastOperandNo = OperandNo;
5724 "!mem.cache_hint must alternate between i32 operand numbers and "
5725 "metadata hint nodes",
5729 "!mem.cache_hint hint node must have even number of operands "
5730 "(key-value pairs)",
5733 StringSet<> SeenKeys;
5734 for (
unsigned K = 0;
K + 1 <
Node->getNumOperands();
K += 2) {
5736 Check(
Key,
"!mem.cache_hint key must be a string", Node);
5738 StringRef KeyStr =
Key->getString();
5740 "!mem.cache_hint hint node contains duplicate key", Node);
5745 "!mem.cache_hint value must be a string or integer", Node);
5752void Verifier::visitInstruction(Instruction &
I) {
5754 Check(BB,
"Instruction not embedded in basic block!", &
I);
5757 for (User *U :
I.users()) {
5758 Check(U != (User *)&
I || !DT.isReachableFromEntry(BB),
5759 "Only PHI nodes may reference their own value!", &
I);
5764 Check(!
I.getType()->isVoidTy() || !
I.hasName(),
5765 "Instruction has a name, but provides a void value!", &
I);
5769 Check(
I.getType()->isVoidTy() ||
I.getType()->isFirstClassType(),
5770 "Instruction returns a non-scalar type!", &
I);
5775 "Invalid use of metadata!", &
I);
5780 for (Use &U :
I.uses()) {
5783 "Instruction referencing"
5784 " instruction not embedded in a basic block!",
5787 CheckFailed(
"Use of instruction is not an instruction!", U);
5796 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i) {
5797 Check(
I.getOperand(i) !=
nullptr,
"Instruction has null operand!", &
I);
5801 if (!
I.getOperand(i)->getType()->isFirstClassType()) {
5802 Check(
false,
"Instruction operands must be first-class values!", &
I);
5808 auto IsAttachedCallOperand = [](
Function *
F,
const CallBase *CBI,
5810 return CBI && CBI->isOperandBundleOfType(
5818 Check((!
F->isIntrinsic() ||
5819 (CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i)) ||
5820 IsAttachedCallOperand(
F, CBI, i)),
5821 "Cannot take the address of an intrinsic!", &
I);
5823 F->getIntrinsicID() == Intrinsic::donothing ||
5824 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
5825 F->getIntrinsicID() == Intrinsic::seh_try_end ||
5826 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
5827 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
5828 F->getIntrinsicID() == Intrinsic::coro_resume ||
5829 F->getIntrinsicID() == Intrinsic::coro_destroy ||
5830 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
5831 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
5832 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
5833 F->getIntrinsicID() ==
5834 Intrinsic::experimental_patchpoint_void ||
5835 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
5836 F->getIntrinsicID() == Intrinsic::fake_use ||
5837 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
5838 F->getIntrinsicID() == Intrinsic::wasm_throw ||
5839 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
5840 IsAttachedCallOperand(
F, CBI, i),
5841 "Cannot invoke an intrinsic other than donothing, patchpoint, "
5842 "statepoint, coro_resume, coro_destroy, clang.arc.attachedcall or "
5845 Check(
F->getParent() == &M,
"Referencing function in another module!", &
I,
5846 &M,
F,
F->getParent());
5849 "Referring to a basic block in another function!", &
I);
5852 "Referring to an argument in another function!", &
I);
5854 Check(GV->
getParent() == &M,
"Referencing global in another module!", &
I,
5858 "Referring to an instruction in another function!", &
I);
5859 verifyDominatesUse(
I, i);
5861 Check(CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i),
5862 "Cannot take the address of an inline asm!", &
I);
5864 visitConstantExprsRecursively(
C);
5868 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_fpmath)) {
5870 "fpmath requires a floating point result!", &
I);
5872 if (ConstantFP *CFP0 =
5874 const APFloat &Accuracy = CFP0->getValueAPF();
5876 "fpmath accuracy must have float type", &
I);
5878 "fpmath accuracy not a positive number!", &
I);
5880 Check(
false,
"invalid fpmath accuracy!", &
I);
5884 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_range)) {
5886 "Ranges are only for loads, calls and invokes!", &
I);
5887 visitRangeMetadata(
I,
Range,
I.getType());
5890 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofpclass)) {
5892 visitNoFPClassMetadata(
I, MD,
I.getType());
5895 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_noalias_addrspace)) {
5898 "noalias.addrspace are only for memory operations!", &
I);
5899 visitNoaliasAddrspaceMetadata(
I,
Range,
I.getType());
5902 if (
I.hasMetadata(LLVMContext::MD_invariant_group)) {
5904 "invariant.group metadata is only for loads and stores", &
I);
5907 if (
I.hasMetadata(LLVMContext::MD_invariant_load)) {
5910 "invariant.load metadata is only for loads and readonly "
5915 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nonnull)) {
5916 Check(
I.getType()->isPointerTy(),
"nonnull applies only to pointer types",
5919 "nonnull applies only to load instructions, use attributes"
5920 " for calls or invokes",
5925 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noundef)) {
5930 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable))
5931 visitDereferenceableMetadata(
I, MD);
5933 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
5934 visitDereferenceableMetadata(
I, MD);
5936 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofreeobj))
5937 visitNoFreeObjMetadata(
I, MD);
5939 if (MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa))
5942 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noalias))
5943 visitAliasScopeListMetadata(MD);
5944 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alias_scope))
5945 visitAliasScopeListMetadata(MD);
5947 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_access_group))
5948 visitAccessGroupMetadata(MD);
5950 if (MDNode *AlignMD =
I.getMetadata(LLVMContext::MD_align)) {
5951 Check(
I.getType()->isPointerTy(),
"align applies only to pointer types",
5954 "align applies only to load instructions, "
5955 "use attributes for calls or invokes",
5957 Check(AlignMD->getNumOperands() == 1,
"align takes one operand!", &
I);
5960 "align metadata value must be an i64!", &
I);
5964 Check(Align <= Value::MaximumAlignment,
5965 "alignment is larger that implementation defined limit", &
I);
5968 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_prof))
5969 visitProfMetadata(
I, MD);
5971 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_memprof))
5972 visitMemProfMetadata(
I, MD);
5974 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callsite))
5975 visitCallsiteMetadata(
I, MD);
5977 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callee_type))
5978 visitCalleeTypeMetadata(
I, MD);
5980 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_DIAssignID))
5981 visitDIAssignIDMetadata(
I, MD);
5983 if (MDNode *MMRA =
I.getMetadata(LLVMContext::MD_mmra))
5984 visitMMRAMetadata(
I, MMRA);
5986 if (MDNode *Annotation =
I.getMetadata(LLVMContext::MD_annotation))
5987 visitAnnotationMetadata(Annotation);
5989 if (MDNode *Captures =
I.getMetadata(LLVMContext::MD_captures))
5990 visitCapturesMetadata(
I, Captures);
5992 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alloc_token))
5993 visitAllocTokenMetadata(
I, MD);
5995 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_inline_history))
5996 visitInlineHistoryMetadata(
I, MD);
5998 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_mem_cache_hint))
5999 visitMemCacheHintMetadata(
I, MD);
6001 if (MDNode *MD =
I.getMetadata(
"amdgpu.expected.active.lanes")) {
6003 "!amdgpu.expected.active.lanes must have exactly one operand", &
I,
6008 "!amdgpu.expected.active.lanes operand must be an i32 constant", &
I,
6012 if (MDNode *
N =
I.getDebugLoc().getAsMDNode()) {
6014 visitMDNode(*
N, AreDebugLocsAllowed::Yes);
6017 if (
DL->getAtomGroup()) {
6018 CheckDI(
DL->getScope()->getSubprogram()->getKeyInstructionsEnabled(),
6019 "DbgLoc uses atomGroup but DISubprogram doesn't have Key "
6020 "Instructions enabled",
6021 DL,
DL->getScope()->getSubprogram());
6027 I.getAllMetadata(MDs);
6028 for (
auto Attachment : MDs) {
6029 unsigned Kind = Attachment.first;
6031 (
Kind == LLVMContext::MD_dbg ||
Kind == LLVMContext::MD_loop)
6032 ? AreDebugLocsAllowed::Yes
6033 : AreDebugLocsAllowed::
No;
6034 visitMDNode(*Attachment.second, AllowLocs);
6051 "const x86_amx is not allowed in argument!");
6057 case Intrinsic::assume: {
6061 "assume with operand bundles must have i1 true condition",
Call);
6067 auto GetTypeAt = [&](
unsigned Index) {
6068 return OBU.Inputs[
Index]->getType();
6073 CheckFailed(
"tags must be valid attribute names",
Call);
6075 case BundleAttr::Align:
6076 Check(OBU.Inputs.size() >= 2 && OBU.Inputs.size() <= 3,
6077 "alignment assumptions should have 2 or 3 arguments",
Call);
6080 Check(GetTypeAt(1)->isIntegerTy() &&
6081 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6082 "second argument should be an integer with a maximum width of 64 "
6085 Check(OBU.Inputs.size() < 3 ||
6086 (GetTypeAt(2)->isIntegerTy() &&
6087 GetTypeAt(2)->getIntegerBitWidth() <= 64),
6088 "third argument should be an integer with a maximum width of 64 "
6092 case BundleAttr::Cold:
6093 Check(OBU.Inputs.size() == 0,
6094 "cold assumptions should have no arguments",
Call);
6096 case BundleAttr::Dereferenceable:
6097 case BundleAttr::DereferenceableOrNull:
6098 Check(OBU.Inputs.size() == 2,
6099 "dereferenceable assumptions should have 2 arguments",
Call);
6102 Check(GetTypeAt(1)->isIntegerTy() &&
6103 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6104 "second argument should be an integer with a maximum width of 64 "
6108 case BundleAttr::Ignore:
6110 case BundleAttr::NonNull:
6111 Check(OBU.Inputs.size() == 1,
6112 "nonnull assumptions should have 1 argument",
Call);
6116 case BundleAttr::NoUndef:
6117 Check(OBU.Inputs.size() == 1,
6118 "noundef assumptions should have 1 argument",
Call);
6120 case BundleAttr::SeparateStorage:
6121 Check(OBU.Inputs.size() == 2,
6122 "separate_storage assumptions should have 2 arguments",
Call);
6124 "arguments to separate_storage assumptions should be pointers",
6131 case Intrinsic::ucmp:
6132 case Intrinsic::scmp: {
6137 "result type must be at least 2 bits wide",
Call);
6139 bool IsDestTypeVector = DestTy->
isVectorTy();
6141 "ucmp/scmp argument and result types must both be either vector or "
6144 if (IsDestTypeVector) {
6147 Check(SrcVecLen == DestVecLen,
6148 "return type and arguments must have the same number of "
6154 case Intrinsic::coro_begin:
6155 case Intrinsic::coro_begin_custom_abi:
6157 "id argument of llvm.coro.begin must refer to coro.id");
6159 case Intrinsic::coro_id: {
6161 "align argument only accepts constants");
6164 "promise argument must refer to an alloca");
6169 "coro argument must refer to a function");
6173 if (BeforeCoroSplit)
6176 Check(!BeforeCoroEarly,
"cannot run CoroSplit before CoroEarly");
6179 "info argument of llvm.coro.id must refer to an initialized "
6183 "info argument of llvm.coro.id must refer to either a struct or "
6187 case Intrinsic::is_fpclass: {
6190 "unsupported bits for llvm.is.fpclass test mask");
6193 case Intrinsic::fptrunc_round: {
6198 MD = MAV->getMetadata();
6200 Check(MD !=
nullptr,
"missing rounding mode argument",
Call);
6203 (
"invalid value for llvm.fptrunc.round metadata operand"
6204 " (the operand should be a string)"),
6207 std::optional<RoundingMode> RoundMode =
6209 Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
6210 "unsupported rounding mode argument",
Call);
6213 case Intrinsic::convert_to_arbitrary_fp: {
6221 "if floating-point operand is a vector, integer operand must also "
6224 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6225 "floating-point and integer vector operands must have the same "
6232 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6234 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6235 StringRef Interp = InterpStr->getString();
6237 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6242 "unsupported interpretation metadata string",
Call);
6245 if (
unsigned FormatBits =
6248 "integer type bit width must equal the arbitrary FP format width",
6253 Check(RoundingMAV,
"missing rounding mode metadata operand",
Call);
6255 Check(RoundingStr,
"rounding mode metadata operand must be a string",
Call);
6257 std::optional<RoundingMode>
RM =
6259 Check(RM && *RM != RoundingMode::Dynamic,
6260 "unsupported rounding mode argument",
Call);
6263 case Intrinsic::convert_from_arbitrary_fp: {
6271 "if floating-point operand is a vector, integer operand must also "
6274 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6275 "floating-point and integer vector operands must have the same "
6282 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6284 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6285 StringRef Interp = InterpStr->getString();
6287 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6292 "unsupported interpretation metadata string",
Call);
6295 if (
unsigned FormatBits =
6298 "integer type bit width must equal the arbitrary FP format width",
6302#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6303#include "llvm/IR/VPIntrinsics.def"
6304#undef BEGIN_REGISTER_VP_INTRINSIC
6307#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
6308 case Intrinsic::INTRINSIC:
6309#include "llvm/IR/ConstrainedOps.def"
6313 case Intrinsic::dbg_declare:
6314 case Intrinsic::dbg_value:
6315 case Intrinsic::dbg_assign:
6316 case Intrinsic::dbg_label:
6323 case Intrinsic::memcpy:
6324 case Intrinsic::memcpy_inline:
6325 case Intrinsic::memmove:
6326 case Intrinsic::memset:
6327 case Intrinsic::memset_inline:
6329 case Intrinsic::experimental_memset_pattern: {
6331 Check(Memset->getValue()->getType()->isSized(),
6332 "unsized types cannot be used as memset patterns",
Call);
6335 case Intrinsic::memcpy_element_unordered_atomic:
6336 case Intrinsic::memmove_element_unordered_atomic:
6337 case Intrinsic::memset_element_unordered_atomic: {
6340 ConstantInt *ElementSizeCI =
6342 const APInt &ElementSizeVal = ElementSizeCI->
getValue();
6344 "element size of the element-wise atomic memory intrinsic "
6345 "must be a power of 2",
6348 auto IsValidAlignment = [&](MaybeAlign
Alignment) {
6351 Check(IsValidAlignment(AMI->getDestAlign()),
6352 "incorrect alignment of the destination argument",
Call);
6354 Check(IsValidAlignment(AMT->getSourceAlign()),
6355 "incorrect alignment of the source argument",
Call);
6359 case Intrinsic::call_preallocated_setup: {
6361 bool FoundCall =
false;
6364 Check(UseCall !=
nullptr,
6365 "Uses of llvm.call.preallocated.setup must be calls");
6367 if (IID == Intrinsic::call_preallocated_arg) {
6369 Check(AllocArgIndex !=
nullptr,
6370 "llvm.call.preallocated.alloc arg index must be a constant");
6371 auto AllocArgIndexInt = AllocArgIndex->getValue();
6372 Check(AllocArgIndexInt.sge(0) &&
6373 AllocArgIndexInt.slt(NumArgs->getValue()),
6374 "llvm.call.preallocated.alloc arg index must be between 0 and "
6376 "llvm.call.preallocated.setup's argument count");
6377 }
else if (IID == Intrinsic::call_preallocated_teardown) {
6380 Check(!FoundCall,
"Can have at most one call corresponding to a "
6381 "llvm.call.preallocated.setup");
6383 size_t NumPreallocatedArgs = 0;
6384 for (
unsigned i = 0; i < UseCall->arg_size(); i++) {
6385 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
6386 ++NumPreallocatedArgs;
6389 Check(NumPreallocatedArgs != 0,
6390 "cannot use preallocated intrinsics on a call without "
6391 "preallocated arguments");
6392 Check(NumArgs->equalsInt(NumPreallocatedArgs),
6393 "llvm.call.preallocated.setup arg size must be equal to number "
6394 "of preallocated arguments "
6404 auto PreallocatedBundle =
6406 Check(PreallocatedBundle,
6407 "Use of llvm.call.preallocated.setup outside intrinsics "
6408 "must be in \"preallocated\" operand bundle");
6409 Check(PreallocatedBundle->Inputs.front().get() == &
Call,
6410 "preallocated bundle must have token from corresponding "
6411 "llvm.call.preallocated.setup");
6416 case Intrinsic::call_preallocated_arg: {
6419 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6420 "llvm.call.preallocated.arg token argument must be a "
6421 "llvm.call.preallocated.setup");
6423 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
6424 "call site attribute");
6427 case Intrinsic::call_preallocated_teardown: {
6430 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6431 "llvm.call.preallocated.teardown token argument must be a "
6432 "llvm.call.preallocated.setup");
6435 case Intrinsic::gcroot:
6436 case Intrinsic::gcwrite:
6437 case Intrinsic::gcread:
6438 if (ID == Intrinsic::gcroot) {
6441 Check(AI,
"llvm.gcroot parameter #1 must be an alloca.",
Call);
6443 "llvm.gcroot parameter #2 must be a constant.",
Call);
6446 "llvm.gcroot parameter #1 must either be a pointer alloca, "
6447 "or argument #2 must be a non-null constant.",
6453 "Enclosing function does not use GC.",
Call);
6455 case Intrinsic::init_trampoline:
6457 "llvm.init_trampoline parameter #2 must resolve to a function.",
6460 case Intrinsic::reloc_none: {
6463 "llvm.reloc.none argument must be a metadata string", &
Call);
6466 case Intrinsic::stackprotector:
6468 "llvm.stackprotector parameter #2 must resolve to an alloca.",
Call);
6470 case Intrinsic::localescape: {
6474 Check(!SawFrameEscape,
"multiple calls to llvm.localescape in one function",
6481 "llvm.localescape only accepts static allocas",
Call);
6484 SawFrameEscape =
true;
6487 case Intrinsic::localrecover: {
6490 Check(Fn && !Fn->isDeclaration(),
6491 "llvm.localrecover first "
6492 "argument must be function defined in this module",
6495 auto &
Entry = FrameEscapeInfo[Fn];
6496 Entry.second = unsigned(
6497 std::max(
uint64_t(
Entry.second), IdxArg->getLimitedValue(~0U) + 1));
6501 case Intrinsic::experimental_gc_statepoint:
6503 Check(!CI->isInlineAsm(),
6504 "gc.statepoint support for inline assembly unimplemented", CI);
6506 "Enclosing function does not use GC.",
Call);
6508 verifyStatepoint(
Call);
6510 case Intrinsic::experimental_gc_result: {
6512 "Enclosing function does not use GC.",
Call);
6520 Check(StatepointCall && StatepointCall->getIntrinsicID() ==
6521 Intrinsic::experimental_gc_statepoint,
6522 "gc.result operand #1 must be from a statepoint",
Call,
6526 auto *TargetFuncType =
6529 "gc.result result type does not match wrapped callee",
Call);
6532 case Intrinsic::experimental_gc_relocate: {
6536 "gc.relocate must return a pointer or a vector of pointers",
Call);
6544 LandingPad->getParent()->getUniquePredecessor();
6548 Check(InvokeBB,
"safepoints should have unique landingpads",
6549 LandingPad->getParent());
6553 "gc relocate should be linked to a statepoint", InvokeBB);
6560 "gc relocate is incorrectly tied to the statepoint",
Call, Token);
6569 "gc.relocate operand #2 must be integer offset",
Call);
6573 "gc.relocate operand #3 must be integer offset",
Call);
6583 Check(BaseIndex < Opt->Inputs.size(),
6584 "gc.relocate: statepoint base index out of bounds",
Call);
6585 Check(DerivedIndex < Opt->Inputs.size(),
6586 "gc.relocate: statepoint derived index out of bounds",
Call);
6599 "gc.relocate: relocated value must be a pointer",
Call);
6600 Check(DerivedType->isPtrOrPtrVectorTy(),
6601 "gc.relocate: relocated value must be a pointer",
Call);
6603 Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
6604 "gc.relocate: vector relocates to vector and pointer to pointer",
6607 ResultType->getPointerAddressSpace() ==
6608 DerivedType->getPointerAddressSpace(),
6609 "gc.relocate: relocating a pointer shouldn't change its address space",
6613 Check(GC,
"gc.relocate: calling function must have GCStrategy",
6616 auto isGCPtr = [&
GC](
Type *PTy) {
6617 return GC->isGCManagedPointer(PTy->getScalarType()).value_or(
true);
6619 Check(isGCPtr(ResultType),
"gc.relocate: must return gc pointer",
Call);
6621 "gc.relocate: relocated value must be a gc pointer",
Call);
6622 Check(isGCPtr(DerivedType),
6623 "gc.relocate: relocated value must be a gc pointer",
Call);
6627 case Intrinsic::experimental_patchpoint: {
6630 "patchpoint: invalid return type used with anyregcc",
Call);
6634 case Intrinsic::eh_exceptioncode:
6635 case Intrinsic::eh_exceptionpointer: {
6637 "eh.exceptionpointer argument must be a catchpad",
Call);
6640 case Intrinsic::get_active_lane_mask: {
6643 "get_active_lane_mask: element type is not i1",
Call);
6646 case Intrinsic::experimental_get_vector_length: {
6648 Check(!VF->isNegative() && !VF->isZero(),
6649 "get_vector_length: VF must be positive",
Call);
6652 case Intrinsic::experimental_guard: {
6655 "experimental_guard must have exactly one "
6656 "\"deopt\" operand bundle");
6660 case Intrinsic::experimental_deoptimize: {
6664 "experimental_deoptimize must have exactly one "
6665 "\"deopt\" operand bundle");
6667 "experimental_deoptimize return type must match caller return type");
6672 "calls to experimental_deoptimize must be followed by a return");
6676 "calls to experimental_deoptimize must be followed by a return "
6677 "of the value computed by experimental_deoptimize");
6682 case Intrinsic::vastart: {
6684 "va_start called in a non-varargs function");
6687 case Intrinsic::get_dynamic_area_offset: {
6689 Check(IntTy &&
DL.getPointerSizeInBits(
DL.getAllocaAddrSpace()) ==
6690 IntTy->getBitWidth(),
6691 "get_dynamic_area_offset result type must be scalar integer matching "
6692 "alloca address space width",
6696 case Intrinsic::smul_fix:
6697 case Intrinsic::smul_fix_sat:
6698 case Intrinsic::umul_fix:
6699 case Intrinsic::umul_fix_sat:
6700 case Intrinsic::sdiv_fix:
6701 case Intrinsic::sdiv_fix_sat:
6702 case Intrinsic::udiv_fix:
6703 case Intrinsic::udiv_fix_sat: {
6707 if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
6708 ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
6710 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
6714 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
6715 "to the width of the operands");
6719 case Intrinsic::lrint:
6720 case Intrinsic::llrint:
6721 case Intrinsic::lround:
6722 case Intrinsic::llround: {
6726 IF->
getName() +
": argument and result disagree on vector use",
6730 Check(VTy->getElementCount() == RTy->getElementCount(),
6731 IF->
getName() +
": argument must be same length as result", &
Call);
6735 case Intrinsic::bswap: {
6738 Check(
Size % 16 == 0,
"bswap must be an even number of bytes", &
Call);
6741 case Intrinsic::invariant_start: {
6743 Check(InvariantSize &&
6744 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
6745 "invariant_start parameter must be -1, 0 or a positive number",
6749 case Intrinsic::matrix_multiply:
6750 case Intrinsic::matrix_transpose:
6751 case Intrinsic::matrix_column_major_load:
6752 case Intrinsic::matrix_column_major_store: {
6754 Value *Stride =
nullptr;
6755 ConstantInt *NumRows;
6756 ConstantInt *NumColumns;
6758 Type *Op0ElemTy =
nullptr;
6759 Type *Op1ElemTy =
nullptr;
6761 case Intrinsic::matrix_multiply: {
6766 ->getNumElements() ==
6768 "First argument of a matrix operation does not match specified "
6771 ->getNumElements() ==
6773 "Second argument of a matrix operation does not match specified "
6783 case Intrinsic::matrix_transpose:
6790 case Intrinsic::matrix_column_major_load: {
6797 case Intrinsic::matrix_column_major_store: {
6810 Check(ResultTy->getElementType()->isIntegerTy() ||
6811 ResultTy->getElementType()->isFloatingPointTy(),
6812 "Result type must be an integer or floating-point type!", IF);
6815 Check(ResultTy->getElementType() == Op0ElemTy,
6816 "Vector element type mismatch of the result and first operand "
6821 Check(ResultTy->getElementType() == Op1ElemTy,
6822 "Vector element type mismatch of the result and second operand "
6828 "Result of a matrix operation does not fit in the returned vector!");
6832 "Stride bitwidth cannot exceed 64!", IF);
6836 case Intrinsic::stepvector: {
6838 Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
6839 VecTy->getScalarSizeInBits() >= 8,
6840 "stepvector only supported for vectors of integers "
6841 "with a bitwidth of at least 8.",
6845 case Intrinsic::experimental_vector_match: {
6854 Check(Op1Ty && Op2Ty && MaskTy,
"Operands must be vectors.", &
Call);
6856 "Second operand must be a fixed length vector.", &
Call);
6858 "First operand must be a vector of integers.", &
Call);
6859 Check(Op1Ty->getElementType() == Op2Ty->getElementType(),
6860 "First two operands must have the same element type.", &
Call);
6861 Check(Op1Ty->getElementCount() == MaskTy->getElementCount(),
6862 "First operand and mask must have the same number of elements.",
6864 Check(MaskTy->getElementType()->isIntegerTy(1),
6865 "Mask must be a vector of i1's.", &
Call);
6870 case Intrinsic::vector_insert: {
6879 ElementCount VecEC = VecTy->getElementCount();
6880 ElementCount SubVecEC = SubVecTy->getElementCount();
6881 Check(VecTy->getElementType() == SubVecTy->getElementType(),
6882 "vector_insert parameters must have the same element "
6886 "vector_insert index must be a constant multiple of "
6887 "the subvector's known minimum vector length.");
6892 Check(VecEC.
isScalable(),
"cannot vector_insert a scalable vector into "
6902 "subvector operand of vector_insert would overrun the "
6903 "vector being inserted into.");
6907 case Intrinsic::vector_extract: {
6915 ElementCount VecEC = VecTy->getElementCount();
6916 ElementCount ResultEC = ResultTy->getElementCount();
6918 Check(ResultTy->getElementType() == VecTy->getElementType(),
6919 "vector_extract result must have the same element "
6920 "type as the input vector.",
6923 "vector_extract index must be a constant multiple of "
6924 "the result type's known minimum vector length.");
6929 Check(VecEC.
isScalable(),
"cannot vector_extract a scalable vector from "
6939 "vector_extract would overrun.");
6943 case Intrinsic::vector_partial_reduce_fadd:
6944 case Intrinsic::vector_partial_reduce_add: {
6948 unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
6949 unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
6951 Check((VecWidth % AccWidth) == 0,
6952 "Invalid vector widths for partial "
6953 "reduction. The width of the input vector "
6954 "must be a positive integer multiple of "
6955 "the width of the accumulator vector.");
6958 case Intrinsic::experimental_noalias_scope_decl: {
6962 case Intrinsic::preserve_array_access_index:
6963 case Intrinsic::preserve_struct_access_index:
6964 case Intrinsic::aarch64_ldaxr:
6965 case Intrinsic::aarch64_ldxr:
6966 case Intrinsic::arm_ldaex:
6967 case Intrinsic::arm_ldrex: {
6969 Check(ElemTy,
"Intrinsic requires elementtype attribute on first argument.",
6973 case Intrinsic::aarch64_stlxr:
6974 case Intrinsic::aarch64_stxr:
6975 case Intrinsic::arm_stlex:
6976 case Intrinsic::arm_strex: {
6979 "Intrinsic requires elementtype attribute on second argument.",
6983 case Intrinsic::aarch64_prefetch: {
6985 "write argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6987 "target argument to llvm.aarch64.prefetch must be 0-3",
Call);
6989 "stream argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6991 "isdata argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6994 case Intrinsic::aarch64_range_prefetch: {
6996 "write argument to llvm.aarch64.range.prefetch must be 0 or 1",
Call);
6998 "stream argument to llvm.aarch64.range.prefetch must be 0 or 1",
7002 case Intrinsic::riscv_vsetvli:
7003 case Intrinsic::riscv_vsetvlimax: {
7008 "llvm.riscv.vsetvli/vsetvlimax result must be i32 or i64", &
Call);
7011 bool HasAVL =
ID == Intrinsic::riscv_vsetvli;
7012 unsigned Offset = HasAVL ? 1 : 0;
7017 Check(VSEW <= 3,
"llvm.riscv.vsetvli/vsetvlimax VSEW must be 0-3", &
Call);
7019 "llvm.riscv.vsetvli/vsetvlimax VLMUL is reserved", &
Call);
7022 case Intrinsic::callbr_landingpad: {
7024 Check(CBR,
"intrinstic requires callbr operand", &
Call);
7031 CheckFailed(
"Intrinsic in block must have 1 unique predecessor", &
Call);
7035 CheckFailed(
"Intrinsic must have corresponding callbr in predecessor",
7040 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
7041 "block in indirect destination list",
7044 Check(&
First == &
Call,
"No other instructions may proceed intrinsic",
7048 case Intrinsic::structured_gep: {
7054 "Intrinsic first parameter is missing an ElementType attribute",
7062 "Index operand type must be an integer", &
Call);
7065 T = AT->getElementType();
7067 Check(CI,
"Indexing into a struct requires a constant int", &
Call);
7069 "Indexing in a struct should be inbounds", &
Call);
7072 T = VT->getElementType();
7074 CheckFailed(
"Reached a non-composite type with more indices to process",
7080 case Intrinsic::structured_alloca:
7082 "@llvm.structured.alloca calls require elementtype attribute.",
7085 case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
7086 case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
7089 Check(RegCount % 8 == 0,
7090 "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
7093 case Intrinsic::experimental_convergence_entry:
7094 case Intrinsic::experimental_convergence_anchor:
7096 case Intrinsic::experimental_convergence_loop:
7098 case Intrinsic::ptrmask: {
7102 "llvm.ptrmask intrinsic first argument must be pointer or vector "
7107 "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
7112 "llvm.ptrmask intrinsic arguments must have the same number of "
7116 "llvm.ptrmask intrinsic second argument bitwidth must match "
7117 "pointer index type size of first argument",
7121 case Intrinsic::thread_pointer: {
7123 DL.getDefaultGlobalsAddressSpace(),
7124 "llvm.thread.pointer intrinsic return type must be for the globals "
7129 case Intrinsic::threadlocal_address: {
7132 "llvm.threadlocal.address first argument must be a GlobalValue");
7134 "llvm.threadlocal.address operand isThreadLocal() must be true");
7137 case Intrinsic::lifetime_start:
7138 case Intrinsic::lifetime_end: {
7142 (
II &&
II->getIntrinsicID() == Intrinsic::structured_alloca),
7143 "llvm.lifetime.start/end can only be used on alloca or poison",
7147 case Intrinsic::sponentry: {
7148 const unsigned StackAS =
DL.getAllocaAddrSpace();
7151 "llvm.sponentry must return a pointer to the stack", &
Call);
7154 case Intrinsic::write_volatile_register: {
7158 "llvm.write_volatile_register metadata must be a single MDString",
7162 case Intrinsic::ptrauth_auth_with_pc_and_resign: {
7167 "ptrauth.auth.with.pc.and.resign key must be IA (0) or IB (1)",
7176 if (
F->hasPersonalityFn() &&
7180 if (BlockEHFuncletColors.
empty())
7184 bool InEHFunclet =
false;
7188 for (BasicBlock *ColorFirstBB : CV)
7189 if (
auto It = ColorFirstBB->getFirstNonPHIIt();
7190 It != ColorFirstBB->end())
7195 bool HasToken =
false;
7202 Check(HasToken,
"Missing funclet token on intrinsic call", &
Call);
7229void Verifier::visit(DbgLabelRecord &DLR) {
7231 "invalid #dbg_label intrinsic variable", &DLR, DLR.
getRawLabel());
7244 CheckDI(Loc,
"#dbg_label record requires a !dbg attachment", &DLR, BB,
F);
7248 if (!LabelSP || !LocSP)
7252 "mismatched subprogram between #dbg_label label and !dbg attachment",
7253 &DLR, BB,
F, Label,
Label->getScope()->getSubprogram(), Loc,
7254 Loc->getScope()->getSubprogram());
7257void Verifier::visit(DbgVariableRecord &DVR) {
7261 CheckDI(DVR.
getType() == DbgVariableRecord::LocationType::Value ||
7262 DVR.
getType() == DbgVariableRecord::LocationType::Declare ||
7263 DVR.
getType() == DbgVariableRecord::LocationType::DeclareValue ||
7264 DVR.
getType() == DbgVariableRecord::LocationType::Assign,
7265 "invalid #dbg record type", &DVR, DVR.
getType(), BB,
F);
7273 "invalid #dbg record address/value", &DVR, MD, BB,
F);
7275 visitValueAsMetadata(*VAM,
F);
7278 Type *Ty = VAM->getValue()->getType();
7280 "location of #dbg_declare must be a pointer or int", &DVR, MD, BB,
7284 visitDIArgList(*AL,
F);
7298 "invalid #dbg_assign DIAssignID", &DVR, DVR.
getRawAssignID(), BB,
7301 AreDebugLocsAllowed::No);
7310 "invalid #dbg_assign address", &DVR, DVR.
getRawAddress(), BB,
F);
7312 visitValueAsMetadata(*VAM,
F);
7315 "invalid #dbg_assign address expression", &DVR,
7322 "inst not in same function as #dbg_assign",
I, &DVR, BB,
F);
7332 &DVR, DLNode, BB,
F);
7338 if (!VarSP || !LocSP)
7342 "mismatched subprogram between #dbg record variable and DILocation",
7344 Loc->getScope()->getSubprogram(), BB,
F);
7349void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
7351 case Intrinsic::experimental_vp_splice: {
7354 int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
7356 AttributeList
Attrs = VPI.
getParent()->getParent()->getAttributes();
7357 if (
Attrs.hasFnAttr(Attribute::VScaleRange))
7358 KnownMinNumElements *=
Attrs.getFnAttrs().getVScaleRangeMin();
7360 Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
7361 (Idx >= 0 && Idx < KnownMinNumElements),
7362 "The splice index exceeds the range [-VL, VL-1] where VL is the "
7363 "known minimum number of elements in the vector. For scalable "
7364 "vectors the minimum number of elements is determined from "
7372void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
7374 bool HasRoundingMD =
7378 NumOperands += (1 + HasRoundingMD);
7384 "invalid arguments for constrained FP intrinsic", &FPI);
7387 case Intrinsic::experimental_constrained_fcmp:
7388 case Intrinsic::experimental_constrained_fcmps: {
7391 "invalid predicate for constrained FP comparison intrinsic", &FPI);
7395 case Intrinsic::experimental_constrained_fptosi:
7396 case Intrinsic::experimental_constrained_fptoui: {
7400 "Intrinsic first argument must be floating point", &FPI);
7407 "Intrinsic first argument and result disagree on vector use", &FPI);
7409 "Intrinsic result must be an integer", &FPI);
7412 "Intrinsic first argument and result vector lengths must be equal",
7418 case Intrinsic::experimental_constrained_sitofp:
7419 case Intrinsic::experimental_constrained_uitofp: {
7423 "Intrinsic first argument must be integer", &FPI);
7430 "Intrinsic first argument and result disagree on vector use", &FPI);
7432 "Intrinsic result must be a floating point", &FPI);
7435 "Intrinsic first argument and result vector lengths must be equal",
7441 case Intrinsic::experimental_constrained_fptrunc:
7442 case Intrinsic::experimental_constrained_fpext: {
7448 "Intrinsic first argument must be FP or FP vector", &FPI);
7450 "Intrinsic result must be FP or FP vector", &FPI);
7452 "Intrinsic first argument and result disagree on vector use", &FPI);
7456 "Intrinsic first argument and result vector lengths must be equal",
7459 if (FPI.
getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
7461 "Intrinsic first argument's type must be larger than result type",
7465 "Intrinsic first argument's type must be smaller than result type",
7481 "invalid exception behavior argument", &FPI);
7482 if (HasRoundingMD) {
7488void Verifier::verifyFragmentExpression(
const DbgVariableRecord &DVR) {
7493 if (!V || !
E || !
E->isValid())
7497 auto Fragment =
E->getFragmentInfo();
7507 if (
V->isArtificial())
7510 verifyFragmentExpression(*V, *Fragment, &DVR);
7513template <
typename ValueOrMetadata>
7514void Verifier::verifyFragmentExpression(
const DIVariable &V,
7516 ValueOrMetadata *
Desc) {
7519 auto VarSize =
V.getSizeInBits();
7525 CheckDI(FragSize + FragOffset <= *VarSize,
7526 "fragment is larger than or outside of variable",
Desc, &V);
7527 CheckDI(FragSize != *VarSize,
"fragment covers entire variable",
Desc, &V);
7530void Verifier::verifyFnArgs(
const DbgVariableRecord &DVR) {
7542 CheckDI(Var,
"#dbg record without variable");
7544 unsigned ArgNo = Var->
getArg();
7550 if (DebugFnArgs.
size() < ArgNo)
7551 DebugFnArgs.
resize(ArgNo,
nullptr);
7553 auto *Prev = DebugFnArgs[ArgNo - 1];
7554 DebugFnArgs[ArgNo - 1] = Var;
7555 CheckDI(!Prev || (Prev == Var),
"conflicting debug info for argument", &DVR,
7559void Verifier::verifyNotEntryValue(
const DbgVariableRecord &DVR) {
7563 if (!
E || !
E->isValid())
7573 ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
7578 "Entry values are only allowed in MIR unless they target a "
7579 "swiftasync Argument",
7583void Verifier::verifyCompileUnits() {
7587 if (
M.getContext().isODRUniquingDebugTypes())
7589 auto *CUs =
M.getNamedMetadata(
"llvm.dbg.cu");
7590 SmallPtrSet<const Metadata *, 2> Listed;
7593 for (
const auto *CU : CUVisited)
7594 CheckDI(Listed.
count(CU),
"DICompileUnit not listed in llvm.dbg.cu", CU);
7598void Verifier::verifyDeoptimizeCallingConvs() {
7599 if (DeoptimizeDeclarations.
empty())
7603 for (
const auto *
F :
ArrayRef(DeoptimizeDeclarations).slice(1)) {
7604 Check(
First->getCallingConv() ==
F->getCallingConv(),
7605 "All llvm.experimental.deoptimize declarations must have the same "
7606 "calling convention",
7611void Verifier::verifyAttachedCallBundle(
const CallBase &
Call,
7612 const OperandBundleUse &BU) {
7615 Check((FTy->getReturnType()->isPointerTy() ||
7617 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
7618 "function returning a pointer or a non-returning function that has a "
7623 "operand bundle \"clang.arc.attachedcall\" requires one function as "
7631 Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
7632 IID == Intrinsic::objc_claimAutoreleasedReturnValue ||
7633 IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
7634 "invalid function argument",
Call);
7636 StringRef FnName = Fn->getName();
7637 Check((FnName ==
"objc_retainAutoreleasedReturnValue" ||
7638 FnName ==
"objc_claimAutoreleasedReturnValue" ||
7639 FnName ==
"objc_unsafeClaimAutoreleasedReturnValue"),
7640 "invalid function argument",
Call);
7644void Verifier::verifyNoAliasScopeDecl() {
7645 if (NoAliasScopeDecls.
empty())
7649 for (
auto *
II : NoAliasScopeDecls) {
7650 assert(
II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
7651 "Not a llvm.experimental.noalias.scope.decl ?");
7654 Check(ScopeListMV !=
nullptr,
7655 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
7660 Check(ScopeListMD !=
nullptr,
"!id.scope.list must point to an MDNode",
II);
7661 Check(ScopeListMD->getNumOperands() == 1,
7662 "!id.scope.list must point to a list with a single scope",
II);
7663 visitAliasScopeListMetadata(ScopeListMD);
7673 auto GetScope = [](IntrinsicInst *
II) {
7676 return &
cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
7681 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
7682 return GetScope(Lhs) < GetScope(Rhs);
7689 auto ItCurrent = NoAliasScopeDecls.begin();
7690 while (ItCurrent != NoAliasScopeDecls.end()) {
7691 auto CurScope = GetScope(*ItCurrent);
7692 auto ItNext = ItCurrent;
7695 }
while (ItNext != NoAliasScopeDecls.end() &&
7696 GetScope(*ItNext) == CurScope);
7701 if (ItNext - ItCurrent < 32)
7705 Check(!DT.dominates(
I, J),
7706 "llvm.experimental.noalias.scope.decl dominates another one "
7707 "with the same scope",
7721 Verifier V(OS,
true, *f.getParent());
7725 return !V.verify(
F);
7729 bool *BrokenDebugInfo) {
7731 Verifier V(OS, !BrokenDebugInfo, M);
7733 bool Broken =
false;
7735 Broken |= !V.verify(
F);
7737 Broken |= !V.verify();
7738 if (BrokenDebugInfo)
7739 *BrokenDebugInfo = V.hasBrokenDebugInfo();
7750 std::unique_ptr<Verifier> V;
7751 bool FatalErrors =
true;
7754 explicit VerifierLegacyPass(
bool FatalErrors)
7755 : FunctionPass(
ID), FatalErrors(FatalErrors) {}
7757 bool doInitialization(
Module &M)
override {
7758 V = std::make_unique<Verifier>(
7764 if (!
V->verify(
F) && FatalErrors) {
7765 errs() <<
"in function " <<
F.getName() <<
'\n';
7771 bool doFinalization(
Module &M)
override {
7772 bool HasErrors =
false;
7774 if (
F.isDeclaration())
7775 HasErrors |= !
V->verify(
F);
7777 HasErrors |= !
V->verify();
7778 if (FatalErrors && (HasErrors ||
V->hasBrokenDebugInfo()))
7783 void getAnalysisUsage(AnalysisUsage &AU)
const override {
7791template <
typename... Tys>
void TBAAVerifier::CheckFailed(Tys &&... Args) {
7793 return Diagnostic->CheckFailed(
Args...);
7796#define CheckTBAA(C, ...) \
7799 CheckFailed(__VA_ARGS__); \
7807TBAAVerifier::TBAABaseNodeSummary
7811 CheckFailed(
"Base nodes must have at least two operands",
I, BaseNode);
7815 auto Itr = TBAABaseNodes.find(BaseNode);
7816 if (Itr != TBAABaseNodes.end())
7819 auto Result = verifyTBAABaseNodeImpl(
I, BaseNode, IsNewFormat);
7820 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
7822 assert(InsertResult.second &&
"We just checked!");
7826TBAAVerifier::TBAABaseNodeSummary
7827TBAAVerifier::verifyTBAABaseNodeImpl(
const Instruction *
I,
7828 const MDNode *BaseNode,
bool IsNewFormat) {
7829 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {
true, ~0
u};
7833 return isValidScalarTBAANode(BaseNode)
7834 ? TBAAVerifier::TBAABaseNodeSummary({
false, 0})
7840 CheckFailed(
"Access tag nodes must have the number of operands that is a "
7841 "multiple of 3!", BaseNode);
7846 CheckFailed(
"Struct tag nodes must have an odd number of operands!",
7856 if (!TypeSizeNode) {
7857 CheckFailed(
"Type size nodes must be constants!",
I, BaseNode);
7864 CheckFailed(
"Struct tag nodes have a string as their first operand",
7871 std::optional<APInt> PrevOffset;
7876 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
7877 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
7878 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
7879 Idx += NumOpsPerField) {
7880 const MDOperand &FieldTy = BaseNode->
getOperand(Idx);
7881 const MDOperand &FieldOffset = BaseNode->
getOperand(Idx + 1);
7883 CheckFailed(
"Incorrect field entry in struct type node!",
I, BaseNode);
7888 auto *OffsetEntryCI =
7890 if (!OffsetEntryCI) {
7891 CheckFailed(
"Offset entries must be constants!",
I, BaseNode);
7897 BitWidth = OffsetEntryCI->getBitWidth();
7899 if (OffsetEntryCI->getBitWidth() !=
BitWidth) {
7901 "Bitwidth between the offsets and struct type entries must match",
I,
7913 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
7916 CheckFailed(
"Offsets must be increasing!",
I, BaseNode);
7920 PrevOffset = OffsetEntryCI->getValue();
7925 if (!MemberSizeNode) {
7926 CheckFailed(
"Member size entries must be constants!",
I, BaseNode);
7933 return Failed ? InvalidNode
7934 : TBAAVerifier::TBAABaseNodeSummary(
false,
BitWidth);
7956 return Parent && Visited.
insert(Parent).second &&
7960bool TBAAVerifier::isValidScalarTBAANode(
const MDNode *MD) {
7961 auto ResultIt = TBAAScalarNodes.find(MD);
7962 if (ResultIt != TBAAScalarNodes.end())
7963 return ResultIt->second;
7965 SmallPtrSet<const MDNode *, 4> Visited;
7967 auto InsertResult = TBAAScalarNodes.insert({MD,
Result});
7969 assert(InsertResult.second &&
"Just checked!");
7978MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(
const Instruction *
I,
7979 const MDNode *BaseNode,
7990 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
7991 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
7992 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
7993 Idx += NumOpsPerField) {
7994 auto *OffsetEntryCI =
7996 if (OffsetEntryCI->getValue().ugt(
Offset)) {
7997 if (Idx == FirstFieldOpNo) {
7998 CheckFailed(
"Could not find TBAA parent in struct type node",
I,
8003 unsigned PrevIdx = Idx - NumOpsPerField;
8004 auto *PrevOffsetEntryCI =
8006 Offset -= PrevOffsetEntryCI->getValue();
8014 Offset -= LastOffsetEntryCI->getValue();
8019 if (!
Type ||
Type->getNumOperands() < 3)
8035 "This instruction shall not have a TBAA access tag!",
I);
8037 bool IsStructPathTBAA =
8041 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
8051 "Access tag metadata must have either 4 or 5 operands",
I, MD);
8054 "Struct tag metadata must have either 3 or 4 operands",
I, MD);
8061 CheckTBAA(AccessSizeNode,
"Access size field must be a constant",
I, MD);
8065 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
8070 "Immutability tag on struct tag metadata must be a constant",
I,
8073 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
8074 "Immutability part of the struct tag metadata must be either 0 or 1",
I,
8079 "Malformed struct tag metadata: base and access-type "
8080 "should be non-null and point to Metadata nodes",
8081 I, MD, BaseNode, AccessType);
8084 CheckTBAA(isValidScalarTBAANode(AccessType),
8085 "Access type node must be a valid scalar type",
I, MD,
8090 CheckTBAA(OffsetCI,
"Offset must be constant integer",
I, MD);
8093 bool SeenAccessTypeInPath =
false;
8099 getFieldNodeFromTBAABaseNode(
I, BaseNode,
Offset, IsNewFormat)) {
8100 if (!StructPath.
insert(BaseNode).second) {
8101 CheckFailed(
"Cycle detected in struct path",
I, MD);
8106 unsigned BaseNodeBitWidth;
8107 std::tie(
Invalid, BaseNodeBitWidth) =
8108 verifyTBAABaseNode(
I, BaseNode, IsNewFormat);
8115 SeenAccessTypeInPath |= BaseNode == AccessType;
8117 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
8122 (BaseNodeBitWidth == 0 &&
Offset == 0) ||
8123 (IsNewFormat && BaseNodeBitWidth == ~0u),
8124 "Access bit-width not the same as description bit-width",
I, MD,
8125 BaseNodeBitWidth,
Offset.getBitWidth());
8127 if (IsNewFormat && SeenAccessTypeInPath)
8131 CheckTBAA(SeenAccessTypeInPath,
"Did not see access type in access path!",
I,
8136char VerifierLegacyPass::ID = 0;
8137INITIALIZE_PASS(VerifierLegacyPass,
"verify",
"Module Verifier",
false,
false)
8140 return new VerifierLegacyPass(FatalErrors);
8158 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
8166 if (res.IRBroken && FatalErrors)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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.
static constexpr Value * getValue(Ty &ValueOrUse)
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 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 isSupportedCallBrIntrinsic(Intrinsic::ID ID)
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 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....
static LLVM_ABI unsigned getArbitraryFPFormatSizeInBits(StringRef Format)
Returns the size in bits of a valid arbitrary floating-point format string, or 0 if the string is not...
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.
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.
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.
bool isElementwise() const
Return true if this RMW has elementwise vector semantics.
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.
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; assumes that the block is well-formed.
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.
auto operand_bundles() const
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.
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value 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.
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).
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
static bool isIntPredicate(Predicate P)
Value * getCondition() const
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.
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.
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 LLVM_ABI 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
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.
DebugLoc getDebugLoc() const
LLVM_ABI BasicBlock * getParent()
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
DIExpression * getAddressExpression() const
LLVM_ABI MDNode * getAsMDNode() const
Return this as a bar MDNode.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
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.
static bool isSupportedFloatingPointType(Type *Ty)
Returns true if Ty is a supported floating-point type for phi, select, or call FPMathOperators.
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.
op_range arg_operands()
arg_operands - iteration adapter for range-for loops.
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.
DISubprogram * getSubprogram() const
Get the attached subprogram.
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 metadata of given kind attached to this GlobalObject.
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.
bool hasCommonLinkage() const
bool hasGlobalUnnamedAddr() const
bool hasAppendingLinkage() const
bool hasAvailableExternallyLinkage() const
Type * getValueType() const
LLVM_ABI bool isInterposable(bool CheckNoIPA=true) const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
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 const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
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.
bool isElementwise() const
Return true if this is an elementwise atomic load.
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.
A Module instance is used to store all the information related to an LLVM module.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
LLVM_ABI StringRef getName() 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.
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
Check if the string is empty.
std::pair< typename Base::iterator, bool > insert(StringRef key)
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,...
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI unsigned getIntegerBitWidth() const
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...
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.
std::pair< iterator, bool > insert(const ValueT &V)
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.
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.
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.
std::optional< ABIType > parseABIType(StringRef S)
Parse the string spelling used by the "float-abi" IR module flag into an ABIType.
@ BasicBlock
Various leaf nodes.
LLVM_ABI bool hasConstrainedFPRoundingModeOperand(ID QID)
Returns true if the intrinsic ID is for one of the "ConstrainedFloating-Point Intrinsics" that take r...