100#include "llvm/IR/IntrinsicsAArch64.h"
101#include "llvm/IR/IntrinsicsARM.h"
102#include "llvm/IR/IntrinsicsBPF.h"
103#include "llvm/IR/IntrinsicsNVPTX.h"
104#include "llvm/IR/IntrinsicsRISCV.h"
105#include "llvm/IR/IntrinsicsWebAssembly.h"
158 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
161 SmallPtrSet<const Metadata *, 32> MDNodes;
164 DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments;
168 DenseMap<const Metadata *, bool> DIScopeChainReachesCycle;
171 SmallPtrSet<const Metadata *, 2> CUVisited;
174 Type *LandingPadResultTy;
181 bool HasDebugInfo =
false;
185 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
189 MapVector<Instruction *, Instruction *> SiblingFuncletInfo;
193 DenseMap<BasicBlock *, ColorVector> BlockEHFuncletColors;
196 SmallPtrSet<const Constant *, 32> ConstantExprVisited;
202 SmallPtrSet<const void *, 32> AttributeListsVisited;
208 SmallPtrSet<const Value *, 32> GlobalValueVisited;
213 TBAAVerifier TBAAVerifyHelper;
218 void checkAtomicMemAccessSize(
Type *Ty,
const Instruction *
I);
221 explicit Verifier(raw_ostream *OS,
bool ShouldTreatBrokenDebugInfoAsError,
223 : VerifierSupport(OS,
M), LandingPadResultTy(nullptr),
224 SawFrameEscape(
false), TBAAVerifyHelper(this) {
225 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
228 bool hasBrokenDebugInfo()
const {
return BrokenDebugInfo; }
231 llvm::TimeTraceScope timeScope(
"Verifier");
233 "An instance of this class only works with a specific module!");
243 for (
const BasicBlock &BB :
F) {
244 if (!BB.empty() && BB.back().isTerminator())
248 *OS <<
"Basic Block in function '" <<
F.getName()
249 <<
"' does not have terminator!\n";
250 BB.printAsOperand(*OS,
true, MST);
258 DT.recalculate(
const_cast<Function &
>(
F));
260 auto FailureCB = [
this](
const Twine &Message) {
261 this->CheckFailed(Message);
263 ConvergenceVerifyHelper.initialize(OS, FailureCB,
F);
268 verifySiblingFuncletUnwinds();
270 if (ConvergenceVerifyHelper.sawTokens())
271 ConvergenceVerifyHelper.verify(DT);
273 InstsInThisBlock.clear();
275 DIScopeChainReachesCycle.clear();
276 LandingPadResultTy =
nullptr;
277 SawFrameEscape =
false;
278 SiblingFuncletInfo.clear();
279 verifyNoAliasScopeDecl();
280 NoAliasScopeDecls.clear();
291 if (
F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
292 DeoptimizeDeclarations.push_back(&
F);
296 verifyFrameRecoverIndices();
297 for (
const GlobalVariable &GV :
M.globals())
298 visitGlobalVariable(GV);
300 for (
const GlobalAlias &GA :
M.aliases())
301 visitGlobalAlias(GA);
303 for (
const GlobalIFunc &GI :
M.ifuncs())
304 visitGlobalIFunc(GI);
306 for (
const NamedMDNode &NMD :
M.named_metadata())
307 visitNamedMDNode(NMD);
309 for (
const StringMapEntry<Comdat> &SMEC :
M.getComdatSymbolTable())
310 visitComdat(SMEC.getValue());
314 visitModuleCommandLines();
315 visitModuleErrnoTBAA();
316 visitModuleRawSections();
318 verifyCompileUnits();
320 verifyDeoptimizeCallingConvs();
321 DISubprogramAttachments.clear();
322 DIScopeChainReachesCycle.clear();
328 enum class AreDebugLocsAllowed {
No,
Yes };
332 enum class RangeLikeMetadataKind {
339 void visitGlobalValue(
const GlobalValue &GV);
340 void visitGlobalVariable(
const GlobalVariable &GV);
341 void visitGlobalAlias(
const GlobalAlias &GA);
342 void visitGlobalIFunc(
const GlobalIFunc &GI);
343 void visitAliaseeSubExpr(
const GlobalAlias &
A,
const Constant &
C);
344 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
345 const GlobalAlias &
A,
const Constant &
C);
346 void visitNamedMDNode(
const NamedMDNode &NMD);
347 void visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs);
348 void visitMetadataAsValue(
const MetadataAsValue &MD,
Function *
F);
349 void visitValueAsMetadata(
const ValueAsMetadata &MD,
Function *
F);
350 void visitDIArgList(
const DIArgList &AL,
Function *
F);
351 void visitComdat(
const Comdat &
C);
352 void visitModuleIdents();
353 void visitModuleCommandLines();
354 void visitModuleErrnoTBAA();
355 void visitModuleRawSections();
356 void visitModuleFlags();
357 void visitModuleFlag(
const MDNode *
Op,
358 DenseMap<const MDString *, const MDNode *> &SeenIDs,
359 SmallVectorImpl<const MDNode *> &Requirements);
360 void visitModuleFlagCGProfileEntry(
const MDOperand &MDO);
362 void visitBasicBlock(BasicBlock &BB);
363 void verifyRangeLikeMetadata(
const Value &
V,
const MDNode *
Range,
Type *Ty,
364 RangeLikeMetadataKind Kind);
365 void visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
366 void visitNoFPClassMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
367 void visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
368 void visitDereferenceableMetadata(Instruction &
I, MDNode *MD);
369 void visitNoFreeObjMetadata(Instruction &
I, MDNode *MD);
370 void visitProfMetadata(Instruction &
I, MDNode *MD);
371 void visitCallStackMetadata(MDNode *MD);
372 void visitMemProfMetadata(Instruction &
I, MDNode *MD);
373 void visitCallsiteMetadata(Instruction &
I, MDNode *MD);
374 void visitCalleeTypeMetadata(Instruction &
I, MDNode *MD);
375 void visitDIAssignIDMetadata(Instruction &
I, MDNode *MD);
376 void visitMMRAMetadata(Instruction &
I, MDNode *MD);
377 void visitAnnotationMetadata(MDNode *Annotation);
378 void visitAliasScopeMetadata(
const MDNode *MD);
379 void visitAliasScopeListMetadata(
const MDNode *MD);
380 void visitAccessGroupMetadata(
const MDNode *MD);
381 void visitCapturesMetadata(Instruction &
I,
const MDNode *Captures);
382 void visitAllocTokenMetadata(Instruction &
I, MDNode *MD);
383 void visitInlineHistoryMetadata(Instruction &
I, MDNode *MD);
384 void visitMemCacheHintMetadata(Instruction &
I, MDNode *MD);
386#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
387#include "llvm/IR/Metadata.def"
388 void visitDIType(
const DIType &
N);
389 void visitDIScope(
const DIScope &
N);
390 void visitDIScopeChain(
const DIScope &
N);
391 bool hasDIScopeCycle(
const Metadata *S);
421 void visitPHINode(
PHINode &PN);
451 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
452 void visitVPIntrinsic(VPIntrinsic &VPI);
453 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
454 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
455 void visitFenceInst(FenceInst &FI);
456 void visitAllocaInst(AllocaInst &AI);
457 void visitExtractValueInst(ExtractValueInst &EVI);
458 void visitInsertValueInst(InsertValueInst &IVI);
459 void visitEHPadPredecessors(Instruction &
I);
460 void visitLandingPadInst(LandingPadInst &LPI);
461 void visitResumeInst(ResumeInst &RI);
462 void visitCatchPadInst(CatchPadInst &CPI);
463 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
464 void visitCleanupPadInst(CleanupPadInst &CPI);
465 void visitFuncletPadInst(FuncletPadInst &FPI);
466 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
467 void visitCleanupReturnInst(CleanupReturnInst &CRI);
469 void verifySwiftErrorCall(CallBase &
Call,
const Value *SwiftErrorVal);
470 void verifySwiftErrorValue(
const Value *SwiftErrorVal);
471 void verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs, StringRef
Context);
472 void verifyMustTailCall(CallInst &CI);
473 bool verifyAttributeCount(AttributeList Attrs,
unsigned Params);
474 void verifyAttributeTypes(AttributeSet Attrs,
const Value *
V);
475 void verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
const Value *
V);
476 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
478 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
479 const Value *
V,
bool IsIntrinsic,
bool IsInlineAsm);
480 void verifyFunctionMetadata(
ArrayRef<std::pair<unsigned, MDNode *>> MDs);
481 void verifyUnknownProfileMetadata(MDNode *MD);
482 void visitConstantExprsRecursively(
const Constant *EntryC);
483 void visitConstantExpr(
const ConstantExpr *CE);
484 void visitConstantPtrAuth(
const ConstantPtrAuth *CPA);
485 void verifyInlineAsmCall(
const CallBase &
Call);
486 void verifyStatepoint(
const CallBase &
Call);
487 void verifyFrameRecoverIndices();
488 void verifySiblingFuncletUnwinds();
490 void verifyFragmentExpression(
const DbgVariableRecord &
I);
491 template <
typename ValueOrMetadata>
492 void verifyFragmentExpression(
const DIVariable &
V,
494 ValueOrMetadata *
Desc);
495 void verifyFnArgs(
const DbgVariableRecord &DVR);
496 void verifyNotEntryValue(
const DbgVariableRecord &
I);
499 void verifyCompileUnits();
503 void verifyDeoptimizeCallingConvs();
505 void verifyAttachedCallBundle(
const CallBase &
Call,
506 const OperandBundleUse &BU);
509 void verifyNoAliasScopeDecl();
515#define Check(C, ...) \
518 CheckFailed(__VA_ARGS__); \
525#define CheckDI(C, ...) \
528 DebugInfoCheckFailed(__VA_ARGS__); \
534 if (!
I.getDbgMarker())
536 CheckDI(
I.getDbgMarker()->MarkedInstr == &
I,
537 "Instruction has invalid DebugMarker", &
I);
539 "PHI Node must not have any attached DbgRecords", &
I);
541 CheckDI(DR.getMarker() ==
I.getDbgMarker(),
542 "DbgRecord had invalid DebugMarker", &
I, &DR);
545 visitMDNode(*
Loc, AreDebugLocsAllowed::Yes);
550 verifyFragmentExpression(*DVR);
551 verifyNotEntryValue(*DVR);
558void Verifier::visit(Instruction &
I) {
560 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i)
561 Check(
I.getOperand(i) !=
nullptr,
"Operand is null", &
I);
573 while (!WorkList.
empty()) {
575 if (!Visited.
insert(Cur).second)
582void Verifier::visitGlobalValue(
const GlobalValue &GV) {
584 "Global is external, but doesn't have external or weak linkage!", &GV);
587 if (
const MDNode *Associated =
588 GO->getMetadata(LLVMContext::MD_associated)) {
589 Check(Associated->getNumOperands() == 1,
590 "associated metadata must have one operand", &GV, Associated);
591 const Metadata *
Op = Associated->getOperand(0).get();
592 Check(
Op,
"associated metadata must have a global value", GO, Associated);
595 Check(VM,
"associated metadata must be ValueAsMetadata", GO, Associated);
598 "associated value must be pointer typed", GV, Associated);
600 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
602 "associated metadata must point to a GlobalObject", GO, Stripped);
603 Check(Stripped != GO,
604 "global values should not associate to themselves", GO,
610 if (
const MDNode *AbsoluteSymbol =
611 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
612 verifyRangeLikeMetadata(*GO, AbsoluteSymbol,
613 DL.getIntPtrType(GO->getType()),
614 RangeLikeMetadataKind::AbsoluteSymbol);
617 if (GO->hasMetadata(LLVMContext::MD_implicit_ref)) {
618 Check(!GO->isDeclaration(),
619 "ref metadata must not be placed on a declaration", GO);
622 GO->getMetadata(LLVMContext::MD_implicit_ref, MDs);
623 for (
const MDNode *MD : MDs) {
624 Check(MD->getNumOperands() == 1,
"ref metadata must have one operand",
628 Check(VM,
"ref metadata must be ValueAsMetadata", GO, MD);
631 "ref value must be pointer typed", GV, MD);
635 "ref metadata must point to a GlobalObject", GO, Stripped);
636 Check(Stripped != GO,
"values should not reference themselves", GO,
642 if (
auto *Props = GO->getMetadata(LLVMContext::MD_elf_section_properties)) {
643 Check(Props->getNumOperands() == 2,
644 "elf_section_properties metadata must have two operands", GO,
646 if (Props->getNumOperands() == 2) {
648 Check(
Type,
"type field must be ConstantAsMetadata", GO, Props);
650 Check(TypeInt,
"type field must be ConstantInt", GO, Props);
653 Check(Entsize,
"entsize field must be ConstantAsMetadata", GO, Props);
655 Check(EntsizeInt,
"entsize field must be ConstantInt", GO, Props);
661 "Only global variables can have appending linkage!", &GV);
665 Check(GVar && GVar->getValueType()->isArrayTy(),
666 "Only global arrays can have appending linkage!", GVar);
670 Check(!GV.
hasComdat(),
"Declaration may not be in a Comdat!", &GV);
674 "dllexport GlobalValue must have default or protected visibility",
679 "dllimport GlobalValue must have default visibility", &GV);
680 Check(!GV.
isDSOLocal(),
"GlobalValue with DLLImport Storage is dso_local!",
686 "Global is marked as dllimport, but not external", &GV);
691 "GlobalValue with local linkage or non-default "
692 "visibility must be dso_local!",
697 if (!
I->getParent() || !
I->getParent()->getParent())
698 CheckFailed(
"Global is referenced by parentless instruction!", &GV, &M,
700 else if (
I->getParent()->getParent()->getParent() != &M)
701 CheckFailed(
"Global is referenced in a different module!", &GV, &M,
I,
702 I->getParent()->getParent(),
703 I->getParent()->getParent()->getParent());
706 if (
F->getParent() != &M)
707 CheckFailed(
"Global is used by function in a different module", &GV, &M,
715void Verifier::visitGlobalVariable(
const GlobalVariable &GV) {
723 Check(
A->value() <= Value::MaximumAlignment,
724 "huge alignment values are unsupported", &GV);
729 "Global variable initializer type does not match global "
733 "Global variable initializer must be sized", &GV);
739 "'common' global must have a zero initializer!", &GV);
742 Check(!GV.
hasComdat(),
"'common' global may not be in a Comdat!", &GV);
747 GV.
getName() ==
"llvm.global_dtors")) {
749 "invalid linkage for intrinsic global variable", &GV);
751 "invalid uses of intrinsic global variable", &GV);
758 PointerType::get(
Context,
DL.getProgramAddressSpace());
759 Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
760 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
761 STy->getTypeAtIndex(1) == FuncPtrTy,
762 "wrong type for intrinsic global variable", &GV);
763 Check(STy->getNumElements() == 3,
764 "the third field of the element type is mandatory, "
765 "specify ptr null to migrate from the obsoleted 2-field form");
766 Type *ETy = STy->getTypeAtIndex(2);
775 for (
const Use &U : Init->operands()) {
777 if (!Structor || Structor->getNumOperands() != 3)
780 "signing of ctors/dtors should be requested via module flags");
786 GV.
getName() ==
"llvm.compiler.used")) {
788 "invalid linkage for intrinsic global variable", &GV);
790 "invalid uses of intrinsic global variable", &GV);
794 Check(PTy,
"wrong type for intrinsic global variable", &GV);
798 Check(InitArray,
"wrong initializer for intrinsic global variable",
800 for (
Value *
Op : InitArray->operands()) {
804 Twine(
"invalid ") + GV.
getName() +
" member",
V);
806 Twine(
"members of ") + GV.
getName() +
" must be named",
V);
815 for (MDNode *MD : MDs) {
817 visitDIGlobalVariableExpression(*GVE);
819 CheckDI(
false,
"!dbg attachment of global variable must be a "
820 "DIGlobalVariableExpression");
830 "Global @" + GV.
getName() +
" has illegal target extension type",
839 "Global variable is too large to fit into the address space", &GV,
843 visitGlobalValue(GV);
850 visitGlobalValue(GV);
853void Verifier::visitAliaseeSubExpr(
const GlobalAlias &GA,
const Constant &
C) {
854 SmallPtrSet<const GlobalAlias*, 4> Visited;
856 visitAliaseeSubExpr(Visited, GA,
C);
859void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
860 const GlobalAlias &GA,
const Constant &
C) {
864 "available_externally alias must point to available_externally "
875 Check(Visited.
insert(GA2).second,
"Aliases cannot form a cycle", &GA);
877 Check(!GA2->isInterposable(),
878 "Alias cannot point to an interposable alias", &GA);
887 visitConstantExprsRecursively(CE);
889 for (
const Use &U :
C.operands()) {
892 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
894 visitAliaseeSubExpr(Visited, GA, *C2);
898void Verifier::visitGlobalAlias(
const GlobalAlias &GA) {
900 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
901 "weak_odr, external, or available_externally linkage!",
904 Check(Aliasee,
"Aliasee cannot be NULL!", &GA);
906 "Alias and aliasee types should match!", &GA);
909 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
911 visitAliaseeSubExpr(GA, *Aliasee);
913 visitGlobalValue(GA);
916void Verifier::visitGlobalIFunc(
const GlobalIFunc &GI) {
917 visitGlobalValue(GI);
921 for (
const auto &
I : MDs) {
922 CheckDI(
I.first != LLVMContext::MD_dbg,
923 "an ifunc may not have a !dbg attachment", &GI);
924 Check(
I.first != LLVMContext::MD_prof,
925 "an ifunc may not have a !prof attachment", &GI);
926 visitMDNode(*
I.second, AreDebugLocsAllowed::No);
930 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
931 "weak_odr, or external linkage!",
936 Check(Resolver,
"IFunc must have a Function resolver", &GI);
938 "IFunc resolver must be a definition", &GI);
945 "IFunc resolver must return a pointer", &GI);
948 "IFunc resolver has incorrect type", &GI);
951void Verifier::visitNamedMDNode(
const NamedMDNode &NMD) {
956 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
957 for (
const MDNode *MD : NMD.
operands()) {
958 if (NMD.
getName() ==
"llvm.dbg.cu")
964 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
975 return T->getRawScope();
977 return SP->getRawScope();
979 return LB->getRawScope();
981 return NS->getRawScope();
983 return CB->getRawScope();
985 return M->getRawScope();
990bool Verifier::hasDIScopeCycle(
const Metadata *S) {
991 SmallPtrSet<const Metadata *, 8> Seen;
992 auto CacheSeen = [&](
bool HasCycle) {
994 DIScopeChainReachesCycle[
M] = HasCycle;
999 auto It = DIScopeChainReachesCycle.
find(Scope);
1000 bool IsInCache = It != DIScopeChainReachesCycle.
end();
1002 return CacheSeen(It->second);
1003 bool AlreadySeen = !Seen.
insert(Scope).second;
1005 return CacheSeen(
true);
1011 return CacheSeen(
false);
1014void Verifier::visitDIScopeChain(
const DIScope &
N) {
1015 CheckDI(!hasDIScopeCycle(&
N),
"DIScope scope chain must not contain a cycle",
1019void Verifier::visitMDNode(
const MDNode &BaseMD,
1020 AreDebugLocsAllowed AllowLocs) {
1023 if (!MDNodes.
insert(&BaseMD).second)
1026 std::queue<const MDNode *> Worklist;
1027 Worklist.push(&BaseMD);
1029 while (!Worklist.empty()) {
1030 const MDNode *CurrentMD = Worklist.front();
1033 "MDNode context does not match Module context!", CurrentMD);
1038 case Metadata::MDTupleKind:
1040#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
1041 case Metadata::CLASS##Kind: \
1042 visit##CLASS(cast<CLASS>(*CurrentMD)); \
1044#include "llvm/IR/Metadata.def"
1049 visitDIScopeChain(*S);
1057 "DILocation not allowed within this metadata node", CurrentMD,
1065 visitValueAsMetadata(*
V,
nullptr);
1086 "Expected second operand to be an integer constant of type i32 or "
1098 Check(AlignMD && AlignMD->getType()->isIntegerTy(32),
1099 "Expected the alignment to be an integer constant of type i32",
1104 "Expected the alignment to be a power of two", CurrentMD);
1105 Check(Align <= Value::MaximumAlignment,
1106 "Alignment is larger than the implementation defined limit",
1118 "Expecting only the metadata name", CurrentMD);
1123 Check(CurrentMD->
isResolved(),
"All nodes should be resolved!", CurrentMD);
1127void Verifier::visitValueAsMetadata(
const ValueAsMetadata &MD,
Function *
F) {
1130 "Unexpected metadata round-trip through values", &MD, MD.
getValue());
1136 Check(
F,
"function-local metadata used outside a function", L);
1142 Check(
I->getParent(),
"function-local metadata not in basic block", L,
I);
1149 assert(ActualF &&
"Unimplemented function local metadata case!");
1151 Check(ActualF ==
F,
"function-local metadata used in wrong function", L);
1154void Verifier::visitDIArgList(
const DIArgList &AL,
Function *
F) {
1155 for (
const ValueAsMetadata *VAM :
AL.getArgs())
1156 visitValueAsMetadata(*VAM,
F);
1159void Verifier::visitMetadataAsValue(
const MetadataAsValue &MDV,
Function *
F) {
1162 visitMDNode(*
N, AreDebugLocsAllowed::No);
1168 if (!MDNodes.
insert(MD).second)
1172 visitValueAsMetadata(*
V,
F);
1175 visitDIArgList(*AL,
F);
1183void Verifier::visitDILocation(
const DILocation &
N) {
1185 "location requires a valid scope", &
N,
N.getRawScope());
1186 if (
auto *IA =
N.getRawInlinedAt())
1189 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1190 if (
auto *L =
N.getRawIRLayers())
1194void Verifier::visitDILayerLoc(
const DILayerLoc &
N) {
1196 "layer kind must be a non-null MDString", &
N,
N.getRawKind());
1198 "layer file must be a non-null DIFile", &
N,
N.getRawFile());
1201void Verifier::visitDILayerLocList(
const DILayerLocList &
N) {
1202 CheckDI(
N.getNumLayers() > 0,
"DILayerLocList must be non-empty", &
N);
1203 for (
const MDOperand &
Op :
N.layers())
1205 "DILayerLocList entry must be a DILayerLoc", &
N,
Op.get());
1208void Verifier::visitGenericDINode(
const GenericDINode &
N) {
1212void Verifier::visitDIScope(
const DIScope &
N) {
1213 if (
auto *
F =
N.getRawFile())
1217void Verifier::visitDIType(
const DIType &
N) {
1220 CheckDI(
N.getRawFile() ||
N.getLine() == 0,
"line specified with no file", &
N,
1224void Verifier::visitDISubrangeType(
const DISubrangeType &
N) {
1227 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1230 auto *LBound =
N.getRawLowerBound();
1234 "LowerBound must be signed constant or DIVariable or DIExpression or "
1237 auto *UBound =
N.getRawUpperBound();
1241 "UpperBound must be signed constant or DIVariable or DIExpression or "
1244 auto *Stride =
N.getRawStride();
1247 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1248 auto *Bias =
N.getRawBias();
1251 "Bias must be signed constant or DIVariable or DIExpression", &
N);
1253 auto *
Size =
N.getRawSizeInBits();
1255 "SizeInBits must be a constant");
1258void Verifier::visitDISubrange(
const DISubrange &
N) {
1259 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1260 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1261 "Subrange can have any one of count or upperBound", &
N);
1262 auto *CBound =
N.getRawCountNode();
1265 "Count must be signed constant or DIVariable or DIExpression", &
N);
1266 auto Count =
N.getCount();
1269 "invalid subrange count", &
N);
1270 auto *LBound =
N.getRawLowerBound();
1273 "LowerBound must be signed constant or DIVariable or DIExpression",
1275 auto *UBound =
N.getRawUpperBound();
1278 "UpperBound must be signed constant or DIVariable or DIExpression",
1280 auto *Stride =
N.getRawStride();
1283 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1286void Verifier::visitDIGenericSubrange(
const DIGenericSubrange &
N) {
1287 CheckDI(
N.getTag() == dwarf::DW_TAG_generic_subrange,
"invalid tag", &
N);
1288 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1289 "GenericSubrange can have any one of count or upperBound", &
N);
1290 auto *CBound =
N.getRawCountNode();
1292 "Count must be signed constant or DIVariable or DIExpression", &
N);
1293 auto *LBound =
N.getRawLowerBound();
1294 CheckDI(LBound,
"GenericSubrange must contain lowerBound", &
N);
1296 "LowerBound must be signed constant or DIVariable or DIExpression",
1298 auto *UBound =
N.getRawUpperBound();
1300 "UpperBound must be signed constant or DIVariable or DIExpression",
1302 auto *Stride =
N.getRawStride();
1303 CheckDI(Stride,
"GenericSubrange must contain stride", &
N);
1305 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1308void Verifier::visitDIEnumerator(
const DIEnumerator &
N) {
1309 CheckDI(
N.getTag() == dwarf::DW_TAG_enumerator,
"invalid tag", &
N);
1312void Verifier::visitDIBasicType(
const DIBasicType &
N) {
1315 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type ||
1316 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1317 N.getTag() == dwarf::DW_TAG_string_type,
1320 auto *
Size =
N.getRawSizeInBits();
1322 "SizeInBits must be a constant");
1325void Verifier::visitDIFixedPointType(
const DIFixedPointType &
N) {
1326 visitDIBasicType(
N);
1328 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type,
"invalid tag", &
N);
1329 CheckDI(
N.getEncoding() == dwarf::DW_ATE_signed_fixed ||
1330 N.getEncoding() == dwarf::DW_ATE_unsigned_fixed,
1331 "invalid encoding", &
N);
1335 "invalid kind", &
N);
1337 N.getFactorRaw() == 0,
1338 "factor should be 0 for rationals", &
N);
1340 (
N.getNumeratorRaw() == 0 &&
N.getDenominatorRaw() == 0),
1341 "numerator and denominator should be 0 for non-rationals", &
N);
1344void Verifier::visitDIStringType(
const DIStringType &
N) {
1347 CheckDI(
N.getTag() == dwarf::DW_TAG_string_type,
"invalid tag", &
N);
1348 CheckDI(!(
N.isBigEndian() &&
N.isLittleEndian()),
"has conflicting flags",
1350 if (
N.getRawCharType())
1352 N.getRawCharType());
1355void Verifier::visitDIDerivedType(
const DIDerivedType &
N) {
1359 CheckDI(
N.getTag() == dwarf::DW_TAG_typedef ||
1360 N.getTag() == dwarf::DW_TAG_pointer_type ||
1361 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1362 N.getTag() == dwarf::DW_TAG_reference_type ||
1363 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1364 N.getTag() == dwarf::DW_TAG_const_type ||
1365 N.getTag() == dwarf::DW_TAG_immutable_type ||
1366 N.getTag() == dwarf::DW_TAG_volatile_type ||
1367 N.getTag() == dwarf::DW_TAG_restrict_type ||
1368 N.getTag() == dwarf::DW_TAG_atomic_type ||
1369 N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
1370 N.getTag() == dwarf::DW_TAG_member ||
1371 (
N.getTag() == dwarf::DW_TAG_variable &&
N.isStaticMember()) ||
1372 N.getTag() == dwarf::DW_TAG_inheritance ||
1373 N.getTag() == dwarf::DW_TAG_friend ||
1374 N.getTag() == dwarf::DW_TAG_set_type ||
1375 N.getTag() == dwarf::DW_TAG_template_alias,
1377 if (
N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1378 CheckDI(
isType(
N.getRawExtraData()),
"invalid pointer to member type", &
N,
1379 N.getRawExtraData());
1380 }
else if (
N.getTag() == dwarf::DW_TAG_template_alias) {
1382 N.getRawExtraData());
1383 }
else if (
N.getTag() == dwarf::DW_TAG_inheritance ||
1384 N.getTag() == dwarf::DW_TAG_member ||
1385 N.getTag() == dwarf::DW_TAG_variable) {
1386 auto *ExtraData =
N.getRawExtraData();
1387 auto IsValidExtraData = [&]() {
1388 if (ExtraData ==
nullptr)
1394 if (
Tuple->getNumOperands() != 1)
1401 "extraData must be ConstantAsMetadata, MDString, DIObjCProperty, "
1402 "or MDTuple with single ConstantAsMetadata operand",
1406 if (
N.getTag() == dwarf::DW_TAG_set_type) {
1407 if (
auto *
T =
N.getRawBaseType()) {
1412 (Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1413 (Subrange &&
Subrange->getTag() == dwarf::DW_TAG_subrange_type) ||
1414 (
Basic && (
Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1415 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1416 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1417 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1418 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1419 "invalid set base type", &
N,
T);
1424 N.getRawBaseType());
1426 if (
N.getDWARFAddressSpace()) {
1427 CheckDI(
N.getTag() == dwarf::DW_TAG_pointer_type ||
1428 N.getTag() == dwarf::DW_TAG_reference_type ||
1429 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1430 "DWARF address space only applies to pointer or reference types",
1434 auto *
Size =
N.getRawSizeInBits();
1437 "SizeInBits must be a constant or DIVariable or DIExpression");
1442 return ((Flags & DINode::FlagLValueReference) &&
1443 (Flags & DINode::FlagRValueReference)) ||
1444 ((Flags & DINode::FlagTypePassByValue) &&
1445 (Flags & DINode::FlagTypePassByReference));
1448void Verifier::visitTemplateParams(
const MDNode &
N,
const Metadata &RawParams) {
1450 CheckDI(Params,
"invalid template params", &
N, &RawParams);
1457void Verifier::visitDICompositeType(
const DICompositeType &
N) {
1461 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type ||
1462 N.getTag() == dwarf::DW_TAG_structure_type ||
1463 N.getTag() == dwarf::DW_TAG_union_type ||
1464 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1465 N.getTag() == dwarf::DW_TAG_class_type ||
1466 N.getTag() == dwarf::DW_TAG_variant_part ||
1467 N.getTag() == dwarf::DW_TAG_variant ||
1468 N.getTag() == dwarf::DW_TAG_namelist,
1472 N.getRawBaseType());
1475 "invalid composite elements", &
N,
N.getRawElements());
1477 N.getRawVTableHolder());
1479 "invalid reference flags", &
N);
1480 unsigned DIBlockByRefStruct = 1 << 4;
1481 CheckDI((
N.getFlags() & DIBlockByRefStruct) == 0,
1482 "DIBlockByRefStruct on DICompositeType is no longer supported", &
N);
1484 "DISubprogram contains null entry in `elements` field", &
N);
1487 const DINodeArray
Elements =
N.getElements();
1489 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1490 "invalid vector, expected one element of type subrange", &
N);
1493 if (
auto *Params =
N.getRawTemplateParams())
1494 visitTemplateParams(
N, *Params);
1496 if (
auto *
D =
N.getRawDiscriminator()) {
1498 "discriminator can only appear on variant part");
1501 if (
N.getRawDataLocation()) {
1502 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1503 "dataLocation can only appear in array type");
1506 if (
N.getRawAssociated()) {
1507 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1508 "associated can only appear in array type");
1511 if (
N.getRawAllocated()) {
1512 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1513 "allocated can only appear in array type");
1516 if (
N.getRawRank()) {
1517 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1518 "rank can only appear in array type");
1521 if (
N.getTag() == dwarf::DW_TAG_array_type) {
1522 CheckDI(
N.getRawBaseType(),
"array types must have a base type", &
N);
1525 auto *
Size =
N.getRawSizeInBits();
1528 "SizeInBits must be a constant or DIVariable or DIExpression");
1531void Verifier::visitDISubroutineType(
const DISubroutineType &
N) {
1533 CheckDI(
N.getTag() == dwarf::DW_TAG_subroutine_type,
"invalid tag", &
N);
1534 if (
auto *Types =
N.getRawTypeArray()) {
1536 for (
Metadata *Ty :
N.getTypeArray()->operands()) {
1537 CheckDI(
isType(Ty),
"invalid subroutine type ref", &
N, Types, Ty);
1541 "invalid reference flags", &
N);
1544void Verifier::visitDIFile(
const DIFile &
N) {
1545 CheckDI(
N.getTag() == dwarf::DW_TAG_file_type,
"invalid tag", &
N);
1546 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum =
N.getChecksum();
1548 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1549 "invalid checksum kind", &
N);
1551 switch (Checksum->Kind) {
1562 CheckDI(Checksum->Value.size() ==
Size,
"invalid checksum length", &
N);
1564 "invalid checksum", &
N);
1568void Verifier::visitDICompileUnit(
const DICompileUnit &
N) {
1569 CheckDI(
N.isDistinct(),
"compile units must be distinct", &
N);
1570 CheckDI(
N.getTag() == dwarf::DW_TAG_compile_unit,
"invalid tag", &
N);
1576 CheckDI(!
N.getFile()->getFilename().empty(),
"invalid filename", &
N,
1580 "invalid emission kind", &
N);
1583 "invalid language dialect", &
N);
1585 if (
auto *Array =
N.getRawEnumTypes()) {
1587 for (
Metadata *
Op :
N.getEnumTypes()->operands()) {
1589 CheckDI(Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1590 "invalid enum type", &
N,
N.getEnumTypes(),
Op);
1592 "function-local enum in a DICompileUnit's enum list", &
N,
1593 N.getEnumTypes(),
Op);
1596 if (
auto *Array =
N.getRawRetainedTypes()) {
1598 for (
Metadata *
Op :
N.getRetainedTypes()->operands()) {
1602 "invalid retained type", &
N,
Op);
1605 if (
auto *Array =
N.getRawGlobalVariables()) {
1607 for (
Metadata *
Op :
N.getGlobalVariables()->operands()) {
1609 CheckDI(GVE,
"invalid global variable ref", &
N,
Op);
1611 "function-local variables are not allowed in a DICompileUnit's "
1612 "global variables list",
1616 if (
auto *Array =
N.getRawImportedEntities()) {
1618 for (
Metadata *
Op :
N.getImportedEntities()->operands()) {
1620 CheckDI(IE,
"invalid imported entity ref", &
N,
Op);
1622 "function-local imports are not allowed in a DICompileUnit's "
1623 "imported entities list",
1627 if (
auto *Array =
N.getRawMacros()) {
1636void Verifier::visitDISubprogram(
const DISubprogram &
N) {
1637 CheckDI(
N.getTag() == dwarf::DW_TAG_subprogram,
"invalid tag", &
N);
1639 if (
auto *
F =
N.getRawFile())
1642 CheckDI(
N.getLine() == 0,
"line specified with no file", &
N,
N.getLine());
1643 auto *
T =
N.getRawType();
1644 CheckDI(
T,
"DISubprogram requires a non-null type", &
N);
1646 CheckDI(
isType(
N.getRawContainingType()),
"invalid containing type", &
N,
1647 N.getRawContainingType());
1648 if (
auto *Params =
N.getRawTemplateParams())
1649 visitTemplateParams(
N, *Params);
1650 if (
auto *S =
N.getRawDeclaration())
1652 "invalid subprogram declaration", &
N, S);
1653 if (
auto *RawNode =
N.getRawRetainedNodes()) {
1655 CheckDI(Node,
"invalid retained nodes list", &
N, RawNode);
1657 DenseMap<unsigned, DILocalVariable *>
Args;
1659 CheckDI(
Op,
"nullptr in retained nodes", &
N, Node);
1663 bool IsTypeCorrect = DISubprogram::visitRetainedNode<bool>(
1666 "invalid retained nodes, expected DILocalVariable, DILabel, "
1667 "DIImportedEntity, DIType or DIGlobalVariableExpression",
1674 "invalid retained nodes, retained node is not local", &
N, Node,
1677 DISubprogram *RetainedNodeSP =
getSubprogram(RetainedNodeScope);
1678 DICompileUnit *RetainedNodeUnit =
1679 RetainedNodeSP ? RetainedNodeSP->getUnit() :
nullptr;
1681 RetainedNodeSP == &
N,
1682 "invalid retained nodes, retained node does not belong to subprogram",
1683 &
N, Node, RetainedNode, RetainedNodeScope, RetainedNodeSP,
1689 if (
unsigned ArgNum = DV->getArg()) {
1691 CheckDI(Inserted || DV == ArgI->second,
1692 "invalid retained nodes, more than one local variable with the "
1693 "same argument index",
1694 &
N,
N.getUnit(), Node, RetainedNode, Args[ArgNum]);
1699 "invalid reference flags", &
N);
1701 auto *
Unit =
N.getRawUnit();
1702 if (
N.isDefinition()) {
1704 CheckDI(
N.isDistinct(),
"subprogram definitions must be distinct", &
N);
1705 CheckDI(Unit,
"subprogram definitions must have a compile unit", &
N);
1710 if (CT && CT->getRawIdentifier() &&
1711 M.getContext().isODRUniquingDebugTypes())
1713 "definition subprograms cannot be nested within DICompositeType "
1714 "when enabling ODR",
1718 CheckDI(!Unit,
"subprogram declarations must not have a compile unit", &
N);
1720 "subprogram declaration must not have a declaration field");
1723 if (
auto *RawThrownTypes =
N.getRawThrownTypes()) {
1725 CheckDI(ThrownTypes,
"invalid thrown types list", &
N, RawThrownTypes);
1731 if (
N.areAllCallsDescribed())
1733 "DIFlagAllCallsDescribed must be attached to a definition");
1736void Verifier::visitDILexicalBlockBase(
const DILexicalBlockBase &
N) {
1737 CheckDI(
N.getTag() == dwarf::DW_TAG_lexical_block,
"invalid tag", &
N);
1739 "invalid local scope", &
N,
N.getRawScope());
1741 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1744void Verifier::visitDILexicalBlock(
const DILexicalBlock &
N) {
1745 visitDILexicalBlockBase(
N);
1748 "cannot have column info without line info", &
N);
1751void Verifier::visitDILexicalBlockFile(
const DILexicalBlockFile &
N) {
1752 visitDILexicalBlockBase(
N);
1755void Verifier::visitDICommonBlock(
const DICommonBlock &
N) {
1756 CheckDI(
N.getTag() == dwarf::DW_TAG_common_block,
"invalid tag", &
N);
1757 if (
auto *S =
N.getRawScope())
1759 if (
auto *S =
N.getRawDecl())
1763void Verifier::visitDINamespace(
const DINamespace &
N) {
1764 CheckDI(
N.getTag() == dwarf::DW_TAG_namespace,
"invalid tag", &
N);
1765 if (
auto *S =
N.getRawScope())
1769void Verifier::visitDIMacro(
const DIMacro &
N) {
1772 "invalid macinfo type", &
N);
1773 CheckDI(!
N.getName().empty(),
"anonymous macro", &
N);
1774 if (!
N.getValue().empty()) {
1775 assert(
N.getValue().data()[0] !=
' ' &&
"Macro value has a space prefix");
1779void Verifier::visitDIMacroFile(
const DIMacroFile &
N) {
1781 "invalid macinfo type", &
N);
1782 if (
auto *
F =
N.getRawFile())
1785 if (
auto *Array =
N.getRawElements()) {
1787 for (
Metadata *
Op :
N.getElements()->operands()) {
1793void Verifier::visitDIModule(
const DIModule &
N) {
1794 CheckDI(
N.getTag() == dwarf::DW_TAG_module,
"invalid tag", &
N);
1795 CheckDI(!
N.getName().empty(),
"anonymous module", &
N);
1798void Verifier::visitDITemplateParameter(
const DITemplateParameter &
N) {
1802void Verifier::visitDITemplateTypeParameter(
const DITemplateTypeParameter &
N) {
1803 visitDITemplateParameter(
N);
1805 CheckDI(
N.getTag() == dwarf::DW_TAG_template_type_parameter,
"invalid tag",
1809void Verifier::visitDITemplateValueParameter(
1810 const DITemplateValueParameter &
N) {
1811 visitDITemplateParameter(
N);
1813 CheckDI(
N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1814 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1815 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1819void Verifier::visitDIVariable(
const DIVariable &
N) {
1820 if (
auto *S =
N.getRawScope())
1822 if (
auto *
F =
N.getRawFile())
1826void Verifier::visitDIGlobalVariable(
const DIGlobalVariable &
N) {
1830 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1833 if (
N.isDefinition())
1834 CheckDI(
N.getType(),
"missing global variable type", &
N);
1835 if (
auto *Member =
N.getRawStaticDataMemberDeclaration()) {
1837 "invalid static data member declaration", &
N, Member);
1841void Verifier::visitDILocalVariable(
const DILocalVariable &
N) {
1846 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1848 "local variable requires a valid scope", &
N,
N.getRawScope());
1849 if (
auto Ty =
N.getType())
1853void Verifier::visitDIAssignID(
const DIAssignID &
N) {
1854 CheckDI(!
N.getNumOperands(),
"DIAssignID has no arguments", &
N);
1855 CheckDI(
N.isDistinct(),
"DIAssignID must be distinct", &
N);
1858void Verifier::visitDILabel(
const DILabel &
N) {
1859 if (
auto *S =
N.getRawScope())
1861 if (
auto *
F =
N.getRawFile())
1864 CheckDI(
N.getTag() == dwarf::DW_TAG_label,
"invalid tag", &
N);
1866 "label requires a valid scope", &
N,
N.getRawScope());
1869void Verifier::visitDIExpression(
const DIExpression &
N) {
1870 CheckDI(
N.isValid(),
"invalid expression", &
N);
1873void Verifier::visitDIGlobalVariableExpression(
1874 const DIGlobalVariableExpression &GVE) {
1877 visitDIGlobalVariable(*Var);
1879 visitDIExpression(*Expr);
1880 if (
auto Fragment = Expr->getFragmentInfo())
1885void Verifier::visitDIObjCProperty(
const DIObjCProperty &
N) {
1886 CheckDI(
N.getTag() == dwarf::DW_TAG_APPLE_property,
"invalid tag", &
N);
1887 if (
auto *
T =
N.getRawType())
1889 if (
auto *
F =
N.getRawFile())
1893void Verifier::visitDIProperty(
const DIProperty &
N) {
1894 CheckDI(
N.getTag() == dwarf::DW_TAG_property,
"invalid tag", &
N);
1895 if (
auto *
T =
N.getRawType())
1897 if (
auto *
F =
N.getRawFile())
1901 if (DINode *BackingStorage =
N.getBackingStorage()) {
1903 CheckDI(DT && DT->getTag() == dwarf::DW_TAG_member,
1904 "property backing storage must be a member", &
N, BackingStorage);
1908void Verifier::visitDIImportedEntity(
const DIImportedEntity &
N) {
1909 CheckDI(
N.getTag() == dwarf::DW_TAG_imported_module ||
1910 N.getTag() == dwarf::DW_TAG_imported_declaration,
1912 if (
auto *S =
N.getRawScope())
1918void Verifier::visitComdat(
const Comdat &
C) {
1921 if (
TT.isOSBinFormatCOFF())
1922 if (
const GlobalValue *GV =
M.getNamedValue(
C.getName()))
1927void Verifier::visitModuleIdents() {
1928 const NamedMDNode *Idents =
M.getNamedMetadata(
"llvm.ident");
1934 for (
const MDNode *
N : Idents->
operands()) {
1935 Check(
N->getNumOperands() == 1,
1936 "incorrect number of operands in llvm.ident metadata",
N);
1938 (
"invalid value for llvm.ident metadata entry operand"
1939 "(the operand should be a string)"),
1944void Verifier::visitModuleCommandLines() {
1945 const NamedMDNode *CommandLines =
M.getNamedMetadata(
"llvm.commandline");
1952 for (
const MDNode *
N : CommandLines->
operands()) {
1953 Check(
N->getNumOperands() == 1,
1954 "incorrect number of operands in llvm.commandline metadata",
N);
1956 (
"invalid value for llvm.commandline metadata entry operand"
1957 "(the operand should be a string)"),
1962void Verifier::visitModuleErrnoTBAA() {
1963 const NamedMDNode *ErrnoTBAA =
M.getNamedMetadata(
"llvm.errno.tbaa");
1968 "llvm.errno.tbaa must have at least one operand", ErrnoTBAA);
1970 for (
const MDNode *
N : ErrnoTBAA->
operands())
1974void Verifier::visitModuleRawSections() {
1975 const NamedMDNode *RawSections =
M.getNamedMetadata(
"llvm.raw.sections");
1979 for (
const MDNode *
N : RawSections->
operands()) {
1980 if (
N->getNumOperands() != 4) {
1981 CheckFailed(
"llvm.raw.sections entry must have four operands",
N);
1985 "llvm.raw.sections entry operand 0 must be a string "
1990 "llvm.raw.sections entry operand 1 must be an integer "
1994 CheckFailed(
"llvm.raw.sections entry operand 1 must be a power of two "
2001 "llvm.raw.sections entry operand 2 must be an integer "
2004 if (FlagsCI->getZExtValue() != 0) {
2005 CheckFailed(
"llvm.raw.sections entry operand 2 must be zero (flags are "
2006 "reserved for future use)",
2011 "llvm.raw.sections entry operand 3 must be a string "
2017void Verifier::visitModuleFlags() {
2018 const NamedMDNode *
Flags =
M.getModuleFlagsMetadata();
2022 DenseMap<const MDString*, const MDNode*> SeenIDs;
2026 std::optional<uint64_t> PAuthABIPlatform;
2027 std::optional<uint64_t> PAuthABIVersion;
2030 uint64_t HasPtrauthInitFiniAddr = 0;
2032 for (
const MDNode *MDN :
Flags->operands()) {
2033 visitModuleFlag(MDN, SeenIDs, Requirements);
2034 if (MDN->getNumOperands() != 3)
2038 auto GetFlagNamed = [&](StringRef
Name) -> std::optional<uint64_t> {
2039 if (FlagName->getString() != Name)
2040 return std::nullopt;
2041 if (
const auto *FlagValue =
2043 return FlagValue->getZExtValue();
2045 CheckFailed(Name +
": module flag expects integer value");
2046 return std::nullopt;
2049 if (
auto Value = GetFlagNamed(
"aarch64-elf-pauthabi-platform"))
2050 PAuthABIPlatform = *
Value;
2051 else if (
auto Value = GetFlagNamed(
"aarch64-elf-pauthabi-version"))
2052 PAuthABIVersion = *
Value;
2053 else if (
auto Value = GetFlagNamed(
"ptrauth-init-fini"))
2054 HasPtrauthInitFini = *
Value;
2055 else if (
auto Value =
2056 GetFlagNamed(
"ptrauth-init-fini-address-discrimination"))
2057 HasPtrauthInitFiniAddr = *
Value;
2062 "ptrauth-init-fini must be 0 or 1");
2064 "ptrauth-init-fini-address-discrimination must be 0 or 1, if set");
2065 if (HasPtrauthInitFiniAddr)
2066 Check(HasPtrauthInitFini,
"ptrauth-init-fini-address-discrimination module "
2067 "flag requires ptrauth-init-fini");
2069 if (PAuthABIPlatform.has_value() != PAuthABIVersion.has_value())
2070 CheckFailed(
"either both or no 'aarch64-elf-pauthabi-platform' and "
2071 "'aarch64-elf-pauthabi-version' module flags must be present");
2074 for (
const MDNode *Requirement : Requirements) {
2078 const MDNode *
Op = SeenIDs.
lookup(Flag);
2080 CheckFailed(
"invalid requirement on flag, flag is not present in module",
2085 if (
Op->getOperand(2) != ReqValue) {
2086 CheckFailed((
"invalid requirement on flag, "
2087 "flag does not have the required value"),
2095Verifier::visitModuleFlag(
const MDNode *
Op,
2096 DenseMap<const MDString *, const MDNode *> &SeenIDs,
2097 SmallVectorImpl<const MDNode *> &Requirements) {
2101 "incorrect number of operands in module flag",
Op);
2102 Module::ModFlagBehavior MFB;
2103 if (!Module::isValidModFlagBehavior(
Op->getOperand(0), MFB)) {
2105 "invalid behavior operand in module flag (expected constant integer)",
2108 "invalid behavior operand in module flag (unexpected constant)",
2112 Check(ID,
"invalid ID operand in module flag (expected metadata string)",
2118 case Module::Warning:
2119 case Module::Override:
2125 Check(
V &&
V->getValue().isNonNegative(),
2126 "invalid value for 'min' module flag (expected constant non-negative "
2134 "invalid value for 'max' module flag (expected constant integer)",
2139 case Module::Require: {
2144 "invalid value for 'require' module flag (expected metadata pair)",
2147 (
"invalid value for 'require' module flag "
2148 "(first value operand should be a string)"),
2149 Value->getOperand(0));
2157 case Module::Append:
2158 case Module::AppendUnique: {
2161 "invalid value for 'append'-type module flag "
2162 "(expected a metadata node)",
2169 if (MFB != Module::Require) {
2172 "module flag identifiers must be unique (or of 'require' type)", ID);
2175 StringRef
Name =
ID->getString();
2176 if (Name ==
"wchar_size") {
2179 Check(
Value,
"wchar_size metadata requires constant integer argument");
2183 if (Name ==
"long-double-type") {
2184 Check(MFB == Module::Error,
2185 "long-double-type module flag must use 'error' merge behavior",
Op);
2187 Check(
Value,
"long-double-type metadata requires a string argument");
2190 "invalid long-double-type metadata value",
Op);
2194 if (Name ==
"float-abi") {
2195 Check(MFB == Module::Error,
2196 "float-abi module flag must use 'error' merge behavior",
Op);
2198 Check(
Value,
"float-abi metadata requires a string argument");
2201 "invalid float-abi metadata value",
Op);
2205 if (Name ==
"thread-model") {
2206 Check(MFB == Module::Error,
2207 "thread-model module flag must use 'error' merge behavior",
Op);
2209 Check(
Value,
"thread-model metadata requires a string argument");
2212 "invalid thread-model metadata value",
Op);
2216 if (Name ==
"target-abi") {
2219 "target-abi metadata requires a non-empty string argument",
Op);
2223 if (
ID->getString() ==
"exception-model") {
2224 Check(MFB == Module::Error,
2225 "exception-model module flag must use 'error' merge behavior",
Op);
2227 Check(
Value,
"exception-model metadata requires a string argument");
2230 "invalid exception-model metadata value",
Op);
2234 if (Name ==
"debugger-tuning") {
2237 "debugger-tuning metadata requires a non-empty string argument",
Op);
2241 if (Name ==
"Linker Options") {
2245 Check(
M.getNamedMetadata(
"llvm.linker.options"),
2246 "'Linker Options' named metadata no longer supported");
2250 if (Name ==
"SemanticInterposition") {
2251 ConstantInt *
Value =
2254 "SemanticInterposition metadata requires constant integer argument");
2258 if (Name ==
"CG Profile") {
2259 for (
const MDOperand &MDO :
cast<MDNode>(
Op->getOperand(2))->operands())
2260 visitModuleFlagCGProfileEntry(MDO);
2268void Verifier::visitModuleFlagCGProfileEntry(
const MDOperand &MDO) {
2269 auto CheckFunction = [&](
const MDOperand &FuncMDO) {
2274 "expected a Function or null", FuncMDO);
2277 Check(Node &&
Node->getNumOperands() == 3,
"expected a MDNode triple", MDO);
2278 CheckFunction(
Node->getOperand(0));
2279 CheckFunction(
Node->getOperand(1));
2282 "expected an integer constant",
Node->getOperand(2));
2285void Verifier::verifyAttributeTypes(AttributeSet Attrs,
const Value *
V) {
2288 if (
A.isStringAttribute()) {
2289#define GET_ATTR_NAMES
2290#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
2291#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
2292 if (A.getKindAsString() == #DISPLAY_NAME) { \
2293 auto V = A.getValueAsString(); \
2294 if (!(V.empty() || V == "true" || V == "false")) \
2295 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
2299#include "llvm/IR/Attributes.inc"
2303 if (
A.isIntAttribute() != Attribute::isIntAttrKind(
A.getKindAsEnum())) {
2304 CheckFailed(
"Attribute '" +
A.getAsString() +
"' should have an Argument",
2313void Verifier::verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
2315 if (!
Attrs.hasAttributes())
2318 verifyAttributeTypes(Attrs,
V);
2321 Check(Attr.isStringAttribute() ||
2322 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
2323 "Attribute '" + Attr.getAsString() +
"' does not apply to parameters",
2326 if (
Attrs.hasAttribute(Attribute::ImmArg)) {
2327 unsigned AttrCount =
2328 Attrs.getNumAttributes() -
Attrs.hasAttribute(Attribute::Range);
2329 Check(AttrCount == 1,
2330 "Attribute 'immarg' is incompatible with other attributes except the "
2331 "'range' attribute",
2337 unsigned AttrCount = 0;
2338 AttrCount +=
Attrs.hasAttribute(Attribute::ByVal);
2339 AttrCount +=
Attrs.hasAttribute(Attribute::InAlloca);
2340 AttrCount +=
Attrs.hasAttribute(Attribute::Preallocated);
2341 AttrCount +=
Attrs.hasAttribute(Attribute::StructRet) ||
2342 Attrs.hasAttribute(Attribute::InReg);
2343 AttrCount +=
Attrs.hasAttribute(Attribute::Nest);
2344 AttrCount +=
Attrs.hasAttribute(Attribute::ByRef);
2345 Check(AttrCount <= 1,
2346 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
2347 "'byref', and 'sret' are incompatible!",
2350 Check(!(
Attrs.hasAttribute(Attribute::InAlloca) &&
2351 Attrs.hasAttribute(Attribute::ReadOnly)),
2353 "'inalloca and readonly' are incompatible!",
2356 Check(!(
Attrs.hasAttribute(Attribute::StructRet) &&
2357 Attrs.hasAttribute(Attribute::Returned)),
2359 "'sret and returned' are incompatible!",
2362 Check(!(
Attrs.hasAttribute(Attribute::ZExt) &&
2363 Attrs.hasAttribute(Attribute::SExt)),
2365 "'zeroext and signext' are incompatible!",
2368 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2369 Attrs.hasAttribute(Attribute::ReadOnly)),
2371 "'readnone and readonly' are incompatible!",
2374 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2375 Attrs.hasAttribute(Attribute::WriteOnly)),
2377 "'readnone and writeonly' are incompatible!",
2380 Check(!(
Attrs.hasAttribute(Attribute::ReadOnly) &&
2381 Attrs.hasAttribute(Attribute::WriteOnly)),
2383 "'readonly and writeonly' are incompatible!",
2386 Check(!(
Attrs.hasAttribute(Attribute::NoInline) &&
2387 Attrs.hasAttribute(Attribute::AlwaysInline)),
2389 "'noinline and alwaysinline' are incompatible!",
2392 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2393 Attrs.hasAttribute(Attribute::ReadNone)),
2394 "Attributes writable and readnone are incompatible!",
V);
2396 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2397 Attrs.hasAttribute(Attribute::ReadOnly)),
2398 "Attributes writable and readonly are incompatible!",
V);
2400 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty, Attrs);
2402 if (!Attr.isStringAttribute() &&
2403 IncompatibleAttrs.
contains(Attr.getKindAsEnum())) {
2404 CheckFailed(
"Attribute '" + Attr.getAsString() +
2405 "' applied to incompatible type!",
V);
2411 if (
Attrs.hasAttribute(Attribute::Alignment)) {
2412 Align AttrAlign =
Attrs.getAlignment().valueOrOne();
2413 Check(AttrAlign.
value() <= Value::MaximumAlignment,
2414 "huge alignment values are unsupported",
V);
2416 if (
Attrs.hasAttribute(Attribute::ByVal)) {
2419 "Attribute 'byval' does not support unsized types!",
V);
2423 "'byval' argument has illegal target extension type",
V);
2427 "scalable 'byval' arguments are unsupported",
V);
2428 Check(
DL.getTypeAllocSize(ByValTy).getKnownMinValue() < (1ULL << 32),
2429 "huge 'byval' arguments are unsupported",
V);
2431 if (
Attrs.hasAttribute(Attribute::ByRef)) {
2433 "Attribute 'byref' does not support unsized types!",
V);
2434 Check(
DL.getTypeAllocSize(
Attrs.getByRefType()).getKnownMinValue() <
2436 "huge 'byref' arguments are unsupported",
V);
2438 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
2440 "Attribute 'inalloca' does not support unsized types!",
V);
2441 Check(
DL.getTypeAllocSize(
Attrs.getInAllocaType()).getKnownMinValue() <
2443 "huge 'inalloca' arguments are unsupported",
V);
2445 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
2446 Check(
Attrs.getPreallocatedType()->isSized(),
2447 "Attribute 'preallocated' does not support unsized types!",
V);
2449 DL.getTypeAllocSize(
Attrs.getPreallocatedType()).getKnownMinValue() <
2451 "huge 'preallocated' arguments are unsupported",
V);
2455 if (
Attrs.hasAttribute(Attribute::Initializes)) {
2456 auto Inits =
Attrs.getAttribute(Attribute::Initializes).getInitializes();
2457 Check(!Inits.empty(),
"Attribute 'initializes' does not support empty list",
2460 "Attribute 'initializes' does not support unordered ranges",
V);
2463 if (
Attrs.hasAttribute(Attribute::NoFPClass)) {
2464 uint64_t Val =
Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
2465 Check(Val != 0,
"Attribute 'nofpclass' must have at least one test bit set",
2468 "Invalid value for 'nofpclass' test mask",
V);
2470 if (
Attrs.hasAttribute(Attribute::Range)) {
2471 const ConstantRange &CR =
2472 Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2474 "Range bit width must match type bit width!",
V);
2478void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
2480 if (
Attrs.hasFnAttr(Attr)) {
2481 StringRef S =
Attrs.getFnAttr(Attr).getValueAsString();
2484 CheckFailed(
"\"" + Attr +
"\" takes an unsigned integer: " + S,
V);
2490void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
2491 const Value *
V,
bool IsIntrinsic,
2493 if (
Attrs.isEmpty())
2496 if (AttributeListsVisited.
insert(
Attrs.getRawPointer()).second) {
2498 "Attribute list does not match Module context!", &Attrs,
V);
2499 for (
const auto &AttrSet : Attrs) {
2500 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(
Context),
2501 "Attribute set does not match Module context!", &AttrSet,
V);
2502 for (
const auto &
A : AttrSet) {
2504 "Attribute does not match Module context!", &
A,
V);
2509 bool SawNest =
false;
2510 bool SawReturned =
false;
2511 bool SawSRet =
false;
2512 bool SawSwiftSelf =
false;
2513 bool SawSwiftAsync =
false;
2514 bool SawSwiftError =
false;
2517 AttributeSet RetAttrs =
Attrs.getRetAttrs();
2520 Attribute::canUseAsRetAttr(
RetAttr.getKindAsEnum()),
2521 "Attribute '" +
RetAttr.getAsString() +
2522 "' does not apply to function return values",
2525 unsigned MaxParameterWidth = 0;
2526 auto GetMaxParameterWidth = [&MaxParameterWidth](
Type *Ty) {
2529 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2530 if (
Size > MaxParameterWidth)
2531 MaxParameterWidth =
Size;
2535 GetMaxParameterWidth(FT->getReturnType());
2536 verifyParameterAttrs(RetAttrs, FT->getReturnType(),
V);
2539 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2540 Type *Ty = FT->getParamType(i);
2541 AttributeSet ArgAttrs =
Attrs.getParamAttrs(i);
2545 "immarg attribute only applies to intrinsics",
V);
2548 "Attribute 'elementtype' can only be applied to intrinsics"
2553 verifyParameterAttrs(ArgAttrs, Ty,
V);
2554 GetMaxParameterWidth(Ty);
2557 Check(!SawNest,
"More than one parameter has attribute nest!",
V);
2562 Check(!SawReturned,
"More than one parameter has attribute returned!",
V);
2564 "Incompatible argument and return types for 'returned' attribute",
2570 Check(!SawSRet,
"Cannot have multiple 'sret' parameters!",
V);
2571 Check(i == 0 || i == 1,
2572 "Attribute 'sret' is not on first or second parameter!",
V);
2577 Check(!SawSwiftSelf,
"Cannot have multiple 'swiftself' parameters!",
V);
2578 SawSwiftSelf =
true;
2582 Check(!SawSwiftAsync,
"Cannot have multiple 'swiftasync' parameters!",
V);
2583 SawSwiftAsync =
true;
2587 Check(!SawSwiftError,
"Cannot have multiple 'swifterror' parameters!",
V);
2588 SawSwiftError =
true;
2592 Check(i == FT->getNumParams() - 1,
2593 "inalloca isn't on the last parameter!",
V);
2597 if (!
Attrs.hasFnAttrs())
2600 verifyAttributeTypes(
Attrs.getFnAttrs(),
V);
2603 Attribute::canUseAsFnAttr(
FnAttr.getKindAsEnum()),
2604 "Attribute '" +
FnAttr.getAsString() +
2605 "' does not apply to functions!",
2608 Check(!(
Attrs.hasFnAttr(Attribute::NoInline) &&
2609 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2610 "Attributes 'noinline and alwaysinline' are incompatible!",
V);
2612 if (
Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2614 "Attribute 'optnone' requires 'noinline'!",
V);
2616 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2617 "Attributes 'optsize and optnone' are incompatible!",
V);
2620 "Attributes 'minsize and optnone' are incompatible!",
V);
2622 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
2623 "Attributes 'optdebug and optnone' are incompatible!",
V);
2626 Check(!(
Attrs.hasFnAttr(Attribute::SanitizeRealtime) &&
2627 Attrs.hasFnAttr(Attribute::SanitizeRealtimeBlocking)),
2629 "'sanitize_realtime and sanitize_realtime_blocking' are incompatible!",
2632 Check(!(
Attrs.hasFnAttr(Attribute::SanitizeThread) &&
2633 Attrs.hasFnAttr(Attribute::SanitizeConcurrency)),
2634 "Attributes 'sanitize_thread and sanitize_concurrency' are "
2638 if (
Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
2639 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2640 "Attributes 'optsize and optdebug' are incompatible!",
V);
2643 "Attributes 'minsize and optdebug' are incompatible!",
V);
2646 Check(!
Attrs.hasAttrSomewhere(Attribute::Writable) ||
2647 isModSet(
Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
2648 "Attribute writable and memory without argmem: write are incompatible!",
2651 if (
Attrs.hasFnAttr(
"aarch64_pstate_sm_enabled")) {
2652 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_sm_compatible"),
2653 "Attributes 'aarch64_pstate_sm_enabled and "
2654 "aarch64_pstate_sm_compatible' are incompatible!",
2658 Check((
Attrs.hasFnAttr(
"aarch64_new_za") +
Attrs.hasFnAttr(
"aarch64_in_za") +
2659 Attrs.hasFnAttr(
"aarch64_inout_za") +
2660 Attrs.hasFnAttr(
"aarch64_out_za") +
2661 Attrs.hasFnAttr(
"aarch64_preserves_za") +
2662 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2663 "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2664 "'aarch64_inout_za', 'aarch64_preserves_za' and "
2665 "'aarch64_za_state_agnostic' are mutually exclusive",
2669 Attrs.hasFnAttr(
"aarch64_in_zt0") +
2670 Attrs.hasFnAttr(
"aarch64_inout_zt0") +
2671 Attrs.hasFnAttr(
"aarch64_out_zt0") +
2672 Attrs.hasFnAttr(
"aarch64_preserves_zt0") +
2673 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2674 "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
2675 "'aarch64_inout_zt0', 'aarch64_preserves_zt0' and "
2676 "'aarch64_za_state_agnostic' are mutually exclusive",
2679 if (
Attrs.hasFnAttr(Attribute::JumpTable)) {
2682 "Attribute 'jumptable' requires 'unnamed_addr'",
V);
2685 if (
auto Args =
Attrs.getFnAttrs().getAllocSizeArgs()) {
2686 auto CheckParam = [&](StringRef
Name,
unsigned ParamNo) {
2687 if (ParamNo >= FT->getNumParams()) {
2688 CheckFailed(
"'allocsize' " + Name +
" argument is out of bounds",
V);
2692 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2693 CheckFailed(
"'allocsize' " + Name +
2694 " argument must refer to an integer parameter",
2702 if (!CheckParam(
"element size",
Args->first))
2705 if (
Args->second && !CheckParam(
"number of elements", *
Args->second))
2709 if (
Attrs.hasFnAttr(Attribute::AllocKind)) {
2712 K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
2714 {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
2717 "'allockind()' requires exactly one of alloc, realloc, and free");
2718 if ((
Type == AllocFnKind::Free) &&
2719 ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
2720 AllocFnKind::Aligned)) != AllocFnKind::Unknown))
2721 CheckFailed(
"'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2722 "or aligned modifiers.");
2723 AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
2724 if ((K & ZeroedUninit) == ZeroedUninit)
2725 CheckFailed(
"'allockind()' can't be both zeroed and uninitialized");
2729 StringRef S =
A.getValueAsString();
2730 Check(!S.
empty(),
"'alloc-variant-zeroed' must not be empty");
2738 "'alloc-variant-zeroed' must name a function belonging to the "
2739 "same 'alloc-family'");
2742 (
Variant->getFnAttribute(Attribute::AllocKind).getAllocKind() &
2743 AllocFnKind::Zeroed) != AllocFnKind::Unknown,
2744 "'alloc-variant-zeroed' must name a function with "
2745 "'allockind(\"zeroed\")'");
2748 "'alloc-variant-zeroed' must name a function with the same "
2753 "'alloc-variant-zeroed' must name a function with the same "
2754 "calling convention");
2758 if (
Attrs.hasFnAttr(Attribute::VScaleRange)) {
2759 unsigned VScaleMin =
Attrs.getFnAttrs().getVScaleRangeMin();
2761 CheckFailed(
"'vscale_range' minimum must be greater than 0",
V);
2763 CheckFailed(
"'vscale_range' minimum must be power-of-two value",
V);
2764 std::optional<unsigned> VScaleMax =
Attrs.getFnAttrs().getVScaleRangeMax();
2765 if (VScaleMax && VScaleMin > VScaleMax)
2766 CheckFailed(
"'vscale_range' minimum cannot be greater than maximum",
V);
2768 CheckFailed(
"'vscale_range' maximum must be power-of-two value",
V);
2771 if (
Attribute FPAttr =
Attrs.getFnAttr(
"frame-pointer"); FPAttr.isValid()) {
2772 StringRef
FP = FPAttr.getValueAsString();
2773 if (
FP !=
"all" &&
FP !=
"non-leaf" &&
FP !=
"none" &&
FP !=
"reserved" &&
2774 FP !=
"non-leaf-no-reserve")
2775 CheckFailed(
"invalid value for 'frame-pointer' attribute: " +
FP,
V);
2778 checkUnsignedBaseTenFuncAttr(Attrs,
"tail-pad-to-size",
V);
2779 checkUnsignedBaseTenFuncAttr(Attrs,
"tail-pad-value",
V);
2780 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-prefix",
V);
2781 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-entry",
V);
2782 if (
Attrs.hasFnAttr(
"patchable-function-entry-section"))
2783 Check(!
Attrs.getFnAttr(
"patchable-function-entry-section")
2786 "\"patchable-function-entry-section\" must not be empty");
2787 checkUnsignedBaseTenFuncAttr(Attrs,
"warn-stack-size",
V);
2788 checkUnsignedBaseTenFuncAttr(Attrs,
"unsafe-stack-size",
V);
2790 checkUnsignedBaseTenFuncAttr(Attrs, Attr,
V);
2792 if (
auto A =
Attrs.getFnAttr(
"sign-return-address");
A.isValid()) {
2793 StringRef S =
A.getValueAsString();
2794 if (S !=
"none" && S !=
"all" && S !=
"non-leaf")
2795 CheckFailed(
"invalid value for 'sign-return-address' attribute: " + S,
V);
2798 if (
auto A =
Attrs.getFnAttr(
"sign-return-address-key");
A.isValid()) {
2799 StringRef S =
A.getValueAsString();
2800 if (S !=
"a_key" && S !=
"b_key")
2801 CheckFailed(
"invalid value for 'sign-return-address-key' attribute: " + S,
2803 if (
auto AA =
Attrs.getFnAttr(
"sign-return-address"); !AA.isValid()) {
2805 "'sign-return-address-key' present without `sign-return-address`");
2809 if (
auto A =
Attrs.getFnAttr(
"sign-return-address-harden");
A.isValid()) {
2810 StringRef S =
A.getValueAsString();
2811 if (S !=
"load-return-address" && S !=
"none")
2813 "invalid value for 'sign-return-address-harden' attribute: " + S,
V);
2814 auto SignRetA =
Attrs.getFnAttr(
"sign-return-address");
2815 auto PAuthRetA =
Attrs.getFnAttr(
"ptrauth-returns");
2816 if (!SignRetA.isValid() && !PAuthRetA.isValid())
2817 CheckFailed(
"'sign-return-address-harden' present without "
2818 "'sign-return-address' or 'ptrauth-returns'");
2821 if (
auto A =
Attrs.getFnAttr(
"branch-target-enforcement");
A.isValid()) {
2822 StringRef S =
A.getValueAsString();
2823 if (S !=
"" && S !=
"true" && S !=
"false")
2825 "invalid value for 'branch-target-enforcement' attribute: " + S,
V);
2828 if (
auto A =
Attrs.getFnAttr(
"branch-protection-pauth-lr");
A.isValid()) {
2829 StringRef S =
A.getValueAsString();
2830 if (S !=
"" && S !=
"true" && S !=
"false")
2832 "invalid value for 'branch-protection-pauth-lr' attribute: " + S,
V);
2835 if (
auto A =
Attrs.getFnAttr(
"guarded-control-stack");
A.isValid()) {
2836 StringRef S =
A.getValueAsString();
2837 if (S !=
"" && S !=
"true" && S !=
"false")
2838 CheckFailed(
"invalid value for 'guarded-control-stack' attribute: " + S,
2842 if (
auto A =
Attrs.getFnAttr(
"vector-function-abi-variant");
A.isValid()) {
2843 StringRef S =
A.getValueAsString();
2846 CheckFailed(
"invalid name for a VFABI variant: " + S,
V);
2849 if (
auto A =
Attrs.getFnAttr(
"modular-format");
A.isValid()) {
2850 StringRef S =
A.getValueAsString();
2854 "modular-format attribute requires at least 5 arguments",
V);
2855 unsigned UpperBound = FT->getNumParams() + (FT->isVarArg() ? 1 : 0);
2857 Check(!Args[1].getAsInteger(10, FormatIdx),
2858 "modular-format attribute format string index is not an integer",
V);
2859 Check(FormatIdx > 0,
2860 "modular-format attribute format string index must be greater than 0",
2862 Check(FormatIdx <= UpperBound,
2863 "modular-format attribute format string index is out of bounds",
V);
2864 unsigned FirstArgIdx;
2865 Check(!Args[2].getAsInteger(10, FirstArgIdx),
2866 "modular-format attribute first arg index is not an integer",
V);
2867 Check(FirstArgIdx <= UpperBound,
2868 "modular-format attribute first arg index is out of bounds",
V);
2870 "modular-format attribute modular implementation function name "
2874 "modular-format attribute implementation name cannot be empty",
V);
2877 if (
auto A =
Attrs.getFnAttr(
"target-features");
A.isValid()) {
2878 StringRef S =
A.getValueAsString();
2880 for (
auto FeatureFlag :
split(S,
',')) {
2881 if (FeatureFlag.empty())
2883 "target-features attribute should not contain an empty string");
2885 Check(FeatureFlag[0] ==
'+' || FeatureFlag[0] ==
'-',
2886 "target feature '" + FeatureFlag +
2887 "' must start with a '+' or '-'",
2893 Check(!(
Attrs.hasFnAttr(Attribute::Hot) &&
Attrs.hasFnAttr(Attribute::Cold)),
2894 "Attributes 'hot' and 'cold' are incompatible");
2896 if (
Attrs.hasFnAttr(
"mnop-mcount")) {
2897 auto A =
Attrs.getFnAttr(
"fentry-call");
2898 Check(
A.isValid() &&
A.getValueAsString() ==
"true",
2899 "mnop-mcount only supported with fentry-call");
2902 if (
Attrs.hasFnAttr(
"mrecord-mcount")) {
2903 auto A =
Attrs.getFnAttr(
"fentry-call");
2904 Check(
A.isValid() &&
A.getValueAsString() ==
"true",
2905 "mrecord-mcount only supported with fentry-call");
2909void Verifier::verifyUnknownProfileMetadata(MDNode *MD) {
2911 "'unknown' !prof should have a single additional operand", MD);
2914 "'unknown' !prof should have an additional operand of type "
2917 "the 'unknown' !prof operand should not be an empty string");
2920void Verifier::verifyFunctionMetadata(
2921 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2922 for (
const auto &Pair : MDs) {
2923 if (Pair.first == LLVMContext::MD_prof) {
2924 MDNode *MD = Pair.second;
2926 "!prof annotations should have no less than 2 operands", MD);
2931 verifyUnknownProfileMetadata(MD);
2936 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null",
2939 "expected string with name of the !prof annotation", MD);
2943 "first operand should be 'function_entry_count'", MD);
2946 Check(MD->
getOperand(1) !=
nullptr,
"second operand should not be null",
2949 "expected integer argument to function_entry_count", MD);
2950 }
else if (Pair.first == LLVMContext::MD_kcfi_type) {
2951 MDNode *MD = Pair.second;
2953 "!kcfi_type must have exactly one operand", MD);
2954 Check(MD->
getOperand(0) !=
nullptr,
"!kcfi_type operand must not be null",
2957 "expected a constant operand for !kcfi_type", MD);
2960 "expected a constant integer operand for !kcfi_type", MD);
2962 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2963 }
else if (Pair.first ==
Context.getMDKindID(
"reqd_work_group_size")) {
2964 MDNode *MD = Pair.second;
2966 "reqd_work_group_size must have exactly three operands", MD);
2971 for (
unsigned I = 0;
I != 3; ++
I) {
2973 Check(
C,
"reqd_work_group_size operands must be integer constants", MD);
2977 const APInt &
Value =
C->getValue();
2979 "reqd_work_group_size operands must fit in 64 bits", MD);
2980 if (
Value.getActiveBits() > 64)
2984 Check(Dim == 0 || Product <= std::numeric_limits<uint64_t>::max() / Dim,
2985 "reqd_work_group_size product must fit in 64 bits", MD);
2986 if (Dim != 0 && Product > std::numeric_limits<uint64_t>::max() / Dim)
2994void Verifier::visitConstantExprsRecursively(
const Constant *EntryC) {
2998 if (!ConstantExprVisited.
insert(EntryC).second)
3002 Stack.push_back(EntryC);
3004 while (!
Stack.empty()) {
3009 visitConstantExpr(CE);
3012 visitConstantPtrAuth(CPA);
3017 Check(GV->
getParent() == &M,
"Referencing global in another module!",
3023 for (
const Use &U :
C->operands()) {
3027 if (!ConstantExprVisited.
insert(OpC).second)
3029 Stack.push_back(OpC);
3034void Verifier::visitConstantExpr(
const ConstantExpr *CE) {
3035 if (
CE->getOpcode() == Instruction::BitCast) {
3038 "Invalid bitcast", CE);
3039 Check(
DL.getTypeSizeInBits(
CE->getOperand(0)->getType()) ==
3040 DL.getTypeSizeInBits(
CE->getType()),
3041 "Invalid bitcast", CE);
3042 }
else if (
CE->getOpcode() == Instruction::PtrToAddr)
3043 checkPtrToAddr(
CE->getOperand(0)->getType(),
CE->getType(), *CE);
3044 else if (
CE->getOpcode() == Instruction::GetElementPtr)
3048void Verifier::visitConstantPtrAuth(
const ConstantPtrAuth *CPA) {
3050 "signed ptrauth constant base pointer must have pointer type");
3053 "signed ptrauth constant must have same type as its base pointer");
3056 "signed ptrauth constant key must be i32 constant integer");
3059 "signed ptrauth constant address discriminator must be a pointer");
3062 "signed ptrauth constant discriminator must be i64 constant integer");
3065 "signed ptrauth constant deactivation symbol must be a pointer");
3069 "signed ptrauth constant deactivation symbol must be a global value "
3073bool Verifier::verifyAttributeCount(AttributeList Attrs,
unsigned Params) {
3076 return Attrs.getNumAttrSets() <= Params + 2;
3079void Verifier::verifyInlineAsmCall(
const CallBase &
Call) {
3082 unsigned LabelNo = 0;
3083 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
3093 if (CI.isIndirect) {
3096 "Operand for indirect constraint must have pointer type", &
Call);
3099 "Operand for indirect constraint must have elementtype attribute",
3103 "Elementtype attribute can only be applied for indirect "
3112 Check(LabelNo == CallBr->getNumIndirectDests(),
3113 "Number of label constraints does not match number of callbr dests",
3116 Check(LabelNo == 0,
"Label constraints can only be used with callbr",
3122void Verifier::verifyStatepoint(
const CallBase &
Call) {
3127 "gc.statepoint must read and write all memory to preserve "
3128 "reordering restrictions required by safepoint semantics",
3131 const int64_t NumPatchBytes =
3134 Check(NumPatchBytes >= 0,
3135 "gc.statepoint number of patchable bytes must be "
3140 Check(TargetElemType,
3141 "gc.statepoint callee argument must have elementtype attribute",
Call);
3143 Check(TargetFuncType,
3144 "gc.statepoint callee elementtype must be function type",
Call);
3147 Check(NumCallArgs >= 0,
3148 "gc.statepoint number of arguments to underlying call "
3151 const int NumParams = (int)TargetFuncType->getNumParams();
3152 if (TargetFuncType->isVarArg()) {
3153 Check(NumCallArgs >= NumParams,
3154 "gc.statepoint mismatch in number of vararg call args",
Call);
3157 Check(TargetFuncType->getReturnType()->isVoidTy(),
3158 "gc.statepoint doesn't support wrapping non-void "
3159 "vararg functions yet",
3162 Check(NumCallArgs == NumParams,
3163 "gc.statepoint mismatch in number of call args",
Call);
3168 "unknown flag used in gc.statepoint flags argument",
Call);
3173 for (
int i = 0; i < NumParams; i++) {
3174 Type *ParamType = TargetFuncType->getParamType(i);
3176 Check(ArgType == ParamType,
3177 "gc.statepoint call argument does not match wrapped "
3181 if (TargetFuncType->isVarArg()) {
3182 AttributeSet ArgAttrs =
Attrs.getParamAttrs(5 + i);
3184 "Attribute 'sret' cannot be used for vararg call arguments!",
Call);
3188 const int EndCallArgsInx = 4 + NumCallArgs;
3192 "gc.statepoint number of transition arguments "
3193 "must be constant integer",
3195 const int NumTransitionArgs =
3197 Check(NumTransitionArgs == 0,
3198 "gc.statepoint w/inline transition bundle is deprecated",
Call);
3199 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
3203 "gc.statepoint number of deoptimization arguments "
3204 "must be constant integer",
3207 Check(NumDeoptArgs == 0,
3208 "gc.statepoint w/inline deopt operands is deprecated",
Call);
3210 const int ExpectedNumArgs = 7 + NumCallArgs;
3212 "gc.statepoint too many arguments",
Call);
3219 Check(UserCall,
"illegal use of statepoint token",
Call, U);
3223 "gc.result or gc.relocate are the only value uses "
3224 "of a gc.statepoint",
3227 Check(UserCall->getArgOperand(0) == &
Call,
3228 "gc.result connected to wrong gc.statepoint",
Call, UserCall);
3230 Check(UserCall->getArgOperand(0) == &
Call,
3231 "gc.relocate connected to wrong gc.statepoint",
Call, UserCall);
3245void Verifier::verifyFrameRecoverIndices() {
3246 for (
auto &Counts : FrameEscapeInfo) {
3248 unsigned EscapedObjectCount = Counts.second.first;
3249 unsigned MaxRecoveredIndex = Counts.second.second;
3250 Check(MaxRecoveredIndex <= EscapedObjectCount,
3251 "all indices passed to llvm.localrecover must be less than the "
3252 "number of arguments passed to llvm.localescape in the parent "
3261 UnwindDest =
II->getUnwindDest();
3263 UnwindDest = CSI->getUnwindDest();
3269void Verifier::verifySiblingFuncletUnwinds() {
3270 llvm::TimeTraceScope timeScope(
"Verifier verify sibling funclet unwinds");
3271 SmallPtrSet<Instruction *, 8> Visited;
3272 SmallPtrSet<Instruction *, 8>
Active;
3273 for (
const auto &Pair : SiblingFuncletInfo) {
3275 if (Visited.
count(PredPad))
3281 if (
Active.count(SuccPad)) {
3284 SmallVector<Instruction *, 8> CycleNodes;
3287 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
3288 if (CycleTerminator != CyclePad)
3291 }
while (CyclePad != SuccPad);
3292 Check(
false,
"EH pads can't handle each other's exceptions",
3293 ArrayRef<Instruction *>(CycleNodes));
3296 if (!Visited.
insert(SuccPad).second)
3300 auto TermI = SiblingFuncletInfo.find(PredPad);
3301 if (TermI == SiblingFuncletInfo.end())
3314void Verifier::visitFunction(
const Function &
F) {
3315 visitGlobalValue(
F);
3318 FunctionType *FT =
F.getFunctionType();
3319 unsigned NumArgs =
F.arg_size();
3322 "Function context does not match Module context!", &
F);
3324 Check(!
F.hasCommonLinkage(),
"Functions may not have common linkage", &
F);
3325 Check(FT->getNumParams() == NumArgs,
3326 "# formal arguments must match # of arguments for function type!", &
F,
3328 Check(
F.getReturnType()->isFirstClassType() ||
3329 F.getReturnType()->isVoidTy() ||
F.getReturnType()->isStructTy(),
3330 "Functions cannot return aggregate values!", &
F);
3332 Check(!
F.hasStructRetAttr() ||
F.getReturnType()->isVoidTy(),
3333 "Invalid struct return type!", &
F);
3335 if (MaybeAlign
A =
F.getAlign()) {
3336 Check(
A->value() <= Value::MaximumAlignment,
3337 "huge alignment values are unsupported", &
F);
3340 AttributeList
Attrs =
F.getAttributes();
3342 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
3343 "Attribute after last parameter!", &
F);
3345 bool IsIntrinsic =
F.isIntrinsic();
3348 verifyFunctionAttrs(FT, Attrs, &
F, IsIntrinsic,
false);
3354 "Attribute 'builtin' can only be applied to a callsite.", &
F);
3356 Check(!
Attrs.hasAttrSomewhere(Attribute::ElementType),
3357 "Attribute 'elementtype' can only be applied to a callsite.", &
F);
3359 if (
Attrs.hasFnAttr(Attribute::Naked))
3360 for (
const Argument &Arg :
F.args())
3361 Check(Arg.use_empty(),
"cannot use argument of naked function", &Arg);
3366 switch (
F.getCallingConv()) {
3368 case CallingConv::C:
3370 case CallingConv::X86_INTR: {
3371 Check(
F.arg_empty() ||
Attrs.hasParamAttr(0, Attribute::ByVal),
3372 "Calling convention parameter requires byval", &
F);
3375 case CallingConv::AMDGPU_KERNEL:
3376 case CallingConv::SPIR_KERNEL:
3377 case CallingConv::AMDGPU_CS_Chain:
3378 case CallingConv::AMDGPU_CS_ChainPreserve:
3379 Check(
F.getReturnType()->isVoidTy(),
3380 "Calling convention requires void return type", &
F);
3382 case CallingConv::AMDGPU_VS:
3383 case CallingConv::AMDGPU_HS:
3384 case CallingConv::AMDGPU_GS:
3385 case CallingConv::AMDGPU_PS:
3386 case CallingConv::AMDGPU_CS:
3387 Check(!
F.hasStructRetAttr(),
"Calling convention does not allow sret", &
F);
3388 if (
F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3389 const unsigned StackAS =
DL.getAllocaAddrSpace();
3391 for (
const Argument &Arg :
F.args()) {
3392 Check(!
Attrs.hasParamAttr(i, Attribute::ByVal),
3393 "Calling convention disallows byval", &
F);
3394 Check(!
Attrs.hasParamAttr(i, Attribute::Preallocated),
3395 "Calling convention disallows preallocated", &
F);
3396 Check(!
Attrs.hasParamAttr(i, Attribute::InAlloca),
3397 "Calling convention disallows inalloca", &
F);
3399 if (
Attrs.hasParamAttr(i, Attribute::ByRef)) {
3402 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
3403 "Calling convention disallows stack byref", &
F);
3411 case CallingConv::Fast:
3412 case CallingConv::Cold:
3413 case CallingConv::Intel_OCL_BI:
3414 case CallingConv::PTX_Device:
3416 "Calling convention does not support varargs or "
3417 "perfect forwarding!",
3420 case CallingConv::PTX_Kernel:
3424 Check(!
F.hasFnAttribute(Attr),
3425 "'" + Attr +
"' is not allowed on kernel functions", &
F);
3427 "Calling convention does not support varargs or "
3428 "perfect forwarding!",
3431 case CallingConv::AMDGPU_Gfx_WholeWave:
3432 Check(!
F.arg_empty() &&
F.arg_begin()->getType()->isIntegerTy(1),
3433 "Calling convention requires first argument to be i1", &
F);
3434 Check(!
F.arg_begin()->hasInRegAttr(),
3435 "Calling convention requires first argument to not be inreg", &
F);
3437 "Calling convention does not support varargs or "
3438 "perfect forwarding!",
3445 for (
const Argument &Arg :
F.args()) {
3446 Check(Arg.getType() == FT->getParamType(i),
3447 "Argument value does not match function argument type!", &Arg,
3448 FT->getParamType(i));
3449 Check(Arg.getType()->isFirstClassType(),
3450 "Function arguments must have first-class types!", &Arg);
3452 Check(!Arg.getType()->isMetadataTy(),
3453 "Function takes metadata but isn't an intrinsic", &Arg, &
F);
3454 Check(!Arg.getType()->isTokenLikeTy(),
3455 "Function takes token but isn't an intrinsic", &Arg, &
F);
3456 Check(!Arg.getType()->isX86_AMXTy(),
3457 "Function takes x86_amx but isn't an intrinsic", &Arg, &
F);
3461 if (
Attrs.hasParamAttr(i, Attribute::SwiftError)) {
3462 verifySwiftErrorValue(&Arg);
3468 Check(!
F.getReturnType()->isTokenLikeTy(),
3469 "Function returns a token but isn't an intrinsic", &
F);
3470 Check(!
F.getReturnType()->isX86_AMXTy(),
3471 "Function returns a x86_amx but isn't an intrinsic", &
F);
3476 F.getAllMetadata(MDs);
3477 assert(
F.hasMetadata() != MDs.
empty() &&
"Bit out-of-sync");
3478 verifyFunctionMetadata(MDs);
3484 if (
F.hasPersonalityFn()) {
3487 Check(Per->getParent() ==
F.getParent(),
3488 "Referencing personality function in another module!", &
F,
3489 F.getParent(), Per, Per->getParent());
3493 BlockEHFuncletColors.
clear();
3495 if (
F.isMaterializable()) {
3497 Check(MDs.
empty(),
"unmaterialized function cannot have metadata", &
F,
3499 }
else if (
F.isDeclaration()) {
3500 for (
const auto &
I : MDs) {
3502 CheckDI(
I.first != LLVMContext::MD_dbg ||
3504 "function declaration may only have a unique !dbg attachment",
3506 Check(
I.first != LLVMContext::MD_prof,
3507 "function declaration may not have a !prof attachment", &
F);
3510 visitMDNode(*
I.second, AreDebugLocsAllowed::Yes);
3512 Check(!
F.hasPersonalityFn(),
3513 "Function declaration shouldn't have a personality routine", &
F);
3517 Check(!IsIntrinsic,
"llvm intrinsics cannot be defined!", &
F);
3522 "Entry block to function must not have predecessors!", Entry);
3525 if (
Entry->hasAddressTaken()) {
3527 "blockaddress may not be used with the entry block!", Entry);
3530 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
3531 NumKCFIAttachments = 0;
3533 for (
const auto &
I : MDs) {
3535 auto AllowLocs = AreDebugLocsAllowed::No;
3539 case LLVMContext::MD_dbg: {
3540 ++NumDebugAttachments;
3541 CheckDI(NumDebugAttachments == 1,
3542 "function must have a single !dbg attachment", &
F,
I.second);
3544 "function !dbg attachment must be a subprogram", &
F,
I.second);
3546 "function definition may only have a distinct !dbg attachment",
3550 const Function *&AttachedTo = DISubprogramAttachments[
SP];
3551 CheckDI(!AttachedTo || AttachedTo == &
F,
3552 "DISubprogram attached to more than one function", SP, &
F);
3554 AllowLocs = AreDebugLocsAllowed::Yes;
3557 case LLVMContext::MD_prof:
3558 ++NumProfAttachments;
3559 Check(NumProfAttachments == 1,
3560 "function must have a single !prof attachment", &
F,
I.second);
3562 case LLVMContext::MD_kcfi_type:
3563 ++NumKCFIAttachments;
3564 Check(NumKCFIAttachments == 1,
3565 "function must have a single !kcfi_type attachment", &
F,
3568 case LLVMContext::MD_annotation:
3569 visitAnnotationMetadata(
I.second);
3574 visitMDNode(*
I.second, AllowLocs);
3582 bool isMaterialized =
F.getParent()->isMaterialized();
3583 if (
F.isIntrinsic() && isMaterialized) {
3585 if (
F.hasAddressTaken(&U,
false,
true,
false,
3587 Check(
false,
"Invalid user of intrinsic instruction!", U);
3594 if (IID && (isMaterialized || !
F.materialized_use_empty())) {
3598 raw_string_ostream ErrOS(ErrMsg);
3601 Printable PrintDecl([&
F](raw_ostream &OS) {
F.print(OS); });
3602 Check(IsValid, ErrMsg, PrintDecl);
3609 IID, OverloadTys,
const_cast<Module *
>(
F.getParent()), FT);
3610 Check(ExpectedName ==
F.getName(),
3611 "Intrinsic name not mangled correctly for type arguments! "
3619 if (isMaterialized &&
F.hasFnAttribute(
"oracle-function")) {
3620 Check(
F.hasLocalLinkage(),
"oracle function must have local linkage", &
F);
3621 for (
const Use &U :
F.uses()) {
3623 Check(
II &&
II->getIntrinsicID() == Intrinsic::speculative_load &&
3624 II->isArgOperand(&U) &&
II->getArgOperandNo(&U) == 2,
3625 "oracle function may only be used as the oracle operand of "
3626 "llvm.speculative.load",
3631 auto *
N =
F.getSubprogram();
3632 HasDebugInfo = (
N !=
nullptr);
3640 SmallPtrSet<const MDNode *, 32> Seen;
3652 "DILocation's scope must be a DILocalScope",
N, &
F, &
I,
DL, Parent);
3654 DILocalScope *
Scope =
DL->getInlinedAtScope();
3655 Check(Scope,
"Failed to find DILocalScope",
DL);
3657 if (!Seen.
insert(Scope).second)
3661 if (hasDIScopeCycle(Scope))
3664 DISubprogram *
SP =
Scope->getSubprogram();
3668 if ((Scope != SP) && !Seen.
insert(SP).second)
3672 "!dbg attachment points at wrong subprogram for function",
N, &
F,
3676 for (
auto &
I : BB) {
3677 VisitDebugLoc(
I,
I.getDebugLoc().getAsMDNode());
3679 if (
auto MD =
I.getMetadata(LLVMContext::MD_loop))
3682 if (BrokenDebugInfo)
3689void Verifier::visitBasicBlock(BasicBlock &BB) {
3690 InstsInThisBlock.
clear();
3691 ConvergenceVerifyHelper.
visit(BB);
3699 for (
const PHINode &PN : BB.
phis()) {
3700 Check(PN.getNumIncomingValues() == Preds.size(),
3701 "PHINode should have one entry for each predecessor of its "
3702 "parent basic block!",
3707 Values.reserve(PN.getNumIncomingValues());
3708 for (
unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3710 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3713 for (
unsigned i = 0, e =
Values.size(); i != e; ++i) {
3720 "PHI node has multiple entries for the same basic block with "
3721 "different incoming values!",
3727 "PHI node entries do not match predecessors!", &PN,
3728 Values[i].first, Preds[i]);
3736 Check(
I.getParent() == &BB,
"Instruction has bogus parent pointer!");
3740 CheckDI(!BB.getTrailingDbgRecords(),
"Basic Block has trailing DbgRecords!",
3744void Verifier::visitTerminator(Instruction &
I) {
3746 Check(&
I ==
I.getParent()->getTerminator(),
3747 "Terminator found in the middle of a basic block!",
I.getParent());
3748 visitInstruction(
I);
3751void Verifier::visitCondBrInst(CondBrInst &BI) {
3753 "Branch condition is not 'i1' type!", &BI, BI.
getCondition());
3754 visitTerminator(BI);
3757void Verifier::visitReturnInst(ReturnInst &RI) {
3760 if (
F->getReturnType()->isVoidTy())
3762 "Found return instr that returns non-void in Function of void "
3764 &RI,
F->getReturnType());
3767 "Function return type does not match operand "
3768 "type of return inst!",
3769 &RI,
F->getReturnType());
3773 visitTerminator(RI);
3776void Verifier::visitSwitchInst(SwitchInst &SI) {
3777 Check(
SI.getType()->isVoidTy(),
"Switch must have void result type!", &SI);
3780 Type *SwitchTy =
SI.getCondition()->getType();
3781 SmallPtrSet<ConstantInt*, 32>
Constants;
3782 for (
auto &Case :
SI.cases()) {
3784 "Case value is not a constant integer.", &SI);
3785 Check(Case.getCaseValue()->getType() == SwitchTy,
3786 "Switch constants must all be same type as switch value!", &SI);
3788 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3791 visitTerminator(SI);
3794void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
3796 "Indirectbr operand must have pointer type!", &BI);
3799 "Indirectbr destinations must all have pointer type!", &BI);
3801 visitTerminator(BI);
3810void Verifier::visitCallBrInst(CallBrInst &CBI) {
3813 "callbr: indirect function / invalid signature");
3815 "callbr for intrinsics currently doesn't support operand bundles");
3819 "callbr currently only supports asm-goto and selected intrinsics");
3824 Check(!
IA->canThrow(),
"Unwinding from Callbr is not allowed");
3826 verifyInlineAsmCall(CBI);
3828 visitTerminator(CBI);
3831void Verifier::visitSelectInst(SelectInst &SI) {
3834 "Invalid operands for select instruction!", &SI);
3836 Check(
SI.getTrueValue()->getType() ==
SI.getType(),
3837 "Select values must have same type as select instruction!", &SI);
3838 visitInstruction(SI);
3844void Verifier::visitUserOp1(Instruction &
I) {
3845 Check(
false,
"User-defined operators should not live outside of a pass!", &
I);
3848void Verifier::visitTruncInst(TruncInst &
I) {
3850 Type *SrcTy =
I.getOperand(0)->getType();
3851 Type *DestTy =
I.getType();
3860 "trunc source and destination must both be a vector or neither", &
I);
3861 Check(SrcBitSize > DestBitSize,
"DestTy too big for Trunc", &
I);
3863 visitInstruction(
I);
3866void Verifier::visitZExtInst(ZExtInst &
I) {
3868 Type *SrcTy =
I.getOperand(0)->getType();
3869 Type *DestTy =
I.getType();
3875 "zext source and destination must both be a vector or neither", &
I);
3879 Check(SrcBitSize < DestBitSize,
"Type too small for ZExt", &
I);
3881 visitInstruction(
I);
3884void Verifier::visitSExtInst(SExtInst &
I) {
3886 Type *SrcTy =
I.getOperand(0)->getType();
3887 Type *DestTy =
I.getType();
3896 "sext source and destination must both be a vector or neither", &
I);
3897 Check(SrcBitSize < DestBitSize,
"Type too small for SExt", &
I);
3899 visitInstruction(
I);
3902void Verifier::visitFPTruncInst(FPTruncInst &
I) {
3904 Type *SrcTy =
I.getOperand(0)->getType();
3905 Type *DestTy =
I.getType();
3913 "fptrunc source and destination must both be a vector or neither", &
I);
3914 Check(SrcBitSize > DestBitSize,
"DestTy too big for FPTrunc", &
I);
3916 visitInstruction(
I);
3919void Verifier::visitFPExtInst(FPExtInst &
I) {
3921 Type *SrcTy =
I.getOperand(0)->getType();
3922 Type *DestTy =
I.getType();
3931 "fpext source and destination must both be a vector or neither", &
I);
3932 Check(SrcBitSize < DestBitSize,
"DestTy too small for FPExt", &
I);
3934 visitInstruction(
I);
3937void Verifier::visitUIToFPInst(UIToFPInst &
I) {
3939 Type *SrcTy =
I.getOperand(0)->getType();
3940 Type *DestTy =
I.getType();
3945 Check(SrcVec == DstVec,
3946 "UIToFP source and dest must both be vector or scalar", &
I);
3948 "UIToFP source must be integer or integer vector", &
I);
3952 if (SrcVec && DstVec)
3955 "UIToFP source and dest vector length mismatch", &
I);
3957 visitInstruction(
I);
3960void Verifier::visitSIToFPInst(SIToFPInst &
I) {
3962 Type *SrcTy =
I.getOperand(0)->getType();
3963 Type *DestTy =
I.getType();
3968 Check(SrcVec == DstVec,
3969 "SIToFP source and dest must both be vector or scalar", &
I);
3971 "SIToFP source must be integer or integer vector", &
I);
3975 if (SrcVec && DstVec)
3978 "SIToFP source and dest vector length mismatch", &
I);
3980 visitInstruction(
I);
3983void Verifier::visitFPToUIInst(FPToUIInst &
I) {
3985 Type *SrcTy =
I.getOperand(0)->getType();
3986 Type *DestTy =
I.getType();
3991 Check(SrcVec == DstVec,
3992 "FPToUI source and dest must both be vector or scalar", &
I);
3995 "FPToUI result must be integer or integer vector", &
I);
3997 if (SrcVec && DstVec)
4000 "FPToUI source and dest vector length mismatch", &
I);
4002 visitInstruction(
I);
4005void Verifier::visitFPToSIInst(FPToSIInst &
I) {
4007 Type *SrcTy =
I.getOperand(0)->getType();
4008 Type *DestTy =
I.getType();
4013 Check(SrcVec == DstVec,
4014 "FPToSI source and dest must both be vector or scalar", &
I);
4017 "FPToSI result must be integer or integer vector", &
I);
4019 if (SrcVec && DstVec)
4022 "FPToSI source and dest vector length mismatch", &
I);
4024 visitInstruction(
I);
4027void Verifier::checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &
V) {
4036 Check(VSrc->getElementCount() == VDest->getElementCount(),
4037 "PtrToAddr vector length mismatch",
V);
4040 Type *AddrTy =
DL.getAddressType(SrcTy);
4041 Check(AddrTy == DestTy,
"PtrToAddr result must be address width",
V);
4044void Verifier::visitPtrToAddrInst(PtrToAddrInst &
I) {
4045 checkPtrToAddr(
I.getOperand(0)->getType(),
I.getType(),
I);
4046 visitInstruction(
I);
4049void Verifier::visitPtrToIntInst(PtrToIntInst &
I) {
4051 Type *SrcTy =
I.getOperand(0)->getType();
4052 Type *DestTy =
I.getType();
4063 Check(VSrc->getElementCount() == VDest->getElementCount(),
4064 "PtrToInt Vector length mismatch", &
I);
4067 visitInstruction(
I);
4070void Verifier::visitIntToPtrInst(IntToPtrInst &
I) {
4072 Type *SrcTy =
I.getOperand(0)->getType();
4073 Type *DestTy =
I.getType();
4083 Check(VSrc->getElementCount() == VDest->getElementCount(),
4084 "IntToPtr Vector length mismatch", &
I);
4086 visitInstruction(
I);
4089void Verifier::visitBitCastInst(BitCastInst &
I) {
4092 "Invalid bitcast", &
I);
4093 Check(
DL.getTypeSizeInBits(
I.getSrcTy()) ==
4094 DL.getTypeSizeInBits(
I.getDestTy()),
4095 "Invalid bitcast", &
I);
4096 visitInstruction(
I);
4099void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &
I) {
4100 Type *SrcTy =
I.getOperand(0)->getType();
4101 Type *DestTy =
I.getType();
4108 "AddrSpaceCast must be between different address spaces", &
I);
4110 Check(SrcVTy->getElementCount() ==
4112 "AddrSpaceCast vector pointer number of elements mismatch", &
I);
4113 visitInstruction(
I);
4118void Verifier::visitPHINode(PHINode &PN) {
4125 "PHI nodes not grouped at top of basic block!", &PN, PN.
getParent());
4134 "PHI node operands are not the same type as the result!", &PN);
4139 visitInstruction(PN);
4142void Verifier::visitCallBase(CallBase &
Call) {
4144 "Called function must be a pointer!",
Call);
4148 if (FTy->isVarArg())
4150 "Called function requires more parameters than were provided!",
Call);
4153 "Incorrect number of arguments passed to called function!",
Call);
4156 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
4158 "Call parameter type does not match function signature!",
4164 "Attribute after last parameter!",
Call);
4171 "Intrinsic called with incompatible signature",
Call);
4175 "calling convention does not permit calls",
Call);
4181 auto VerifyTypeAlign = [&](
Type *Ty,
const Twine &Message) {
4184 Align ABIAlign =
DL.getABITypeAlign(Ty);
4185 Check(ABIAlign.
value() <= Value::MaximumAlignment,
4186 "Incorrect alignment of " + Message +
" to called function!",
Call);
4190 VerifyTypeAlign(FTy->getReturnType(),
"return type");
4191 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
4192 Type *Ty = FTy->getParamType(i);
4193 VerifyTypeAlign(Ty,
"argument passed");
4197 if (
Attrs.hasFnAttr(Attribute::Speculatable)) {
4201 "speculatable attribute may not apply to call sites",
Call);
4204 if (
Attrs.hasFnAttr(Attribute::Preallocated)) {
4206 "preallocated as a call site attribute can only be on "
4207 "llvm.call.preallocated.arg");
4210 Check(!
Attrs.hasFnAttr(Attribute::DenormalFPEnv),
4211 "denormal_fpenv attribute may not apply to call sites",
Call);
4222 Check(AI->isUsedWithInAlloca(),
4223 "inalloca argument for call has mismatched alloca", AI,
Call);
4229 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
4233 Check(AI->isSwiftError(),
4234 "swifterror argument for call has mismatched alloca", AI,
Call);
4238 Check(ArgI,
"swifterror argument should come from an alloca or parameter",
4239 SwiftErrorArg,
Call);
4240 Check(ArgI->hasSwiftErrorAttr(),
4241 "swifterror argument for call has mismatched parameter", ArgI,
4245 if (
Attrs.hasParamAttr(i, Attribute::ImmArg)) {
4248 Check(Callee &&
Callee->hasParamAttribute(i, Attribute::ImmArg),
4257 "immarg operand has non-immediate parameter", ArgVal,
Call);
4263 const ConstantRange &CR =
4266 formatv(
"immarg value {} for arg {} out of range {}",
4267 CI->getValue(), i, CR),
4274 formatv(
"immarg value {} for arg {} out of range set",
4284 Check(hasOB != isMustTail,
4285 "preallocated operand either requires a preallocated bundle or "
4286 "the call to be musttail (but not both)",
4291 if (FTy->isVarArg()) {
4293 bool SawNest =
false;
4294 bool SawReturned =
false;
4296 for (
unsigned Idx = 0;
Idx < FTy->getNumParams(); ++
Idx) {
4297 if (
Attrs.hasParamAttr(Idx, Attribute::Nest))
4299 if (
Attrs.hasParamAttr(Idx, Attribute::Returned))
4304 for (
unsigned Idx = FTy->getNumParams(); Idx <
Call.
arg_size(); ++Idx) {
4306 AttributeSet ArgAttrs =
Attrs.getParamAttrs(Idx);
4307 verifyParameterAttrs(ArgAttrs, Ty, &
Call);
4310 Check(!SawNest,
"More than one parameter has attribute nest!",
Call);
4315 Check(!SawReturned,
"More than one parameter has attribute returned!",
4318 "Incompatible argument and return types for 'returned' "
4328 "Attribute 'sret' cannot be used for vararg call arguments!",
4333 "inalloca isn't on the last argument!",
Call);
4339 for (
Type *ParamTy : FTy->params()) {
4340 Check(!ParamTy->isMetadataTy(),
4341 "Function has metadata parameter but isn't an intrinsic",
Call);
4342 Check(!ParamTy->isTokenLikeTy(),
4343 "Function has token parameter but isn't an intrinsic",
Call);
4349 Check(!FTy->getReturnType()->isTokenLikeTy(),
4350 "Return type cannot be token for indirect call!");
4351 Check(!FTy->getReturnType()->isX86_AMXTy(),
4352 "Return type cannot be x86_amx for indirect call!");
4356 visitIntrinsicCall(ID,
Call);
4361 bool FoundDeoptBundle =
false, FoundFuncletBundle =
false,
4362 FoundGCTransitionBundle =
false, FoundCFGuardTargetBundle =
false,
4363 FoundPreallocatedBundle =
false, FoundGCLiveBundle =
false,
4364 FoundPtrauthBundle =
false, FoundKCFIBundle =
false,
4365 FoundAttachedCallBundle =
false;
4370 "Operand bundle operands cannot be labels",
Call);
4373 Check(!FoundDeoptBundle,
"Multiple deopt operand bundles",
Call);
4374 FoundDeoptBundle =
true;
4376 Check(!FoundGCTransitionBundle,
"Multiple gc-transition operand bundles",
4378 FoundGCTransitionBundle =
true;
4380 Check(!FoundFuncletBundle,
"Multiple funclet operand bundles",
Call);
4381 FoundFuncletBundle =
true;
4383 "Expected exactly one funclet bundle operand",
Call);
4385 "Funclet bundle operands should correspond to a FuncletPadInst",
4388 Check(!FoundCFGuardTargetBundle,
"Multiple CFGuardTarget operand bundles",
4390 FoundCFGuardTargetBundle =
true;
4392 "Expected exactly one cfguardtarget bundle operand",
Call);
4394 Check(!FoundPtrauthBundle,
"Multiple ptrauth operand bundles",
Call);
4395 FoundPtrauthBundle =
true;
4397 "Expected exactly two ptrauth bundle operands",
Call);
4399 BU.
Inputs[0]->getType()->isIntegerTy(32),
4400 "Ptrauth bundle key operand must be an i32 constant",
Call);
4402 "Ptrauth bundle discriminator operand must be an i64",
Call);
4404 Check(!FoundKCFIBundle,
"Multiple kcfi operand bundles",
Call);
4405 FoundKCFIBundle =
true;
4406 Check(BU.
Inputs.size() == 1,
"Expected exactly one kcfi bundle operand",
4409 BU.
Inputs[0]->getType()->isIntegerTy(32),
4410 "Kcfi bundle operand must be an i32 constant",
Call);
4412 Check(!FoundPreallocatedBundle,
"Multiple preallocated operand bundles",
4414 FoundPreallocatedBundle =
true;
4416 "Expected exactly one preallocated bundle operand",
Call);
4419 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
4420 "\"preallocated\" argument must be a token from "
4421 "llvm.call.preallocated.setup",
4424 Check(!FoundGCLiveBundle,
"Multiple gc-live operand bundles",
Call);
4425 FoundGCLiveBundle =
true;
4427 Check(!FoundAttachedCallBundle,
4428 "Multiple \"clang.arc.attachedcall\" operand bundles",
Call);
4429 FoundAttachedCallBundle =
true;
4430 verifyAttachedCallBundle(
Call, BU);
4436 "Direct call cannot have a ptrauth bundle",
Call);
4448 "inlinable function call in a function with "
4449 "debug info must have a !dbg location",
4453 verifyInlineAsmCall(
Call);
4457 visitInstruction(
Call);
4460void Verifier::verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs,
4463 Twine(
"inalloca attribute not allowed in ") +
Context);
4465 Twine(
"inreg attribute not allowed in ") +
Context);
4466 Check(!
Attrs.contains(Attribute::SwiftError),
4467 Twine(
"swifterror attribute not allowed in ") +
Context);
4468 Check(!
Attrs.contains(Attribute::Preallocated),
4469 Twine(
"preallocated attribute not allowed in ") +
Context);
4471 Twine(
"byref attribute not allowed in ") +
Context);
4476 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
4477 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
4478 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
4480 AttrBuilder Copy(
C);
4481 for (
auto AK : ABIAttrs) {
4482 Attribute Attr = Attrs.getParamAttrs(
I).getAttribute(AK);
4484 Copy.addAttribute(Attr);
4488 if (Attrs.hasParamAttr(
I, Attribute::Alignment) &&
4489 (Attrs.hasParamAttr(
I, Attribute::ByVal) ||
4490 Attrs.hasParamAttr(
I, Attribute::ByRef)))
4491 Copy.addAlignmentAttr(Attrs.getParamAlignment(
I));
4495void Verifier::verifyMustTailCall(CallInst &CI) {
4499 FunctionType *CallerTy =
F->getFunctionType();
4501 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
4502 "cannot guarantee tail call due to mismatched varargs", &CI);
4503 Check(CallerTy->getReturnType() == CalleeTy->getReturnType(),
4504 "cannot guarantee tail call due to mismatched return types", &CI);
4508 "cannot guarantee tail call due to mismatched calling conv", &CI);
4516 Check(Ret,
"musttail call must precede a ret", &CI);
4519 "musttail call result must be returned", Ret);
4521 AttributeList CallerAttrs =
F->getAttributes();
4526 CI.
getCallingConv() == CallingConv::Tail ?
"tailcc" :
"swifttailcc";
4530 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4532 SmallString<32>
Context{CCName, StringRef(
" musttail caller")};
4533 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4535 for (
unsigned I = 0,
E = CalleeTy->getNumParams();
I !=
E; ++
I) {
4537 SmallString<32>
Context{CCName, StringRef(
" musttail callee")};
4538 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4541 Check(!CallerTy->isVarArg(), Twine(
"cannot guarantee ") + CCName +
4542 " tail call for varargs function");
4548 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
4549 "cannot guarantee tail call due to mismatched parameter counts", &CI);
4550 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4551 Check(CallerTy->getParamType(
I) == CalleeTy->getParamType(
I),
4552 "cannot guarantee tail call due to mismatched parameter types",
4559 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4562 Check(CallerABIAttrs == CalleeABIAttrs,
4563 "cannot guarantee tail call due to mismatched ABI impacting "
4564 "function attributes",
4569void Verifier::visitCallInst(CallInst &CI) {
4573 verifyMustTailCall(CI);
4576void Verifier::visitInvokeInst(InvokeInst &
II) {
4582 II.getUnwindDest()->isEHPad(),
4583 "The unwind destination does not have an exception handling instruction!",
4586 visitTerminator(
II);
4591void Verifier::visitUnaryOperator(UnaryOperator &U) {
4592 Check(
U.getType() ==
U.getOperand(0)->getType(),
4593 "Unary operators must have same type for"
4594 "operands and result!",
4597 switch (
U.getOpcode()) {
4600 case Instruction::FNeg:
4601 Check(
U.getType()->isFPOrFPVectorTy(),
4602 "FNeg operator only works with float types!", &U);
4608 visitInstruction(U);
4614void Verifier::visitBinaryOperator(BinaryOperator &
B) {
4615 Check(
B.getOperand(0)->getType() ==
B.getOperand(1)->getType(),
4616 "Both operands to a binary operator are not of the same type!", &
B);
4618 switch (
B.getOpcode()) {
4621 case Instruction::Add:
4622 case Instruction::Sub:
4623 case Instruction::Mul:
4624 case Instruction::SDiv:
4625 case Instruction::UDiv:
4626 case Instruction::SRem:
4627 case Instruction::URem:
4628 Check(
B.getType()->isIntOrIntVectorTy(),
4629 "Integer arithmetic operators only work with integral types!", &
B);
4630 Check(
B.getType() ==
B.getOperand(0)->getType(),
4631 "Integer arithmetic operators must have same type "
4632 "for operands and result!",
4637 case Instruction::FAdd:
4638 case Instruction::FSub:
4639 case Instruction::FMul:
4640 case Instruction::FDiv:
4641 case Instruction::FRem:
4642 Check(
B.getType()->isFPOrFPVectorTy(),
4643 "Floating-point arithmetic operators only work with "
4644 "floating-point types!",
4646 Check(
B.getType() ==
B.getOperand(0)->getType(),
4647 "Floating-point arithmetic operators must have same type "
4648 "for operands and result!",
4652 case Instruction::And:
4653 case Instruction::Or:
4654 case Instruction::Xor:
4655 Check(
B.getType()->isIntOrIntVectorTy(),
4656 "Logical operators only work with integral types!", &
B);
4657 Check(
B.getType() ==
B.getOperand(0)->getType(),
4658 "Logical operators must have same type for operands and result!", &
B);
4660 case Instruction::Shl:
4661 case Instruction::LShr:
4662 case Instruction::AShr:
4663 Check(
B.getType()->isIntOrIntVectorTy(),
4664 "Shifts only work with integral types!", &
B);
4665 Check(
B.getType() ==
B.getOperand(0)->getType(),
4666 "Shift return type must be same as operands!", &
B);
4672 visitInstruction(
B);
4675void Verifier::visitICmpInst(ICmpInst &IC) {
4679 Check(Op0Ty == Op1Ty,
4680 "Both operands to ICmp instruction are not of the same type!", &IC);
4683 "Invalid operand types for ICmp instruction", &IC);
4687 visitInstruction(IC);
4690void Verifier::visitFCmpInst(FCmpInst &FC) {
4692 Type *Op0Ty =
FC.getOperand(0)->getType();
4693 Type *Op1Ty =
FC.getOperand(1)->getType();
4694 Check(Op0Ty == Op1Ty,
4695 "Both operands to FCmp instruction are not of the same type!", &FC);
4700 Check(
FC.isFPPredicate(),
"Invalid predicate in FCmp instruction!", &FC);
4702 visitInstruction(FC);
4705void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
4707 "Invalid extractelement operands!", &EI);
4708 visitInstruction(EI);
4711void Verifier::visitInsertElementInst(InsertElementInst &IE) {
4714 "Invalid insertelement operands!", &IE);
4715 visitInstruction(IE);
4718void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
4720 SV.getShuffleMask()),
4721 "Invalid shufflevector operands!", &SV);
4722 visitInstruction(SV);
4725void Verifier::visitBitInsertInst(BitInsertInst &BII) {
4728 Check(
false, Reason, &BII);
4731 "bitinsert val type cannot be wider than base type!", &BII);
4732 visitInstruction(BII);
4735void Verifier::visitVAArgInst(VAArgInst &VAA) {
4738 "va_arg with an aggregate type is not supported", &VAA);
4739 visitInstruction(VAA);
4742void Verifier::visitBitExtractInst(BitExtractInst &BEI) {
4745 Check(
false, Reason, &BEI);
4748 "bitextract result type cannot be wider than source type!", &BEI);
4749 visitInstruction(BEI);
4752void Verifier::checkGEPOperator(
const GEPOperator &
GEP) {
4753 Type *TargetTy =
GEP.getPointerOperandType()->getScalarType();
4756 "GEP base pointer is not a vector or a vector of pointers", &
GEP);
4757 Check(
GEP.getSourceElementType()->isSized(),
"GEP into unsized type!", &
GEP);
4759 Type *SrcTy =
GEP.getSourceElementType();
4761 SrcTy = ATy->getElementType();
4763 "getelementptr cannot target structure that contains scalable vector "
4767 SmallVector<Value *, 16> Idxs(
GEP.indices());
4769 all_of(Idxs, [](
Value *
V) {
return V->getType()->isIntOrIntVectorTy(); }),
4770 "GEP indexes must be integers", &
GEP);
4773 Check(ElTy,
"Invalid indices for GEP pointer type!", &
GEP);
4777 Check(PtrTy &&
GEP.getResultElementType() == ElTy,
4778 "GEP is not of right type for indices!", &
GEP, ElTy);
4782 ElementCount GEPWidth = GEPVTy->getElementCount();
4783 if (
GEP.getPointerOperandType()->isVectorTy())
4787 "Vector GEP result width doesn't match operand's", &
GEP);
4788 for (
Value *Idx : Idxs) {
4789 Type *IndexTy =
Idx->getType();
4791 ElementCount IndexWidth = IndexVTy->getElementCount();
4792 Check(IndexWidth == GEPWidth,
"Invalid GEP index vector width", &
GEP);
4795 "All GEP indices should be of integer type");
4802 GTI != GTE; ++GTI) {
4803 if (GTI.isVector()) {
4804 Type *ElemTy = GTI.getIndexedType();
4805 Check(
DL.typeSizeEqualsStoreSize(ElemTy),
4806 "GEP into vector with non-byte-addressable element type", &
GEP);
4810 Check(
GEP.getPointerAddressSpace() == PtrTy->getAddressSpace(),
4811 "GEP address space doesn't match type", &
GEP);
4814void Verifier::visitGetElementPtrInst(GetElementPtrInst &
GEP) {
4816 GEP.getModule()->getModuleFlag(
"require-logical-pointer")))
4817 Check(!MD->getZExtValue(),
4818 "Non-logical getelementptr disallowed for this module.");
4821 visitInstruction(
GEP);
4825 return A.getUpper() ==
B.getLower() ||
A.getLower() ==
B.getUpper();
4830void Verifier::verifyRangeLikeMetadata(
const Value &
I,
const MDNode *
Range,
4831 Type *Ty, RangeLikeMetadataKind Kind) {
4832 unsigned NumOperands =
Range->getNumOperands();
4833 Check(NumOperands % 2 == 0,
"Unfinished range!",
Range);
4834 unsigned NumRanges = NumOperands / 2;
4835 Check(NumRanges >= 1,
"It should have at least one range!",
Range);
4837 ConstantRange LastRange(1,
true);
4838 for (
unsigned i = 0; i < NumRanges; ++i) {
4841 Check(
Low,
"The lower limit must be an integer!",
Low);
4846 Check(
High->getType() ==
Low->getType(),
"Range pair types must match!",
4849 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4851 "noalias.addrspace type must be i32!", &
I);
4854 "Range types must match instruction type!", &
I);
4857 APInt HighV =
High->getValue();
4858 APInt LowV =
Low->getValue();
4863 "The upper and lower limits cannot be the same value", &
I);
4865 ConstantRange CurRange(LowV, HighV);
4866 Check(!CurRange.isEmptySet() &&
4867 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
4868 !CurRange.isFullSet()),
4869 "Range must not be empty!",
Range);
4871 Check(CurRange.intersectWith(LastRange).isEmptySet(),
4872 "Intervals are overlapping",
Range);
4873 Check(LowV.
sgt(LastRange.getLower()),
"Intervals are not in order",
4878 LastRange = ConstantRange(LowV, HighV);
4880 if (NumRanges > 2) {
4885 ConstantRange FirstRange(FirstLow, FirstHigh);
4886 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
4887 "Intervals are overlapping",
Range);
4893void Verifier::visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty) {
4895 "precondition violation");
4896 verifyRangeLikeMetadata(
I,
Range, Ty, RangeLikeMetadataKind::Range);
4899void Verifier::visitNoFPClassMetadata(Instruction &
I, MDNode *NoFPClass,
4901 Check(AttributeFuncs::isNoFPClassCompatibleType(Ty),
4902 "nofpclass only applies to floating-point typed loads",
I);
4905 "nofpclass must have exactly one entry", NoFPClass);
4906 ConstantInt *MaskVal =
4909 "nofpclass entry must be a constant i32", NoFPClass);
4911 Check(Val != 0,
"'nofpclass' must have at least one test bit set", NoFPClass,
4915 "Invalid value for 'nofpclass' test mask", NoFPClass,
I);
4918void Verifier::visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
4921 "precondition violation");
4922 verifyRangeLikeMetadata(
I,
Range, Ty,
4923 RangeLikeMetadataKind::NoaliasAddrspace);
4926void Verifier::checkAtomicMemAccessSize(
Type *Ty,
const Instruction *
I) {
4927 unsigned Size =
DL.getTypeSizeInBits(Ty).getFixedValue();
4928 Check(
Size >= 8,
"atomic memory access' size must be byte-sized", Ty,
I);
4930 "atomic memory access' operand must have a power-of-two size", Ty,
I);
4933void Verifier::visitLoadInst(LoadInst &LI) {
4935 Check(PTy,
"Load operand must be a pointer.", &LI);
4938 Check(
A->value() <= Value::MaximumAlignment,
4939 "huge alignment values are unsupported", &LI);
4941 Check(ElTy->
isSized(),
"loading unsized types is not allowed", &LI);
4944 LI.
getOrdering() != AtomicOrdering::AcquireRelease,
4945 "Load cannot have Release ordering", &LI);
4949 "atomic elementwise load cannot be sequentially consistent.", &LI);
4952 "atomic elementwise load operand must have fixed vector type!", &LI,
4955 checkAtomicMemAccessSize(VecTy->getElementType(), &LI);
4961 "atomic load operand must have integer, byte, pointer, floating "
4962 "point, or vector type!",
4965 checkAtomicMemAccessSize(ElTy, &LI);
4969 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4972 visitInstruction(LI);
4975void Verifier::visitStoreInst(StoreInst &SI) {
4977 Check(PTy,
"Store operand must be a pointer.", &SI);
4978 Type *ElTy =
SI.getOperand(0)->getType();
4979 if (MaybeAlign
A =
SI.getAlign()) {
4980 Check(
A->value() <= Value::MaximumAlignment,
4981 "huge alignment values are unsupported", &SI);
4983 Check(ElTy->
isSized(),
"storing unsized types is not allowed", &SI);
4984 if (
SI.isAtomic()) {
4985 Check(
SI.getOrdering() != AtomicOrdering::Acquire &&
4986 SI.getOrdering() != AtomicOrdering::AcquireRelease,
4987 "Store cannot have Acquire ordering", &SI);
4989 if (
SI.isElementwise()) {
4990 Check(
SI.getOrdering() != AtomicOrdering::SequentiallyConsistent,
4991 "atomic elementwise store cannot be sequentially consistent.", &SI);
4995 "atomic elementwise store operand must have fixed vector type!",
4998 checkAtomicMemAccessSize(VecTy->getElementType(), &SI);
5004 "atomic store operand must have integer, byte, pointer, floating "
5005 "point, or vector type!",
5007 checkAtomicMemAccessSize(ElTy, &SI);
5009 Check(!
SI.isElementwise(),
"non-atomic store cannot be elementwise", &SI);
5011 "Non-atomic store cannot have SynchronizationScope specified", &SI);
5013 visitInstruction(SI);
5017void Verifier::verifySwiftErrorCall(CallBase &
Call,
5018 const Value *SwiftErrorVal) {
5020 if (
I.value() == SwiftErrorVal) {
5022 "swifterror value when used in a callsite should be marked "
5023 "with swifterror attribute",
5024 SwiftErrorVal,
Call);
5029void Verifier::verifySwiftErrorValue(
const Value *SwiftErrorVal) {
5032 for (
const User *U : SwiftErrorVal->
users()) {
5035 "swifterror value can only be loaded and stored from, or "
5036 "as a swifterror argument!",
5040 Check(StoreI->getOperand(1) == SwiftErrorVal,
5041 "swifterror value should be the second operand when used "
5045 verifySwiftErrorCall(*
const_cast<CallBase *
>(
Call), SwiftErrorVal);
5049void Verifier::visitAllocaInst(AllocaInst &AI) {
5052 Check(!MD->getZExtValue(),
5053 "Non-logical alloca disallowed for this module.");
5056 Check(Ty->
isSized(),
"Cannot allocate unsized type", &AI);
5060 "Alloca has illegal target extension type", &AI);
5062 "Alloca array size must have integer type", &AI);
5064 Check(
A->value() <= Value::MaximumAlignment,
5065 "huge alignment values are unsupported", &AI);
5071 "swifterror alloca must not be array allocation", &AI);
5072 verifySwiftErrorValue(&AI);
5075 visitInstruction(AI);
5081void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
5084 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
5085 checkAtomicMemAccessSize(ElTy, &CXI);
5086 visitInstruction(CXI);
5089void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
5091 "atomicrmw instructions cannot be unordered.", &RMWI);
5097 "atomicrmw elementwise cannot be sequentially consistent.", &RMWI);
5099 Check(VecTy,
"atomicrmw elementwise operand must have fixed vector type!",
5102 checkAtomicMemAccessSize(VecTy->getElementType(), &RMWI);
5109 " operand must be an integer type, a floating-point type, a "
5110 "pointer type, or a fixed vector of any of these types!",
5115 " operand must have floating-point or fixed vector of "
5122 " operand must have integer or fixed vector of integer type!",
5125 checkAtomicMemAccessSize(ElTy, &RMWI);
5127 "Invalid binary operation!", &RMWI);
5128 visitInstruction(RMWI);
5131void Verifier::visitFenceInst(FenceInst &FI) {
5133 Check(Ordering == AtomicOrdering::Acquire ||
5134 Ordering == AtomicOrdering::Release ||
5135 Ordering == AtomicOrdering::AcquireRelease ||
5136 Ordering == AtomicOrdering::SequentiallyConsistent,
5137 "fence instructions may only have acquire, release, acq_rel, or "
5138 "seq_cst ordering.",
5140 visitInstruction(FI);
5143void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
5146 "Invalid ExtractValueInst operands!", &EVI);
5148 visitInstruction(EVI);
5151void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
5155 "Invalid InsertValueInst operands!", &IVI);
5157 visitInstruction(IVI);
5162 return FPI->getParentPad();
5167void Verifier::visitEHPadPredecessors(Instruction &
I) {
5173 Check(BB != &
F->getEntryBlock(),
"EH pad cannot be in entry block.", &
I);
5181 Check(
II &&
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
5182 "Block containing LandingPadInst must be jumped to "
5183 "only by the unwind edge of an invoke.",
5191 "Block containg CatchPadInst must be jumped to "
5192 "only by its catchswitch.",
5194 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
5195 "Catchswitch cannot unwind to one of its catchpads",
5196 CPI->getCatchSwitch(), CPI);
5208 Check(
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
5209 "EH pad must be jumped to via an unwind edge", ToPad,
II);
5212 if (CalledFn && CalledFn->isIntrinsic() &&
II->doesNotThrow() &&
5216 FromPad = Bundle->Inputs[0];
5220 FromPad = CRI->getOperand(0);
5221 Check(FromPad != ToPadParent,
"A cleanupret must exit its cleanup", CRI);
5225 Check(
false,
"EH pad must be jumped to via an unwind edge", ToPad, TI);
5229 SmallPtrSet<Value *, 8> Seen;
5231 Check(FromPad != ToPad,
5232 "EH pad cannot handle exceptions raised within it", FromPad, TI);
5233 if (FromPad == ToPadParent) {
5238 "A single unwind edge may only enter one EH pad", TI);
5239 Check(Seen.
insert(FromPad).second,
"EH pad jumps through a cycle of pads",
5245 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
5250void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
5254 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
5256 visitEHPadPredecessors(LPI);
5258 if (!LandingPadResultTy)
5259 LandingPadResultTy = LPI.
getType();
5262 "The landingpad instruction should have a consistent result type "
5263 "inside a function.",
5267 Check(
F->hasPersonalityFn(),
5268 "LandingPadInst needs to be in a function with a personality.", &LPI);
5273 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
5279 "Catch operand does not have pointer type!", &LPI);
5281 Check(LPI.
isFilter(i),
"Clause is neither catch nor filter!", &LPI);
5283 "Filter operand is not an array of constants!", &LPI);
5287 visitInstruction(LPI);
5290void Verifier::visitResumeInst(ResumeInst &RI) {
5292 "ResumeInst needs to be in a function with a personality.", &RI);
5294 if (!LandingPadResultTy)
5298 "The resume instruction should have a consistent result type "
5299 "inside a function.",
5302 visitTerminator(RI);
5305void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
5309 Check(
F->hasPersonalityFn(),
5310 "CatchPadInst needs to be in a function with a personality.", &CPI);
5313 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
5319 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
5324 return isa<Constant>(V) || isa<AllocaInst>(V);
5326 "Argument operand must be alloca or constant.", &CPI);
5328 visitEHPadPredecessors(CPI);
5329 visitFuncletPadInst(CPI);
5332void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
5334 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
5337 visitTerminator(CatchReturn);
5340void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
5344 Check(
F->hasPersonalityFn(),
5345 "CleanupPadInst needs to be in a function with a personality.", &CPI);
5350 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
5354 "CleanupPadInst has an invalid parent.", &CPI);
5356 visitEHPadPredecessors(CPI);
5357 visitFuncletPadInst(CPI);
5360void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
5361 User *FirstUser =
nullptr;
5362 Value *FirstUnwindPad =
nullptr;
5364 SmallPtrSet<FuncletPadInst *, 8> Seen;
5366 while (!Worklist.empty()) {
5367 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
5369 "FuncletPadInst must not be nested within itself", CurrentPad);
5370 Value *UnresolvedAncestorPad =
nullptr;
5371 for (User *U : CurrentPad->
users()) {
5374 UnwindDest = CRI->getUnwindDest();
5380 if (CSI->unwindsToCaller())
5382 UnwindDest = CSI->getUnwindDest();
5384 UnwindDest =
II->getUnwindDest();
5394 Worklist.push_back(CPI);
5409 if (UnwindParent == CurrentPad)
5415 Value *ExitedPad = CurrentPad;
5418 if (ExitedPad == &FPI) {
5423 UnresolvedAncestorPad = &FPI;
5427 if (ExitedParent == UnwindParent) {
5431 UnresolvedAncestorPad = ExitedParent;
5434 ExitedPad = ExitedParent;
5440 UnresolvedAncestorPad = &FPI;
5447 Check(UnwindPad == FirstUnwindPad,
5448 "Unwind edges out of a funclet "
5449 "pad must have the same unwind "
5451 &FPI, U, FirstUser);
5454 FirstUnwindPad = UnwindPad;
5463 if (CurrentPad != &FPI)
5466 if (UnresolvedAncestorPad) {
5467 if (CurrentPad == UnresolvedAncestorPad) {
5471 assert(CurrentPad == &FPI);
5479 Value *ResolvedPad = CurrentPad;
5480 while (!Worklist.empty()) {
5481 Value *UnclePad = Worklist.back();
5485 while (ResolvedPad != AncestorPad) {
5487 if (ResolvedParent == UnresolvedAncestorPad) {
5490 ResolvedPad = ResolvedParent;
5494 if (ResolvedPad != AncestorPad)
5497 Worklist.pop_back();
5502 if (FirstUnwindPad) {
5504 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
5505 Value *SwitchUnwindPad;
5506 if (SwitchUnwindDest)
5510 Check(SwitchUnwindPad == FirstUnwindPad,
5511 "Unwind edges out of a catch must have the same unwind dest as "
5512 "the parent catchswitch",
5513 &FPI, FirstUser, CatchSwitch);
5517 visitInstruction(FPI);
5520void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
5524 Check(
F->hasPersonalityFn(),
5525 "CatchSwitchInst needs to be in a function with a personality.",
5531 "CatchSwitchInst not the first non-PHI instruction in the block.",
5536 "CatchSwitchInst has an invalid parent.", ParentPad);
5541 "CatchSwitchInst must unwind to an EH block which is not a "
5547 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
5551 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
5553 for (BasicBlock *Handler : CatchSwitch.
handlers()) {
5555 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
5558 visitEHPadPredecessors(CatchSwitch);
5559 visitTerminator(CatchSwitch);
5562void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
5564 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
5570 "CleanupReturnInst must unwind to an EH block which is not a "
5575 visitTerminator(CRI);
5578void Verifier::verifyDominatesUse(Instruction &
I,
unsigned i) {
5584 if (
II->getNormalDest() ==
II->getUnwindDest())
5598 const Use &
U =
I.getOperandUse(i);
5599 Check(DT.dominates(
Op, U),
"Instruction does not dominate all uses!",
Op, &
I);
5602void Verifier::visitDereferenceableMetadata(Instruction&
I, MDNode* MD) {
5603 Check(
I.getType()->isPointerTy(),
5604 "dereferenceable, dereferenceable_or_null "
5605 "apply only to pointer types",
5608 "dereferenceable, dereferenceable_or_null apply only to load"
5609 " and inttoptr instructions, use attributes for calls or invokes",
5612 "dereferenceable, dereferenceable_or_null "
5613 "take one operand!",
5618 "dereferenceable_or_null metadata value must be an i64!",
5622void Verifier::visitNoFreeObjMetadata(Instruction &
I, MDNode *MD) {
5623 Check(
I.getType()->isPointerTy(),
"nofreeobj applies only to pointer types",
5626 "nofreeobj applies only to inttoptr instruction", &
I);
5630void Verifier::visitProfMetadata(Instruction &
I, MDNode *MD) {
5631 auto GetBranchingTerminatorNumOperands = [&]() {
5632 unsigned ExpectedNumOperands = 0;
5636 ExpectedNumOperands =
SI->getNumSuccessors();
5638 ExpectedNumOperands = 1;
5640 ExpectedNumOperands = IBI->getNumDestinations();
5642 ExpectedNumOperands = 2;
5645 return ExpectedNumOperands;
5648 "!prof annotations should have at least 1 operand", MD);
5650 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null", MD);
5652 "expected string with name of the !prof annotation", MD);
5658 "'unknown' !prof should only appear on instructions on which "
5659 "'branch_weights' would",
5661 verifyUnknownProfileMetadata(MD);
5666 "!prof annotations should have no less than 2 operands", MD);
5672 Check(NumBranchWeights == 1 || NumBranchWeights == 2,
5673 "Wrong number of InvokeInst branch_weights operands", MD);
5675 const unsigned ExpectedNumOperands = GetBranchingTerminatorNumOperands();
5676 if (ExpectedNumOperands == 0)
5677 CheckFailed(
"!prof branch_weights are not allowed for this instruction",
5680 Check(NumBranchWeights == ExpectedNumOperands,
"Wrong number of operands",
5686 Check(MDO,
"second operand should not be null", MD);
5688 "!prof brunch_weights operand is not a const int");
5693 Check(KindInt,
"VP !prof missing kind argument", MD);
5696 Check(Kind >= InstrProfValueKind::IPVK_First &&
5697 Kind <= InstrProfValueKind::IPVK_Last,
5698 "Invalid VP !prof kind", MD);
5700 "VP !prof should have an even number "
5701 "of arguments after 'VP'",
5703 if (Kind == InstrProfValueKind::IPVK_IndirectCallTarget ||
5704 Kind == InstrProfValueKind::IPVK_MemOPSize)
5706 "VP !prof indirect call or memop size expected to be applied to "
5707 "CallBase instructions only",
5710 DenseSet<uint64_t> ProfileValues;
5712 ConstantInt *ProfileValue =
5714 Check(ProfileValue,
"VP !prof value operand is not a const int", MD);
5716 auto [ValueIt,
Inserted] = ProfileValues.
insert(ProfileValueInt);
5717 Check(Inserted,
"VP !prof should not have duplicate profile values", MD);
5720 CheckFailed(
"expected either branch_weights or VP profile name", MD);
5724void Verifier::visitDIAssignIDMetadata(Instruction &
I, MDNode *MD) {
5725 assert(
I.hasMetadata(LLVMContext::MD_DIAssignID));
5730 bool ExpectedInstTy =
5732 CheckDI(ExpectedInstTy,
"!DIAssignID attached to unexpected instruction kind",
5735 CheckDI(DVR->getFunction() ==
I.getFunction(),
5736 "DVRAssign not in same function as inst", DVR, &
I);
5739void Verifier::visitMMRAMetadata(Instruction &
I, MDNode *MD) {
5741 "!mmra metadata attached to unexpected instruction kind",
I, MD);
5752 for (
const MDOperand &MDOp : MD->
operands())
5754 "!mmra metadata tuple operand is not an MMRA tag",
I, MDOp.get());
5757void Verifier::visitCallStackMetadata(MDNode *MD) {
5761 "call stack metadata should have at least 1 operand", MD);
5765 "call stack metadata operand should be constant integer",
Op);
5768void Verifier::visitMemProfMetadata(Instruction &
I, MDNode *MD) {
5771 Check(
I.hasMetadata(LLVMContext::MD_callsite),
5772 "!memprof metadata requires !callsite metadata", &
I, MD);
5774 "!memprof annotations should have at least 1 metadata operand "
5779 for (
auto &MIBOp : MD->
operands()) {
5784 Check(MIB->getNumOperands() >= 2,
5785 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
5788 Check(MIB->getOperand(0) !=
nullptr,
5789 "!memprof MemInfoBlock first operand should not be null", MIB);
5791 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
5793 visitCallStackMetadata(StackMD);
5797 "!memprof MemInfoBlock second operand should be an MDString", MIB);
5800 for (
unsigned I = 2;
I < MIB->getNumOperands(); ++
I) {
5802 Check(OpNode,
"Not all !memprof MemInfoBlock operands 2 to N are MDNode",
5804 Check(OpNode->getNumOperands() == 2,
5805 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with 2 "
5810 [](
const MDOperand &
Op) {
5811 return mdconst::hasa<ConstantInt>(Op);
5813 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with "
5814 "ConstantInt operands",
5820void Verifier::visitCallsiteMetadata(Instruction &
I, MDNode *MD) {
5824 visitCallStackMetadata(MD);
5827void Verifier::visitCalleeTypeMetadata(Instruction &
I, MDNode *MD) {
5832 "The callee_type metadata must be a list of callgraph metadata nodes",
5835 Check(CallgraphMD->getNumOperands() == 1,
5836 "Well-formed callgraph metadata must contain exactly one "
5840 "The operand of callgraph metadata for functions must be an MDString",
5845void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
5848 "annotation must have at least one operand");
5850 bool TupleOfStrings =
5856 "operands must be a string or a tuple of strings");
5860void Verifier::visitAliasScopeMetadata(
const MDNode *MD) {
5865 "first scope operand must be self-referential or string", MD);
5868 "third scope operand must be string (if used)", MD);
5871 Check(
Domain !=
nullptr,
"second scope operand must be MDNode", MD);
5873 unsigned NumDomainOps =
Domain->getNumOperands();
5874 Check(NumDomainOps >= 2 && NumDomainOps <= 3,
5875 "domain must have two or three operands",
Domain);
5878 "first domain operand must be self-referential or string",
Domain);
5879 const auto *Disjoint =
5881 Check(Disjoint && Disjoint->getBitWidth() == 1,
5882 "second domain operand must be an i1 constant",
Domain);
5883 if (NumDomainOps == 3)
5885 "third domain operand must be string (if used)",
Domain);
5888void Verifier::visitAliasScopeListMetadata(
const MDNode *MD) {
5891 Check(OpMD !=
nullptr,
"scope list must consist of MDNodes", MD);
5892 visitAliasScopeMetadata(OpMD);
5896void Verifier::visitAccessGroupMetadata(
const MDNode *MD) {
5897 auto IsValidAccessScope = [](
const MDNode *MD) {
5912 Check(OpMD !=
nullptr,
"Access scope list must consist of MDNodes", MD);
5913 Check(IsValidAccessScope(OpMD),
5914 "Access scope list contains invalid access scope", MD);
5918void Verifier::visitCapturesMetadata(Instruction &
I,
const MDNode *Captures) {
5919 static const char *ValidArgs[] = {
"address_is_null",
"address",
5920 "read_provenance",
"provenance"};
5923 Check(SI,
"!captures metadata can only be applied to store instructions", &
I);
5924 Check(
SI->getValueOperand()->getType()->isPointerTy(),
5925 "!captures metadata can only be applied to store with value operand of "
5933 Check(Str,
"!captures metadata must be a list of strings", &
I);
5935 "invalid entry in !captures metadata", &
I, Str);
5939void Verifier::visitAllocTokenMetadata(Instruction &
I, MDNode *MD) {
5942 "!alloc_token must have 2 or 3 operands", MD);
5945 "expected integer constant", MD);
5948 "expected function name string", MD);
5951void Verifier::visitInlineHistoryMetadata(Instruction &
I, MDNode *MD) {
5960 ->stripPointerCastsAndAliases()),
5961 "!inline_history operands must be functions or null", MD);
5965void Verifier::visitMemCacheHintMetadata(Instruction &
I, MDNode *MD) {
5966 Check(
I.mayReadOrWriteMemory(),
5967 "!mem.cache_hint is only valid on memory operations", &
I);
5970 "!mem.cache_hint must have even number of operands "
5971 "(operand_no, hint_node pairs)",
5977 "!mem.cache_hint is not supported on non-intrinsic calls", &
I);
5979 unsigned NumOperands = CB ? CB->arg_size() :
I.getNumOperands();
5981 SmallDenseSet<unsigned, 4> SeenOperandNos;
5982 std::optional<uint64_t> LastOperandNo;
5988 "!mem.cache_hint must alternate between i32 operand numbers and "
5989 "metadata hint nodes",
5992 Check(OpNoCI->getValue().isNonNegative(),
5993 "!mem.cache_hint operand number must be non-negative", MD);
5995 uint64_t OperandNo = OpNoCI->getZExtValue();
5996 Check(OperandNo < NumOperands,
5997 "!mem.cache_hint operand number is out of range", &
I);
6000 CB ? CB->getArgOperand(OperandNo) :
I.getOperand(OperandNo);
6002 "!mem.cache_hint operand number must refer to a pointer operand", &
I);
6005 Check(Inserted,
"!mem.cache_hint contains duplicate operand number", MD);
6007 Check(!Inserted || !LastOperandNo || OperandNo > *LastOperandNo,
6008 "!mem.cache_hint operand numbers must be in increasing order", MD);
6009 LastOperandNo = OperandNo;
6013 "!mem.cache_hint must alternate between i32 operand numbers and "
6014 "metadata hint nodes",
6018 "!mem.cache_hint hint node must have even number of operands "
6019 "(key-value pairs)",
6022 StringSet<> SeenKeys;
6023 for (
unsigned K = 0;
K + 1 <
Node->getNumOperands();
K += 2) {
6025 Check(
Key,
"!mem.cache_hint key must be a string", Node);
6027 StringRef KeyStr =
Key->getString();
6029 "!mem.cache_hint hint node contains duplicate key", Node);
6034 "!mem.cache_hint value must be a string or integer", Node);
6041void Verifier::visitInstruction(Instruction &
I) {
6043 Check(BB,
"Instruction not embedded in basic block!", &
I);
6046 for (User *U :
I.users()) {
6047 Check(U != (User *)&
I || !DT.isReachableFromEntry(BB),
6048 "Only PHI nodes may reference their own value!", &
I);
6053 Check(!
I.getType()->isVoidTy() || !
I.hasName(),
6054 "Instruction has a name, but provides a void value!", &
I);
6058 Check(
I.getType()->isVoidTy() ||
I.getType()->isFirstClassType(),
6059 "Instruction returns a non-scalar type!", &
I);
6064 "Invalid use of metadata!", &
I);
6069 for (Use &U :
I.uses()) {
6072 "Instruction referencing"
6073 " instruction not embedded in a basic block!",
6076 CheckFailed(
"Use of instruction is not an instruction!", U);
6085 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i) {
6086 Check(
I.getOperand(i) !=
nullptr,
"Instruction has null operand!", &
I);
6090 if (!
I.getOperand(i)->getType()->isFirstClassType()) {
6091 Check(
false,
"Instruction operands must be first-class values!", &
I);
6097 auto IsAttachedCallOperand = [](
Function *
F,
const CallBase *CBI,
6099 return CBI && CBI->isOperandBundleOfType(
6107 Check((!
F->isIntrinsic() ||
6108 (CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i)) ||
6109 IsAttachedCallOperand(
F, CBI, i)),
6110 "Cannot take the address of an intrinsic!", &
I);
6112 F->getIntrinsicID() == Intrinsic::donothing ||
6113 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
6114 F->getIntrinsicID() == Intrinsic::seh_try_end ||
6115 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
6116 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
6117 F->getIntrinsicID() == Intrinsic::coro_resume ||
6118 F->getIntrinsicID() == Intrinsic::coro_destroy ||
6119 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
6120 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
6121 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
6122 F->getIntrinsicID() ==
6123 Intrinsic::experimental_patchpoint_void ||
6124 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
6125 F->getIntrinsicID() == Intrinsic::fake_use ||
6126 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
6127 F->getIntrinsicID() == Intrinsic::wasm_throw ||
6128 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
6129 F->getIntrinsicID() == Intrinsic::bpf_unwind_exit ||
6130 IsAttachedCallOperand(
F, CBI, i),
6131 "Cannot invoke an intrinsic other than donothing, patchpoint, "
6132 "statepoint, coro_resume, coro_destroy, clang.arc.attachedcall, "
6133 "wasm.(re)throw or bpf.unwind.exit",
6135 Check(
F->getParent() == &M,
"Referencing function in another module!", &
I,
6136 &M,
F,
F->getParent());
6139 "Referring to a basic block in another function!", &
I);
6142 "Referring to an argument in another function!", &
I);
6144 Check(GV->
getParent() == &M,
"Referencing global in another module!", &
I,
6148 "Referring to an instruction in another function!", &
I);
6149 verifyDominatesUse(
I, i);
6151 Check(CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i),
6152 "Cannot take the address of an inline asm!", &
I);
6154 visitConstantExprsRecursively(
C);
6158 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_fpmath)) {
6160 "fpmath requires a floating point result!", &
I);
6162 if (ConstantFP *CFP0 =
6164 const APFloat &Accuracy = CFP0->getValueAPF();
6166 "fpmath accuracy must have float type", &
I);
6168 "fpmath accuracy not a positive number!", &
I);
6170 Check(
false,
"invalid fpmath accuracy!", &
I);
6174 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_range)) {
6176 "Ranges are only for loads, calls and invokes!", &
I);
6177 visitRangeMetadata(
I,
Range,
I.getType());
6180 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofpclass)) {
6182 visitNoFPClassMetadata(
I, MD,
I.getType());
6185 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_noalias_addrspace)) {
6188 "noalias.addrspace are only for memory operations!", &
I);
6189 visitNoaliasAddrspaceMetadata(
I,
Range,
I.getType());
6192 if (
I.hasMetadata(LLVMContext::MD_invariant_group)) {
6194 "invariant.group metadata is only for loads and stores", &
I);
6197 if (
I.hasMetadata(LLVMContext::MD_invariant_load)) {
6200 "invariant.load metadata is only for loads and readonly "
6205 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nonnull)) {
6206 Check(
I.getType()->isPointerTy(),
"nonnull applies only to pointer types",
6209 "nonnull applies only to load instructions, use attributes"
6210 " for calls or invokes",
6215 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noundef)) {
6220 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable))
6221 visitDereferenceableMetadata(
I, MD);
6223 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
6224 visitDereferenceableMetadata(
I, MD);
6226 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofreeobj))
6227 visitNoFreeObjMetadata(
I, MD);
6229 if (MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa))
6232 if (MDNode *TBAAStruct =
I.getMetadata(LLVMContext::MD_tbaa_struct))
6235 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noalias))
6236 visitAliasScopeListMetadata(MD);
6237 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alias_scope))
6238 visitAliasScopeListMetadata(MD);
6240 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_access_group))
6241 visitAccessGroupMetadata(MD);
6243 if (MDNode *AlignMD =
I.getMetadata(LLVMContext::MD_align)) {
6244 Check(
I.getType()->isPointerTy(),
"align applies only to pointer types",
6247 "align applies only to load instructions, "
6248 "use attributes for calls or invokes",
6250 Check(AlignMD->getNumOperands() == 1,
"align takes one operand!", &
I);
6253 "align metadata value must be an i64!", &
I);
6257 Check(Align <= Value::MaximumAlignment,
6258 "alignment is larger that implementation defined limit", &
I);
6261 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_prof))
6262 visitProfMetadata(
I, MD);
6264 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_memprof))
6265 visitMemProfMetadata(
I, MD);
6267 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callsite))
6268 visitCallsiteMetadata(
I, MD);
6270 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callee_type))
6271 visitCalleeTypeMetadata(
I, MD);
6273 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_DIAssignID))
6274 visitDIAssignIDMetadata(
I, MD);
6276 if (MDNode *MMRA =
I.getMetadata(LLVMContext::MD_mmra))
6277 visitMMRAMetadata(
I, MMRA);
6279 if (MDNode *Annotation =
I.getMetadata(LLVMContext::MD_annotation))
6280 visitAnnotationMetadata(Annotation);
6282 if (MDNode *Captures =
I.getMetadata(LLVMContext::MD_captures))
6283 visitCapturesMetadata(
I, Captures);
6285 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alloc_token))
6286 visitAllocTokenMetadata(
I, MD);
6288 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_inline_history))
6289 visitInlineHistoryMetadata(
I, MD);
6291 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_mem_cache_hint))
6292 visitMemCacheHintMetadata(
I, MD);
6294 if (MDNode *MD =
I.getMetadata(
"amdgpu.expected.active.lanes")) {
6296 "!amdgpu.expected.active.lanes must have exactly one operand", &
I,
6301 "!amdgpu.expected.active.lanes operand must be an i32 constant", &
I,
6305 if (MDNode *MD =
I.getMetadata(
"amdgpu.cfs")) {
6307 "!amdgpu.cfs must have exactly one operand", &
I, MD);
6311 "!amdgpu.cfs operand must be an i32 constant", &
I, MD);
6313 "!amdgpu.cfs operand must be in the range [0, 3]", &
I, MD);
6316 if (MDNode *
N =
I.getDebugLoc().getAsMDNode()) {
6318 visitMDNode(*
N, AreDebugLocsAllowed::Yes);
6321 if (
DL->getAtomGroup()) {
6323 CheckDI(SP &&
SP->getKeyInstructionsEnabled(),
6324 "DbgLoc uses atomGroup but DISubprogram doesn't have Key "
6325 "Instructions enabled",
6332 I.getAllMetadata(MDs);
6333 for (
auto Attachment : MDs) {
6334 unsigned Kind = Attachment.first;
6336 (
Kind == LLVMContext::MD_dbg ||
Kind == LLVMContext::MD_loop)
6337 ? AreDebugLocsAllowed::Yes
6338 : AreDebugLocsAllowed::
No;
6339 visitMDNode(*Attachment.second, AllowLocs);
6356 "const x86_amx is not allowed in argument!");
6368 case Intrinsic::assume: {
6372 "assume with operand bundles must have i1 true condition",
Call);
6378 auto GetTypeAt = [&](
unsigned Index) {
6379 return OBU.Inputs[
Index]->getType();
6384 CheckFailed(
"tags must be valid attribute names",
Call);
6386 case BundleAttr::Align:
6387 Check(OBU.Inputs.size() >= 2 && OBU.Inputs.size() <= 3,
6388 "alignment assumptions should have 2 or 3 arguments",
Call);
6391 Check(GetTypeAt(1)->isIntegerTy() &&
6392 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6393 "second argument should be an integer with a maximum width of 64 "
6396 Check(OBU.Inputs.size() < 3 ||
6397 (GetTypeAt(2)->isIntegerTy() &&
6398 GetTypeAt(2)->getIntegerBitWidth() <= 64),
6399 "third argument should be an integer with a maximum width of 64 "
6403 case BundleAttr::Cold:
6404 Check(OBU.Inputs.size() == 0,
6405 "cold assumptions should have no arguments",
Call);
6407 case BundleAttr::Dereferenceable:
6408 case BundleAttr::DereferenceableOrNull:
6409 Check(OBU.Inputs.size() == 2,
6410 "dereferenceable assumptions should have 2 arguments",
Call);
6413 Check(GetTypeAt(1)->isIntegerTy() &&
6414 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6415 "second argument should be an integer with a maximum width of 64 "
6419 case BundleAttr::Ignore:
6421 case BundleAttr::NonNull:
6422 Check(OBU.Inputs.size() == 1,
6423 "nonnull assumptions should have 1 argument",
Call);
6427 case BundleAttr::NoUndef:
6428 Check(OBU.Inputs.size() == 1,
6429 "noundef assumptions should have 1 argument",
Call);
6431 case BundleAttr::Range: {
6432 Check(OBU.Inputs.size() == 3,
6433 "range assumptions should have 3 arguments",
Call);
6434 Check(GetTypeAt(0)->isIntegerTy(),
6435 "first argument should be an integer",
Call);
6437 Check(LowerBound,
"second argument should be a constant integer",
Call);
6439 Check(UpperBound,
"third argument should be a constant integer",
Call);
6441 "an empty range has to be represented as `0, 0`");
6442 Check(GetTypeAt(0)->getIntegerBitWidth() ==
6443 GetTypeAt(1)->getIntegerBitWidth() &&
6444 GetTypeAt(1)->getIntegerBitWidth() ==
6445 GetTypeAt(2)->getIntegerBitWidth(),
6446 "all arguments should have the same bit width",
Call);
6448 case BundleAttr::SeparateStorage:
6449 Check(OBU.Inputs.size() == 2,
6450 "separate_storage assumptions should have 2 arguments",
Call);
6452 "arguments to separate_storage assumptions should be pointers",
6459 case Intrinsic::ucmp:
6460 case Intrinsic::scmp: {
6465 "result type must be at least 2 bits wide",
Call);
6467 bool IsDestTypeVector = DestTy->
isVectorTy();
6469 "ucmp/scmp argument and result types must both be either vector or "
6472 if (IsDestTypeVector) {
6475 Check(SrcVecLen == DestVecLen,
6476 "return type and arguments must have the same number of "
6482 case Intrinsic::coro_begin:
6483 case Intrinsic::coro_begin_custom_abi:
6485 "id argument of llvm.coro.begin must refer to coro.id");
6487 case Intrinsic::coro_id: {
6489 "align argument only accepts constants");
6492 "promise argument must refer to an alloca");
6497 "coro argument must refer to a function");
6501 if (BeforeCoroSplit)
6504 Check(!BeforeCoroEarly,
"cannot run CoroSplit before CoroEarly");
6507 "info argument of llvm.coro.id must refer to an initialized "
6511 "info argument of llvm.coro.id must refer to either a struct or "
6515 case Intrinsic::is_fpclass: {
6518 "unsupported bits for llvm.is.fpclass test mask");
6521 case Intrinsic::fptrunc_round: {
6526 MD = MAV->getMetadata();
6528 Check(MD !=
nullptr,
"missing rounding mode argument",
Call);
6531 (
"invalid value for llvm.fptrunc.round metadata operand"
6532 " (the operand should be a string)"),
6535 std::optional<RoundingMode> RoundMode =
6537 Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
6538 "unsupported rounding mode argument",
Call);
6541 case Intrinsic::convert_to_arbitrary_fp: {
6549 "if floating-point operand is a vector, integer operand must also "
6552 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6553 "floating-point and integer vector operands must have the same "
6560 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6562 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6563 StringRef Interp = InterpStr->getString();
6565 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6570 "unsupported interpretation metadata string",
Call);
6573 if (
unsigned FormatBits =
6576 "integer type bit width must equal the arbitrary FP format width",
6581 Check(RoundingMAV,
"missing rounding mode metadata operand",
Call);
6583 Check(RoundingStr,
"rounding mode metadata operand must be a string",
Call);
6585 std::optional<RoundingMode>
RM =
6587 Check(RM && *RM != RoundingMode::Dynamic,
6588 "unsupported rounding mode argument",
Call);
6591 case Intrinsic::convert_from_arbitrary_fp: {
6599 "if floating-point operand is a vector, integer operand must also "
6602 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6603 "floating-point and integer vector operands must have the same "
6610 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6612 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6613 StringRef Interp = InterpStr->getString();
6615 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6620 "unsupported interpretation metadata string",
Call);
6623 if (
unsigned FormatBits =
6626 "integer type bit width must equal the arbitrary FP format width",
6630#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6631#include "llvm/IR/VPIntrinsics.def"
6632#undef BEGIN_REGISTER_VP_INTRINSIC
6635#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
6636 case Intrinsic::INTRINSIC:
6637#include "llvm/IR/ConstrainedOps.def"
6641 case Intrinsic::dbg_declare:
6642 case Intrinsic::dbg_value:
6643 case Intrinsic::dbg_assign:
6644 case Intrinsic::dbg_label:
6651 case Intrinsic::memcpy:
6652 case Intrinsic::memcpy_inline:
6653 case Intrinsic::memmove:
6654 case Intrinsic::memset:
6655 case Intrinsic::memset_inline:
6657 case Intrinsic::experimental_memset_pattern: {
6659 Check(Memset->getValue()->getType()->isSized(),
6660 "unsized types cannot be used as memset patterns",
Call);
6663 case Intrinsic::memcpy_element_unordered_atomic:
6664 case Intrinsic::memmove_element_unordered_atomic:
6665 case Intrinsic::memset_element_unordered_atomic: {
6668 ConstantInt *ElementSizeCI =
6670 const APInt &ElementSizeVal = ElementSizeCI->
getValue();
6672 "element size of the element-wise atomic memory intrinsic "
6673 "must be a power of 2",
6676 auto IsValidAlignment = [&](MaybeAlign
Alignment) {
6679 Check(IsValidAlignment(AMI->getDestAlign()),
6680 "incorrect alignment of the destination argument",
Call);
6682 Check(IsValidAlignment(AMT->getSourceAlign()),
6683 "incorrect alignment of the source argument",
Call);
6687 case Intrinsic::call_preallocated_setup: {
6689 bool FoundCall =
false;
6692 Check(UseCall !=
nullptr,
6693 "Uses of llvm.call.preallocated.setup must be calls");
6695 if (IID == Intrinsic::call_preallocated_arg) {
6697 Check(AllocArgIndex !=
nullptr,
6698 "llvm.call.preallocated.alloc arg index must be a constant");
6699 auto AllocArgIndexInt = AllocArgIndex->getValue();
6700 Check(AllocArgIndexInt.sge(0) &&
6701 AllocArgIndexInt.slt(NumArgs->getValue()),
6702 "llvm.call.preallocated.alloc arg index must be between 0 and "
6704 "llvm.call.preallocated.setup's argument count");
6705 }
else if (IID == Intrinsic::call_preallocated_teardown) {
6708 Check(!FoundCall,
"Can have at most one call corresponding to a "
6709 "llvm.call.preallocated.setup");
6711 size_t NumPreallocatedArgs = 0;
6712 for (
unsigned i = 0; i < UseCall->arg_size(); i++) {
6713 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
6714 ++NumPreallocatedArgs;
6717 Check(NumPreallocatedArgs != 0,
6718 "cannot use preallocated intrinsics on a call without "
6719 "preallocated arguments");
6720 Check(NumArgs->equalsInt(NumPreallocatedArgs),
6721 "llvm.call.preallocated.setup arg size must be equal to number "
6722 "of preallocated arguments "
6732 auto PreallocatedBundle =
6734 Check(PreallocatedBundle,
6735 "Use of llvm.call.preallocated.setup outside intrinsics "
6736 "must be in \"preallocated\" operand bundle");
6737 Check(PreallocatedBundle->Inputs.front().get() == &
Call,
6738 "preallocated bundle must have token from corresponding "
6739 "llvm.call.preallocated.setup");
6744 case Intrinsic::call_preallocated_arg: {
6747 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6748 "llvm.call.preallocated.arg token argument must be a "
6749 "llvm.call.preallocated.setup");
6751 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
6752 "call site attribute");
6755 case Intrinsic::call_preallocated_teardown: {
6758 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6759 "llvm.call.preallocated.teardown token argument must be a "
6760 "llvm.call.preallocated.setup");
6763 case Intrinsic::gcroot:
6764 case Intrinsic::gcwrite:
6765 case Intrinsic::gcread:
6766 if (ID == Intrinsic::gcroot) {
6769 Check(AI,
"llvm.gcroot parameter #1 must be an alloca.",
Call);
6771 "llvm.gcroot parameter #2 must be a constant.",
Call);
6774 "llvm.gcroot parameter #1 must either be a pointer alloca, "
6775 "or argument #2 must be a non-null constant.",
6781 "Enclosing function does not use GC.",
Call);
6783 case Intrinsic::init_trampoline:
6785 "llvm.init_trampoline parameter #2 must resolve to a function.",
6788 case Intrinsic::reloc_none: {
6791 "llvm.reloc.none argument must be a metadata string", &
Call);
6794 case Intrinsic::stackprotector:
6796 "llvm.stackprotector parameter #2 must resolve to an alloca.",
Call);
6798 case Intrinsic::localescape: {
6802 Check(!SawFrameEscape,
"multiple calls to llvm.localescape in one function",
6809 "llvm.localescape only accepts static allocas",
Call);
6812 SawFrameEscape =
true;
6815 case Intrinsic::localrecover: {
6818 Check(Fn && !Fn->isDeclaration(),
6819 "llvm.localrecover first "
6820 "argument must be function defined in this module",
6823 auto &
Entry = FrameEscapeInfo[Fn];
6824 Entry.second = unsigned(
6825 std::max(
uint64_t(
Entry.second), IdxArg->getLimitedValue(~0U) + 1));
6829 case Intrinsic::experimental_gc_statepoint:
6831 Check(!CI->isInlineAsm(),
6832 "gc.statepoint support for inline assembly unimplemented", CI);
6834 "Enclosing function does not use GC.",
Call);
6836 verifyStatepoint(
Call);
6838 case Intrinsic::experimental_gc_result: {
6840 "Enclosing function does not use GC.",
Call);
6848 Check(StatepointCall && StatepointCall->getIntrinsicID() ==
6849 Intrinsic::experimental_gc_statepoint,
6850 "gc.result operand #1 must be from a statepoint",
Call,
6854 auto *TargetFuncType =
6857 "gc.result result type does not match wrapped callee",
Call);
6860 case Intrinsic::experimental_gc_relocate: {
6862 "gc.relocate must return a pointer or a vector of pointers",
Call);
6870 LandingPad->getParent()->getUniquePredecessor();
6874 Check(InvokeBB,
"safepoints should have unique landingpads",
6875 LandingPad->getParent());
6877 "gc relocate should be linked to a statepoint", InvokeBB);
6884 "gc relocate is incorrectly tied to the statepoint",
Call, Token);
6893 "gc.relocate operand #2 must be integer offset",
Call);
6897 "gc.relocate operand #3 must be integer offset",
Call);
6907 Check(BaseIndex < Opt->Inputs.size(),
6908 "gc.relocate: statepoint base index out of bounds",
Call);
6909 Check(DerivedIndex < Opt->Inputs.size(),
6910 "gc.relocate: statepoint derived index out of bounds",
Call);
6918 "gc.relocate: relocated value must be a pointer",
Call);
6919 Check(DerivedType->isPtrOrPtrVectorTy(),
6920 "gc.relocate: relocated value must be a pointer",
Call);
6922 "gc.relocate: must return the type of the relocated value",
Call);
6925 Check(GC,
"gc.relocate: calling function must have GCStrategy",
6928 auto isGCPtr = [&
GC](
Type *PTy) {
6929 return GC->isGCManagedPointer(PTy->getScalarType()).value_or(
true);
6932 "gc.relocate: relocated value must be a gc pointer",
Call);
6933 Check(isGCPtr(DerivedType),
6934 "gc.relocate: relocated value must be a gc pointer",
Call);
6938 case Intrinsic::experimental_patchpoint: {
6941 "patchpoint: invalid return type used with anyregcc",
Call);
6945 case Intrinsic::eh_exceptioncode:
6946 case Intrinsic::eh_exceptionpointer: {
6948 "eh.exceptionpointer argument must be a catchpad",
Call);
6951 case Intrinsic::get_active_lane_mask: {
6954 "get_active_lane_mask: element type is not i1",
Call);
6957 case Intrinsic::mask_beforefirst: {
6959 "mask.beforefirst element type must be i1",
Call);
6962 case Intrinsic::experimental_get_vector_length: {
6964 Check(!VF->isNegative() && !VF->isZero(),
6965 "get_vector_length: VF must be positive",
Call);
6968 case Intrinsic::experimental_guard: {
6971 "experimental_guard must have exactly one "
6972 "\"deopt\" operand bundle");
6976 case Intrinsic::experimental_deoptimize: {
6980 "experimental_deoptimize must have exactly one "
6981 "\"deopt\" operand bundle");
6983 "experimental_deoptimize return type must match caller return type");
6988 "calls to experimental_deoptimize must be followed by a return");
6992 "calls to experimental_deoptimize must be followed by a return "
6993 "of the value computed by experimental_deoptimize");
6998 case Intrinsic::vastart: {
7000 "va_start called in a non-varargs function");
7003 case Intrinsic::get_dynamic_area_offset: {
7004 Check(
DL.getPointerSizeInBits(
DL.getAllocaAddrSpace()) ==
7006 "get_dynamic_area_offset result type must match alloca address "
7011 case Intrinsic::smul_fix:
7012 case Intrinsic::smul_fix_sat:
7013 case Intrinsic::umul_fix:
7014 case Intrinsic::umul_fix_sat:
7015 case Intrinsic::sdiv_fix:
7016 case Intrinsic::sdiv_fix_sat:
7017 case Intrinsic::udiv_fix:
7018 case Intrinsic::udiv_fix_sat: {
7022 if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
7023 ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
7025 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
7029 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
7030 "to the width of the operands");
7034 case Intrinsic::lrint:
7035 case Intrinsic::llrint:
7036 case Intrinsic::lround:
7037 case Intrinsic::llround: {
7041 IF->
getName() +
": argument and result disagree on vector use",
7045 Check(VTy->getElementCount() == RTy->getElementCount(),
7046 IF->
getName() +
": argument must be same length as result", &
Call);
7050 case Intrinsic::bswap: {
7053 Check(
Size % 16 == 0,
"bswap must be an even number of bytes", &
Call);
7056 case Intrinsic::invariant_start: {
7058 Check(InvariantSize &&
7059 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
7060 "invariant_start parameter must be -1, 0 or a positive number",
7064 case Intrinsic::matrix_multiply:
7065 case Intrinsic::matrix_transpose:
7066 case Intrinsic::matrix_column_major_load:
7067 case Intrinsic::matrix_column_major_store: {
7069 Value *Stride =
nullptr;
7070 ConstantInt *NumRows;
7071 ConstantInt *NumColumns;
7072 FixedVectorType *ResultTy;
7073 Type *Op0ElemTy =
nullptr;
7074 Type *Op1ElemTy =
nullptr;
7076 case Intrinsic::matrix_multiply: {
7083 Check(Op0Ty && Op1Ty && RetTy,
7084 "Matrix operations require fixed-length vectors!", &
Call);
7085 Check(Op0Ty->getNumElements() ==
7087 "First argument of a matrix operation does not match specified "
7089 Check(Op1Ty->getNumElements() ==
7091 "Second argument of a matrix operation does not match specified "
7095 Op0ElemTy = Op0Ty->getElementType();
7096 Op1ElemTy = Op1Ty->getElementType();
7099 case Intrinsic::matrix_transpose: {
7104 Check(Op0Ty && RetTy,
"Matrix operations require fixed-length vectors!",
7107 Op0ElemTy = Op0Ty->getElementType();
7110 case Intrinsic::matrix_column_major_load: {
7115 Check(RetTy,
"Matrix operations require fixed-length vectors!", &
Call);
7119 case Intrinsic::matrix_column_major_store: {
7124 Check(Op0Ty,
"Matrix operations require fixed-length vectors!", &
Call);
7126 Op0ElemTy = Op0Ty->getElementType();
7135 "Result type must be an integer or floating-point type!", IF);
7139 "Vector element type mismatch of the result and first operand "
7145 "Vector element type mismatch of the result and second operand "
7151 "Result of a matrix operation does not fit in the returned vector!");
7155 "Stride bitwidth cannot exceed 64!", IF);
7159 case Intrinsic::stepvector: {
7161 Check(VecTy->getScalarSizeInBits() >= 8,
7162 "stepvector only supported for vectors of integers "
7163 "with a bitwidth of at least 8.",
7167 case Intrinsic::experimental_vector_match: {
7175 "Second operand must be a fixed length vector.", &
Call);
7176 Check(Op1Ty->getElementType() == Op2Ty->getElementType(),
7177 "First two operands must have the same element type.", &
Call);
7180 case Intrinsic::speculative_load: {
7183 "llvm.speculative.load return type must be a byte type or a "
7189 "llvm.speculative.load byte type must have a bit width that is "
7194 uint64_t MinSizeInBits =
DL.getTypeSizeInBits(LoadTy).getKnownMinValue();
7196 "llvm.speculative.load return type size in bytes must be a "
7197 "positive power of 2",
7200 constexpr unsigned NumFixedArgs = 3;
7202 Check(NumArgs >= NumFixedArgs,
7203 "llvm.speculative.load requires at least 3 arguments", &
Call);
7208 Check(NumArgs == NumFixedArgs,
7209 "llvm.speculative.load direct form has too many arguments", &
Call);
7214 "llvm.speculative.load third argument must be i64 or a direct "
7215 "reference to an oracle function",
7218 Check(OracleFn->hasFnAttribute(
"oracle-function"),
7219 "llvm.speculative.load oracle function must have the "
7220 "\"oracle-function\" attribute",
7224 Check(OracleFn->onlyReadsMemory() && OracleFn->onlyAccessesArgMemory() &&
7225 OracleFn->doesNotThrow() && OracleFn->hasNoSync() &&
7226 OracleFn->willReturn(),
7227 "llvm.speculative.load oracle function must be nounwind, nosync "
7228 "and willreturn, must not have side effects and may only read "
7229 "memory through its arguments",
7232 FunctionType *FTy = OracleFn->getFunctionType();
7233 Check(FTy->getReturnType()->isIntegerTy(64),
7234 "llvm.speculative.load oracle function must return i64", &
Call);
7236 Check(!FTy->isVarArg(),
7237 "llvm.speculative.load oracle function must have a fixed argument "
7240 Check(NumArgs - NumFixedArgs == FTy->getNumParams(),
7241 "llvm.speculative.load oracle function argument count mismatch",
7243 for (
auto [ParamTy, Arg] :
7245 Check(ParamTy == Arg->getType(),
7246 "llvm.speculative.load oracle function argument type mismatch",
7251 case Intrinsic::vector_repeat: {
7255 Check(ArgTy,
"vector_repeat argument must be a fixed-length vector.",
7257 Check(ResultTy,
"vector_repeat result must be a scalable vector.", &
Call);
7259 "vector_repeat argument and result must have the same element "
7262 Check(ArgTy->getNumElements() == ResultTy->getMinNumElements(),
7263 "vector_repeat argument and result must have the same minimum "
7268 case Intrinsic::vector_insert: {
7277 ElementCount VecEC = VecTy->getElementCount();
7278 ElementCount SubVecEC =
SubVecTy->getElementCount();
7279 Check(VecTy->getElementType() ==
SubVecTy->getElementType(),
7280 "vector_insert parameters must have the same element "
7284 "vector_insert index must be a constant multiple of "
7285 "the subvector's known minimum vector length.");
7290 Check(VecEC.
isScalable(),
"cannot vector_insert a scalable vector into "
7300 "subvector operand of vector_insert would overrun the "
7301 "vector being inserted into.");
7305 case Intrinsic::vector_extract: {
7313 ElementCount VecEC = VecTy->getElementCount();
7314 ElementCount ResultEC = ResultTy->getElementCount();
7316 Check(ResultTy->getElementType() == VecTy->getElementType(),
7317 "vector_extract result must have the same element "
7318 "type as the input vector.",
7321 "vector_extract index must be a constant multiple of "
7322 "the result type's known minimum vector length.");
7327 Check(VecEC.
isScalable(),
"cannot vector_extract a scalable vector from "
7337 "vector_extract would overrun.");
7341 case Intrinsic::vector_partial_reduce_fadd:
7342 case Intrinsic::vector_partial_reduce_add: {
7346 unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
7347 unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
7349 Check((VecWidth % AccWidth) == 0,
7350 "Invalid vector widths for partial "
7351 "reduction. The width of the input vector "
7352 "must be a positive integer multiple of "
7353 "the width of the accumulator vector.");
7355 Check(AccTy->getElementType() == VecTy->getElementType(),
7356 "The element type of the input vector must match the element type "
7357 "of the accumulator vector.",
7361 case Intrinsic::experimental_noalias_scope_decl: {
7365 case Intrinsic::preserve_array_access_index:
7366 case Intrinsic::preserve_struct_access_index:
7367 case Intrinsic::aarch64_ldaxr:
7368 case Intrinsic::aarch64_ldxr:
7369 case Intrinsic::arm_ldaex:
7370 case Intrinsic::arm_ldrex: {
7372 Check(ElemTy,
"Intrinsic requires elementtype attribute on first argument.",
7376 case Intrinsic::aarch64_stlxr:
7377 case Intrinsic::aarch64_stxr:
7378 case Intrinsic::arm_stlex:
7379 case Intrinsic::arm_strex: {
7382 "Intrinsic requires elementtype attribute on second argument.",
7386 case Intrinsic::aarch64_prefetch: {
7388 "write argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
7390 "target argument to llvm.aarch64.prefetch must be 0-3",
Call);
7392 "stream argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
7394 "isdata argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
7397 case Intrinsic::aarch64_range_prefetch: {
7399 "write argument to llvm.aarch64.range.prefetch must be 0 or 1",
Call);
7401 "stream argument to llvm.aarch64.range.prefetch must be 0 or 1",
7405 case Intrinsic::riscv_vsetvli:
7406 case Intrinsic::riscv_vsetvlimax: {
7411 "llvm.riscv.vsetvli/vsetvlimax result must be i32 or i64", &
Call);
7414 bool HasAVL =
ID == Intrinsic::riscv_vsetvli;
7415 unsigned Offset = HasAVL ? 1 : 0;
7420 Check(VSEW <= 3,
"llvm.riscv.vsetvli/vsetvlimax VSEW must be 0-3", &
Call);
7422 "llvm.riscv.vsetvli/vsetvlimax VLMUL is reserved", &
Call);
7425 case Intrinsic::riscv_sati: {
7429 "llvm.riscv.sati immediate must be in the range [1, bitwidth]",
7433 case Intrinsic::riscv_usati: {
7437 "llvm.riscv.usati immediate must be in the range [0, bitwidth-1]",
7441 case Intrinsic::callbr_landingpad: {
7443 Check(CBR,
"intrinstic requires callbr operand", &
Call);
7450 CheckFailed(
"Intrinsic in block must have 1 unique predecessor", &
Call);
7454 CheckFailed(
"Intrinsic must have corresponding callbr in predecessor",
7459 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
7460 "block in indirect destination list",
7463 Check(&
First == &
Call,
"No other instructions may proceed intrinsic",
7467 case Intrinsic::structured_gep: {
7473 "Intrinsic first parameter is missing an ElementType attribute",
7481 "Index operand type must be an integer", &
Call);
7484 T = AT->getElementType();
7486 Check(CI,
"Indexing into a struct requires a constant int", &
Call);
7488 "Indexing in a struct should be inbounds", &
Call);
7491 T = VT->getElementType();
7493 CheckFailed(
"Reached a non-composite type with more indices to process",
7499 case Intrinsic::structured_alloca:
7501 "@llvm.structured.alloca calls require elementtype attribute.",
7504 case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
7505 case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
7508 Check(RegCount % 8 == 0,
7509 "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
7512 case Intrinsic::nvvm_cp_async_bulk_global_to_shared_cta:
7513 case Intrinsic::nvvm_cp_async_bulk_global_to_shared_cta_relaxed: {
7515 const unsigned FlagValidPatternIndex = ArgSize - 1;
7516 const unsigned IgnoreOOBFlagIndex = 8;
7519 const auto *FlagValidPattern =
7521 Check(!IgnoreOOB || FlagValidPattern->isZero(),
7522 "flag_valid_pattern must be 0 (disabled) when ignore_oob is enabled",
7526 case Intrinsic::experimental_convergence_entry:
7527 case Intrinsic::experimental_convergence_anchor:
7529 case Intrinsic::experimental_convergence_loop:
7531 case Intrinsic::ptrmask: {
7535 "llvm.ptrmask intrinsic first argument must be pointer or vector "
7540 "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
7545 "llvm.ptrmask intrinsic arguments must have the same number of "
7549 "llvm.ptrmask intrinsic second argument bitwidth must match "
7550 "pointer index type size of first argument",
7554 case Intrinsic::thread_pointer: {
7556 DL.getDefaultGlobalsAddressSpace(),
7557 "llvm.thread.pointer intrinsic return type must be for the globals "
7562 case Intrinsic::threadlocal_address: {
7565 "llvm.threadlocal.address first argument must be a GlobalValue");
7567 "llvm.threadlocal.address operand isThreadLocal() must be true");
7570 case Intrinsic::lifetime_start:
7571 case Intrinsic::lifetime_end: {
7575 (
II &&
II->getIntrinsicID() == Intrinsic::structured_alloca),
7576 "llvm.lifetime.start/end can only be used on alloca or poison",
7580 case Intrinsic::sponentry: {
7581 const unsigned StackAS =
DL.getAllocaAddrSpace();
7584 "llvm.sponentry must return a pointer to the stack", &
Call);
7587 case Intrinsic::write_volatile_register: {
7591 "llvm.write_volatile_register metadata must be a single MDString",
7595 case Intrinsic::ptrauth_auth_with_pc_and_resign: {
7600 "ptrauth.auth.with.pc.and.resign key must be IA (0) or IB (1)",
7609 if (
F->hasPersonalityFn() &&
7613 if (BlockEHFuncletColors.
empty())
7620 auto ColorsIt = BlockEHFuncletColors.
find(CallBB);
7621 if (ColorsIt != BlockEHFuncletColors.
end()) {
7623 bool InEHFunclet =
false;
7626 for (BasicBlock *ColorFirstBB : CV)
7627 if (
auto It = ColorFirstBB->getFirstNonPHIIt();
7628 It != ColorFirstBB->end())
7633 bool HasToken =
false;
7640 Check(HasToken,
"Missing funclet token on intrinsic call", &
Call);
7654DISubprogram *Verifier::getSubprogram(
Metadata *LocalScope) {
7655 if (hasDIScopeCycle(LocalScope))
7672void Verifier::visit(DbgLabelRecord &DLR) {
7674 "invalid #dbg_label intrinsic variable", &DLR, DLR.
getRawLabel());
7687 CheckDI(Loc,
"#dbg_label record requires a !dbg attachment", &DLR, BB,
F);
7691 if (!LabelSP || !LocSP)
7695 "mismatched subprogram between #dbg_label label and !dbg attachment",
7696 &DLR, BB,
F, Label,
Label->getScope()->getSubprogram(), Loc,
7697 Loc->getScope()->getSubprogram());
7700void Verifier::visit(DbgVariableRecord &DVR) {
7704 CheckDI(DVR.
getType() == DbgVariableRecord::LocationType::Value ||
7705 DVR.
getType() == DbgVariableRecord::LocationType::Declare ||
7706 DVR.
getType() == DbgVariableRecord::LocationType::DeclareValue ||
7707 DVR.
getType() == DbgVariableRecord::LocationType::Assign,
7708 "invalid #dbg record type", &DVR, DVR.
getType(), BB,
F);
7716 "invalid #dbg record address/value", &DVR, MD, BB,
F);
7718 "!DIAssignID should only be used by Assign DVRs.", MD, &DVR);
7720 visitValueAsMetadata(*VAM,
F);
7723 Type *Ty = VAM->getValue()->getType();
7725 "location of #dbg_declare must be a pointer or int", &DVR, MD, BB,
7729 visitDIArgList(*AL,
F);
7745 for (DIExpression::ExprOperand
Op : Expr->
expr_ops()) {
7749 "#dbg record expression references nonexistent location operand",
7756 "invalid #dbg_assign DIAssignID", &DVR, DVR.
getRawAssignID(), BB,
7759 AreDebugLocsAllowed::No);
7768 "invalid #dbg_assign address", &DVR, DVR.
getRawAddress(), BB,
F);
7770 visitValueAsMetadata(*VAM,
F);
7773 "invalid #dbg_assign address expression", &DVR,
7780 "inst not in same function as #dbg_assign",
I, &DVR, BB,
F);
7790 &DVR, DLNode, BB,
F);
7796 if (!VarSP || !LocSP)
7800 "mismatched subprogram between #dbg record variable and DILocation",
7802 Loc->getScope()->getSubprogram(), BB,
F);
7807void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
7809 case Intrinsic::experimental_vp_splice: {
7812 int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
7814 AttributeList
Attrs = VPI.
getParent()->getParent()->getAttributes();
7815 if (
Attrs.hasFnAttr(Attribute::VScaleRange))
7816 KnownMinNumElements *=
Attrs.getFnAttrs().getVScaleRangeMin();
7818 Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
7819 (Idx >= 0 && Idx < KnownMinNumElements),
7820 "The splice index exceeds the range [-VL, VL-1] where VL is the "
7821 "known minimum number of elements in the vector. For scalable "
7822 "vectors the minimum number of elements is determined from "
7830void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
7832 case Intrinsic::experimental_constrained_fcmp:
7833 case Intrinsic::experimental_constrained_fcmps: {
7836 "invalid predicate for constrained FP comparison intrinsic", &FPI);
7840 case Intrinsic::experimental_constrained_fptosi:
7841 case Intrinsic::experimental_constrained_fptoui: {
7850 "Intrinsic first argument and result disagree on vector use", &FPI);
7853 "Intrinsic first argument and result vector lengths must be equal",
7859 case Intrinsic::experimental_constrained_sitofp:
7860 case Intrinsic::experimental_constrained_uitofp: {
7869 "Intrinsic first argument and result disagree on vector use", &FPI);
7872 "Intrinsic first argument and result vector lengths must be equal",
7878 case Intrinsic::experimental_constrained_fptrunc:
7879 case Intrinsic::experimental_constrained_fpext: {
7885 "Intrinsic first argument and result disagree on vector use", &FPI);
7889 "Intrinsic first argument and result vector lengths must be equal",
7892 if (FPI.
getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
7894 "Intrinsic first argument's type must be larger than result type",
7898 "Intrinsic first argument's type must be smaller than result type",
7914 "invalid exception behavior argument", &FPI);
7921void Verifier::verifyFragmentExpression(
const DbgVariableRecord &DVR) {
7926 if (!
V || !
E || !
E->isValid())
7940 if (
V->isArtificial())
7943 verifyFragmentExpression(*
V, *
Fragment, &DVR);
7946template <
typename ValueOrMetadata>
7947void Verifier::verifyFragmentExpression(
const DIVariable &
V,
7949 ValueOrMetadata *
Desc) {
7952 auto VarSize =
V.getSizeInBits();
7956 unsigned FragSize =
Fragment.SizeInBits;
7957 unsigned FragOffset =
Fragment.OffsetInBits;
7958 CheckDI(FragSize + FragOffset <= *VarSize,
7959 "fragment is larger than or outside of variable",
Desc, &
V);
7960 CheckDI(FragSize != *VarSize,
"fragment covers entire variable",
Desc, &
V);
7963void Verifier::verifyFnArgs(
const DbgVariableRecord &DVR) {
7975 CheckDI(Var,
"#dbg record without variable");
7977 unsigned ArgNo = Var->
getArg();
7983 if (DebugFnArgs.
size() < ArgNo)
7984 DebugFnArgs.
resize(ArgNo,
nullptr);
7986 auto *Prev = DebugFnArgs[ArgNo - 1];
7987 DebugFnArgs[ArgNo - 1] = Var;
7988 CheckDI(!Prev || (Prev == Var),
"conflicting debug info for argument", &DVR,
7992void Verifier::verifyNotEntryValue(
const DbgVariableRecord &DVR) {
7996 if (!
E || !
E->isValid())
8006 ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
8011 "Entry values are only allowed in MIR unless they target a "
8012 "swiftasync Argument",
8016void Verifier::verifyCompileUnits() {
8020 if (
M.getContext().isODRUniquingDebugTypes())
8022 auto *CUs =
M.getNamedMetadata(
"llvm.dbg.cu");
8023 SmallPtrSet<const Metadata *, 2> Listed;
8026 for (
const auto *CU : CUVisited)
8027 CheckDI(Listed.
count(CU),
"DICompileUnit not listed in llvm.dbg.cu", CU);
8031void Verifier::verifyDeoptimizeCallingConvs() {
8032 if (DeoptimizeDeclarations.
empty())
8036 for (
const auto *
F :
ArrayRef(DeoptimizeDeclarations).slice(1)) {
8037 Check(
First->getCallingConv() ==
F->getCallingConv(),
8038 "All llvm.experimental.deoptimize declarations must have the same "
8039 "calling convention",
8044void Verifier::verifyAttachedCallBundle(
const CallBase &
Call,
8045 const OperandBundleUse &BU) {
8048 Check((FTy->getReturnType()->isPointerTy() ||
8050 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
8051 "function returning a pointer or a non-returning function that has a "
8056 "operand bundle \"clang.arc.attachedcall\" requires one function as "
8064 Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
8065 IID == Intrinsic::objc_claimAutoreleasedReturnValue ||
8066 IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
8067 "invalid function argument",
Call);
8069 StringRef FnName = Fn->getName();
8070 Check((FnName ==
"objc_retainAutoreleasedReturnValue" ||
8071 FnName ==
"objc_claimAutoreleasedReturnValue" ||
8072 FnName ==
"objc_unsafeClaimAutoreleasedReturnValue"),
8073 "invalid function argument",
Call);
8077void Verifier::verifyNoAliasScopeDecl() {
8078 if (NoAliasScopeDecls.
empty())
8082 for (
auto *
II : NoAliasScopeDecls) {
8083 assert(
II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
8084 "Not a llvm.experimental.noalias.scope.decl ?");
8087 Check(ScopeListMV !=
nullptr,
8088 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
8093 Check(ScopeListMD !=
nullptr,
"!id.scope.list must point to an MDNode",
II);
8094 Check(ScopeListMD->getNumOperands() == 1,
8095 "!id.scope.list must point to a list with a single scope",
II);
8096 visitAliasScopeListMetadata(ScopeListMD);
8101 if (!
getIROptions(
M.getContext()).verify_noalias_scope_decl_dom)
8106 auto GetScope = [](IntrinsicInst *
II) {
8109 return &
cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
8114 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
8115 return GetScope(Lhs) < GetScope(Rhs);
8122 auto ItCurrent = NoAliasScopeDecls.begin();
8123 while (ItCurrent != NoAliasScopeDecls.end()) {
8124 auto CurScope = GetScope(*ItCurrent);
8125 auto ItNext = ItCurrent;
8128 }
while (ItNext != NoAliasScopeDecls.end() &&
8129 GetScope(*ItNext) == CurScope);
8134 if (ItNext - ItCurrent < 32)
8138 Check(!DT.dominates(
I, J),
8139 "llvm.experimental.noalias.scope.decl dominates another one "
8140 "with the same scope",
8154 Verifier
V(OS,
true, *f.getParent());
8158 return !V.verify(
F);
8162 bool *BrokenDebugInfo) {
8164 Verifier
V(OS, !BrokenDebugInfo, M);
8166 bool Broken =
false;
8168 Broken |= !V.verify(
F);
8170 Broken |= !V.verify();
8171 if (BrokenDebugInfo)
8172 *BrokenDebugInfo = V.hasBrokenDebugInfo();
8183 std::unique_ptr<Verifier>
V;
8184 bool FatalErrors =
true;
8187 explicit VerifierLegacyPass(
bool FatalErrors)
8188 : FunctionPass(
ID), FatalErrors(FatalErrors) {}
8190 bool doInitialization(
Module &M)
override {
8191 V = std::make_unique<Verifier>(
8197 if (!
V->verify(
F) && FatalErrors) {
8198 errs() <<
"in function " <<
F.getName() <<
'\n';
8204 bool doFinalization(
Module &M)
override {
8205 bool HasErrors =
false;
8207 if (
F.isDeclaration())
8208 HasErrors |= !
V->verify(
F);
8210 HasErrors |= !
V->verify();
8211 if (FatalErrors && (HasErrors ||
V->hasBrokenDebugInfo()))
8216 void getAnalysisUsage(AnalysisUsage &AU)
const override {
8224template <
typename... Tys>
void TBAAVerifier::CheckFailed(Tys &&... Args) {
8226 return Diagnostic->CheckFailed(
Args...);
8229#define CheckTBAA(C, ...) \
8232 CheckFailed(__VA_ARGS__); \
8240TBAAVerifier::TBAABaseNodeSummary
8244 CheckFailed(
"Base nodes must have at least two operands",
I, BaseNode);
8248 auto Itr = TBAABaseNodes.find(BaseNode);
8249 if (Itr != TBAABaseNodes.end())
8252 auto Result = verifyTBAABaseNodeImpl(
I, BaseNode, IsNewFormat);
8253 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
8255 assert(InsertResult.second &&
"We just checked!");
8259TBAAVerifier::TBAABaseNodeSummary
8260TBAAVerifier::verifyTBAABaseNodeImpl(
const Instruction *
I,
8261 const MDNode *BaseNode,
bool IsNewFormat) {
8262 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {
true, ~0
u};
8266 return isValidScalarTBAANode(BaseNode)
8267 ? TBAAVerifier::TBAABaseNodeSummary({
false, 0})
8273 CheckFailed(
"Access tag nodes must have the number of operands that is a "
8274 "multiple of 3!", BaseNode);
8279 CheckFailed(
"Struct tag nodes must have an odd number of operands!",
8289 if (!TypeSizeNode) {
8290 CheckFailed(
"Type size nodes must be constants!",
I, BaseNode);
8297 CheckFailed(
"Struct tag nodes have a string as their first operand",
8304 std::optional<APInt> PrevOffset;
8309 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8310 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8312 Idx += NumOpsPerField) {
8313 const MDOperand &FieldTy = BaseNode->
getOperand(Idx);
8314 const MDOperand &FieldOffset = BaseNode->
getOperand(Idx + 1);
8316 CheckFailed(
"Incorrect field entry in struct type node!",
I, BaseNode);
8321 auto *OffsetEntryCI =
8323 if (!OffsetEntryCI) {
8324 CheckFailed(
"Offset entries must be constants!",
I, BaseNode);
8330 BitWidth = OffsetEntryCI->getBitWidth();
8332 if (OffsetEntryCI->getBitWidth() !=
BitWidth) {
8334 "Bitwidth between the offsets and struct type entries must match",
I,
8346 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
8349 CheckFailed(
"Offsets must be increasing!",
I, BaseNode);
8353 PrevOffset = OffsetEntryCI->getValue();
8358 if (!MemberSizeNode) {
8359 CheckFailed(
"Member size entries must be constants!",
I, BaseNode);
8366 return Failed ? InvalidNode
8367 : TBAAVerifier::TBAABaseNodeSummary(
false,
BitWidth);
8389 return Parent && Visited.
insert(Parent).second &&
8393bool TBAAVerifier::isValidScalarTBAANode(
const MDNode *MD) {
8394 auto ResultIt = TBAAScalarNodes.find(MD);
8395 if (ResultIt != TBAAScalarNodes.end())
8396 return ResultIt->second;
8398 SmallPtrSet<const MDNode *, 4> Visited;
8400 auto InsertResult = TBAAScalarNodes.insert({MD,
Result});
8402 assert(InsertResult.second &&
"Just checked!");
8411MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(
const Instruction *
I,
8412 const MDNode *BaseNode,
8423 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8424 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8426 Idx += NumOpsPerField) {
8427 auto *OffsetEntryCI =
8429 if (OffsetEntryCI->getValue().ugt(
Offset)) {
8430 if (Idx == FirstFieldOpNo) {
8431 CheckFailed(
"Could not find TBAA parent in struct type node",
I,
8436 unsigned PrevIdx =
Idx - NumOpsPerField;
8437 auto *PrevOffsetEntryCI =
8439 Offset -= PrevOffsetEntryCI->getValue();
8447 Offset -= LastOffsetEntryCI->getValue();
8452 if (!
Type ||
Type->getNumOperands() < 3)
8464 if (!Visited.
insert(
N).second)
8484 "This instruction shall not have a TBAA access tag!",
I);
8486 bool IsStructPathTBAA =
8490 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
8500 "Access tag metadata must have either 4 or 5 operands",
I, MD);
8503 "Struct tag metadata must have either 3 or 4 operands",
I, MD);
8510 CheckTBAA(AccessSizeNode,
"Access size field must be a constant",
I, MD);
8514 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
8519 "Immutability tag on struct tag metadata must be a constant",
I,
8522 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
8523 "Immutability part of the struct tag metadata must be either 0 or 1",
I,
8528 "Malformed struct tag metadata: base and access-type "
8529 "should be non-null and point to Metadata nodes",
8530 I, MD, BaseNode, AccessType);
8533 CheckTBAA(isValidScalarTBAANode(AccessType),
8534 "Access type node must be a valid scalar type",
I, MD,
8538 "Cycle detected in access type parent chain",
I, MD, AccessType);
8542 CheckTBAA(OffsetCI,
"Offset must be constant integer",
I, MD);
8545 bool SeenAccessTypeInPath =
false;
8551 getFieldNodeFromTBAABaseNode(
I, BaseNode,
Offset, IsNewFormat)) {
8552 if (!StructPath.
insert(BaseNode).second) {
8553 CheckFailed(
"Cycle detected in struct path",
I, MD);
8558 unsigned BaseNodeBitWidth;
8559 std::tie(
Invalid, BaseNodeBitWidth) =
8560 verifyTBAABaseNode(
I, BaseNode, IsNewFormat);
8567 SeenAccessTypeInPath |= BaseNode == AccessType;
8569 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
8574 (BaseNodeBitWidth == 0 &&
Offset == 0) ||
8575 (IsNewFormat && BaseNodeBitWidth == ~0u),
8576 "Access bit-width not the same as description bit-width",
I, MD,
8577 BaseNodeBitWidth,
Offset.getBitWidth());
8579 if (IsNewFormat && SeenAccessTypeInPath)
8583 CheckTBAA(SeenAccessTypeInPath,
"Did not see access type in access path!",
I,
8594 "!tbaa.struct operands must come in groups of three",
I, MD);
8596 std::optional<APInt> PrevOffset;
8597 for (
unsigned Idx = 0, E = MD->
getNumOperands(); Idx != E; Idx += 3) {
8600 CheckTBAA(OffsetCI,
"!tbaa.struct field offset must be a constant integer",
8604 "!tbaa.struct field size must be a constant integer",
I, MD);
8607 CheckTBAA(
Tag,
"!tbaa.struct field tag must be null or an MDNode",
I, MD);
8615 std::max(PrevOffset->getBitWidth(),
Offset.getBitWidth());
8617 "!tbaa.struct field offsets must be non-decreasing",
I, MD);
8624char VerifierLegacyPass::ID = 0;
8625INITIALIZE_PASS(VerifierLegacyPass,
"verify",
"Module Verifier",
false,
false)
8628 return new VerifierLegacyPass(FatalErrors);
8646 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
8654 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
Function Alias Analysis false
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.
SmallVector< MachineOperand, 4 > 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)
#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 const Metadata * getRawDIScopeParent(const Metadata *S)
Parent scope operand of S, or null if S has no parent (a DIFile, DICompileUnit, or non-scope).
static bool isDINode(const Metadata *MD)
static bool isSupportedCallBrIntrinsic(Intrinsic::ID ID)
static bool isScope(const Metadata *MD)
static bool hasAcyclicTBAAParentChain(const MDNode *MD)
Returns true if the parent chain of the TBAA type node MD is acyclic.
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 bool isNewFormatTBAATypeNode(const MDNode *Type)
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 const char * areInvalidOperands(Value *Base, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitinsert operation, otherwise return nul...
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).
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
This class represents a function call, abstracting a target machine's calling convention.
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)
Conditional Branch instruction.
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
iterator_range< expr_op_iterator > expr_ops() const
DbgVariableFragmentInfo FragmentInfo
LLVM_ABI bool isValid() const
@ 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....
LLVM_ABI bool isKillLocation() const
LocationType getType() const
MDNode * getRawExpression() const
MDNode * getRawAddressExpression() const
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
LLVM_ABI unsigned getNumVariableLocationOps() 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.
iterator find(const_arg_type_t< KeyT > Val)
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.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
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.
unsigned getNumElements() const
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)
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
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.
Indirect Branch Instruction.
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.
iterator_range< user_iterator > users()
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.
An instruction for reading from memory.
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
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.
Return a value (possibly void), from a function.
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.
This class represents the LLVM 'select' instruction.
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.
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.
An instruction for storing to memory.
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)
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,...
LLVM_ABI bool visitTBAAStructMetadata(const Instruction *I, const MDNode *MD)
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.
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'.
bool isSized() const
Return true if it makes sense to take the size of this type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isByteOrByteVectorTy() const
Return true if this is a byte type or a vector of byte types.
bool isAggregateType() const
Return true if the type is an aggregate 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.
LLVM_ABI unsigned getByteBitWidth() const
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
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.
LLVM_ABI bool containsNonLocalTargetExtType() const
Return true if this type is or contains a target extension type that disallows being used as a local.
LLVM_ABI bool containsNonGlobalTargetExtType() const
Return true if this type is or contains a target extension type that disallows being used as a global...
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.
Type * getElementType() const
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.
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...
LLVM_ABI StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
static const int NoAliasScopeDeclScopeArg
LLVM_ABI bool isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
LLVM_ABI bool isImmArgValueInRangeSet(ID IID, unsigned ArgIdx, const APInt &Value)
Returns true if Value satisfies the range constraints specified for argument ArgIdx of intrinsic IID.
std::variant< std::monostate, Loc::Single, Loc::Multi, Loc::MMI, Loc::EntryValue > Variant
Alias for the std::variant specialization base class of DbgVariable.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
constexpr StringLiteral AbiPreserveAttrs[]
@ System
Synchronized with respect to all concurrently executing threads.
LLVM_ABI std::optional< VFInfo > tryDemangleForVFABI(StringRef MangledName, const FunctionType *FTy)
Function to construct a VFInfo out of a mangled names in the following format:
@ CE
Windows NT (Windows on ARM)
AssignmentInstRange getAssignmentInsts(DIAssignID *ID)
Return a range of instructions (typically just one) that have ID as an attachment.
SmallVector< DbgVariableRecord * > getAssignmentMarkers(DIAssignID *ID)
@ DW_LLVM_LANG_DIALECT_max
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
NodeAddr< NodeBase * > Node
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
std::optional< LongDoubleFormat > parseLongDoubleFormat(StringRef Name)
Parses an IR floating-point type name into a LongDoubleFormat, returning std::nullopt if it does not ...
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool canInstructionHaveMMRAs(const Instruction &I)
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
RelativeUniformCounterPtr Values
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
testing::Matcher< const detail::ErrorHolder & > Failed()
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
LLVM_ABI DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
void verifyAMDGPUAlloca(VerifierSupport &VS, const AllocaInst &AI)
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
gep_type_iterator gep_type_end(const User *GEP)
bool isa_and_nonnull(const Y &Val)
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
void verifyAMDGPUFunctionMetadata(VerifierSupport &VS, const Function &F)
std::optional< ExceptionHandling > parseExceptionModel(StringRef Name)
Parses the string spelling used by the "exception-model" IR module flag into an ExceptionHandling val...
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
GenericConvergenceVerifier< SSAContext > ConvergenceVerifier
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
bool isModSet(const ModRefInfo MRI)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void verifyAMDGPUIntrinsicCall(VerifierSupport &VS, Intrinsic::ID ID, CallBase &Call)
bool isPointerTy(const Type *T)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
constexpr BooleanLoopTags OldBooleanLoopTags[]
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI bool isValueProfileMD(const MDNode *ProfileData)
Checks if an MDNode contains value profiling Metadata.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI unsigned getNumBranchWeights(const MDNode &ProfileData)
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
LLVM_ABI FunctionPass * createVerifierPass(bool FatalErrors=true)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
DWARFExpression::Operation Op
std::optional< ThreadModel > parseThreadModel(StringRef S)
Parse the string spelling used by the "thread-model" IR module flag into a ThreadModel.
ArrayRef(const T &OneElt) -> ArrayRef< T >
const IROptions & getIROptions(const LLVMContext &C)
constexpr unsigned BitWidth
TinyPtrVector< BasicBlock * > ColorVector
LLVM_ABI const char * LLVMLoopEstimatedTripCount
Profile-based loop metadata that should be accessed only by using llvm::getLoopEstimatedTripCount and...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI std::optional< RoundingMode > convertStrToRoundingMode(StringRef)
Returns a valid RoundingMode enumerator when given a string that is valid as input in constrained int...
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI std::unique_ptr< GCStrategy > getGCStrategy(const StringRef Name)
Lookup the GCStrategy object associated with the given gc name.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
void verifyNVVMIntrinsicCall(VerifierSupport &VS, Intrinsic::ID ID, CallBase &Call)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
bool pred_empty(const BasicBlock *BB)
void verifyAMDGPUGlobalVariable(VerifierSupport &VS, const GlobalVariable &GV)
bool isHexDigit(char C)
Checks if character C is a hexadecimal numeric character.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
void verifyAMDGPUModuleFlag(VerifierSupport &VS, const MDString *ID, Module::ModFlagBehavior MFB, const MDNode *Op)
bool isAMDGPUCallBrIntrinsic(Intrinsic::ID ID)
constexpr bool isCallableCC(CallingConv::ID CC)
LLVM_ABI bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
A special type used by analysis passes to provide an address that identifies that particular analysis...
static LLVM_ABI const char * UnknownBranchWeightsMarker
static LLVM_ABI const char * ValueProfile
static LLVM_ABI const char * FunctionEntryCount
static LLVM_ABI const char * BranchWeights
uint32_t getTagID() const
Return the tag of this operand bundle as an integer.