98#include "llvm/IR/IntrinsicsAArch64.h"
99#include "llvm/IR/IntrinsicsARM.h"
100#include "llvm/IR/IntrinsicsNVPTX.h"
101#include "llvm/IR/IntrinsicsWebAssembly.h"
142 cl::desc(
"Ensure that llvm.experimental.noalias.scope.decl for identical "
143 "scopes are not dominating"));
168 Type *LandingPadResultTy;
175 bool HasDebugInfo =
false;
218 SawFrameEscape(
false), TBAAVerifyHelper(this) {
219 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
222 bool hasBrokenDebugInfo()
const {
return BrokenDebugInfo; }
224 bool verify(
const Function &
F) {
225 llvm::TimeTraceScope timeScope(
"Verifier");
227 "An instance of this class only works with a specific module!");
237 for (
const BasicBlock &BB :
F) {
238 if (!BB.empty() && BB.back().isTerminator())
242 *OS <<
"Basic Block in function '" <<
F.getName()
243 <<
"' does not have terminator!\n";
244 BB.printAsOperand(*OS,
true, MST);
252 DT.recalculate(
const_cast<Function &
>(
F));
254 auto FailureCB = [
this](
const Twine &Message) {
255 this->CheckFailed(Message);
257 ConvergenceVerifyHelper.initialize(OS, FailureCB,
F);
262 verifySiblingFuncletUnwinds();
264 if (ConvergenceVerifyHelper.sawTokens())
265 ConvergenceVerifyHelper.verify(DT);
267 InstsInThisBlock.clear();
269 LandingPadResultTy =
nullptr;
270 SawFrameEscape =
false;
271 SiblingFuncletInfo.clear();
272 verifyNoAliasScopeDecl();
273 NoAliasScopeDecls.clear();
283 for (
const Function &
F : M)
284 if (
F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
285 DeoptimizeDeclarations.push_back(&
F);
289 verifyFrameRecoverIndices();
290 for (
const GlobalVariable &GV :
M.globals())
291 visitGlobalVariable(GV);
293 for (
const GlobalAlias &GA :
M.aliases())
294 visitGlobalAlias(GA);
296 for (
const GlobalIFunc &GI :
M.ifuncs())
297 visitGlobalIFunc(GI);
299 for (
const NamedMDNode &NMD :
M.named_metadata())
300 visitNamedMDNode(NMD);
302 for (
const StringMapEntry<Comdat> &SMEC :
M.getComdatSymbolTable())
303 visitComdat(SMEC.getValue());
307 visitModuleCommandLines();
308 visitModuleErrnoTBAA();
310 verifyCompileUnits();
312 verifyDeoptimizeCallingConvs();
313 DISubprogramAttachments.clear();
319 enum class AreDebugLocsAllowed {
No,
Yes };
323 enum class RangeLikeMetadataKind {
330 void visitGlobalValue(
const GlobalValue &GV);
331 void visitGlobalVariable(
const GlobalVariable &GV);
332 void visitGlobalAlias(
const GlobalAlias &GA);
333 void visitGlobalIFunc(
const GlobalIFunc &GI);
334 void visitAliaseeSubExpr(
const GlobalAlias &
A,
const Constant &
C);
335 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
336 const GlobalAlias &
A,
const Constant &
C);
337 void visitNamedMDNode(
const NamedMDNode &NMD);
338 void visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs);
339 void visitMetadataAsValue(
const MetadataAsValue &MD, Function *
F);
340 void visitValueAsMetadata(
const ValueAsMetadata &MD, Function *
F);
341 void visitDIArgList(
const DIArgList &AL, Function *
F);
342 void visitComdat(
const Comdat &
C);
343 void visitModuleIdents();
344 void visitModuleCommandLines();
345 void visitModuleErrnoTBAA();
346 void visitModuleFlags();
347 void visitModuleFlag(
const MDNode *
Op,
348 DenseMap<const MDString *, const MDNode *> &SeenIDs,
349 SmallVectorImpl<const MDNode *> &Requirements);
350 void visitModuleFlagCGProfileEntry(
const MDOperand &MDO);
351 void visitFunction(
const Function &
F);
352 void visitBasicBlock(BasicBlock &BB);
353 void verifyRangeLikeMetadata(
const Value &V,
const MDNode *
Range,
Type *Ty,
354 RangeLikeMetadataKind Kind);
355 void visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
356 void visitNoFPClassMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
357 void visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
358 void visitDereferenceableMetadata(Instruction &
I, MDNode *MD);
359 void visitNofreeMetadata(Instruction &
I, MDNode *MD);
360 void visitProfMetadata(Instruction &
I, MDNode *MD);
361 void visitCallStackMetadata(MDNode *MD);
362 void visitMemProfMetadata(Instruction &
I, MDNode *MD);
363 void visitCallsiteMetadata(Instruction &
I, MDNode *MD);
364 void visitCalleeTypeMetadata(Instruction &
I, MDNode *MD);
365 void visitDIAssignIDMetadata(Instruction &
I, MDNode *MD);
366 void visitMMRAMetadata(Instruction &
I, MDNode *MD);
367 void visitAnnotationMetadata(MDNode *Annotation);
368 void visitAliasScopeMetadata(
const MDNode *MD);
369 void visitAliasScopeListMetadata(
const MDNode *MD);
370 void visitAccessGroupMetadata(
const MDNode *MD);
371 void visitCapturesMetadata(Instruction &
I,
const MDNode *Captures);
372 void visitAllocTokenMetadata(Instruction &
I, MDNode *MD);
373 void visitInlineHistoryMetadata(Instruction &
I, MDNode *MD);
374 void visitMemCacheHintMetadata(Instruction &
I, MDNode *MD);
376#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
377#include "llvm/IR/Metadata.def"
378 void visitDIType(
const DIType &
N);
379 void visitDIScope(
const DIScope &
N);
403 void checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V);
408 void visitPHINode(
PHINode &PN);
417 void visitVAArgInst(
VAArgInst &VAA) { visitInstruction(VAA); }
418 void visitCallInst(CallInst &CI);
419 void visitInvokeInst(InvokeInst &
II);
420 void visitGetElementPtrInst(GetElementPtrInst &
GEP);
421 void visitLoadInst(LoadInst &LI);
422 void visitStoreInst(StoreInst &SI);
423 void verifyDominatesUse(Instruction &
I,
unsigned i);
424 void visitInstruction(Instruction &
I);
425 void visitTerminator(Instruction &
I);
426 void visitCondBrInst(CondBrInst &BI);
427 void visitReturnInst(ReturnInst &RI);
428 void visitSwitchInst(SwitchInst &SI);
429 void visitIndirectBrInst(IndirectBrInst &BI);
430 void visitCallBrInst(CallBrInst &CBI);
431 void visitSelectInst(SelectInst &SI);
432 void visitUserOp1(Instruction &
I);
433 void visitUserOp2(Instruction &
I) { visitUserOp1(
I); }
435 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
436 void visitVPIntrinsic(VPIntrinsic &VPI);
437 void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
438 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
439 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
440 void visitFenceInst(FenceInst &FI);
441 void visitAllocaInst(AllocaInst &AI);
442 void visitExtractValueInst(ExtractValueInst &EVI);
443 void visitInsertValueInst(InsertValueInst &IVI);
444 void visitEHPadPredecessors(Instruction &
I);
445 void visitLandingPadInst(LandingPadInst &LPI);
446 void visitResumeInst(ResumeInst &RI);
447 void visitCatchPadInst(CatchPadInst &CPI);
448 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
449 void visitCleanupPadInst(CleanupPadInst &CPI);
450 void visitFuncletPadInst(FuncletPadInst &FPI);
451 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
452 void visitCleanupReturnInst(CleanupReturnInst &CRI);
454 void verifySwiftErrorCall(CallBase &
Call,
const Value *SwiftErrorVal);
455 void verifySwiftErrorValue(
const Value *SwiftErrorVal);
456 void verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs, StringRef
Context);
457 void verifyMustTailCall(CallInst &CI);
458 bool verifyAttributeCount(AttributeList Attrs,
unsigned Params);
459 void verifyAttributeTypes(AttributeSet Attrs,
const Value *V);
460 void verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
const Value *V);
461 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
463 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
464 const Value *V,
bool IsIntrinsic,
bool IsInlineAsm);
465 void verifyFunctionMetadata(
ArrayRef<std::pair<unsigned, MDNode *>> MDs);
466 void verifyUnknownProfileMetadata(MDNode *MD);
467 void visitConstantExprsRecursively(
const Constant *EntryC);
468 void visitConstantExpr(
const ConstantExpr *CE);
469 void visitConstantPtrAuth(
const ConstantPtrAuth *CPA);
470 void verifyInlineAsmCall(
const CallBase &
Call);
471 void verifyStatepoint(
const CallBase &
Call);
472 void verifyFrameRecoverIndices();
473 void verifySiblingFuncletUnwinds();
475 void verifyFragmentExpression(
const DbgVariableRecord &
I);
476 template <
typename ValueOrMetadata>
477 void verifyFragmentExpression(
const DIVariable &V,
479 ValueOrMetadata *
Desc);
480 void verifyFnArgs(
const DbgVariableRecord &DVR);
481 void verifyNotEntryValue(
const DbgVariableRecord &
I);
484 void verifyCompileUnits();
488 void verifyDeoptimizeCallingConvs();
490 void verifyAttachedCallBundle(
const CallBase &
Call,
491 const OperandBundleUse &BU);
494 void verifyNoAliasScopeDecl();
500#define Check(C, ...) \
503 CheckFailed(__VA_ARGS__); \
510#define CheckDI(C, ...) \
513 DebugInfoCheckFailed(__VA_ARGS__); \
521 CheckDI(
I.DebugMarker->MarkedInstr == &
I,
522 "Instruction has invalid DebugMarker", &
I);
524 "PHI Node must not have any attached DbgRecords", &
I);
526 CheckDI(DR.getMarker() ==
I.DebugMarker,
527 "DbgRecord had invalid DebugMarker", &
I, &DR);
530 visitMDNode(*
Loc, AreDebugLocsAllowed::Yes);
535 verifyFragmentExpression(*DVR);
536 verifyNotEntryValue(*DVR);
543void Verifier::visit(Instruction &
I) {
545 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i)
546 Check(
I.getOperand(i) !=
nullptr,
"Operand is null", &
I);
558 while (!WorkList.
empty()) {
560 if (!Visited.
insert(Cur).second)
567void Verifier::visitGlobalValue(
const GlobalValue &GV) {
569 "Global is external, but doesn't have external or weak linkage!", &GV);
572 if (
const MDNode *Associated =
573 GO->getMetadata(LLVMContext::MD_associated)) {
574 Check(Associated->getNumOperands() == 1,
575 "associated metadata must have one operand", &GV, Associated);
576 const Metadata *
Op = Associated->getOperand(0).get();
577 Check(
Op,
"associated metadata must have a global value", GO, Associated);
580 Check(VM,
"associated metadata must be ValueAsMetadata", GO, Associated);
583 "associated value must be pointer typed", GV, Associated);
585 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
587 "associated metadata must point to a GlobalObject", GO, Stripped);
588 Check(Stripped != GO,
589 "global values should not associate to themselves", GO,
595 if (
const MDNode *AbsoluteSymbol =
596 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
597 verifyRangeLikeMetadata(*GO, AbsoluteSymbol,
598 DL.getIntPtrType(GO->getType()),
599 RangeLikeMetadataKind::AbsoluteSymbol);
602 if (GO->hasMetadata(LLVMContext::MD_implicit_ref)) {
603 Check(!GO->isDeclaration(),
604 "ref metadata must not be placed on a declaration", GO);
607 GO->getMetadata(LLVMContext::MD_implicit_ref, MDs);
608 for (
const MDNode *MD : MDs) {
609 Check(MD->getNumOperands() == 1,
"ref metadata must have one operand",
613 Check(VM,
"ref metadata must be ValueAsMetadata", GO, MD);
616 "ref value must be pointer typed", GV, MD);
620 "ref metadata must point to a GlobalObject", GO, Stripped);
621 Check(Stripped != GO,
"values should not reference themselves", GO,
627 if (
auto *Props = GO->getMetadata(LLVMContext::MD_elf_section_properties)) {
628 Check(Props->getNumOperands() == 2,
629 "elf_section_properties metadata must have two operands", GO,
631 if (Props->getNumOperands() == 2) {
633 Check(
Type,
"type field must be ConstantAsMetadata", GO, Props);
635 Check(TypeInt,
"type field must be ConstantInt", GO, Props);
638 Check(Entsize,
"entsize field must be ConstantAsMetadata", GO, Props);
640 Check(EntsizeInt,
"entsize field must be ConstantInt", GO, Props);
646 "Only global variables can have appending linkage!", &GV);
651 "Only global arrays can have appending linkage!", GVar);
655 Check(!GV.
hasComdat(),
"Declaration may not be in a Comdat!", &GV);
659 "dllexport GlobalValue must have default or protected visibility",
664 "dllimport GlobalValue must have default visibility", &GV);
665 Check(!GV.
isDSOLocal(),
"GlobalValue with DLLImport Storage is dso_local!",
671 "Global is marked as dllimport, but not external", &GV);
676 "GlobalValue with local linkage or non-default "
677 "visibility must be dso_local!",
682 if (!
I->getParent() || !
I->getParent()->getParent())
683 CheckFailed(
"Global is referenced by parentless instruction!", &GV, &M,
685 else if (
I->getParent()->getParent()->getParent() != &M)
686 CheckFailed(
"Global is referenced in a different module!", &GV, &M,
I,
687 I->getParent()->getParent(),
688 I->getParent()->getParent()->getParent());
691 if (
F->getParent() != &M)
692 CheckFailed(
"Global is used by function in a different module", &GV, &M,
700void Verifier::visitGlobalVariable(
const GlobalVariable &GV) {
704 Check(
A->value() <= Value::MaximumAlignment,
705 "huge alignment values are unsupported", &GV);
710 "Global variable initializer type does not match global "
714 "Global variable initializer must be sized", &GV);
720 "'common' global must have a zero initializer!", &GV);
723 Check(!GV.
hasComdat(),
"'common' global may not be in a Comdat!", &GV);
728 GV.
getName() ==
"llvm.global_dtors")) {
730 "invalid linkage for intrinsic global variable", &GV);
732 "invalid uses of intrinsic global variable", &GV);
739 PointerType::get(
Context,
DL.getProgramAddressSpace());
743 "wrong type for intrinsic global variable", &GV);
745 "the third field of the element type is mandatory, "
746 "specify ptr null to migrate from the obsoleted 2-field form");
754 GV.
getName() ==
"llvm.compiler.used")) {
756 "invalid linkage for intrinsic global variable", &GV);
758 "invalid uses of intrinsic global variable", &GV);
762 Check(PTy,
"wrong type for intrinsic global variable", &GV);
766 Check(InitArray,
"wrong initializer for intrinsic global variable",
772 Twine(
"invalid ") + GV.
getName() +
" member", V);
774 Twine(
"members of ") + GV.
getName() +
" must be named", V);
783 for (
auto *MD : MDs) {
785 visitDIGlobalVariableExpression(*GVE);
787 CheckDI(
false,
"!dbg attachment of global variable must be a "
788 "DIGlobalVariableExpression");
798 "Global @" + GV.
getName() +
" has illegal target extension type",
807 "Global variable is too large to fit into the address space", &GV,
811 visitGlobalValue(GV);
818 visitGlobalValue(GV);
821void Verifier::visitAliaseeSubExpr(
const GlobalAlias &GA,
const Constant &
C) {
822 SmallPtrSet<const GlobalAlias*, 4> Visited;
824 visitAliaseeSubExpr(Visited, GA,
C);
827void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
828 const GlobalAlias &GA,
const Constant &
C) {
832 "available_externally alias must point to available_externally "
843 Check(Visited.
insert(GA2).second,
"Aliases cannot form a cycle", &GA);
845 Check(!GA2->isInterposable(),
846 "Alias cannot point to an interposable alias", &GA);
855 visitConstantExprsRecursively(CE);
857 for (
const Use &U :
C.operands()) {
860 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
862 visitAliaseeSubExpr(Visited, GA, *C2);
866void Verifier::visitGlobalAlias(
const GlobalAlias &GA) {
868 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
869 "weak_odr, external, or available_externally linkage!",
872 Check(Aliasee,
"Aliasee cannot be NULL!", &GA);
874 "Alias and aliasee types should match!", &GA);
877 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
879 visitAliaseeSubExpr(GA, *Aliasee);
881 visitGlobalValue(GA);
884void Verifier::visitGlobalIFunc(
const GlobalIFunc &GI) {
885 visitGlobalValue(GI);
889 for (
const auto &
I : MDs) {
890 CheckDI(
I.first != LLVMContext::MD_dbg,
891 "an ifunc may not have a !dbg attachment", &GI);
892 Check(
I.first != LLVMContext::MD_prof,
893 "an ifunc may not have a !prof attachment", &GI);
894 visitMDNode(*
I.second, AreDebugLocsAllowed::No);
898 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
899 "weak_odr, or external linkage!",
904 Check(Resolver,
"IFunc must have a Function resolver", &GI);
906 "IFunc resolver must be a definition", &GI);
913 "IFunc resolver must return a pointer", &GI);
916 "IFunc resolver has incorrect type", &GI);
919void Verifier::visitNamedMDNode(
const NamedMDNode &NMD) {
924 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
925 for (
const MDNode *MD : NMD.
operands()) {
926 if (NMD.
getName() ==
"llvm.dbg.cu")
932 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
936void Verifier::visitMDNode(
const MDNode &BaseMD,
937 AreDebugLocsAllowed AllowLocs) {
940 if (!MDNodes.
insert(&BaseMD).second)
943 std::queue<const MDNode *> Worklist;
944 Worklist.push(&BaseMD);
946 while (!Worklist.empty()) {
947 const MDNode *CurrentMD = Worklist.front();
950 "MDNode context does not match Module context!", CurrentMD);
955 case Metadata::MDTupleKind:
957#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
958 case Metadata::CLASS##Kind: \
959 visit##CLASS(cast<CLASS>(*CurrentMD)); \
961#include "llvm/IR/Metadata.def"
970 "DILocation not allowed within this metadata node", CurrentMD,
978 visitValueAsMetadata(*V,
nullptr);
992 "Expected second operand to be an integer constant of type i32 or "
1000 Check(CurrentMD->
isResolved(),
"All nodes should be resolved!", CurrentMD);
1004void Verifier::visitValueAsMetadata(
const ValueAsMetadata &MD, Function *
F) {
1007 "Unexpected metadata round-trip through values", &MD, MD.
getValue());
1013 Check(
F,
"function-local metadata used outside a function", L);
1019 Check(
I->getParent(),
"function-local metadata not in basic block", L,
I);
1025 assert(ActualF &&
"Unimplemented function local metadata case!");
1027 Check(ActualF ==
F,
"function-local metadata used in wrong function", L);
1030void Verifier::visitDIArgList(
const DIArgList &AL, Function *
F) {
1031 for (
const ValueAsMetadata *VAM :
AL.getArgs())
1032 visitValueAsMetadata(*VAM,
F);
1035void Verifier::visitMetadataAsValue(
const MetadataAsValue &MDV, Function *
F) {
1038 visitMDNode(*
N, AreDebugLocsAllowed::No);
1044 if (!MDNodes.
insert(MD).second)
1048 visitValueAsMetadata(*V,
F);
1051 visitDIArgList(*AL,
F);
1059void Verifier::visitDILocation(
const DILocation &
N) {
1061 "location requires a valid scope", &
N,
N.getRawScope());
1062 if (
auto *IA =
N.getRawInlinedAt())
1065 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1068void Verifier::visitGenericDINode(
const GenericDINode &
N) {
1072void Verifier::visitDIScope(
const DIScope &
N) {
1073 if (
auto *
F =
N.getRawFile())
1077void Verifier::visitDIType(
const DIType &
N) {
1080 CheckDI(
N.getRawFile() ||
N.getLine() == 0,
"line specified with no file", &
N,
1084void Verifier::visitDISubrangeType(
const DISubrangeType &
N) {
1087 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1090 auto *LBound =
N.getRawLowerBound();
1094 "LowerBound must be signed constant or DIVariable or DIExpression or "
1097 auto *UBound =
N.getRawUpperBound();
1101 "UpperBound must be signed constant or DIVariable or DIExpression or "
1104 auto *Stride =
N.getRawStride();
1107 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1108 auto *Bias =
N.getRawBias();
1111 "Bias must be signed constant or DIVariable or DIExpression", &
N);
1113 auto *
Size =
N.getRawSizeInBits();
1115 "SizeInBits must be a constant");
1118void Verifier::visitDISubrange(
const DISubrange &
N) {
1119 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1120 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1121 "Subrange can have any one of count or upperBound", &
N);
1122 auto *CBound =
N.getRawCountNode();
1125 "Count must be signed constant or DIVariable or DIExpression", &
N);
1126 auto Count =
N.getCount();
1129 "invalid subrange count", &
N);
1130 auto *LBound =
N.getRawLowerBound();
1133 "LowerBound must be signed constant or DIVariable or DIExpression",
1135 auto *UBound =
N.getRawUpperBound();
1138 "UpperBound must be signed constant or DIVariable or DIExpression",
1140 auto *Stride =
N.getRawStride();
1143 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1146void Verifier::visitDIGenericSubrange(
const DIGenericSubrange &
N) {
1147 CheckDI(
N.getTag() == dwarf::DW_TAG_generic_subrange,
"invalid tag", &
N);
1148 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1149 "GenericSubrange can have any one of count or upperBound", &
N);
1150 auto *CBound =
N.getRawCountNode();
1152 "Count must be signed constant or DIVariable or DIExpression", &
N);
1153 auto *LBound =
N.getRawLowerBound();
1154 CheckDI(LBound,
"GenericSubrange must contain lowerBound", &
N);
1156 "LowerBound must be signed constant or DIVariable or DIExpression",
1158 auto *UBound =
N.getRawUpperBound();
1160 "UpperBound must be signed constant or DIVariable or DIExpression",
1162 auto *Stride =
N.getRawStride();
1163 CheckDI(Stride,
"GenericSubrange must contain stride", &
N);
1165 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1168void Verifier::visitDIEnumerator(
const DIEnumerator &
N) {
1169 CheckDI(
N.getTag() == dwarf::DW_TAG_enumerator,
"invalid tag", &
N);
1172void Verifier::visitDIBasicType(
const DIBasicType &
N) {
1175 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type ||
1176 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1177 N.getTag() == dwarf::DW_TAG_string_type,
1180 auto *
Size =
N.getRawSizeInBits();
1182 "SizeInBits must be a constant");
1185void Verifier::visitDIFixedPointType(
const DIFixedPointType &
N) {
1186 visitDIBasicType(
N);
1188 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type,
"invalid tag", &
N);
1189 CheckDI(
N.getEncoding() == dwarf::DW_ATE_signed_fixed ||
1190 N.getEncoding() == dwarf::DW_ATE_unsigned_fixed,
1191 "invalid encoding", &
N);
1195 "invalid kind", &
N);
1197 N.getFactorRaw() == 0,
1198 "factor should be 0 for rationals", &
N);
1200 (
N.getNumeratorRaw() == 0 &&
N.getDenominatorRaw() == 0),
1201 "numerator and denominator should be 0 for non-rationals", &
N);
1204void Verifier::visitDIStringType(
const DIStringType &
N) {
1207 CheckDI(
N.getTag() == dwarf::DW_TAG_string_type,
"invalid tag", &
N);
1208 CheckDI(!(
N.isBigEndian() &&
N.isLittleEndian()),
"has conflicting flags",
1212void Verifier::visitDIDerivedType(
const DIDerivedType &
N) {
1216 CheckDI(
N.getTag() == dwarf::DW_TAG_typedef ||
1217 N.getTag() == dwarf::DW_TAG_pointer_type ||
1218 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1219 N.getTag() == dwarf::DW_TAG_reference_type ||
1220 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1221 N.getTag() == dwarf::DW_TAG_const_type ||
1222 N.getTag() == dwarf::DW_TAG_immutable_type ||
1223 N.getTag() == dwarf::DW_TAG_volatile_type ||
1224 N.getTag() == dwarf::DW_TAG_restrict_type ||
1225 N.getTag() == dwarf::DW_TAG_atomic_type ||
1226 N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
1227 N.getTag() == dwarf::DW_TAG_member ||
1228 (
N.getTag() == dwarf::DW_TAG_variable &&
N.isStaticMember()) ||
1229 N.getTag() == dwarf::DW_TAG_inheritance ||
1230 N.getTag() == dwarf::DW_TAG_friend ||
1231 N.getTag() == dwarf::DW_TAG_set_type ||
1232 N.getTag() == dwarf::DW_TAG_template_alias,
1234 if (
N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1235 CheckDI(
isType(
N.getRawExtraData()),
"invalid pointer to member type", &
N,
1236 N.getRawExtraData());
1237 }
else if (
N.getTag() == dwarf::DW_TAG_template_alias) {
1239 N.getRawExtraData());
1240 }
else if (
N.getTag() == dwarf::DW_TAG_inheritance ||
1241 N.getTag() == dwarf::DW_TAG_member ||
1242 N.getTag() == dwarf::DW_TAG_variable) {
1243 auto *ExtraData =
N.getRawExtraData();
1244 auto IsValidExtraData = [&]() {
1245 if (ExtraData ==
nullptr)
1251 if (Tuple->getNumOperands() != 1)
1258 "extraData must be ConstantAsMetadata, MDString, DIObjCProperty, "
1259 "or MDTuple with single ConstantAsMetadata operand",
1263 if (
N.getTag() == dwarf::DW_TAG_set_type) {
1264 if (
auto *
T =
N.getRawBaseType()) {
1269 (Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1270 (Subrange &&
Subrange->getTag() == dwarf::DW_TAG_subrange_type) ||
1271 (
Basic && (
Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1272 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1273 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1274 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1275 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1276 "invalid set base type", &
N,
T);
1281 N.getRawBaseType());
1283 if (
N.getDWARFAddressSpace()) {
1284 CheckDI(
N.getTag() == dwarf::DW_TAG_pointer_type ||
1285 N.getTag() == dwarf::DW_TAG_reference_type ||
1286 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1287 "DWARF address space only applies to pointer or reference types",
1291 auto *
Size =
N.getRawSizeInBits();
1294 "SizeInBits must be a constant or DIVariable or DIExpression");
1299 return ((Flags & DINode::FlagLValueReference) &&
1300 (Flags & DINode::FlagRValueReference)) ||
1301 ((Flags & DINode::FlagTypePassByValue) &&
1302 (Flags & DINode::FlagTypePassByReference));
1305void Verifier::visitTemplateParams(
const MDNode &
N,
const Metadata &RawParams) {
1307 CheckDI(Params,
"invalid template params", &
N, &RawParams);
1314void Verifier::visitDICompositeType(
const DICompositeType &
N) {
1318 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type ||
1319 N.getTag() == dwarf::DW_TAG_structure_type ||
1320 N.getTag() == dwarf::DW_TAG_union_type ||
1321 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1322 N.getTag() == dwarf::DW_TAG_class_type ||
1323 N.getTag() == dwarf::DW_TAG_variant_part ||
1324 N.getTag() == dwarf::DW_TAG_variant ||
1325 N.getTag() == dwarf::DW_TAG_namelist,
1329 N.getRawBaseType());
1332 "invalid composite elements", &
N,
N.getRawElements());
1334 N.getRawVTableHolder());
1336 "invalid reference flags", &
N);
1337 unsigned DIBlockByRefStruct = 1 << 4;
1338 CheckDI((
N.getFlags() & DIBlockByRefStruct) == 0,
1339 "DIBlockByRefStruct on DICompositeType is no longer supported", &
N);
1341 "DISubprogram contains null entry in `elements` field", &
N);
1344 const DINodeArray
Elements =
N.getElements();
1346 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1347 "invalid vector, expected one element of type subrange", &
N);
1350 if (
auto *Params =
N.getRawTemplateParams())
1351 visitTemplateParams(
N, *Params);
1353 if (
auto *
D =
N.getRawDiscriminator()) {
1355 "discriminator can only appear on variant part");
1358 if (
N.getRawDataLocation()) {
1359 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1360 "dataLocation can only appear in array type");
1363 if (
N.getRawAssociated()) {
1364 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1365 "associated can only appear in array type");
1368 if (
N.getRawAllocated()) {
1369 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1370 "allocated can only appear in array type");
1373 if (
N.getRawRank()) {
1374 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1375 "rank can only appear in array type");
1378 if (
N.getTag() == dwarf::DW_TAG_array_type) {
1379 CheckDI(
N.getRawBaseType(),
"array types must have a base type", &
N);
1382 auto *
Size =
N.getRawSizeInBits();
1385 "SizeInBits must be a constant or DIVariable or DIExpression");
1388void Verifier::visitDISubroutineType(
const DISubroutineType &
N) {
1390 CheckDI(
N.getTag() == dwarf::DW_TAG_subroutine_type,
"invalid tag", &
N);
1391 if (
auto *Types =
N.getRawTypeArray()) {
1393 for (
Metadata *Ty :
N.getTypeArray()->operands()) {
1394 CheckDI(
isType(Ty),
"invalid subroutine type ref", &
N, Types, Ty);
1398 "invalid reference flags", &
N);
1401void Verifier::visitDIFile(
const DIFile &
N) {
1402 CheckDI(
N.getTag() == dwarf::DW_TAG_file_type,
"invalid tag", &
N);
1403 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum =
N.getChecksum();
1405 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1406 "invalid checksum kind", &
N);
1408 switch (Checksum->Kind) {
1419 CheckDI(Checksum->Value.size() ==
Size,
"invalid checksum length", &
N);
1421 "invalid checksum", &
N);
1425void Verifier::visitDICompileUnit(
const DICompileUnit &
N) {
1426 CheckDI(
N.isDistinct(),
"compile units must be distinct", &
N);
1427 CheckDI(
N.getTag() == dwarf::DW_TAG_compile_unit,
"invalid tag", &
N);
1433 CheckDI(!
N.getFile()->getFilename().empty(),
"invalid filename", &
N,
1437 "invalid emission kind", &
N);
1440 "invalid language dialect", &
N);
1442 if (
auto *Array =
N.getRawEnumTypes()) {
1444 for (
Metadata *
Op :
N.getEnumTypes()->operands()) {
1446 CheckDI(Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1447 "invalid enum type", &
N,
N.getEnumTypes(),
Op);
1449 "function-local enum in a DICompileUnit's enum list", &
N,
1450 N.getEnumTypes(),
Op);
1453 if (
auto *Array =
N.getRawRetainedTypes()) {
1455 for (
Metadata *
Op :
N.getRetainedTypes()->operands()) {
1459 "invalid retained type", &
N,
Op);
1462 if (
auto *Array =
N.getRawGlobalVariables()) {
1464 for (
Metadata *
Op :
N.getGlobalVariables()->operands()) {
1466 "invalid global variable ref", &
N,
Op);
1469 if (
auto *Array =
N.getRawImportedEntities()) {
1471 for (
Metadata *
Op :
N.getImportedEntities()->operands()) {
1473 CheckDI(IE,
"invalid imported entity ref", &
N,
Op);
1475 "function-local imports are not allowed in a DICompileUnit's "
1476 "imported entities list",
1480 if (
auto *Array =
N.getRawMacros()) {
1489void Verifier::visitDISubprogram(
const DISubprogram &
N) {
1490 CheckDI(
N.getTag() == dwarf::DW_TAG_subprogram,
"invalid tag", &
N);
1492 if (
auto *
F =
N.getRawFile())
1495 CheckDI(
N.getLine() == 0,
"line specified with no file", &
N,
N.getLine());
1496 auto *
T =
N.getRawType();
1497 CheckDI(
T,
"DISubprogram requires a non-null type", &
N);
1499 CheckDI(
isType(
N.getRawContainingType()),
"invalid containing type", &
N,
1500 N.getRawContainingType());
1501 if (
auto *Params =
N.getRawTemplateParams())
1502 visitTemplateParams(
N, *Params);
1503 if (
auto *S =
N.getRawDeclaration())
1505 "invalid subprogram declaration", &
N, S);
1506 if (
auto *RawNode =
N.getRawRetainedNodes()) {
1508 CheckDI(Node,
"invalid retained nodes list", &
N, RawNode);
1510 DenseMap<unsigned, DILocalVariable *>
Args;
1512 CheckDI(
Op,
"nullptr in retained nodes", &
N, Node);
1514 auto True = [](
const Metadata *) {
return true; };
1515 auto False = [](
const Metadata *) {
return false; };
1516 bool IsTypeCorrect = DISubprogram::visitRetainedNode<bool>(
1517 Op, True, True, True, True, False);
1519 "invalid retained nodes, expected DILocalVariable, DILabel, "
1520 "DIImportedEntity or DIType",
1527 "invalid retained nodes, retained node is not local", &
N, Node,
1530 DISubprogram *RetainedNodeSP = RetainedNodeScope->getSubprogram();
1531 DICompileUnit *RetainedNodeUnit =
1532 RetainedNodeSP ? RetainedNodeSP->getUnit() :
nullptr;
1534 RetainedNodeSP == &
N,
1535 "invalid retained nodes, retained node does not belong to subprogram",
1536 &
N, Node, RetainedNode, RetainedNodeScope, RetainedNodeSP,
1542 if (
unsigned ArgNum = DV->getArg()) {
1544 CheckDI(Inserted || DV == ArgI->second,
1545 "invalid retained nodes, more than one local variable with the "
1546 "same argument index",
1547 &
N,
N.getUnit(), Node, RetainedNode, Args[ArgNum]);
1552 "invalid reference flags", &
N);
1554 auto *
Unit =
N.getRawUnit();
1555 if (
N.isDefinition()) {
1557 CheckDI(
N.isDistinct(),
"subprogram definitions must be distinct", &
N);
1558 CheckDI(Unit,
"subprogram definitions must have a compile unit", &
N);
1563 if (CT && CT->getRawIdentifier() &&
1564 M.getContext().isODRUniquingDebugTypes())
1566 "definition subprograms cannot be nested within DICompositeType "
1567 "when enabling ODR",
1571 CheckDI(!Unit,
"subprogram declarations must not have a compile unit", &
N);
1573 "subprogram declaration must not have a declaration field");
1576 if (
auto *RawThrownTypes =
N.getRawThrownTypes()) {
1578 CheckDI(ThrownTypes,
"invalid thrown types list", &
N, RawThrownTypes);
1584 if (
N.areAllCallsDescribed())
1586 "DIFlagAllCallsDescribed must be attached to a definition");
1589void Verifier::visitDILexicalBlockBase(
const DILexicalBlockBase &
N) {
1590 CheckDI(
N.getTag() == dwarf::DW_TAG_lexical_block,
"invalid tag", &
N);
1592 "invalid local scope", &
N,
N.getRawScope());
1594 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1597void Verifier::visitDILexicalBlock(
const DILexicalBlock &
N) {
1598 visitDILexicalBlockBase(
N);
1601 "cannot have column info without line info", &
N);
1604void Verifier::visitDILexicalBlockFile(
const DILexicalBlockFile &
N) {
1605 visitDILexicalBlockBase(
N);
1608void Verifier::visitDICommonBlock(
const DICommonBlock &
N) {
1609 CheckDI(
N.getTag() == dwarf::DW_TAG_common_block,
"invalid tag", &
N);
1610 if (
auto *S =
N.getRawScope())
1612 if (
auto *S =
N.getRawDecl())
1616void Verifier::visitDINamespace(
const DINamespace &
N) {
1617 CheckDI(
N.getTag() == dwarf::DW_TAG_namespace,
"invalid tag", &
N);
1618 if (
auto *S =
N.getRawScope())
1622void Verifier::visitDIMacro(
const DIMacro &
N) {
1625 "invalid macinfo type", &
N);
1626 CheckDI(!
N.getName().empty(),
"anonymous macro", &
N);
1627 if (!
N.getValue().empty()) {
1628 assert(
N.getValue().data()[0] !=
' ' &&
"Macro value has a space prefix");
1632void Verifier::visitDIMacroFile(
const DIMacroFile &
N) {
1634 "invalid macinfo type", &
N);
1635 if (
auto *
F =
N.getRawFile())
1638 if (
auto *Array =
N.getRawElements()) {
1640 for (
Metadata *
Op :
N.getElements()->operands()) {
1646void Verifier::visitDIModule(
const DIModule &
N) {
1647 CheckDI(
N.getTag() == dwarf::DW_TAG_module,
"invalid tag", &
N);
1648 CheckDI(!
N.getName().empty(),
"anonymous module", &
N);
1651void Verifier::visitDITemplateParameter(
const DITemplateParameter &
N) {
1655void Verifier::visitDITemplateTypeParameter(
const DITemplateTypeParameter &
N) {
1656 visitDITemplateParameter(
N);
1658 CheckDI(
N.getTag() == dwarf::DW_TAG_template_type_parameter,
"invalid tag",
1662void Verifier::visitDITemplateValueParameter(
1663 const DITemplateValueParameter &
N) {
1664 visitDITemplateParameter(
N);
1666 CheckDI(
N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1667 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1668 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1672void Verifier::visitDIVariable(
const DIVariable &
N) {
1673 if (
auto *S =
N.getRawScope())
1675 if (
auto *
F =
N.getRawFile())
1679void Verifier::visitDIGlobalVariable(
const DIGlobalVariable &
N) {
1683 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1686 if (
N.isDefinition())
1687 CheckDI(
N.getType(),
"missing global variable type", &
N);
1688 if (
auto *Member =
N.getRawStaticDataMemberDeclaration()) {
1690 "invalid static data member declaration", &
N, Member);
1694void Verifier::visitDILocalVariable(
const DILocalVariable &
N) {
1699 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1701 "local variable requires a valid scope", &
N,
N.getRawScope());
1702 if (
auto Ty =
N.getType())
1706void Verifier::visitDIAssignID(
const DIAssignID &
N) {
1707 CheckDI(!
N.getNumOperands(),
"DIAssignID has no arguments", &
N);
1708 CheckDI(
N.isDistinct(),
"DIAssignID must be distinct", &
N);
1711void Verifier::visitDILabel(
const DILabel &
N) {
1712 if (
auto *S =
N.getRawScope())
1714 if (
auto *
F =
N.getRawFile())
1717 CheckDI(
N.getTag() == dwarf::DW_TAG_label,
"invalid tag", &
N);
1719 "label requires a valid scope", &
N,
N.getRawScope());
1722void Verifier::visitDIExpression(
const DIExpression &
N) {
1723 CheckDI(
N.isValid(),
"invalid expression", &
N);
1726void Verifier::visitDIGlobalVariableExpression(
1727 const DIGlobalVariableExpression &GVE) {
1730 visitDIGlobalVariable(*Var);
1732 visitDIExpression(*Expr);
1733 if (
auto Fragment = Expr->getFragmentInfo())
1734 verifyFragmentExpression(*GVE.
getVariable(), *Fragment, &GVE);
1738void Verifier::visitDIObjCProperty(
const DIObjCProperty &
N) {
1739 CheckDI(
N.getTag() == dwarf::DW_TAG_APPLE_property,
"invalid tag", &
N);
1740 if (
auto *
T =
N.getRawType())
1742 if (
auto *
F =
N.getRawFile())
1746void Verifier::visitDIImportedEntity(
const DIImportedEntity &
N) {
1747 CheckDI(
N.getTag() == dwarf::DW_TAG_imported_module ||
1748 N.getTag() == dwarf::DW_TAG_imported_declaration,
1750 if (
auto *S =
N.getRawScope())
1756void Verifier::visitComdat(
const Comdat &
C) {
1759 if (
TT.isOSBinFormatCOFF())
1760 if (
const GlobalValue *GV =
M.getNamedValue(
C.getName()))
1765void Verifier::visitModuleIdents() {
1766 const NamedMDNode *Idents =
M.getNamedMetadata(
"llvm.ident");
1772 for (
const MDNode *
N : Idents->
operands()) {
1773 Check(
N->getNumOperands() == 1,
1774 "incorrect number of operands in llvm.ident metadata",
N);
1776 (
"invalid value for llvm.ident metadata entry operand"
1777 "(the operand should be a string)"),
1782void Verifier::visitModuleCommandLines() {
1783 const NamedMDNode *CommandLines =
M.getNamedMetadata(
"llvm.commandline");
1790 for (
const MDNode *
N : CommandLines->
operands()) {
1791 Check(
N->getNumOperands() == 1,
1792 "incorrect number of operands in llvm.commandline metadata",
N);
1794 (
"invalid value for llvm.commandline metadata entry operand"
1795 "(the operand should be a string)"),
1800void Verifier::visitModuleErrnoTBAA() {
1801 const NamedMDNode *ErrnoTBAA =
M.getNamedMetadata(
"llvm.errno.tbaa");
1806 "llvm.errno.tbaa must have at least one operand", ErrnoTBAA);
1808 for (
const MDNode *
N : ErrnoTBAA->
operands())
1812void Verifier::visitModuleFlags() {
1813 const NamedMDNode *
Flags =
M.getModuleFlagsMetadata();
1817 DenseMap<const MDString*, const MDNode*> SeenIDs;
1819 uint64_t PAuthABIPlatform = -1;
1820 uint64_t PAuthABIVersion = -1;
1821 for (
const MDNode *MDN :
Flags->operands()) {
1822 visitModuleFlag(MDN, SeenIDs, Requirements);
1823 if (MDN->getNumOperands() != 3)
1826 if (FlagName->getString() ==
"aarch64-elf-pauthabi-platform") {
1827 if (
const auto *PAP =
1829 PAuthABIPlatform = PAP->getZExtValue();
1830 }
else if (FlagName->getString() ==
"aarch64-elf-pauthabi-version") {
1831 if (
const auto *PAV =
1833 PAuthABIVersion = PAV->getZExtValue();
1838 if ((PAuthABIPlatform == uint64_t(-1)) != (PAuthABIVersion == uint64_t(-1)))
1839 CheckFailed(
"either both or no 'aarch64-elf-pauthabi-platform' and "
1840 "'aarch64-elf-pauthabi-version' module flags must be present");
1843 for (
const MDNode *Requirement : Requirements) {
1845 const Metadata *ReqValue = Requirement->getOperand(1);
1847 const MDNode *
Op = SeenIDs.
lookup(Flag);
1849 CheckFailed(
"invalid requirement on flag, flag is not present in module",
1854 if (
Op->getOperand(2) != ReqValue) {
1855 CheckFailed((
"invalid requirement on flag, "
1856 "flag does not have the required value"),
1864Verifier::visitModuleFlag(
const MDNode *
Op,
1865 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1866 SmallVectorImpl<const MDNode *> &Requirements) {
1870 "incorrect number of operands in module flag",
Op);
1871 Module::ModFlagBehavior MFB;
1872 if (!Module::isValidModFlagBehavior(
Op->getOperand(0), MFB)) {
1874 "invalid behavior operand in module flag (expected constant integer)",
1877 "invalid behavior operand in module flag (unexpected constant)",
1881 Check(
ID,
"invalid ID operand in module flag (expected metadata string)",
1887 case Module::Warning:
1888 case Module::Override:
1894 Check(V &&
V->getValue().isNonNegative(),
1895 "invalid value for 'min' module flag (expected constant non-negative "
1903 "invalid value for 'max' module flag (expected constant integer)",
1908 case Module::Require: {
1913 "invalid value for 'require' module flag (expected metadata pair)",
1916 (
"invalid value for 'require' module flag "
1917 "(first value operand should be a string)"),
1918 Value->getOperand(0));
1926 case Module::Append:
1927 case Module::AppendUnique: {
1930 "invalid value for 'append'-type module flag "
1931 "(expected a metadata node)",
1938 if (MFB != Module::Require) {
1941 "module flag identifiers must be unique (or of 'require' type)",
ID);
1944 if (
ID->getString() ==
"wchar_size") {
1947 Check(
Value,
"wchar_size metadata requires constant integer argument");
1950 if (
ID->getString() ==
"Linker Options") {
1954 Check(
M.getNamedMetadata(
"llvm.linker.options"),
1955 "'Linker Options' named metadata no longer supported");
1958 if (
ID->getString() ==
"SemanticInterposition") {
1959 ConstantInt *
Value =
1962 "SemanticInterposition metadata requires constant integer argument");
1965 if (
ID->getString() ==
"CG Profile") {
1966 for (
const MDOperand &MDO :
cast<MDNode>(
Op->getOperand(2))->operands())
1967 visitModuleFlagCGProfileEntry(MDO);
1974void Verifier::visitModuleFlagCGProfileEntry(
const MDOperand &MDO) {
1975 auto CheckFunction = [&](
const MDOperand &FuncMDO) {
1980 "expected a Function or null", FuncMDO);
1983 Check(Node &&
Node->getNumOperands() == 3,
"expected a MDNode triple", MDO);
1984 CheckFunction(
Node->getOperand(0));
1985 CheckFunction(
Node->getOperand(1));
1988 "expected an integer constant",
Node->getOperand(2));
1991void Verifier::verifyAttributeTypes(AttributeSet Attrs,
const Value *V) {
1994 if (
A.isStringAttribute()) {
1995#define GET_ATTR_NAMES
1996#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1997#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
1998 if (A.getKindAsString() == #DISPLAY_NAME) { \
1999 auto V = A.getValueAsString(); \
2000 if (!(V.empty() || V == "true" || V == "false")) \
2001 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
2005#include "llvm/IR/Attributes.inc"
2009 if (
A.isIntAttribute() != Attribute::isIntAttrKind(
A.getKindAsEnum())) {
2010 CheckFailed(
"Attribute '" +
A.getAsString() +
"' should have an Argument",
2019void Verifier::verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
2021 if (!
Attrs.hasAttributes())
2024 verifyAttributeTypes(Attrs, V);
2027 Check(Attr.isStringAttribute() ||
2028 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
2029 "Attribute '" + Attr.getAsString() +
"' does not apply to parameters",
2032 if (
Attrs.hasAttribute(Attribute::ImmArg)) {
2033 unsigned AttrCount =
2034 Attrs.getNumAttributes() -
Attrs.hasAttribute(Attribute::Range);
2035 Check(AttrCount == 1,
2036 "Attribute 'immarg' is incompatible with other attributes except the "
2037 "'range' attribute",
2043 unsigned AttrCount = 0;
2044 AttrCount +=
Attrs.hasAttribute(Attribute::ByVal);
2045 AttrCount +=
Attrs.hasAttribute(Attribute::InAlloca);
2046 AttrCount +=
Attrs.hasAttribute(Attribute::Preallocated);
2047 AttrCount +=
Attrs.hasAttribute(Attribute::StructRet) ||
2048 Attrs.hasAttribute(Attribute::InReg);
2049 AttrCount +=
Attrs.hasAttribute(Attribute::Nest);
2050 AttrCount +=
Attrs.hasAttribute(Attribute::ByRef);
2051 Check(AttrCount <= 1,
2052 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
2053 "'byref', and 'sret' are incompatible!",
2056 Check(!(
Attrs.hasAttribute(Attribute::InAlloca) &&
2057 Attrs.hasAttribute(Attribute::ReadOnly)),
2059 "'inalloca and readonly' are incompatible!",
2062 Check(!(
Attrs.hasAttribute(Attribute::StructRet) &&
2063 Attrs.hasAttribute(Attribute::Returned)),
2065 "'sret and returned' are incompatible!",
2068 Check(!(
Attrs.hasAttribute(Attribute::ZExt) &&
2069 Attrs.hasAttribute(Attribute::SExt)),
2071 "'zeroext and signext' are incompatible!",
2074 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2075 Attrs.hasAttribute(Attribute::ReadOnly)),
2077 "'readnone and readonly' are incompatible!",
2080 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2081 Attrs.hasAttribute(Attribute::WriteOnly)),
2083 "'readnone and writeonly' are incompatible!",
2086 Check(!(
Attrs.hasAttribute(Attribute::ReadOnly) &&
2087 Attrs.hasAttribute(Attribute::WriteOnly)),
2089 "'readonly and writeonly' are incompatible!",
2092 Check(!(
Attrs.hasAttribute(Attribute::NoInline) &&
2093 Attrs.hasAttribute(Attribute::AlwaysInline)),
2095 "'noinline and alwaysinline' are incompatible!",
2098 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2099 Attrs.hasAttribute(Attribute::ReadNone)),
2100 "Attributes writable and readnone are incompatible!", V);
2102 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2103 Attrs.hasAttribute(Attribute::ReadOnly)),
2104 "Attributes writable and readonly are incompatible!", V);
2106 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty, Attrs);
2108 if (!Attr.isStringAttribute() &&
2109 IncompatibleAttrs.
contains(Attr.getKindAsEnum())) {
2110 CheckFailed(
"Attribute '" + Attr.getAsString() +
2111 "' applied to incompatible type!", V);
2117 if (
Attrs.hasAttribute(Attribute::Alignment)) {
2118 Align AttrAlign =
Attrs.getAlignment().valueOrOne();
2119 Check(AttrAlign.
value() <= Value::MaximumAlignment,
2120 "huge alignment values are unsupported", V);
2122 if (
Attrs.hasAttribute(Attribute::ByVal)) {
2124 SmallPtrSet<Type *, 4> Visited;
2126 "Attribute 'byval' does not support unsized types!", V);
2130 "'byval' argument has illegal target extension type", V);
2131 Check(
DL.getTypeAllocSize(ByValTy).getKnownMinValue() < (1ULL << 32),
2132 "huge 'byval' arguments are unsupported", V);
2134 if (
Attrs.hasAttribute(Attribute::ByRef)) {
2135 SmallPtrSet<Type *, 4> Visited;
2136 Check(
Attrs.getByRefType()->isSized(&Visited),
2137 "Attribute 'byref' does not support unsized types!", V);
2138 Check(
DL.getTypeAllocSize(
Attrs.getByRefType()).getKnownMinValue() <
2140 "huge 'byref' arguments are unsupported", V);
2142 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
2143 SmallPtrSet<Type *, 4> Visited;
2144 Check(
Attrs.getInAllocaType()->isSized(&Visited),
2145 "Attribute 'inalloca' does not support unsized types!", V);
2146 Check(
DL.getTypeAllocSize(
Attrs.getInAllocaType()).getKnownMinValue() <
2148 "huge 'inalloca' arguments are unsupported", V);
2150 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
2151 SmallPtrSet<Type *, 4> Visited;
2152 Check(
Attrs.getPreallocatedType()->isSized(&Visited),
2153 "Attribute 'preallocated' does not support unsized types!", V);
2155 DL.getTypeAllocSize(
Attrs.getPreallocatedType()).getKnownMinValue() <
2157 "huge 'preallocated' arguments are unsupported", V);
2161 if (
Attrs.hasAttribute(Attribute::Initializes)) {
2162 auto Inits =
Attrs.getAttribute(Attribute::Initializes).getInitializes();
2163 Check(!Inits.empty(),
"Attribute 'initializes' does not support empty list",
2166 "Attribute 'initializes' does not support unordered ranges", V);
2169 if (
Attrs.hasAttribute(Attribute::NoFPClass)) {
2170 uint64_t Val =
Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
2171 Check(Val != 0,
"Attribute 'nofpclass' must have at least one test bit set",
2174 "Invalid value for 'nofpclass' test mask", V);
2176 if (
Attrs.hasAttribute(Attribute::Range)) {
2177 const ConstantRange &CR =
2178 Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2180 "Range bit width must match type bit width!", V);
2184void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
2186 if (
Attrs.hasFnAttr(Attr)) {
2187 StringRef S =
Attrs.getFnAttr(Attr).getValueAsString();
2190 CheckFailed(
"\"" + Attr +
"\" takes an unsigned integer: " + S, V);
2196void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
2197 const Value *V,
bool IsIntrinsic,
2199 if (
Attrs.isEmpty())
2202 if (AttributeListsVisited.
insert(
Attrs.getRawPointer()).second) {
2204 "Attribute list does not match Module context!", &Attrs, V);
2205 for (
const auto &AttrSet : Attrs) {
2206 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(
Context),
2207 "Attribute set does not match Module context!", &AttrSet, V);
2208 for (
const auto &
A : AttrSet) {
2210 "Attribute does not match Module context!", &
A, V);
2215 bool SawNest =
false;
2216 bool SawReturned =
false;
2217 bool SawSRet =
false;
2218 bool SawSwiftSelf =
false;
2219 bool SawSwiftAsync =
false;
2220 bool SawSwiftError =
false;
2223 AttributeSet RetAttrs =
Attrs.getRetAttrs();
2226 Attribute::canUseAsRetAttr(
RetAttr.getKindAsEnum()),
2227 "Attribute '" +
RetAttr.getAsString() +
2228 "' does not apply to function return values",
2231 unsigned MaxParameterWidth = 0;
2232 auto GetMaxParameterWidth = [&MaxParameterWidth](
Type *Ty) {
2235 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2236 if (
Size > MaxParameterWidth)
2237 MaxParameterWidth =
Size;
2241 GetMaxParameterWidth(FT->getReturnType());
2242 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2245 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2246 Type *Ty = FT->getParamType(i);
2247 AttributeSet ArgAttrs =
Attrs.getParamAttrs(i);
2251 "immarg attribute only applies to intrinsics", V);
2254 "Attribute 'elementtype' can only be applied to intrinsics"
2259 verifyParameterAttrs(ArgAttrs, Ty, V);
2260 GetMaxParameterWidth(Ty);
2263 Check(!SawNest,
"More than one parameter has attribute nest!", V);
2268 Check(!SawReturned,
"More than one parameter has attribute returned!", V);
2270 "Incompatible argument and return types for 'returned' attribute",
2276 Check(!SawSRet,
"Cannot have multiple 'sret' parameters!", V);
2277 Check(i == 0 || i == 1,
2278 "Attribute 'sret' is not on first or second parameter!", V);
2283 Check(!SawSwiftSelf,
"Cannot have multiple 'swiftself' parameters!", V);
2284 SawSwiftSelf =
true;
2288 Check(!SawSwiftAsync,
"Cannot have multiple 'swiftasync' parameters!", V);
2289 SawSwiftAsync =
true;
2293 Check(!SawSwiftError,
"Cannot have multiple 'swifterror' parameters!", V);
2294 SawSwiftError =
true;
2298 Check(i == FT->getNumParams() - 1,
2299 "inalloca isn't on the last parameter!", V);
2303 if (!
Attrs.hasFnAttrs())
2306 verifyAttributeTypes(
Attrs.getFnAttrs(), V);
2309 Attribute::canUseAsFnAttr(
FnAttr.getKindAsEnum()),
2310 "Attribute '" +
FnAttr.getAsString() +
2311 "' does not apply to functions!",
2314 Check(!(
Attrs.hasFnAttr(Attribute::NoInline) &&
2315 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2316 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2318 if (
Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2320 "Attribute 'optnone' requires 'noinline'!", V);
2322 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2323 "Attributes 'optsize and optnone' are incompatible!", V);
2326 "Attributes 'minsize and optnone' are incompatible!", V);
2328 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
2329 "Attributes 'optdebug and optnone' are incompatible!", V);
2332 Check(!(
Attrs.hasFnAttr(Attribute::SanitizeRealtime) &&
2333 Attrs.hasFnAttr(Attribute::SanitizeRealtimeBlocking)),
2335 "'sanitize_realtime and sanitize_realtime_blocking' are incompatible!",
2338 if (
Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
2339 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2340 "Attributes 'optsize and optdebug' are incompatible!", V);
2343 "Attributes 'minsize and optdebug' are incompatible!", V);
2346 Check(!
Attrs.hasAttrSomewhere(Attribute::Writable) ||
2347 isModSet(
Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
2348 "Attribute writable and memory without argmem: write are incompatible!",
2351 if (
Attrs.hasFnAttr(
"aarch64_pstate_sm_enabled")) {
2352 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_sm_compatible"),
2353 "Attributes 'aarch64_pstate_sm_enabled and "
2354 "aarch64_pstate_sm_compatible' are incompatible!",
2358 Check((
Attrs.hasFnAttr(
"aarch64_new_za") +
Attrs.hasFnAttr(
"aarch64_in_za") +
2359 Attrs.hasFnAttr(
"aarch64_inout_za") +
2360 Attrs.hasFnAttr(
"aarch64_out_za") +
2361 Attrs.hasFnAttr(
"aarch64_preserves_za") +
2362 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2363 "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2364 "'aarch64_inout_za', 'aarch64_preserves_za' and "
2365 "'aarch64_za_state_agnostic' are mutually exclusive",
2369 Attrs.hasFnAttr(
"aarch64_in_zt0") +
2370 Attrs.hasFnAttr(
"aarch64_inout_zt0") +
2371 Attrs.hasFnAttr(
"aarch64_out_zt0") +
2372 Attrs.hasFnAttr(
"aarch64_preserves_zt0") +
2373 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2374 "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
2375 "'aarch64_inout_zt0', 'aarch64_preserves_zt0' and "
2376 "'aarch64_za_state_agnostic' are mutually exclusive",
2379 if (
Attrs.hasFnAttr(Attribute::JumpTable)) {
2382 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2385 if (
auto Args =
Attrs.getFnAttrs().getAllocSizeArgs()) {
2386 auto CheckParam = [&](StringRef
Name,
unsigned ParamNo) {
2387 if (ParamNo >= FT->getNumParams()) {
2388 CheckFailed(
"'allocsize' " + Name +
" argument is out of bounds", V);
2392 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2393 CheckFailed(
"'allocsize' " + Name +
2394 " argument must refer to an integer parameter",
2402 if (!CheckParam(
"element size",
Args->first))
2405 if (
Args->second && !CheckParam(
"number of elements", *
Args->second))
2409 if (
Attrs.hasFnAttr(Attribute::AllocKind)) {
2412 K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
2414 {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
2417 "'allockind()' requires exactly one of alloc, realloc, and free");
2418 if ((
Type == AllocFnKind::Free) &&
2419 ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
2420 AllocFnKind::Aligned)) != AllocFnKind::Unknown))
2421 CheckFailed(
"'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2422 "or aligned modifiers.");
2423 AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
2424 if ((K & ZeroedUninit) == ZeroedUninit)
2425 CheckFailed(
"'allockind()' can't be both zeroed and uninitialized");
2429 StringRef S =
A.getValueAsString();
2430 Check(!S.
empty(),
"'alloc-variant-zeroed' must not be empty");
2438 "'alloc-variant-zeroed' must name a function belonging to the "
2439 "same 'alloc-family'");
2442 (
Variant->getFnAttribute(Attribute::AllocKind).getAllocKind() &
2443 AllocFnKind::Zeroed) != AllocFnKind::Unknown,
2444 "'alloc-variant-zeroed' must name a function with "
2445 "'allockind(\"zeroed\")'");
2448 "'alloc-variant-zeroed' must name a function with the same "
2453 "'alloc-variant-zeroed' must name a function with the same "
2454 "calling convention");
2458 if (
Attrs.hasFnAttr(Attribute::VScaleRange)) {
2459 unsigned VScaleMin =
Attrs.getFnAttrs().getVScaleRangeMin();
2461 CheckFailed(
"'vscale_range' minimum must be greater than 0", V);
2463 CheckFailed(
"'vscale_range' minimum must be power-of-two value", V);
2464 std::optional<unsigned> VScaleMax =
Attrs.getFnAttrs().getVScaleRangeMax();
2465 if (VScaleMax && VScaleMin > VScaleMax)
2466 CheckFailed(
"'vscale_range' minimum cannot be greater than maximum", V);
2468 CheckFailed(
"'vscale_range' maximum must be power-of-two value", V);
2471 if (
Attribute FPAttr =
Attrs.getFnAttr(
"frame-pointer"); FPAttr.isValid()) {
2472 StringRef
FP = FPAttr.getValueAsString();
2473 if (
FP !=
"all" &&
FP !=
"non-leaf" &&
FP !=
"none" &&
FP !=
"reserved" &&
2474 FP !=
"non-leaf-no-reserve")
2475 CheckFailed(
"invalid value for 'frame-pointer' attribute: " +
FP, V);
2478 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-prefix", V);
2479 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-entry", V);
2480 if (
Attrs.hasFnAttr(
"patchable-function-entry-section"))
2481 Check(!
Attrs.getFnAttr(
"patchable-function-entry-section")
2484 "\"patchable-function-entry-section\" must not be empty");
2485 checkUnsignedBaseTenFuncAttr(Attrs,
"warn-stack-size", V);
2487 if (
auto A =
Attrs.getFnAttr(
"sign-return-address");
A.isValid()) {
2488 StringRef S =
A.getValueAsString();
2489 if (S !=
"none" && S !=
"all" && S !=
"non-leaf")
2490 CheckFailed(
"invalid value for 'sign-return-address' attribute: " + S, V);
2493 if (
auto A =
Attrs.getFnAttr(
"sign-return-address-key");
A.isValid()) {
2494 StringRef S =
A.getValueAsString();
2495 if (S !=
"a_key" && S !=
"b_key")
2496 CheckFailed(
"invalid value for 'sign-return-address-key' attribute: " + S,
2498 if (
auto AA =
Attrs.getFnAttr(
"sign-return-address"); !AA.isValid()) {
2500 "'sign-return-address-key' present without `sign-return-address`");
2504 if (
auto A =
Attrs.getFnAttr(
"branch-target-enforcement");
A.isValid()) {
2505 StringRef S =
A.getValueAsString();
2506 if (S !=
"" && S !=
"true" && S !=
"false")
2508 "invalid value for 'branch-target-enforcement' attribute: " + S, V);
2511 if (
auto A =
Attrs.getFnAttr(
"branch-protection-pauth-lr");
A.isValid()) {
2512 StringRef S =
A.getValueAsString();
2513 if (S !=
"" && S !=
"true" && S !=
"false")
2515 "invalid value for 'branch-protection-pauth-lr' attribute: " + S, V);
2518 if (
auto A =
Attrs.getFnAttr(
"guarded-control-stack");
A.isValid()) {
2519 StringRef S =
A.getValueAsString();
2520 if (S !=
"" && S !=
"true" && S !=
"false")
2521 CheckFailed(
"invalid value for 'guarded-control-stack' attribute: " + S,
2525 if (
auto A =
Attrs.getFnAttr(
"vector-function-abi-variant");
A.isValid()) {
2526 StringRef S =
A.getValueAsString();
2529 CheckFailed(
"invalid name for a VFABI variant: " + S, V);
2532 if (
auto A =
Attrs.getFnAttr(
"modular-format");
A.isValid()) {
2533 StringRef S =
A.getValueAsString();
2537 "modular-format attribute requires at least 5 arguments", V);
2538 unsigned UpperBound = FT->getNumParams() + (FT->isVarArg() ? 1 : 0);
2540 Check(!Args[1].getAsInteger(10, FormatIdx),
2541 "modular-format attribute format string index is not an integer", V);
2542 Check(FormatIdx > 0,
2543 "modular-format attribute format string index must be greater than 0",
2545 Check(FormatIdx <= UpperBound,
2546 "modular-format attribute format string index is out of bounds", V);
2547 unsigned FirstArgIdx;
2548 Check(!Args[2].getAsInteger(10, FirstArgIdx),
2549 "modular-format attribute first arg index is not an integer", V);
2550 Check(FirstArgIdx <= UpperBound,
2551 "modular-format attribute first arg index is out of bounds", V);
2553 "modular-format attribute modular implementation function name "
2557 "modular-format attribute implementation name cannot be empty", V);
2560 if (
auto A =
Attrs.getFnAttr(
"target-features");
A.isValid()) {
2561 StringRef S =
A.getValueAsString();
2563 for (
auto FeatureFlag :
split(S,
',')) {
2564 if (FeatureFlag.empty())
2566 "target-features attribute should not contain an empty string");
2568 Check(FeatureFlag[0] ==
'+' || FeatureFlag[0] ==
'-',
2569 "target feature '" + FeatureFlag +
2570 "' must start with a '+' or '-'",
2576void Verifier::verifyUnknownProfileMetadata(MDNode *MD) {
2578 "'unknown' !prof should have a single additional operand", MD);
2581 "'unknown' !prof should have an additional operand of type "
2584 "the 'unknown' !prof operand should not be an empty string");
2587void Verifier::verifyFunctionMetadata(
2588 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2589 for (
const auto &Pair : MDs) {
2590 if (Pair.first == LLVMContext::MD_prof) {
2591 MDNode *MD = Pair.second;
2593 "!prof annotations should have no less than 2 operands", MD);
2598 verifyUnknownProfileMetadata(MD);
2603 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null",
2606 "expected string with name of the !prof annotation", MD);
2611 "first operand should be 'function_entry_count'"
2612 " or 'synthetic_function_entry_count'",
2616 Check(MD->
getOperand(1) !=
nullptr,
"second operand should not be null",
2619 "expected integer argument to function_entry_count", MD);
2620 }
else if (Pair.first == LLVMContext::MD_kcfi_type) {
2621 MDNode *MD = Pair.second;
2623 "!kcfi_type must have exactly one operand", MD);
2624 Check(MD->
getOperand(0) !=
nullptr,
"!kcfi_type operand must not be null",
2627 "expected a constant operand for !kcfi_type", MD);
2630 "expected a constant integer operand for !kcfi_type", MD);
2632 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2633 }
else if (Pair.first ==
Context.getMDKindID(
"reqd_work_group_size")) {
2634 MDNode *MD = Pair.second;
2636 "reqd_work_group_size must have exactly three operands", MD);
2640 uint64_t Product = 1;
2641 for (
unsigned I = 0;
I != 3; ++
I) {
2643 Check(
C,
"reqd_work_group_size operands must be integer constants", MD);
2647 const APInt &
Value =
C->getValue();
2649 "reqd_work_group_size operands must fit in 64 bits", MD);
2650 if (
Value.getActiveBits() > 64)
2653 uint64_t Dim =
Value.getZExtValue();
2654 Check(Dim == 0 || Product <= std::numeric_limits<uint64_t>::max() / Dim,
2655 "reqd_work_group_size product must fit in 64 bits", MD);
2656 if (Dim != 0 && Product > std::numeric_limits<uint64_t>::max() / Dim)
2664void Verifier::visitConstantExprsRecursively(
const Constant *EntryC) {
2668 if (!ConstantExprVisited.
insert(EntryC).second)
2672 Stack.push_back(EntryC);
2674 while (!
Stack.empty()) {
2679 visitConstantExpr(CE);
2682 visitConstantPtrAuth(CPA);
2687 Check(GV->
getParent() == &M,
"Referencing global in another module!",
2693 for (
const Use &U :
C->operands()) {
2697 if (!ConstantExprVisited.
insert(OpC).second)
2699 Stack.push_back(OpC);
2704void Verifier::visitConstantExpr(
const ConstantExpr *CE) {
2705 if (
CE->getOpcode() == Instruction::BitCast)
2708 "Invalid bitcast", CE);
2709 else if (
CE->getOpcode() == Instruction::PtrToAddr)
2710 checkPtrToAddr(
CE->getOperand(0)->getType(),
CE->getType(), *CE);
2713void Verifier::visitConstantPtrAuth(
const ConstantPtrAuth *CPA) {
2715 "signed ptrauth constant base pointer must have pointer type");
2718 "signed ptrauth constant must have same type as its base pointer");
2721 "signed ptrauth constant key must be i32 constant integer");
2724 "signed ptrauth constant address discriminator must be a pointer");
2727 "signed ptrauth constant discriminator must be i64 constant integer");
2730 "signed ptrauth constant deactivation symbol must be a pointer");
2734 "signed ptrauth constant deactivation symbol must be a global value "
2738bool Verifier::verifyAttributeCount(AttributeList Attrs,
unsigned Params) {
2741 return Attrs.getNumAttrSets() <= Params + 2;
2744void Verifier::verifyInlineAsmCall(
const CallBase &
Call) {
2747 unsigned LabelNo = 0;
2748 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
2758 if (CI.isIndirect) {
2761 "Operand for indirect constraint must have pointer type", &
Call);
2764 "Operand for indirect constraint must have elementtype attribute",
2768 "Elementtype attribute can only be applied for indirect "
2777 Check(LabelNo == CallBr->getNumIndirectDests(),
2778 "Number of label constraints does not match number of callbr dests",
2781 Check(LabelNo == 0,
"Label constraints can only be used with callbr",
2787void Verifier::verifyStatepoint(
const CallBase &
Call) {
2792 "gc.statepoint must read and write all memory to preserve "
2793 "reordering restrictions required by safepoint semantics",
2796 const int64_t NumPatchBytes =
2799 Check(NumPatchBytes >= 0,
2800 "gc.statepoint number of patchable bytes must be "
2805 Check(TargetElemType,
2806 "gc.statepoint callee argument must have elementtype attribute",
Call);
2808 Check(TargetFuncType,
2809 "gc.statepoint callee elementtype must be function type",
Call);
2812 Check(NumCallArgs >= 0,
2813 "gc.statepoint number of arguments to underlying call "
2816 const int NumParams = (int)TargetFuncType->getNumParams();
2817 if (TargetFuncType->isVarArg()) {
2818 Check(NumCallArgs >= NumParams,
2819 "gc.statepoint mismatch in number of vararg call args",
Call);
2822 Check(TargetFuncType->getReturnType()->isVoidTy(),
2823 "gc.statepoint doesn't support wrapping non-void "
2824 "vararg functions yet",
2827 Check(NumCallArgs == NumParams,
2828 "gc.statepoint mismatch in number of call args",
Call);
2830 const uint64_t
Flags
2832 Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
2833 "unknown flag used in gc.statepoint flags argument",
Call);
2838 for (
int i = 0; i < NumParams; i++) {
2839 Type *ParamType = TargetFuncType->getParamType(i);
2841 Check(ArgType == ParamType,
2842 "gc.statepoint call argument does not match wrapped "
2846 if (TargetFuncType->isVarArg()) {
2847 AttributeSet ArgAttrs =
Attrs.getParamAttrs(5 + i);
2849 "Attribute 'sret' cannot be used for vararg call arguments!",
Call);
2853 const int EndCallArgsInx = 4 + NumCallArgs;
2857 "gc.statepoint number of transition arguments "
2858 "must be constant integer",
2860 const int NumTransitionArgs =
2862 Check(NumTransitionArgs == 0,
2863 "gc.statepoint w/inline transition bundle is deprecated",
Call);
2864 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2868 "gc.statepoint number of deoptimization arguments "
2869 "must be constant integer",
2872 Check(NumDeoptArgs == 0,
2873 "gc.statepoint w/inline deopt operands is deprecated",
Call);
2875 const int ExpectedNumArgs = 7 + NumCallArgs;
2877 "gc.statepoint too many arguments",
Call);
2884 Check(UserCall,
"illegal use of statepoint token",
Call, U);
2888 "gc.result or gc.relocate are the only value uses "
2889 "of a gc.statepoint",
2893 "gc.result connected to wrong gc.statepoint",
Call, UserCall);
2896 "gc.relocate connected to wrong gc.statepoint",
Call, UserCall);
2910void Verifier::verifyFrameRecoverIndices() {
2911 for (
auto &Counts : FrameEscapeInfo) {
2913 unsigned EscapedObjectCount = Counts.second.first;
2914 unsigned MaxRecoveredIndex = Counts.second.second;
2915 Check(MaxRecoveredIndex <= EscapedObjectCount,
2916 "all indices passed to llvm.localrecover must be less than the "
2917 "number of arguments passed to llvm.localescape in the parent "
2926 UnwindDest =
II->getUnwindDest();
2928 UnwindDest = CSI->getUnwindDest();
2934void Verifier::verifySiblingFuncletUnwinds() {
2935 llvm::TimeTraceScope timeScope(
"Verifier verify sibling funclet unwinds");
2936 SmallPtrSet<Instruction *, 8> Visited;
2937 SmallPtrSet<Instruction *, 8>
Active;
2938 for (
const auto &Pair : SiblingFuncletInfo) {
2940 if (Visited.
count(PredPad))
2946 if (
Active.count(SuccPad)) {
2949 SmallVector<Instruction *, 8> CycleNodes;
2952 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
2953 if (CycleTerminator != CyclePad)
2956 }
while (CyclePad != SuccPad);
2957 Check(
false,
"EH pads can't handle each other's exceptions",
2961 if (!Visited.
insert(SuccPad).second)
2965 auto TermI = SiblingFuncletInfo.find(PredPad);
2966 if (TermI == SiblingFuncletInfo.end())
2979void Verifier::visitFunction(
const Function &
F) {
2980 visitGlobalValue(
F);
2983 FunctionType *FT =
F.getFunctionType();
2984 unsigned NumArgs =
F.arg_size();
2987 "Function context does not match Module context!", &
F);
2989 Check(!
F.hasCommonLinkage(),
"Functions may not have common linkage", &
F);
2990 Check(FT->getNumParams() == NumArgs,
2991 "# formal arguments must match # of arguments for function type!", &
F,
2993 Check(
F.getReturnType()->isFirstClassType() ||
2994 F.getReturnType()->isVoidTy() ||
F.getReturnType()->isStructTy(),
2995 "Functions cannot return aggregate values!", &
F);
2997 Check(!
F.hasStructRetAttr() ||
F.getReturnType()->isVoidTy(),
2998 "Invalid struct return type!", &
F);
3000 if (MaybeAlign
A =
F.getAlign()) {
3001 Check(
A->value() <= Value::MaximumAlignment,
3002 "huge alignment values are unsupported", &
F);
3005 AttributeList
Attrs =
F.getAttributes();
3007 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
3008 "Attribute after last parameter!", &
F);
3010 bool IsIntrinsic =
F.isIntrinsic();
3013 verifyFunctionAttrs(FT, Attrs, &
F, IsIntrinsic,
false);
3019 "Attribute 'builtin' can only be applied to a callsite.", &
F);
3021 Check(!
Attrs.hasAttrSomewhere(Attribute::ElementType),
3022 "Attribute 'elementtype' can only be applied to a callsite.", &
F);
3024 if (
Attrs.hasFnAttr(Attribute::Naked))
3025 for (
const Argument &Arg :
F.args())
3026 Check(Arg.use_empty(),
"cannot use argument of naked function", &Arg);
3031 switch (
F.getCallingConv()) {
3033 case CallingConv::C:
3035 case CallingConv::X86_INTR: {
3036 Check(
F.arg_empty() ||
Attrs.hasParamAttr(0, Attribute::ByVal),
3037 "Calling convention parameter requires byval", &
F);
3040 case CallingConv::AMDGPU_KERNEL:
3041 case CallingConv::SPIR_KERNEL:
3042 case CallingConv::AMDGPU_CS_Chain:
3043 case CallingConv::AMDGPU_CS_ChainPreserve:
3044 Check(
F.getReturnType()->isVoidTy(),
3045 "Calling convention requires void return type", &
F);
3047 case CallingConv::AMDGPU_VS:
3048 case CallingConv::AMDGPU_HS:
3049 case CallingConv::AMDGPU_GS:
3050 case CallingConv::AMDGPU_PS:
3051 case CallingConv::AMDGPU_CS:
3052 Check(!
F.hasStructRetAttr(),
"Calling convention does not allow sret", &
F);
3053 if (
F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3054 const unsigned StackAS =
DL.getAllocaAddrSpace();
3056 for (
const Argument &Arg :
F.args()) {
3057 Check(!
Attrs.hasParamAttr(i, Attribute::ByVal),
3058 "Calling convention disallows byval", &
F);
3059 Check(!
Attrs.hasParamAttr(i, Attribute::Preallocated),
3060 "Calling convention disallows preallocated", &
F);
3061 Check(!
Attrs.hasParamAttr(i, Attribute::InAlloca),
3062 "Calling convention disallows inalloca", &
F);
3064 if (
Attrs.hasParamAttr(i, Attribute::ByRef)) {
3067 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
3068 "Calling convention disallows stack byref", &
F);
3076 case CallingConv::Fast:
3077 case CallingConv::Cold:
3078 case CallingConv::Intel_OCL_BI:
3079 case CallingConv::PTX_Kernel:
3080 case CallingConv::PTX_Device:
3082 "Calling convention does not support varargs or "
3083 "perfect forwarding!",
3086 case CallingConv::AMDGPU_Gfx_WholeWave:
3087 Check(!
F.arg_empty() &&
F.arg_begin()->getType()->isIntegerTy(1),
3088 "Calling convention requires first argument to be i1", &
F);
3089 Check(!
F.arg_begin()->hasInRegAttr(),
3090 "Calling convention requires first argument to not be inreg", &
F);
3092 "Calling convention does not support varargs or "
3093 "perfect forwarding!",
3100 for (
const Argument &Arg :
F.args()) {
3101 Check(Arg.getType() == FT->getParamType(i),
3102 "Argument value does not match function argument type!", &Arg,
3103 FT->getParamType(i));
3104 Check(Arg.getType()->isFirstClassType(),
3105 "Function arguments must have first-class types!", &Arg);
3107 Check(!Arg.getType()->isMetadataTy(),
3108 "Function takes metadata but isn't an intrinsic", &Arg, &
F);
3109 Check(!Arg.getType()->isTokenLikeTy(),
3110 "Function takes token but isn't an intrinsic", &Arg, &
F);
3111 Check(!Arg.getType()->isX86_AMXTy(),
3112 "Function takes x86_amx but isn't an intrinsic", &Arg, &
F);
3116 if (
Attrs.hasParamAttr(i, Attribute::SwiftError)) {
3117 verifySwiftErrorValue(&Arg);
3123 Check(!
F.getReturnType()->isTokenLikeTy(),
3124 "Function returns a token but isn't an intrinsic", &
F);
3125 Check(!
F.getReturnType()->isX86_AMXTy(),
3126 "Function returns a x86_amx but isn't an intrinsic", &
F);
3131 F.getAllMetadata(MDs);
3132 assert(
F.hasMetadata() != MDs.
empty() &&
"Bit out-of-sync");
3133 verifyFunctionMetadata(MDs);
3139 if (
F.hasPersonalityFn()) {
3142 Check(Per->getParent() ==
F.getParent(),
3143 "Referencing personality function in another module!", &
F,
3144 F.getParent(), Per, Per->getParent());
3148 BlockEHFuncletColors.
clear();
3150 if (
F.isMaterializable()) {
3152 Check(MDs.
empty(),
"unmaterialized function cannot have metadata", &
F,
3154 }
else if (
F.isDeclaration()) {
3155 for (
const auto &
I : MDs) {
3157 CheckDI(
I.first != LLVMContext::MD_dbg ||
3159 "function declaration may only have a unique !dbg attachment",
3161 Check(
I.first != LLVMContext::MD_prof,
3162 "function declaration may not have a !prof attachment", &
F);
3165 visitMDNode(*
I.second, AreDebugLocsAllowed::Yes);
3167 Check(!
F.hasPersonalityFn(),
3168 "Function declaration shouldn't have a personality routine", &
F);
3172 Check(!IsIntrinsic,
"llvm intrinsics cannot be defined!", &
F);
3177 "Entry block to function must not have predecessors!", Entry);
3180 if (
Entry->hasAddressTaken()) {
3182 "blockaddress may not be used with the entry block!", Entry);
3185 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
3186 NumKCFIAttachments = 0;
3188 for (
const auto &
I : MDs) {
3190 auto AllowLocs = AreDebugLocsAllowed::No;
3194 case LLVMContext::MD_dbg: {
3195 ++NumDebugAttachments;
3196 CheckDI(NumDebugAttachments == 1,
3197 "function must have a single !dbg attachment", &
F,
I.second);
3199 "function !dbg attachment must be a subprogram", &
F,
I.second);
3201 "function definition may only have a distinct !dbg attachment",
3205 const Function *&AttachedTo = DISubprogramAttachments[
SP];
3206 CheckDI(!AttachedTo || AttachedTo == &
F,
3207 "DISubprogram attached to more than one function", SP, &
F);
3209 AllowLocs = AreDebugLocsAllowed::Yes;
3212 case LLVMContext::MD_prof:
3213 ++NumProfAttachments;
3214 Check(NumProfAttachments == 1,
3215 "function must have a single !prof attachment", &
F,
I.second);
3217 case LLVMContext::MD_kcfi_type:
3218 ++NumKCFIAttachments;
3219 Check(NumKCFIAttachments == 1,
3220 "function must have a single !kcfi_type attachment", &
F,
3226 visitMDNode(*
I.second, AllowLocs);
3234 bool isMaterialized =
F.getParent()->isMaterialized();
3235 if (
F.isIntrinsic() && isMaterialized) {
3237 if (
F.hasAddressTaken(&U,
false,
true,
false,
3239 Check(
false,
"Invalid user of intrinsic instruction!", U);
3246 if (IID && (isMaterialized || !
F.materialized_use_empty())) {
3250 raw_string_ostream ErrOS(ErrMsg);
3253 Printable PrintDecl([&
F](raw_ostream &OS) {
F.print(OS); });
3254 Check(IsValid, ErrMsg, PrintDecl);
3261 IID, OverloadTys,
const_cast<Module *
>(
F.getParent()), FT);
3262 Check(ExpectedName ==
F.getName(),
3263 "Intrinsic name not mangled correctly for type arguments! "
3269 auto *
N =
F.getSubprogram();
3270 HasDebugInfo = (
N !=
nullptr);
3278 SmallPtrSet<const MDNode *, 32> Seen;
3290 "DILocation's scope must be a DILocalScope",
N, &
F, &
I,
DL, Parent);
3292 DILocalScope *
Scope =
DL->getInlinedAtScope();
3293 Check(Scope,
"Failed to find DILocalScope",
DL);
3295 if (!Seen.
insert(Scope).second)
3298 DISubprogram *
SP =
Scope->getSubprogram();
3302 if ((Scope != SP) && !Seen.
insert(SP).second)
3306 "!dbg attachment points at wrong subprogram for function",
N, &
F,
3310 for (
auto &
I : BB) {
3311 VisitDebugLoc(
I,
I.getDebugLoc().getAsMDNode());
3313 if (
auto MD =
I.getMetadata(LLVMContext::MD_loop))
3316 if (BrokenDebugInfo)
3323void Verifier::visitBasicBlock(BasicBlock &BB) {
3324 InstsInThisBlock.
clear();
3325 ConvergenceVerifyHelper.
visit(BB);
3336 for (
const PHINode &PN : BB.
phis()) {
3337 Check(PN.getNumIncomingValues() == Preds.size(),
3338 "PHINode should have one entry for each predecessor of its "
3339 "parent basic block!",
3344 Values.reserve(PN.getNumIncomingValues());
3345 for (
unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3347 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3350 for (
unsigned i = 0, e =
Values.size(); i != e; ++i) {
3357 "PHI node has multiple entries for the same basic block with "
3358 "different incoming values!",
3364 "PHI node entries do not match predecessors!", &PN,
3365 Values[i].first, Preds[i]);
3373 Check(
I.getParent() == &BB,
"Instruction has bogus parent pointer!");
3377 CheckDI(!BB.getTrailingDbgRecords(),
"Basic Block has trailing DbgRecords!",
3381void Verifier::visitTerminator(Instruction &
I) {
3383 Check(&
I ==
I.getParent()->getTerminator(),
3384 "Terminator found in the middle of a basic block!",
I.getParent());
3385 visitInstruction(
I);
3388void Verifier::visitCondBrInst(CondBrInst &BI) {
3390 "Branch condition is not 'i1' type!", &BI, BI.
getCondition());
3391 visitTerminator(BI);
3394void Verifier::visitReturnInst(ReturnInst &RI) {
3397 if (
F->getReturnType()->isVoidTy())
3399 "Found return instr that returns non-void in Function of void "
3401 &RI,
F->getReturnType());
3404 "Function return type does not match operand "
3405 "type of return inst!",
3406 &RI,
F->getReturnType());
3410 visitTerminator(RI);
3413void Verifier::visitSwitchInst(SwitchInst &SI) {
3414 Check(
SI.getType()->isVoidTy(),
"Switch must have void result type!", &SI);
3417 Type *SwitchTy =
SI.getCondition()->getType();
3418 SmallPtrSet<ConstantInt*, 32>
Constants;
3419 for (
auto &Case :
SI.cases()) {
3421 "Case value is not a constant integer.", &SI);
3422 Check(Case.getCaseValue()->getType() == SwitchTy,
3423 "Switch constants must all be same type as switch value!", &SI);
3425 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3428 visitTerminator(SI);
3431void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
3433 "Indirectbr operand must have pointer type!", &BI);
3436 "Indirectbr destinations must all have pointer type!", &BI);
3438 visitTerminator(BI);
3447void Verifier::visitCallBrInst(CallBrInst &CBI) {
3450 "callbr: indirect function / invalid signature");
3452 "callbr for intrinsics currently doesn't support operand bundles");
3456 "callbr currently only supports asm-goto and selected intrinsics");
3461 Check(!
IA->canThrow(),
"Unwinding from Callbr is not allowed");
3463 verifyInlineAsmCall(CBI);
3465 visitTerminator(CBI);
3468void Verifier::visitSelectInst(SelectInst &SI) {
3471 "Invalid operands for select instruction!", &SI);
3473 Check(
SI.getTrueValue()->getType() ==
SI.getType(),
3474 "Select values must have same type as select instruction!", &SI);
3475 visitInstruction(SI);
3481void Verifier::visitUserOp1(Instruction &
I) {
3482 Check(
false,
"User-defined operators should not live outside of a pass!", &
I);
3485void Verifier::visitTruncInst(TruncInst &
I) {
3487 Type *SrcTy =
I.getOperand(0)->getType();
3488 Type *DestTy =
I.getType();
3497 "trunc source and destination must both be a vector or neither", &
I);
3498 Check(SrcBitSize > DestBitSize,
"DestTy too big for Trunc", &
I);
3500 visitInstruction(
I);
3503void Verifier::visitZExtInst(ZExtInst &
I) {
3505 Type *SrcTy =
I.getOperand(0)->getType();
3506 Type *DestTy =
I.getType();
3512 "zext source and destination must both be a vector or neither", &
I);
3516 Check(SrcBitSize < DestBitSize,
"Type too small for ZExt", &
I);
3518 visitInstruction(
I);
3521void Verifier::visitSExtInst(SExtInst &
I) {
3523 Type *SrcTy =
I.getOperand(0)->getType();
3524 Type *DestTy =
I.getType();
3533 "sext source and destination must both be a vector or neither", &
I);
3534 Check(SrcBitSize < DestBitSize,
"Type too small for SExt", &
I);
3536 visitInstruction(
I);
3539void Verifier::visitFPTruncInst(FPTruncInst &
I) {
3541 Type *SrcTy =
I.getOperand(0)->getType();
3542 Type *DestTy =
I.getType();
3550 "fptrunc source and destination must both be a vector or neither", &
I);
3551 Check(SrcBitSize > DestBitSize,
"DestTy too big for FPTrunc", &
I);
3553 visitInstruction(
I);
3556void Verifier::visitFPExtInst(FPExtInst &
I) {
3558 Type *SrcTy =
I.getOperand(0)->getType();
3559 Type *DestTy =
I.getType();
3568 "fpext source and destination must both be a vector or neither", &
I);
3569 Check(SrcBitSize < DestBitSize,
"DestTy too small for FPExt", &
I);
3571 visitInstruction(
I);
3574void Verifier::visitUIToFPInst(UIToFPInst &
I) {
3576 Type *SrcTy =
I.getOperand(0)->getType();
3577 Type *DestTy =
I.getType();
3582 Check(SrcVec == DstVec,
3583 "UIToFP source and dest must both be vector or scalar", &
I);
3585 "UIToFP source must be integer or integer vector", &
I);
3589 if (SrcVec && DstVec)
3592 "UIToFP source and dest vector length mismatch", &
I);
3594 visitInstruction(
I);
3597void Verifier::visitSIToFPInst(SIToFPInst &
I) {
3599 Type *SrcTy =
I.getOperand(0)->getType();
3600 Type *DestTy =
I.getType();
3605 Check(SrcVec == DstVec,
3606 "SIToFP source and dest must both be vector or scalar", &
I);
3608 "SIToFP source must be integer or integer vector", &
I);
3612 if (SrcVec && DstVec)
3615 "SIToFP source and dest vector length mismatch", &
I);
3617 visitInstruction(
I);
3620void Verifier::visitFPToUIInst(FPToUIInst &
I) {
3622 Type *SrcTy =
I.getOperand(0)->getType();
3623 Type *DestTy =
I.getType();
3628 Check(SrcVec == DstVec,
3629 "FPToUI source and dest must both be vector or scalar", &
I);
3632 "FPToUI result must be integer or integer vector", &
I);
3634 if (SrcVec && DstVec)
3637 "FPToUI source and dest vector length mismatch", &
I);
3639 visitInstruction(
I);
3642void Verifier::visitFPToSIInst(FPToSIInst &
I) {
3644 Type *SrcTy =
I.getOperand(0)->getType();
3645 Type *DestTy =
I.getType();
3650 Check(SrcVec == DstVec,
3651 "FPToSI source and dest must both be vector or scalar", &
I);
3654 "FPToSI result must be integer or integer vector", &
I);
3656 if (SrcVec && DstVec)
3659 "FPToSI source and dest vector length mismatch", &
I);
3661 visitInstruction(
I);
3664void Verifier::checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V) {
3673 Check(VSrc->getElementCount() == VDest->getElementCount(),
3674 "PtrToAddr vector length mismatch", V);
3677 Type *AddrTy =
DL.getAddressType(SrcTy);
3678 Check(AddrTy == DestTy,
"PtrToAddr result must be address width", V);
3681void Verifier::visitPtrToAddrInst(PtrToAddrInst &
I) {
3682 checkPtrToAddr(
I.getOperand(0)->getType(),
I.getType(),
I);
3683 visitInstruction(
I);
3686void Verifier::visitPtrToIntInst(PtrToIntInst &
I) {
3688 Type *SrcTy =
I.getOperand(0)->getType();
3689 Type *DestTy =
I.getType();
3700 Check(VSrc->getElementCount() == VDest->getElementCount(),
3701 "PtrToInt Vector length mismatch", &
I);
3704 visitInstruction(
I);
3707void Verifier::visitIntToPtrInst(IntToPtrInst &
I) {
3709 Type *SrcTy =
I.getOperand(0)->getType();
3710 Type *DestTy =
I.getType();
3720 Check(VSrc->getElementCount() == VDest->getElementCount(),
3721 "IntToPtr Vector length mismatch", &
I);
3723 visitInstruction(
I);
3726void Verifier::visitBitCastInst(BitCastInst &
I) {
3729 "Invalid bitcast", &
I);
3730 visitInstruction(
I);
3733void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &
I) {
3734 Type *SrcTy =
I.getOperand(0)->getType();
3735 Type *DestTy =
I.getType();
3742 "AddrSpaceCast must be between different address spaces", &
I);
3744 Check(SrcVTy->getElementCount() ==
3746 "AddrSpaceCast vector pointer number of elements mismatch", &
I);
3747 visitInstruction(
I);
3752void Verifier::visitPHINode(PHINode &PN) {
3759 "PHI nodes not grouped at top of basic block!", &PN, PN.
getParent());
3768 "PHI node operands are not the same type as the result!", &PN);
3773 visitInstruction(PN);
3776void Verifier::visitCallBase(CallBase &
Call) {
3778 "Called function must be a pointer!",
Call);
3782 if (FTy->isVarArg())
3784 "Called function requires more parameters than were provided!",
Call);
3787 "Incorrect number of arguments passed to called function!",
Call);
3790 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3792 "Call parameter type does not match function signature!",
3798 "Attribute after last parameter!",
Call);
3805 "Intrinsic called with incompatible signature",
Call);
3809 "calling convention does not permit calls",
Call);
3815 auto VerifyTypeAlign = [&](
Type *Ty,
const Twine &Message) {
3818 Align ABIAlign =
DL.getABITypeAlign(Ty);
3819 Check(ABIAlign.
value() <= Value::MaximumAlignment,
3820 "Incorrect alignment of " + Message +
" to called function!",
Call);
3824 VerifyTypeAlign(FTy->getReturnType(),
"return type");
3825 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3826 Type *Ty = FTy->getParamType(i);
3827 VerifyTypeAlign(Ty,
"argument passed");
3831 if (
Attrs.hasFnAttr(Attribute::Speculatable)) {
3835 "speculatable attribute may not apply to call sites",
Call);
3838 if (
Attrs.hasFnAttr(Attribute::Preallocated)) {
3840 "preallocated as a call site attribute can only be on "
3841 "llvm.call.preallocated.arg");
3844 Check(!
Attrs.hasFnAttr(Attribute::DenormalFPEnv),
3845 "denormal_fpenv attribute may not apply to call sites",
Call);
3856 Check(AI->isUsedWithInAlloca(),
3857 "inalloca argument for call has mismatched alloca", AI,
Call);
3863 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3867 Check(AI->isSwiftError(),
3868 "swifterror argument for call has mismatched alloca", AI,
Call);
3872 Check(ArgI,
"swifterror argument should come from an alloca or parameter",
3873 SwiftErrorArg,
Call);
3874 Check(ArgI->hasSwiftErrorAttr(),
3875 "swifterror argument for call has mismatched parameter", ArgI,
3879 if (
Attrs.hasParamAttr(i, Attribute::ImmArg)) {
3882 Check(Callee &&
Callee->hasParamAttribute(i, Attribute::ImmArg),
3891 "immarg operand has non-immediate parameter", ArgVal,
Call);
3897 const ConstantRange &CR =
3900 "immarg value " + Twine(CI->getValue().getSExtValue()) +
3913 Check(hasOB != isMustTail,
3914 "preallocated operand either requires a preallocated bundle or "
3915 "the call to be musttail (but not both)",
3920 if (FTy->isVarArg()) {
3922 bool SawNest =
false;
3923 bool SawReturned =
false;
3925 for (
unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3926 if (
Attrs.hasParamAttr(Idx, Attribute::Nest))
3928 if (
Attrs.hasParamAttr(Idx, Attribute::Returned))
3933 for (
unsigned Idx = FTy->getNumParams(); Idx <
Call.
arg_size(); ++Idx) {
3935 AttributeSet ArgAttrs =
Attrs.getParamAttrs(Idx);
3936 verifyParameterAttrs(ArgAttrs, Ty, &
Call);
3939 Check(!SawNest,
"More than one parameter has attribute nest!",
Call);
3944 Check(!SawReturned,
"More than one parameter has attribute returned!",
3947 "Incompatible argument and return types for 'returned' "
3957 "Attribute 'sret' cannot be used for vararg call arguments!",
3962 "inalloca isn't on the last argument!",
Call);
3968 for (
Type *ParamTy : FTy->params()) {
3969 Check(!ParamTy->isMetadataTy(),
3970 "Function has metadata parameter but isn't an intrinsic",
Call);
3971 Check(!ParamTy->isTokenLikeTy(),
3972 "Function has token parameter but isn't an intrinsic",
Call);
3978 Check(!FTy->getReturnType()->isTokenLikeTy(),
3979 "Return type cannot be token for indirect call!");
3980 Check(!FTy->getReturnType()->isX86_AMXTy(),
3981 "Return type cannot be x86_amx for indirect call!");
3985 visitIntrinsicCall(
ID,
Call);
3990 bool FoundDeoptBundle =
false, FoundFuncletBundle =
false,
3991 FoundGCTransitionBundle =
false, FoundCFGuardTargetBundle =
false,
3992 FoundPreallocatedBundle =
false, FoundGCLiveBundle =
false,
3993 FoundPtrauthBundle =
false, FoundKCFIBundle =
false,
3994 FoundAttachedCallBundle =
false;
3999 Check(!FoundDeoptBundle,
"Multiple deopt operand bundles",
Call);
4000 FoundDeoptBundle =
true;
4002 Check(!FoundGCTransitionBundle,
"Multiple gc-transition operand bundles",
4004 FoundGCTransitionBundle =
true;
4006 Check(!FoundFuncletBundle,
"Multiple funclet operand bundles",
Call);
4007 FoundFuncletBundle =
true;
4009 "Expected exactly one funclet bundle operand",
Call);
4011 "Funclet bundle operands should correspond to a FuncletPadInst",
4014 Check(!FoundCFGuardTargetBundle,
"Multiple CFGuardTarget operand bundles",
4016 FoundCFGuardTargetBundle =
true;
4018 "Expected exactly one cfguardtarget bundle operand",
Call);
4020 Check(!FoundPtrauthBundle,
"Multiple ptrauth operand bundles",
Call);
4021 FoundPtrauthBundle =
true;
4023 "Expected exactly two ptrauth bundle operands",
Call);
4025 BU.
Inputs[0]->getType()->isIntegerTy(32),
4026 "Ptrauth bundle key operand must be an i32 constant",
Call);
4028 "Ptrauth bundle discriminator operand must be an i64",
Call);
4030 Check(!FoundKCFIBundle,
"Multiple kcfi operand bundles",
Call);
4031 FoundKCFIBundle =
true;
4032 Check(BU.
Inputs.size() == 1,
"Expected exactly one kcfi bundle operand",
4035 BU.
Inputs[0]->getType()->isIntegerTy(32),
4036 "Kcfi bundle operand must be an i32 constant",
Call);
4038 Check(!FoundPreallocatedBundle,
"Multiple preallocated operand bundles",
4040 FoundPreallocatedBundle =
true;
4042 "Expected exactly one preallocated bundle operand",
Call);
4045 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
4046 "\"preallocated\" argument must be a token from "
4047 "llvm.call.preallocated.setup",
4050 Check(!FoundGCLiveBundle,
"Multiple gc-live operand bundles",
Call);
4051 FoundGCLiveBundle =
true;
4053 Check(!FoundAttachedCallBundle,
4054 "Multiple \"clang.arc.attachedcall\" operand bundles",
Call);
4055 FoundAttachedCallBundle =
true;
4056 verifyAttachedCallBundle(
Call, BU);
4062 "Direct call cannot have a ptrauth bundle",
Call);
4074 "inlinable function call in a function with "
4075 "debug info must have a !dbg location",
4079 verifyInlineAsmCall(
Call);
4083 visitInstruction(
Call);
4086void Verifier::verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs,
4089 Twine(
"inalloca attribute not allowed in ") +
Context);
4091 Twine(
"inreg attribute not allowed in ") +
Context);
4092 Check(!
Attrs.contains(Attribute::SwiftError),
4093 Twine(
"swifterror attribute not allowed in ") +
Context);
4094 Check(!
Attrs.contains(Attribute::Preallocated),
4095 Twine(
"preallocated attribute not allowed in ") +
Context);
4097 Twine(
"byref attribute not allowed in ") +
Context);
4102 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
4103 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
4104 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
4106 AttrBuilder Copy(
C);
4107 for (
auto AK : ABIAttrs) {
4108 Attribute Attr = Attrs.getParamAttrs(
I).getAttribute(AK);
4110 Copy.addAttribute(Attr);
4114 if (Attrs.hasParamAttr(
I, Attribute::Alignment) &&
4115 (Attrs.hasParamAttr(
I, Attribute::ByVal) ||
4116 Attrs.hasParamAttr(
I, Attribute::ByRef)))
4117 Copy.addAlignmentAttr(Attrs.getParamAlignment(
I));
4121void Verifier::verifyMustTailCall(CallInst &CI) {
4125 FunctionType *CallerTy =
F->getFunctionType();
4127 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
4128 "cannot guarantee tail call due to mismatched varargs", &CI);
4129 Check(CallerTy->getReturnType() == CalleeTy->getReturnType(),
4130 "cannot guarantee tail call due to mismatched return types", &CI);
4134 "cannot guarantee tail call due to mismatched calling conv", &CI);
4142 Check(Ret,
"musttail call must precede a ret", &CI);
4145 "musttail call result must be returned", Ret);
4147 AttributeList CallerAttrs =
F->getAttributes();
4152 CI.
getCallingConv() == CallingConv::Tail ?
"tailcc" :
"swifttailcc";
4156 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4158 SmallString<32>
Context{CCName, StringRef(
" musttail caller")};
4159 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4161 for (
unsigned I = 0,
E = CalleeTy->getNumParams();
I !=
E; ++
I) {
4163 SmallString<32>
Context{CCName, StringRef(
" musttail callee")};
4164 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4167 Check(!CallerTy->isVarArg(), Twine(
"cannot guarantee ") + CCName +
4168 " tail call for varargs function");
4174 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
4175 "cannot guarantee tail call due to mismatched parameter counts", &CI);
4176 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4177 Check(CallerTy->getParamType(
I) == CalleeTy->getParamType(
I),
4178 "cannot guarantee tail call due to mismatched parameter types",
4185 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4188 Check(CallerABIAttrs == CalleeABIAttrs,
4189 "cannot guarantee tail call due to mismatched ABI impacting "
4190 "function attributes",
4195void Verifier::visitCallInst(CallInst &CI) {
4199 verifyMustTailCall(CI);
4202void Verifier::visitInvokeInst(InvokeInst &
II) {
4208 II.getUnwindDest()->isEHPad(),
4209 "The unwind destination does not have an exception handling instruction!",
4212 visitTerminator(
II);
4217void Verifier::visitUnaryOperator(UnaryOperator &U) {
4218 Check(
U.getType() ==
U.getOperand(0)->getType(),
4219 "Unary operators must have same type for"
4220 "operands and result!",
4223 switch (
U.getOpcode()) {
4226 case Instruction::FNeg:
4227 Check(
U.getType()->isFPOrFPVectorTy(),
4228 "FNeg operator only works with float types!", &U);
4234 visitInstruction(U);
4240void Verifier::visitBinaryOperator(BinaryOperator &
B) {
4241 Check(
B.getOperand(0)->getType() ==
B.getOperand(1)->getType(),
4242 "Both operands to a binary operator are not of the same type!", &
B);
4244 switch (
B.getOpcode()) {
4247 case Instruction::Add:
4248 case Instruction::Sub:
4249 case Instruction::Mul:
4250 case Instruction::SDiv:
4251 case Instruction::UDiv:
4252 case Instruction::SRem:
4253 case Instruction::URem:
4254 Check(
B.getType()->isIntOrIntVectorTy(),
4255 "Integer arithmetic operators only work with integral types!", &
B);
4256 Check(
B.getType() ==
B.getOperand(0)->getType(),
4257 "Integer arithmetic operators must have same type "
4258 "for operands and result!",
4263 case Instruction::FAdd:
4264 case Instruction::FSub:
4265 case Instruction::FMul:
4266 case Instruction::FDiv:
4267 case Instruction::FRem:
4268 Check(
B.getType()->isFPOrFPVectorTy(),
4269 "Floating-point arithmetic operators only work with "
4270 "floating-point types!",
4272 Check(
B.getType() ==
B.getOperand(0)->getType(),
4273 "Floating-point arithmetic operators must have same type "
4274 "for operands and result!",
4278 case Instruction::And:
4279 case Instruction::Or:
4280 case Instruction::Xor:
4281 Check(
B.getType()->isIntOrIntVectorTy(),
4282 "Logical operators only work with integral types!", &
B);
4283 Check(
B.getType() ==
B.getOperand(0)->getType(),
4284 "Logical operators must have same type for operands and result!", &
B);
4286 case Instruction::Shl:
4287 case Instruction::LShr:
4288 case Instruction::AShr:
4289 Check(
B.getType()->isIntOrIntVectorTy(),
4290 "Shifts only work with integral types!", &
B);
4291 Check(
B.getType() ==
B.getOperand(0)->getType(),
4292 "Shift return type must be same as operands!", &
B);
4298 visitInstruction(
B);
4301void Verifier::visitICmpInst(ICmpInst &IC) {
4305 Check(Op0Ty == Op1Ty,
4306 "Both operands to ICmp instruction are not of the same type!", &IC);
4309 "Invalid operand types for ICmp instruction", &IC);
4313 visitInstruction(IC);
4316void Verifier::visitFCmpInst(FCmpInst &FC) {
4318 Type *Op0Ty =
FC.getOperand(0)->getType();
4319 Type *Op1Ty =
FC.getOperand(1)->getType();
4320 Check(Op0Ty == Op1Ty,
4321 "Both operands to FCmp instruction are not of the same type!", &FC);
4326 Check(
FC.isFPPredicate(),
"Invalid predicate in FCmp instruction!", &FC);
4328 visitInstruction(FC);
4331void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
4333 "Invalid extractelement operands!", &EI);
4334 visitInstruction(EI);
4337void Verifier::visitInsertElementInst(InsertElementInst &IE) {
4340 "Invalid insertelement operands!", &IE);
4341 visitInstruction(IE);
4344void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
4347 "Invalid shufflevector operands!", &SV);
4348 visitInstruction(SV);
4351void Verifier::visitGetElementPtrInst(GetElementPtrInst &
GEP) {
4353 GEP.getModule()->getModuleFlag(
"require-logical-pointer")))
4354 Check(!MD->getZExtValue(),
4355 "Non-logical getelementptr disallowed for this module.");
4357 Type *TargetTy =
GEP.getPointerOperandType()->getScalarType();
4360 "GEP base pointer is not a vector or a vector of pointers", &
GEP);
4361 Check(
GEP.getSourceElementType()->isSized(),
"GEP into unsized type!", &
GEP);
4365 "getelementptr cannot target structure that contains scalable vector"
4370 SmallVector<Value *, 16> Idxs(
GEP.indices());
4372 all_of(Idxs, [](
Value *V) {
return V->getType()->isIntOrIntVectorTy(); }),
4373 "GEP indexes must be integers", &
GEP);
4376 Check(ElTy,
"Invalid indices for GEP pointer type!", &
GEP);
4380 Check(PtrTy &&
GEP.getResultElementType() == ElTy,
4381 "GEP is not of right type for indices!", &
GEP, ElTy);
4385 ElementCount GEPWidth = GEPVTy->getElementCount();
4386 if (
GEP.getPointerOperandType()->isVectorTy())
4390 "Vector GEP result width doesn't match operand's", &
GEP);
4391 for (
Value *Idx : Idxs) {
4392 Type *IndexTy = Idx->getType();
4394 ElementCount IndexWidth = IndexVTy->getElementCount();
4395 Check(IndexWidth == GEPWidth,
"Invalid GEP index vector width", &
GEP);
4398 "All GEP indices should be of integer type");
4405 GTI != GTE; ++GTI) {
4406 if (GTI.isVector()) {
4407 Type *ElemTy = GTI.getIndexedType();
4408 Check(
DL.typeSizeEqualsStoreSize(ElemTy),
4409 "GEP into vector with non-byte-addressable element type", &
GEP);
4413 Check(
GEP.getAddressSpace() == PtrTy->getAddressSpace(),
4414 "GEP address space doesn't match type", &
GEP);
4416 visitInstruction(
GEP);
4420 return A.getUpper() ==
B.getLower() ||
A.getLower() ==
B.getUpper();
4425void Verifier::verifyRangeLikeMetadata(
const Value &
I,
const MDNode *
Range,
4426 Type *Ty, RangeLikeMetadataKind Kind) {
4427 unsigned NumOperands =
Range->getNumOperands();
4428 Check(NumOperands % 2 == 0,
"Unfinished range!",
Range);
4429 unsigned NumRanges = NumOperands / 2;
4430 Check(NumRanges >= 1,
"It should have at least one range!",
Range);
4432 ConstantRange LastRange(1,
true);
4433 for (
unsigned i = 0; i < NumRanges; ++i) {
4436 Check(
Low,
"The lower limit must be an integer!",
Low);
4441 Check(
High->getType() ==
Low->getType(),
"Range pair types must match!",
4444 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4446 "noalias.addrspace type must be i32!", &
I);
4449 "Range types must match instruction type!", &
I);
4452 APInt HighV =
High->getValue();
4453 APInt LowV =
Low->getValue();
4458 "The upper and lower limits cannot be the same value", &
I);
4460 ConstantRange CurRange(LowV, HighV);
4461 Check(!CurRange.isEmptySet() &&
4462 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
4463 !CurRange.isFullSet()),
4464 "Range must not be empty!",
Range);
4466 Check(CurRange.intersectWith(LastRange).isEmptySet(),
4467 "Intervals are overlapping",
Range);
4468 Check(LowV.
sgt(LastRange.getLower()),
"Intervals are not in order",
4473 LastRange = ConstantRange(LowV, HighV);
4475 if (NumRanges > 2) {
4480 ConstantRange FirstRange(FirstLow, FirstHigh);
4481 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
4482 "Intervals are overlapping",
Range);
4488void Verifier::visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty) {
4490 "precondition violation");
4491 verifyRangeLikeMetadata(
I,
Range, Ty, RangeLikeMetadataKind::Range);
4494void Verifier::visitNoFPClassMetadata(Instruction &
I, MDNode *NoFPClass,
4496 Check(AttributeFuncs::isNoFPClassCompatibleType(Ty),
4497 "nofpclass only applies to floating-point typed loads",
I);
4500 "nofpclass must have exactly one entry", NoFPClass);
4501 ConstantInt *MaskVal =
4504 "nofpclass entry must be a constant i32", NoFPClass);
4506 Check(Val != 0,
"'nofpclass' must have at least one test bit set", NoFPClass,
4510 "Invalid value for 'nofpclass' test mask", NoFPClass,
I);
4513void Verifier::visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
4516 "precondition violation");
4517 verifyRangeLikeMetadata(
I,
Range, Ty,
4518 RangeLikeMetadataKind::NoaliasAddrspace);
4521void Verifier::checkAtomicMemAccessSize(
Type *Ty,
const Instruction *
I) {
4522 unsigned Size =
DL.getTypeSizeInBits(Ty).getFixedValue();
4523 Check(
Size >= 8,
"atomic memory access' size must be byte-sized", Ty,
I);
4525 "atomic memory access' operand must have a power-of-two size", Ty,
I);
4528void Verifier::visitLoadInst(LoadInst &LI) {
4530 Check(PTy,
"Load operand must be a pointer.", &LI);
4533 Check(
A->value() <= Value::MaximumAlignment,
4534 "huge alignment values are unsupported", &LI);
4536 Check(ElTy->
isSized(),
"loading unsized types is not allowed", &LI);
4539 LI.
getOrdering() != AtomicOrdering::AcquireRelease,
4540 "Load cannot have Release ordering", &LI);
4544 "atomic load operand must have integer, byte, pointer, floating "
4545 "point, or vector type!",
4548 checkAtomicMemAccessSize(ElTy, &LI);
4551 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4554 visitInstruction(LI);
4557void Verifier::visitStoreInst(StoreInst &SI) {
4559 Check(PTy,
"Store operand must be a pointer.", &SI);
4560 Type *ElTy =
SI.getOperand(0)->getType();
4561 if (MaybeAlign
A =
SI.getAlign()) {
4562 Check(
A->value() <= Value::MaximumAlignment,
4563 "huge alignment values are unsupported", &SI);
4565 Check(ElTy->
isSized(),
"storing unsized types is not allowed", &SI);
4566 if (
SI.isAtomic()) {
4567 Check(
SI.getOrdering() != AtomicOrdering::Acquire &&
4568 SI.getOrdering() != AtomicOrdering::AcquireRelease,
4569 "Store cannot have Acquire ordering", &SI);
4573 "atomic store operand must have integer, byte, pointer, floating "
4574 "point, or vector type!",
4576 checkAtomicMemAccessSize(ElTy, &SI);
4579 "Non-atomic store cannot have SynchronizationScope specified", &SI);
4581 visitInstruction(SI);
4585void Verifier::verifySwiftErrorCall(CallBase &
Call,
4586 const Value *SwiftErrorVal) {
4588 if (
I.value() == SwiftErrorVal) {
4590 "swifterror value when used in a callsite should be marked "
4591 "with swifterror attribute",
4592 SwiftErrorVal,
Call);
4597void Verifier::verifySwiftErrorValue(
const Value *SwiftErrorVal) {
4600 for (
const User *U : SwiftErrorVal->
users()) {
4603 "swifterror value can only be loaded and stored from, or "
4604 "as a swifterror argument!",
4608 Check(StoreI->getOperand(1) == SwiftErrorVal,
4609 "swifterror value should be the second operand when used "
4613 verifySwiftErrorCall(*
const_cast<CallBase *
>(
Call), SwiftErrorVal);
4617void Verifier::visitAllocaInst(AllocaInst &AI) {
4620 Check(!MD->getZExtValue(),
4621 "Non-logical alloca disallowed for this module.");
4624 SmallPtrSet<Type*, 4> Visited;
4625 Check(Ty->
isSized(&Visited),
"Cannot allocate unsized type", &AI);
4629 "Alloca has illegal target extension type", &AI);
4631 "Alloca array size must have integer type", &AI);
4633 Check(
A->value() <= Value::MaximumAlignment,
4634 "huge alignment values are unsupported", &AI);
4640 "swifterror alloca must not be array allocation", &AI);
4641 verifySwiftErrorValue(&AI);
4644 visitInstruction(AI);
4650void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4653 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4654 checkAtomicMemAccessSize(ElTy, &CXI);
4655 visitInstruction(CXI);
4658void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
4660 "atomicrmw instructions cannot be unordered.", &RMWI);
4663 Type *ScalarTy = ElTy;
4666 Check(VecTy,
"atomicrmw elementwise operand must have fixed vector type!",
4669 ScalarTy = VecTy->getElementType();
4676 " operand must have integer or floating point type!",
4681 " operand must have floating-point or fixed vector of "
4688 " operand must have integer type!",
4691 checkAtomicMemAccessSize(ElTy, &RMWI);
4693 "Invalid binary operation!", &RMWI);
4694 visitInstruction(RMWI);
4697void Verifier::visitFenceInst(FenceInst &FI) {
4699 Check(Ordering == AtomicOrdering::Acquire ||
4700 Ordering == AtomicOrdering::Release ||
4701 Ordering == AtomicOrdering::AcquireRelease ||
4702 Ordering == AtomicOrdering::SequentiallyConsistent,
4703 "fence instructions may only have acquire, release, acq_rel, or "
4704 "seq_cst ordering.",
4706 visitInstruction(FI);
4709void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
4712 "Invalid ExtractValueInst operands!", &EVI);
4714 visitInstruction(EVI);
4717void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
4721 "Invalid InsertValueInst operands!", &IVI);
4723 visitInstruction(IVI);
4728 return FPI->getParentPad();
4733void Verifier::visitEHPadPredecessors(Instruction &
I) {
4739 Check(BB != &
F->getEntryBlock(),
"EH pad cannot be in entry block.", &
I);
4747 Check(
II &&
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4748 "Block containing LandingPadInst must be jumped to "
4749 "only by the unwind edge of an invoke.",
4757 "Block containg CatchPadInst must be jumped to "
4758 "only by its catchswitch.",
4760 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4761 "Catchswitch cannot unwind to one of its catchpads",
4762 CPI->getCatchSwitch(), CPI);
4774 Check(
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4775 "EH pad must be jumped to via an unwind edge", ToPad,
II);
4778 if (CalledFn && CalledFn->isIntrinsic() &&
II->doesNotThrow() &&
4782 FromPad = Bundle->Inputs[0];
4786 FromPad = CRI->getOperand(0);
4787 Check(FromPad != ToPadParent,
"A cleanupret must exit its cleanup", CRI);
4791 Check(
false,
"EH pad must be jumped to via an unwind edge", ToPad, TI);
4795 SmallPtrSet<Value *, 8> Seen;
4797 Check(FromPad != ToPad,
4798 "EH pad cannot handle exceptions raised within it", FromPad, TI);
4799 if (FromPad == ToPadParent) {
4804 "A single unwind edge may only enter one EH pad", TI);
4805 Check(Seen.
insert(FromPad).second,
"EH pad jumps through a cycle of pads",
4811 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
4816void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
4820 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
4822 visitEHPadPredecessors(LPI);
4824 if (!LandingPadResultTy)
4825 LandingPadResultTy = LPI.
getType();
4828 "The landingpad instruction should have a consistent result type "
4829 "inside a function.",
4833 Check(
F->hasPersonalityFn(),
4834 "LandingPadInst needs to be in a function with a personality.", &LPI);
4839 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
4845 "Catch operand does not have pointer type!", &LPI);
4847 Check(LPI.
isFilter(i),
"Clause is neither catch nor filter!", &LPI);
4849 "Filter operand is not an array of constants!", &LPI);
4853 visitInstruction(LPI);
4856void Verifier::visitResumeInst(ResumeInst &RI) {
4858 "ResumeInst needs to be in a function with a personality.", &RI);
4860 if (!LandingPadResultTy)
4864 "The resume instruction should have a consistent result type "
4865 "inside a function.",
4868 visitTerminator(RI);
4871void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
4875 Check(
F->hasPersonalityFn(),
4876 "CatchPadInst needs to be in a function with a personality.", &CPI);
4879 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4885 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
4890 return isa<Constant>(V) || isa<AllocaInst>(V);
4892 "Argument operand must be alloca or constant.", &CPI);
4894 visitEHPadPredecessors(CPI);
4895 visitFuncletPadInst(CPI);
4898void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
4900 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
4903 visitTerminator(CatchReturn);
4906void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
4910 Check(
F->hasPersonalityFn(),
4911 "CleanupPadInst needs to be in a function with a personality.", &CPI);
4916 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
4920 "CleanupPadInst has an invalid parent.", &CPI);
4922 visitEHPadPredecessors(CPI);
4923 visitFuncletPadInst(CPI);
4926void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
4927 User *FirstUser =
nullptr;
4928 Value *FirstUnwindPad =
nullptr;
4930 SmallPtrSet<FuncletPadInst *, 8> Seen;
4932 while (!Worklist.empty()) {
4933 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
4935 "FuncletPadInst must not be nested within itself", CurrentPad);
4936 Value *UnresolvedAncestorPad =
nullptr;
4937 for (User *U : CurrentPad->
users()) {
4940 UnwindDest = CRI->getUnwindDest();
4946 if (CSI->unwindsToCaller())
4948 UnwindDest = CSI->getUnwindDest();
4950 UnwindDest =
II->getUnwindDest();
4960 Worklist.push_back(CPI);
4975 if (UnwindParent == CurrentPad)
4981 Value *ExitedPad = CurrentPad;
4984 if (ExitedPad == &FPI) {
4989 UnresolvedAncestorPad = &FPI;
4993 if (ExitedParent == UnwindParent) {
4997 UnresolvedAncestorPad = ExitedParent;
5000 ExitedPad = ExitedParent;
5006 UnresolvedAncestorPad = &FPI;
5013 Check(UnwindPad == FirstUnwindPad,
5014 "Unwind edges out of a funclet "
5015 "pad must have the same unwind "
5017 &FPI, U, FirstUser);
5020 FirstUnwindPad = UnwindPad;
5029 if (CurrentPad != &FPI)
5032 if (UnresolvedAncestorPad) {
5033 if (CurrentPad == UnresolvedAncestorPad) {
5037 assert(CurrentPad == &FPI);
5045 Value *ResolvedPad = CurrentPad;
5046 while (!Worklist.empty()) {
5047 Value *UnclePad = Worklist.back();
5051 while (ResolvedPad != AncestorPad) {
5053 if (ResolvedParent == UnresolvedAncestorPad) {
5056 ResolvedPad = ResolvedParent;
5060 if (ResolvedPad != AncestorPad)
5063 Worklist.pop_back();
5068 if (FirstUnwindPad) {
5070 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
5071 Value *SwitchUnwindPad;
5072 if (SwitchUnwindDest)
5076 Check(SwitchUnwindPad == FirstUnwindPad,
5077 "Unwind edges out of a catch must have the same unwind dest as "
5078 "the parent catchswitch",
5079 &FPI, FirstUser, CatchSwitch);
5083 visitInstruction(FPI);
5086void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
5090 Check(
F->hasPersonalityFn(),
5091 "CatchSwitchInst needs to be in a function with a personality.",
5097 "CatchSwitchInst not the first non-PHI instruction in the block.",
5102 "CatchSwitchInst has an invalid parent.", ParentPad);
5107 "CatchSwitchInst must unwind to an EH block which is not a "
5113 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
5117 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
5119 for (BasicBlock *Handler : CatchSwitch.
handlers()) {
5121 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
5124 visitEHPadPredecessors(CatchSwitch);
5125 visitTerminator(CatchSwitch);
5128void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
5130 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
5136 "CleanupReturnInst must unwind to an EH block which is not a "
5141 visitTerminator(CRI);
5144void Verifier::verifyDominatesUse(Instruction &
I,
unsigned i) {
5150 if (
II->getNormalDest() ==
II->getUnwindDest())
5164 const Use &
U =
I.getOperandUse(i);
5165 Check(DT.dominates(
Op, U),
"Instruction does not dominate all uses!",
Op, &
I);
5168void Verifier::visitDereferenceableMetadata(Instruction&
I, MDNode* MD) {
5169 Check(
I.getType()->isPointerTy(),
5170 "dereferenceable, dereferenceable_or_null "
5171 "apply only to pointer types",
5174 "dereferenceable, dereferenceable_or_null apply only to load"
5175 " and inttoptr instructions, use attributes for calls or invokes",
5178 "dereferenceable, dereferenceable_or_null "
5179 "take one operand!",
5184 "dereferenceable_or_null metadata value must be an i64!",
5188void Verifier::visitNofreeMetadata(Instruction &
I, MDNode *MD) {
5189 Check(
I.getType()->isPointerTy(),
"nofree applies only to pointer types", &
I);
5195void Verifier::visitProfMetadata(Instruction &
I, MDNode *MD) {
5196 auto GetBranchingTerminatorNumOperands = [&]() {
5197 unsigned ExpectedNumOperands = 0;
5201 ExpectedNumOperands =
SI->getNumSuccessors();
5203 ExpectedNumOperands = 1;
5205 ExpectedNumOperands = IBI->getNumDestinations();
5207 ExpectedNumOperands = 2;
5210 return ExpectedNumOperands;
5213 "!prof annotations should have at least 1 operand", MD);
5215 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null", MD);
5217 "expected string with name of the !prof annotation", MD);
5223 "'unknown' !prof should only appear on instructions on which "
5224 "'branch_weights' would",
5226 verifyUnknownProfileMetadata(MD);
5231 "!prof annotations should have no less than 2 operands", MD);
5237 Check(NumBranchWeights == 1 || NumBranchWeights == 2,
5238 "Wrong number of InvokeInst branch_weights operands", MD);
5240 const unsigned ExpectedNumOperands = GetBranchingTerminatorNumOperands();
5241 if (ExpectedNumOperands == 0)
5242 CheckFailed(
"!prof branch_weights are not allowed for this instruction",
5245 Check(NumBranchWeights == ExpectedNumOperands,
"Wrong number of operands",
5251 Check(MDO,
"second operand should not be null", MD);
5253 "!prof brunch_weights operand is not a const int");
5258 Check(KindInt,
"VP !prof missing kind argument", MD);
5261 Check(Kind >= InstrProfValueKind::IPVK_First &&
5262 Kind <= InstrProfValueKind::IPVK_Last,
5263 "Invalid VP !prof kind", MD);
5265 "VP !prof should have an even number "
5266 "of arguments after 'VP'",
5268 if (Kind == InstrProfValueKind::IPVK_IndirectCallTarget ||
5269 Kind == InstrProfValueKind::IPVK_MemOPSize)
5271 "VP !prof indirect call or memop size expected to be applied to "
5272 "CallBase instructions only",
5275 DenseSet<uint64_t> ProfileValues;
5277 ConstantInt *ProfileValue =
5279 Check(ProfileValue,
"VP !prof value operand is not a const int", MD);
5280 uint64_t ProfileValueInt = ProfileValue->
getZExtValue();
5281 auto [ValueIt,
Inserted] = ProfileValues.
insert(ProfileValueInt);
5282 Check(Inserted,
"VP !prof should not have duplicate profile values", MD);
5285 CheckFailed(
"expected either branch_weights or VP profile name", MD);
5289void Verifier::visitDIAssignIDMetadata(Instruction &
I, MDNode *MD) {
5290 assert(
I.hasMetadata(LLVMContext::MD_DIAssignID));
5295 bool ExpectedInstTy =
5297 CheckDI(ExpectedInstTy,
"!DIAssignID attached to unexpected instruction kind",
5302 for (
auto *User : AsValue->users()) {
5304 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
5308 CheckDI(DAI->getFunction() ==
I.getFunction(),
5309 "dbg.assign not in same function as inst", DAI, &
I);
5312 for (DbgVariableRecord *DVR :
5315 "!DIAssignID should only be used by Assign DVRs.", MD, DVR);
5316 CheckDI(DVR->getFunction() ==
I.getFunction(),
5317 "DVRAssign not in same function as inst", DVR, &
I);
5321void Verifier::visitMMRAMetadata(Instruction &
I, MDNode *MD) {
5323 "!mmra metadata attached to unexpected instruction kind",
I, MD);
5334 for (
const MDOperand &MDOp : MD->
operands())
5336 "!mmra metadata tuple operand is not an MMRA tag",
I, MDOp.get());
5339void Verifier::visitCallStackMetadata(MDNode *MD) {
5343 "call stack metadata should have at least 1 operand", MD);
5347 "call stack metadata operand should be constant integer",
Op);
5350void Verifier::visitMemProfMetadata(Instruction &
I, MDNode *MD) {
5353 Check(
I.hasMetadata(LLVMContext::MD_callsite),
5354 "!memprof metadata requires !callsite metadata", &
I, MD);
5356 "!memprof annotations should have at least 1 metadata operand "
5361 for (
auto &MIBOp : MD->
operands()) {
5367 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
5371 "!memprof MemInfoBlock first operand should not be null", MIB);
5373 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
5375 visitCallStackMetadata(StackMD);
5379 "!memprof MemInfoBlock second operand should be an MDString", MIB);
5384 Check(OpNode,
"Not all !memprof MemInfoBlock operands 2 to N are MDNode",
5387 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with 2 "
5392 [](
const MDOperand &
Op) {
5393 return mdconst::hasa<ConstantInt>(Op);
5395 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with "
5396 "ConstantInt operands",
5402void Verifier::visitCallsiteMetadata(Instruction &
I, MDNode *MD) {
5406 visitCallStackMetadata(MD);
5409void Verifier::visitCalleeTypeMetadata(Instruction &
I, MDNode *MD) {
5414 "The callee_type metadata must be a list of callgraph metadata nodes",
5417 Check(CallgraphMD->getNumOperands() == 1,
5418 "Well-formed generalized callgraph metadata must contain exactly one "
5422 "The operand of callgraph metadata for functions must be an MDString",
5426 .ends_with(
".generalized"),
5427 "Only generalized callgraph metadata can be part of the callee_type "
5433void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
5436 "annotation must have at least one operand");
5438 bool TupleOfStrings =
5444 "operands must be a string or a tuple of strings");
5448void Verifier::visitAliasScopeMetadata(
const MDNode *MD) {
5453 "first scope operand must be self-referential or string", MD);
5456 "third scope operand must be string (if used)", MD);
5459 Check(
Domain !=
nullptr,
"second scope operand must be MDNode", MD);
5461 unsigned NumDomainOps =
Domain->getNumOperands();
5462 Check(NumDomainOps >= 1 && NumDomainOps <= 2,
5463 "domain must have one or two operands",
Domain);
5466 "first domain operand must be self-referential or string",
Domain);
5467 if (NumDomainOps == 2)
5469 "second domain operand must be string (if used)",
Domain);
5472void Verifier::visitAliasScopeListMetadata(
const MDNode *MD) {
5475 Check(OpMD !=
nullptr,
"scope list must consist of MDNodes", MD);
5476 visitAliasScopeMetadata(OpMD);
5480void Verifier::visitAccessGroupMetadata(
const MDNode *MD) {
5481 auto IsValidAccessScope = [](
const MDNode *MD) {
5486 if (IsValidAccessScope(MD))
5492 Check(OpMD !=
nullptr,
"Access scope list must consist of MDNodes", MD);
5493 Check(IsValidAccessScope(OpMD),
5494 "Access scope list contains invalid access scope", MD);
5498void Verifier::visitCapturesMetadata(Instruction &
I,
const MDNode *Captures) {
5499 static const char *ValidArgs[] = {
"address_is_null",
"address",
5500 "read_provenance",
"provenance"};
5503 Check(SI,
"!captures metadata can only be applied to store instructions", &
I);
5504 Check(
SI->getValueOperand()->getType()->isPointerTy(),
5505 "!captures metadata can only be applied to store with value operand of "
5513 Check(Str,
"!captures metadata must be a list of strings", &
I);
5515 "invalid entry in !captures metadata", &
I, Str);
5519void Verifier::visitAllocTokenMetadata(Instruction &
I, MDNode *MD) {
5524 "expected integer constant", MD);
5527void Verifier::visitInlineHistoryMetadata(Instruction &
I, MDNode *MD) {
5536 ->stripPointerCastsAndAliases()),
5537 "!inline_history operands must be functions or null", MD);
5541void Verifier::visitMemCacheHintMetadata(Instruction &
I, MDNode *MD) {
5542 Check(
I.mayReadOrWriteMemory(),
5543 "!mem.cache_hint is only valid on memory operations", &
I);
5546 "!mem.cache_hint must have even number of operands "
5547 "(operand_no, hint_node pairs)",
5553 "!mem.cache_hint is not supported on non-intrinsic calls", &
I);
5555 unsigned NumOperands = CB ? CB->arg_size() :
I.getNumOperands();
5557 SmallDenseSet<unsigned, 4> SeenOperandNos;
5558 std::optional<uint64_t> LastOperandNo;
5564 "!mem.cache_hint must alternate between i32 operand numbers and "
5565 "metadata hint nodes",
5568 Check(OpNoCI->getValue().isNonNegative(),
5569 "!mem.cache_hint operand number must be non-negative", MD);
5571 uint64_t OperandNo = OpNoCI->getZExtValue();
5572 Check(OperandNo < NumOperands,
5573 "!mem.cache_hint operand number is out of range", &
I);
5576 CB ? CB->getArgOperand(OperandNo) :
I.getOperand(OperandNo);
5578 "!mem.cache_hint operand number must refer to a pointer operand", &
I);
5581 Check(Inserted,
"!mem.cache_hint contains duplicate operand number", MD);
5583 Check(!Inserted || !LastOperandNo || OperandNo > *LastOperandNo,
5584 "!mem.cache_hint operand numbers must be in increasing order", MD);
5585 LastOperandNo = OperandNo;
5589 "!mem.cache_hint must alternate between i32 operand numbers and "
5590 "metadata hint nodes",
5594 "!mem.cache_hint hint node must have even number of operands "
5595 "(key-value pairs)",
5598 StringSet<> SeenKeys;
5599 for (
unsigned K = 0;
K + 1 <
Node->getNumOperands();
K += 2) {
5601 Check(
Key,
"!mem.cache_hint key must be a string", Node);
5603 StringRef KeyStr =
Key->getString();
5605 "!mem.cache_hint hint node contains duplicate key", Node);
5610 "!mem.cache_hint value must be a string or integer", Node);
5617void Verifier::visitInstruction(Instruction &
I) {
5619 Check(BB,
"Instruction not embedded in basic block!", &
I);
5622 for (User *U :
I.users()) {
5623 Check(U != (User *)&
I || !DT.isReachableFromEntry(BB),
5624 "Only PHI nodes may reference their own value!", &
I);
5629 Check(!
I.getType()->isVoidTy() || !
I.hasName(),
5630 "Instruction has a name, but provides a void value!", &
I);
5634 Check(
I.getType()->isVoidTy() ||
I.getType()->isFirstClassType(),
5635 "Instruction returns a non-scalar type!", &
I);
5640 "Invalid use of metadata!", &
I);
5645 for (Use &U :
I.uses()) {
5648 "Instruction referencing"
5649 " instruction not embedded in a basic block!",
5652 CheckFailed(
"Use of instruction is not an instruction!", U);
5661 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i) {
5662 Check(
I.getOperand(i) !=
nullptr,
"Instruction has null operand!", &
I);
5666 if (!
I.getOperand(i)->getType()->isFirstClassType()) {
5667 Check(
false,
"Instruction operands must be first-class values!", &
I);
5673 auto IsAttachedCallOperand = [](
Function *
F,
const CallBase *CBI,
5675 return CBI && CBI->isOperandBundleOfType(
5683 Check((!
F->isIntrinsic() ||
5684 (CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i)) ||
5685 IsAttachedCallOperand(
F, CBI, i)),
5686 "Cannot take the address of an intrinsic!", &
I);
5688 F->getIntrinsicID() == Intrinsic::donothing ||
5689 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
5690 F->getIntrinsicID() == Intrinsic::seh_try_end ||
5691 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
5692 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
5693 F->getIntrinsicID() == Intrinsic::coro_resume ||
5694 F->getIntrinsicID() == Intrinsic::coro_destroy ||
5695 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
5696 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
5697 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
5698 F->getIntrinsicID() ==
5699 Intrinsic::experimental_patchpoint_void ||
5700 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
5701 F->getIntrinsicID() == Intrinsic::fake_use ||
5702 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
5703 F->getIntrinsicID() == Intrinsic::wasm_throw ||
5704 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
5705 IsAttachedCallOperand(
F, CBI, i),
5706 "Cannot invoke an intrinsic other than donothing, patchpoint, "
5707 "statepoint, coro_resume, coro_destroy, clang.arc.attachedcall or "
5710 Check(
F->getParent() == &M,
"Referencing function in another module!", &
I,
5711 &M,
F,
F->getParent());
5714 "Referring to a basic block in another function!", &
I);
5717 "Referring to an argument in another function!", &
I);
5719 Check(GV->
getParent() == &M,
"Referencing global in another module!", &
I,
5723 "Referring to an instruction in another function!", &
I);
5724 verifyDominatesUse(
I, i);
5726 Check(CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i),
5727 "Cannot take the address of an inline asm!", &
I);
5729 visitConstantExprsRecursively(
C);
5733 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_fpmath)) {
5735 "fpmath requires a floating point result!", &
I);
5737 if (ConstantFP *CFP0 =
5739 const APFloat &Accuracy = CFP0->getValueAPF();
5741 "fpmath accuracy must have float type", &
I);
5743 "fpmath accuracy not a positive number!", &
I);
5745 Check(
false,
"invalid fpmath accuracy!", &
I);
5749 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_range)) {
5751 "Ranges are only for loads, calls and invokes!", &
I);
5752 visitRangeMetadata(
I,
Range,
I.getType());
5755 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofpclass)) {
5757 visitNoFPClassMetadata(
I, MD,
I.getType());
5760 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_noalias_addrspace)) {
5763 "noalias.addrspace are only for memory operations!", &
I);
5764 visitNoaliasAddrspaceMetadata(
I,
Range,
I.getType());
5767 if (
I.hasMetadata(LLVMContext::MD_invariant_group)) {
5769 "invariant.group metadata is only for loads and stores", &
I);
5772 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nonnull)) {
5773 Check(
I.getType()->isPointerTy(),
"nonnull applies only to pointer types",
5776 "nonnull applies only to load instructions, use attributes"
5777 " for calls or invokes",
5782 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noundef)) {
5787 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable))
5788 visitDereferenceableMetadata(
I, MD);
5790 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
5791 visitDereferenceableMetadata(
I, MD);
5793 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofree))
5794 visitNofreeMetadata(
I, MD);
5796 if (MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa))
5799 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noalias))
5800 visitAliasScopeListMetadata(MD);
5801 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alias_scope))
5802 visitAliasScopeListMetadata(MD);
5804 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_access_group))
5805 visitAccessGroupMetadata(MD);
5807 if (MDNode *AlignMD =
I.getMetadata(LLVMContext::MD_align)) {
5808 Check(
I.getType()->isPointerTy(),
"align applies only to pointer types",
5811 "align applies only to load instructions, "
5812 "use attributes for calls or invokes",
5814 Check(AlignMD->getNumOperands() == 1,
"align takes one operand!", &
I);
5817 "align metadata value must be an i64!", &
I);
5821 Check(Align <= Value::MaximumAlignment,
5822 "alignment is larger that implementation defined limit", &
I);
5825 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_prof))
5826 visitProfMetadata(
I, MD);
5828 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_memprof))
5829 visitMemProfMetadata(
I, MD);
5831 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callsite))
5832 visitCallsiteMetadata(
I, MD);
5834 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callee_type))
5835 visitCalleeTypeMetadata(
I, MD);
5837 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_DIAssignID))
5838 visitDIAssignIDMetadata(
I, MD);
5840 if (MDNode *MMRA =
I.getMetadata(LLVMContext::MD_mmra))
5841 visitMMRAMetadata(
I, MMRA);
5843 if (MDNode *Annotation =
I.getMetadata(LLVMContext::MD_annotation))
5844 visitAnnotationMetadata(Annotation);
5846 if (MDNode *Captures =
I.getMetadata(LLVMContext::MD_captures))
5847 visitCapturesMetadata(
I, Captures);
5849 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alloc_token))
5850 visitAllocTokenMetadata(
I, MD);
5852 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_inline_history))
5853 visitInlineHistoryMetadata(
I, MD);
5855 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_mem_cache_hint))
5856 visitMemCacheHintMetadata(
I, MD);
5858 if (MDNode *
N =
I.getDebugLoc().getAsMDNode()) {
5860 visitMDNode(*
N, AreDebugLocsAllowed::Yes);
5863 if (
DL->getAtomGroup()) {
5864 CheckDI(
DL->getScope()->getSubprogram()->getKeyInstructionsEnabled(),
5865 "DbgLoc uses atomGroup but DISubprogram doesn't have Key "
5866 "Instructions enabled",
5867 DL,
DL->getScope()->getSubprogram());
5873 I.getAllMetadata(MDs);
5874 for (
auto Attachment : MDs) {
5875 unsigned Kind = Attachment.first;
5877 (
Kind == LLVMContext::MD_dbg ||
Kind == LLVMContext::MD_loop)
5878 ? AreDebugLocsAllowed::Yes
5879 : AreDebugLocsAllowed::
No;
5880 visitMDNode(*Attachment.second, AllowLocs);
5897 "const x86_amx is not allowed in argument!");
5903 case Intrinsic::assume: {
5907 "assume with operand bundles must have i1 true condition",
Call);
5913 auto GetTypeAt = [&](
unsigned Index) {
5914 return OBU.Inputs[
Index]->getType();
5919 CheckFailed(
"tags must be valid attribute names",
Call);
5921 case BundleAttr::Align:
5922 Check(OBU.Inputs.size() >= 2 && OBU.Inputs.size() <= 3,
5923 "alignment assumptions should have 2 or 3 arguments",
Call);
5926 Check(GetTypeAt(1)->isIntegerTy() &&
5927 GetTypeAt(1)->getIntegerBitWidth() <= 64,
5928 "second argument should be an integer with a maximum width of 64 "
5931 Check(OBU.Inputs.size() < 3 ||
5932 GetTypeAt(2)->isIntegerTy() &&
5933 GetTypeAt(2)->getIntegerBitWidth() <= 64,
5934 "third argument should be an integer with a maximum width of 64 "
5938 case BundleAttr::Cold:
5939 Check(OBU.Inputs.size() == 0,
5940 "cold assumptions should have no arguments",
Call);
5942 case BundleAttr::Dereferenceable:
5943 case BundleAttr::DereferenceableOrNull:
5944 Check(OBU.Inputs.size() == 2,
5945 "dereferenceable assumptions should have 2 arguments",
Call);
5948 Check(GetTypeAt(1)->isIntegerTy() &&
5949 GetTypeAt(1)->getIntegerBitWidth() <= 64,
5950 "second argument should be an integer with a maximum width of 64 "
5954 case BundleAttr::Ignore:
5956 case BundleAttr::NonNull:
5957 Check(OBU.Inputs.size() == 1,
5958 "nonnull assumptions should have 1 argument",
Call);
5962 case BundleAttr::NoUndef:
5963 Check(OBU.Inputs.size() == 1,
5964 "noundef assumptions should have 1 argument",
Call);
5966 case BundleAttr::SeparateStorage:
5967 Check(OBU.Inputs.size() == 2,
5968 "separate_storage assumptions should have 2 arguments",
Call);
5970 "arguments to separate_storage assumptions should be pointers",
5977 case Intrinsic::ucmp:
5978 case Intrinsic::scmp: {
5983 "result type must be at least 2 bits wide",
Call);
5985 bool IsDestTypeVector = DestTy->
isVectorTy();
5987 "ucmp/scmp argument and result types must both be either vector or "
5990 if (IsDestTypeVector) {
5993 Check(SrcVecLen == DestVecLen,
5994 "return type and arguments must have the same number of "
6000 case Intrinsic::coro_begin:
6001 case Intrinsic::coro_begin_custom_abi:
6003 "id argument of llvm.coro.begin must refer to coro.id");
6005 case Intrinsic::coro_id: {
6007 "align argument only accepts constants");
6010 "promise argument must refer to an alloca");
6015 "coro argument must refer to a function");
6019 if (BeforeCoroSplit)
6022 Check(!BeforeCoroEarly,
"cannot run CoroSplit before CoroEarly");
6025 "info argument of llvm.coro.id must refer to an initialized "
6029 "info argument of llvm.coro.id must refer to either a struct or "
6033 case Intrinsic::is_fpclass: {
6036 "unsupported bits for llvm.is.fpclass test mask");
6039 case Intrinsic::fptrunc_round: {
6044 MD = MAV->getMetadata();
6046 Check(MD !=
nullptr,
"missing rounding mode argument",
Call);
6049 (
"invalid value for llvm.fptrunc.round metadata operand"
6050 " (the operand should be a string)"),
6053 std::optional<RoundingMode> RoundMode =
6055 Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
6056 "unsupported rounding mode argument",
Call);
6059 case Intrinsic::convert_to_arbitrary_fp: {
6067 "if floating-point operand is a vector, integer operand must also "
6070 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6071 "floating-point and integer vector operands must have the same "
6078 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6080 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6081 StringRef Interp = InterpStr->getString();
6083 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6088 "unsupported interpretation metadata string",
Call);
6092 Check(RoundingMAV,
"missing rounding mode metadata operand",
Call);
6094 Check(RoundingStr,
"rounding mode metadata operand must be a string",
Call);
6096 std::optional<RoundingMode>
RM =
6098 Check(RM && *RM != RoundingMode::Dynamic,
6099 "unsupported rounding mode argument",
Call);
6102 case Intrinsic::convert_from_arbitrary_fp: {
6110 "if floating-point operand is a vector, integer operand must also "
6113 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6114 "floating-point and integer vector operands must have the same "
6121 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6123 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6124 StringRef Interp = InterpStr->getString();
6126 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6131 "unsupported interpretation metadata string",
Call);
6134#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6135#include "llvm/IR/VPIntrinsics.def"
6136#undef BEGIN_REGISTER_VP_INTRINSIC
6139#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
6140 case Intrinsic::INTRINSIC:
6141#include "llvm/IR/ConstrainedOps.def"
6145 case Intrinsic::dbg_declare:
6146 case Intrinsic::dbg_value:
6147 case Intrinsic::dbg_assign:
6148 case Intrinsic::dbg_label:
6155 case Intrinsic::memcpy:
6156 case Intrinsic::memcpy_inline:
6157 case Intrinsic::memmove:
6158 case Intrinsic::memset:
6159 case Intrinsic::memset_inline:
6161 case Intrinsic::experimental_memset_pattern: {
6163 Check(Memset->getValue()->getType()->isSized(),
6164 "unsized types cannot be used as memset patterns",
Call);
6167 case Intrinsic::memcpy_element_unordered_atomic:
6168 case Intrinsic::memmove_element_unordered_atomic:
6169 case Intrinsic::memset_element_unordered_atomic: {
6172 ConstantInt *ElementSizeCI =
6174 const APInt &ElementSizeVal = ElementSizeCI->
getValue();
6176 "element size of the element-wise atomic memory intrinsic "
6177 "must be a power of 2",
6180 auto IsValidAlignment = [&](MaybeAlign Alignment) {
6181 return Alignment && ElementSizeVal.
ule(Alignment->value());
6183 Check(IsValidAlignment(AMI->getDestAlign()),
6184 "incorrect alignment of the destination argument",
Call);
6186 Check(IsValidAlignment(AMT->getSourceAlign()),
6187 "incorrect alignment of the source argument",
Call);
6191 case Intrinsic::call_preallocated_setup: {
6193 bool FoundCall =
false;
6196 Check(UseCall !=
nullptr,
6197 "Uses of llvm.call.preallocated.setup must be calls");
6199 if (IID == Intrinsic::call_preallocated_arg) {
6201 Check(AllocArgIndex !=
nullptr,
6202 "llvm.call.preallocated.alloc arg index must be a constant");
6203 auto AllocArgIndexInt = AllocArgIndex->getValue();
6204 Check(AllocArgIndexInt.sge(0) &&
6205 AllocArgIndexInt.slt(NumArgs->getValue()),
6206 "llvm.call.preallocated.alloc arg index must be between 0 and "
6208 "llvm.call.preallocated.setup's argument count");
6209 }
else if (IID == Intrinsic::call_preallocated_teardown) {
6212 Check(!FoundCall,
"Can have at most one call corresponding to a "
6213 "llvm.call.preallocated.setup");
6215 size_t NumPreallocatedArgs = 0;
6216 for (
unsigned i = 0; i < UseCall->arg_size(); i++) {
6217 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
6218 ++NumPreallocatedArgs;
6221 Check(NumPreallocatedArgs != 0,
6222 "cannot use preallocated intrinsics on a call without "
6223 "preallocated arguments");
6224 Check(NumArgs->equalsInt(NumPreallocatedArgs),
6225 "llvm.call.preallocated.setup arg size must be equal to number "
6226 "of preallocated arguments "
6236 auto PreallocatedBundle =
6238 Check(PreallocatedBundle,
6239 "Use of llvm.call.preallocated.setup outside intrinsics "
6240 "must be in \"preallocated\" operand bundle");
6241 Check(PreallocatedBundle->Inputs.front().get() == &
Call,
6242 "preallocated bundle must have token from corresponding "
6243 "llvm.call.preallocated.setup");
6248 case Intrinsic::call_preallocated_arg: {
6251 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6252 "llvm.call.preallocated.arg token argument must be a "
6253 "llvm.call.preallocated.setup");
6255 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
6256 "call site attribute");
6259 case Intrinsic::call_preallocated_teardown: {
6262 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6263 "llvm.call.preallocated.teardown token argument must be a "
6264 "llvm.call.preallocated.setup");
6267 case Intrinsic::gcroot:
6268 case Intrinsic::gcwrite:
6269 case Intrinsic::gcread:
6270 if (
ID == Intrinsic::gcroot) {
6273 Check(AI,
"llvm.gcroot parameter #1 must be an alloca.",
Call);
6275 "llvm.gcroot parameter #2 must be a constant.",
Call);
6278 "llvm.gcroot parameter #1 must either be a pointer alloca, "
6279 "or argument #2 must be a non-null constant.",
6285 "Enclosing function does not use GC.",
Call);
6287 case Intrinsic::init_trampoline:
6289 "llvm.init_trampoline parameter #2 must resolve to a function.",
6292 case Intrinsic::prefetch:
6294 "rw argument to llvm.prefetch must be 0-1",
Call);
6296 "locality argument to llvm.prefetch must be 0-3",
Call);
6298 "cache type argument to llvm.prefetch must be 0-1",
Call);
6300 case Intrinsic::reloc_none: {
6303 "llvm.reloc.none argument must be a metadata string", &
Call);
6306 case Intrinsic::stackprotector:
6308 "llvm.stackprotector parameter #2 must resolve to an alloca.",
Call);
6310 case Intrinsic::localescape: {
6314 Check(!SawFrameEscape,
"multiple calls to llvm.localescape in one function",
6321 "llvm.localescape only accepts static allocas",
Call);
6324 SawFrameEscape =
true;
6327 case Intrinsic::localrecover: {
6331 "llvm.localrecover first "
6332 "argument must be function defined in this module",
6335 auto &
Entry = FrameEscapeInfo[Fn];
6336 Entry.second = unsigned(
6337 std::max(uint64_t(
Entry.second), IdxArg->getLimitedValue(~0U) + 1));
6341 case Intrinsic::experimental_gc_statepoint:
6343 Check(!CI->isInlineAsm(),
6344 "gc.statepoint support for inline assembly unimplemented", CI);
6346 "Enclosing function does not use GC.",
Call);
6348 verifyStatepoint(
Call);
6350 case Intrinsic::experimental_gc_result: {
6352 "Enclosing function does not use GC.",
Call);
6360 Check(StatepointCall && StatepointCall->getIntrinsicID() ==
6361 Intrinsic::experimental_gc_statepoint,
6362 "gc.result operand #1 must be from a statepoint",
Call,
6366 auto *TargetFuncType =
6369 "gc.result result type does not match wrapped callee",
Call);
6372 case Intrinsic::experimental_gc_relocate: {
6376 "gc.relocate must return a pointer or a vector of pointers",
Call);
6381 if (LandingPadInst *LandingPad =
6385 LandingPad->getParent()->getUniquePredecessor();
6389 Check(InvokeBB,
"safepoints should have unique landingpads",
6390 LandingPad->getParent());
6394 "gc relocate should be linked to a statepoint", InvokeBB);
6401 "gc relocate is incorrectly tied to the statepoint",
Call, Token);
6410 "gc.relocate operand #2 must be integer offset",
Call);
6414 "gc.relocate operand #3 must be integer offset",
Call);
6424 Check(BaseIndex < Opt->Inputs.size(),
6425 "gc.relocate: statepoint base index out of bounds",
Call);
6426 Check(DerivedIndex < Opt->Inputs.size(),
6427 "gc.relocate: statepoint derived index out of bounds",
Call);
6440 "gc.relocate: relocated value must be a pointer",
Call);
6441 Check(DerivedType->isPtrOrPtrVectorTy(),
6442 "gc.relocate: relocated value must be a pointer",
Call);
6444 Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
6445 "gc.relocate: vector relocates to vector and pointer to pointer",
6448 ResultType->getPointerAddressSpace() ==
6449 DerivedType->getPointerAddressSpace(),
6450 "gc.relocate: relocating a pointer shouldn't change its address space",
6454 Check(GC,
"gc.relocate: calling function must have GCStrategy",
6457 auto isGCPtr = [&
GC](
Type *PTy) {
6458 return GC->isGCManagedPointer(PTy->getScalarType()).value_or(
true);
6460 Check(isGCPtr(ResultType),
"gc.relocate: must return gc pointer",
Call);
6462 "gc.relocate: relocated value must be a gc pointer",
Call);
6463 Check(isGCPtr(DerivedType),
6464 "gc.relocate: relocated value must be a gc pointer",
Call);
6468 case Intrinsic::experimental_patchpoint: {
6471 "patchpoint: invalid return type used with anyregcc",
Call);
6475 case Intrinsic::eh_exceptioncode:
6476 case Intrinsic::eh_exceptionpointer: {
6478 "eh.exceptionpointer argument must be a catchpad",
Call);
6481 case Intrinsic::get_active_lane_mask: {
6484 "get_active_lane_mask: element type is not i1",
Call);
6487 case Intrinsic::experimental_get_vector_length: {
6490 "get_vector_length: VF must be positive",
Call);
6493 case Intrinsic::experimental_guard: {
6496 "experimental_guard must have exactly one "
6497 "\"deopt\" operand bundle");
6501 case Intrinsic::experimental_deoptimize: {
6505 "experimental_deoptimize must have exactly one "
6506 "\"deopt\" operand bundle");
6508 "experimental_deoptimize return type must match caller return type");
6513 "calls to experimental_deoptimize must be followed by a return");
6517 "calls to experimental_deoptimize must be followed by a return "
6518 "of the value computed by experimental_deoptimize");
6523 case Intrinsic::vastart: {
6525 "va_start called in a non-varargs function");
6528 case Intrinsic::get_dynamic_area_offset: {
6530 Check(IntTy &&
DL.getPointerSizeInBits(
DL.getAllocaAddrSpace()) ==
6531 IntTy->getBitWidth(),
6532 "get_dynamic_area_offset result type must be scalar integer matching "
6533 "alloca address space width",
6537 case Intrinsic::smul_fix:
6538 case Intrinsic::smul_fix_sat:
6539 case Intrinsic::umul_fix:
6540 case Intrinsic::umul_fix_sat:
6541 case Intrinsic::sdiv_fix:
6542 case Intrinsic::sdiv_fix_sat:
6543 case Intrinsic::udiv_fix:
6544 case Intrinsic::udiv_fix_sat: {
6548 if (
ID == Intrinsic::smul_fix ||
ID == Intrinsic::smul_fix_sat ||
6549 ID == Intrinsic::sdiv_fix ||
ID == Intrinsic::sdiv_fix_sat) {
6551 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
6555 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
6556 "to the width of the operands");
6560 case Intrinsic::lrint:
6561 case Intrinsic::llrint:
6562 case Intrinsic::lround:
6563 case Intrinsic::llround: {
6567 IF->
getName() +
": argument and result disagree on vector use",
6571 Check(VTy->getElementCount() == RTy->getElementCount(),
6572 IF->
getName() +
": argument must be same length as result", &
Call);
6576 case Intrinsic::bswap: {
6579 Check(
Size % 16 == 0,
"bswap must be an even number of bytes", &
Call);
6582 case Intrinsic::invariant_start: {
6584 Check(InvariantSize &&
6586 "invariant_start parameter must be -1, 0 or a positive number",
6590 case Intrinsic::matrix_multiply:
6591 case Intrinsic::matrix_transpose:
6592 case Intrinsic::matrix_column_major_load:
6593 case Intrinsic::matrix_column_major_store: {
6595 ConstantInt *Stride =
nullptr;
6596 ConstantInt *NumRows;
6597 ConstantInt *NumColumns;
6599 Type *Op0ElemTy =
nullptr;
6600 Type *Op1ElemTy =
nullptr;
6602 case Intrinsic::matrix_multiply: {
6607 ->getNumElements() ==
6609 "First argument of a matrix operation does not match specified "
6612 ->getNumElements() ==
6614 "Second argument of a matrix operation does not match specified "
6624 case Intrinsic::matrix_transpose:
6631 case Intrinsic::matrix_column_major_load: {
6638 case Intrinsic::matrix_column_major_store: {
6651 Check(ResultTy->getElementType()->isIntegerTy() ||
6652 ResultTy->getElementType()->isFloatingPointTy(),
6653 "Result type must be an integer or floating-point type!", IF);
6656 Check(ResultTy->getElementType() == Op0ElemTy,
6657 "Vector element type mismatch of the result and first operand "
6662 Check(ResultTy->getElementType() == Op1ElemTy,
6663 "Vector element type mismatch of the result and second operand "
6669 "Result of a matrix operation does not fit in the returned vector!");
6675 "Stride must be greater or equal than the number of rows!", IF);
6680 case Intrinsic::stepvector: {
6682 Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
6683 VecTy->getScalarSizeInBits() >= 8,
6684 "stepvector only supported for vectors of integers "
6685 "with a bitwidth of at least 8.",
6689 case Intrinsic::experimental_vector_match: {
6698 Check(Op1Ty && Op2Ty && MaskTy,
"Operands must be vectors.", &
Call);
6700 "Second operand must be a fixed length vector.", &
Call);
6701 Check(Op1Ty->getElementType()->isIntegerTy(),
6702 "First operand must be a vector of integers.", &
Call);
6703 Check(Op1Ty->getElementType() == Op2Ty->getElementType(),
6704 "First two operands must have the same element type.", &
Call);
6705 Check(Op1Ty->getElementCount() == MaskTy->getElementCount(),
6706 "First operand and mask must have the same number of elements.",
6708 Check(MaskTy->getElementType()->isIntegerTy(1),
6709 "Mask must be a vector of i1's.", &
Call);
6714 case Intrinsic::vector_insert: {
6723 ElementCount VecEC = VecTy->getElementCount();
6724 ElementCount SubVecEC = SubVecTy->getElementCount();
6725 Check(VecTy->getElementType() == SubVecTy->getElementType(),
6726 "vector_insert parameters must have the same element "
6730 "vector_insert index must be a constant multiple of "
6731 "the subvector's known minimum vector length.");
6739 "subvector operand of vector_insert would overrun the "
6740 "vector being inserted into.");
6744 case Intrinsic::vector_extract: {
6752 ElementCount VecEC = VecTy->getElementCount();
6753 ElementCount ResultEC = ResultTy->getElementCount();
6755 Check(ResultTy->getElementType() == VecTy->getElementType(),
6756 "vector_extract result must have the same element "
6757 "type as the input vector.",
6760 "vector_extract index must be a constant multiple of "
6761 "the result type's known minimum vector length.");
6769 "vector_extract would overrun.");
6773 case Intrinsic::vector_partial_reduce_fadd:
6774 case Intrinsic::vector_partial_reduce_add: {
6778 unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
6779 unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
6781 Check((VecWidth % AccWidth) == 0,
6782 "Invalid vector widths for partial "
6783 "reduction. The width of the input vector "
6784 "must be a positive integer multiple of "
6785 "the width of the accumulator vector.");
6788 case Intrinsic::experimental_noalias_scope_decl: {
6792 case Intrinsic::preserve_array_access_index:
6793 case Intrinsic::preserve_struct_access_index:
6794 case Intrinsic::aarch64_ldaxr:
6795 case Intrinsic::aarch64_ldxr:
6796 case Intrinsic::arm_ldaex:
6797 case Intrinsic::arm_ldrex: {
6799 Check(ElemTy,
"Intrinsic requires elementtype attribute on first argument.",
6803 case Intrinsic::aarch64_stlxr:
6804 case Intrinsic::aarch64_stxr:
6805 case Intrinsic::arm_stlex:
6806 case Intrinsic::arm_strex: {
6809 "Intrinsic requires elementtype attribute on second argument.",
6813 case Intrinsic::aarch64_prefetch: {
6815 "write argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6817 "target argument to llvm.aarch64.prefetch must be 0-3",
Call);
6819 "stream argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6821 "isdata argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6824 case Intrinsic::aarch64_range_prefetch: {
6826 "write argument to llvm.aarch64.range.prefetch must be 0 or 1",
Call);
6828 "stream argument to llvm.aarch64.range.prefetch must be 0 or 1",
6832 case Intrinsic::callbr_landingpad: {
6834 Check(CBR,
"intrinstic requires callbr operand", &
Call);
6841 CheckFailed(
"Intrinsic in block must have 1 unique predecessor", &
Call);
6845 CheckFailed(
"Intrinsic must have corresponding callbr in predecessor",
6850 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
6851 "block in indirect destination list",
6854 Check(&
First == &
Call,
"No other instructions may proceed intrinsic",
6858 case Intrinsic::structured_gep: {
6864 "Intrinsic first parameter is missing an ElementType attribute",
6872 "Index operand type must be an integer", &
Call);
6875 T = AT->getElementType();
6877 Check(CI,
"Indexing into a struct requires a constant int", &
Call);
6879 "Indexing in a struct should be inbounds", &
Call);
6882 T = VT->getElementType();
6884 CheckFailed(
"Reached a non-composite type with more indices to process",
6890 case Intrinsic::structured_alloca:
6892 "@llvm.structured.alloca calls require elementtype attribute.",
6895 case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
6896 case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
6899 Check(RegCount % 8 == 0,
6900 "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
6903 case Intrinsic::experimental_convergence_entry:
6904 case Intrinsic::experimental_convergence_anchor:
6906 case Intrinsic::experimental_convergence_loop:
6908 case Intrinsic::ptrmask: {
6912 "llvm.ptrmask intrinsic first argument must be pointer or vector "
6917 "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
6922 "llvm.ptrmask intrinsic arguments must have the same number of "
6926 "llvm.ptrmask intrinsic second argument bitwidth must match "
6927 "pointer index type size of first argument",
6931 case Intrinsic::thread_pointer: {
6933 DL.getDefaultGlobalsAddressSpace(),
6934 "llvm.thread.pointer intrinsic return type must be for the globals "
6939 case Intrinsic::threadlocal_address: {
6942 "llvm.threadlocal.address first argument must be a GlobalValue");
6944 "llvm.threadlocal.address operand isThreadLocal() must be true");
6947 case Intrinsic::lifetime_start:
6948 case Intrinsic::lifetime_end: {
6952 (
II &&
II->getIntrinsicID() == Intrinsic::structured_alloca),
6953 "llvm.lifetime.start/end can only be used on alloca or poison",
6957 case Intrinsic::sponentry: {
6958 const unsigned StackAS =
DL.getAllocaAddrSpace();
6961 "llvm.sponentry must return a pointer to the stack", &
Call);
6964 case Intrinsic::write_volatile_register: {
6968 "llvm.write_volatile_register metadata must be a single MDString",
6977 if (
F->hasPersonalityFn() &&
6981 if (BlockEHFuncletColors.
empty())
6985 bool InEHFunclet =
false;
6989 for (BasicBlock *ColorFirstBB : CV)
6990 if (
auto It = ColorFirstBB->getFirstNonPHIIt();
6991 It != ColorFirstBB->end())
6996 bool HasToken =
false;
7003 Check(HasToken,
"Missing funclet token on intrinsic call", &
Call);
7030void Verifier::visit(DbgLabelRecord &DLR) {
7032 "invalid #dbg_label intrinsic variable", &DLR, DLR.
getRawLabel());
7045 CheckDI(Loc,
"#dbg_label record requires a !dbg attachment", &DLR, BB,
F);
7049 if (!LabelSP || !LocSP)
7053 "mismatched subprogram between #dbg_label label and !dbg attachment",
7054 &DLR, BB,
F, Label,
Label->getScope()->getSubprogram(), Loc,
7055 Loc->getScope()->getSubprogram());
7058void Verifier::visit(DbgVariableRecord &DVR) {
7062 CheckDI(DVR.
getType() == DbgVariableRecord::LocationType::Value ||
7063 DVR.
getType() == DbgVariableRecord::LocationType::Declare ||
7064 DVR.
getType() == DbgVariableRecord::LocationType::DeclareValue ||
7065 DVR.
getType() == DbgVariableRecord::LocationType::Assign,
7066 "invalid #dbg record type", &DVR, DVR.
getType(), BB,
F);
7074 "invalid #dbg record address/value", &DVR, MD, BB,
F);
7076 visitValueAsMetadata(*VAM,
F);
7079 Type *Ty = VAM->getValue()->getType();
7081 "location of #dbg_declare must be a pointer or int", &DVR, MD, BB,
7085 visitDIArgList(*AL,
F);
7099 "invalid #dbg_assign DIAssignID", &DVR, DVR.
getRawAssignID(), BB,
7102 AreDebugLocsAllowed::No);
7111 "invalid #dbg_assign address", &DVR, DVR.
getRawAddress(), BB,
F);
7113 visitValueAsMetadata(*VAM,
F);
7116 "invalid #dbg_assign address expression", &DVR,
7123 "inst not in same function as #dbg_assign",
I, &DVR, BB,
F);
7133 &DVR, DLNode, BB,
F);
7139 if (!VarSP || !LocSP)
7143 "mismatched subprogram between #dbg record variable and DILocation",
7145 Loc->getScope()->getSubprogram(), BB,
F);
7150void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
7154 Check(RetTy->getElementCount() == ValTy->getElementCount(),
7155 "VP cast intrinsic first argument and result vector lengths must be "
7159 switch (VPCast->getIntrinsicID()) {
7160 case Intrinsic::vp_trunc:
7162 "llvm.vp.trunc intrinsic the bit size of first argument must be "
7163 "larger than the bit size of the return type",
7166 case Intrinsic::vp_zext:
7167 case Intrinsic::vp_sext:
7169 "llvm.vp.zext or llvm.vp.sext intrinsic the bit size of first "
7170 "argument must be smaller than the bit size of the return type",
7173 case Intrinsic::vp_fptrunc:
7175 "llvm.vp.fptrunc intrinsic the bit size of first argument must be "
7176 "larger than the bit size of the return type",
7179 case Intrinsic::vp_fpext:
7181 "llvm.vp.fpext intrinsic the bit size of first argument must be "
7182 "smaller than the bit size of the return type",
7191 case Intrinsic::vp_fcmp: {
7194 "invalid predicate for VP FP comparison intrinsic", &VPI);
7197 case Intrinsic::vp_icmp: {
7200 "invalid predicate for VP integer comparison intrinsic", &VPI);
7203 case Intrinsic::vp_is_fpclass: {
7206 "unsupported bits for llvm.vp.is.fpclass test mask");
7209 case Intrinsic::experimental_vp_splice: {
7212 int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
7214 AttributeList
Attrs = VPI.
getParent()->getParent()->getAttributes();
7215 if (
Attrs.hasFnAttr(Attribute::VScaleRange))
7216 KnownMinNumElements *=
Attrs.getFnAttrs().getVScaleRangeMin();
7218 Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
7219 (Idx >= 0 && Idx < KnownMinNumElements),
7220 "The splice index exceeds the range [-VL, VL-1] where VL is the "
7221 "known minimum number of elements in the vector. For scalable "
7222 "vectors the minimum number of elements is determined from "
7230void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
7232 bool HasRoundingMD =
7236 NumOperands += (1 + HasRoundingMD);
7242 "invalid arguments for constrained FP intrinsic", &FPI);
7245 case Intrinsic::experimental_constrained_fcmp:
7246 case Intrinsic::experimental_constrained_fcmps: {
7249 "invalid predicate for constrained FP comparison intrinsic", &FPI);
7253 case Intrinsic::experimental_constrained_fptosi:
7254 case Intrinsic::experimental_constrained_fptoui: {
7258 "Intrinsic first argument must be floating point", &FPI);
7265 "Intrinsic first argument and result disagree on vector use", &FPI);
7267 "Intrinsic result must be an integer", &FPI);
7270 "Intrinsic first argument and result vector lengths must be equal",
7276 case Intrinsic::experimental_constrained_sitofp:
7277 case Intrinsic::experimental_constrained_uitofp: {
7281 "Intrinsic first argument must be integer", &FPI);
7288 "Intrinsic first argument and result disagree on vector use", &FPI);
7290 "Intrinsic result must be a floating point", &FPI);
7293 "Intrinsic first argument and result vector lengths must be equal",
7299 case Intrinsic::experimental_constrained_fptrunc:
7300 case Intrinsic::experimental_constrained_fpext: {
7306 "Intrinsic first argument must be FP or FP vector", &FPI);
7308 "Intrinsic result must be FP or FP vector", &FPI);
7310 "Intrinsic first argument and result disagree on vector use", &FPI);
7314 "Intrinsic first argument and result vector lengths must be equal",
7317 if (FPI.
getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
7319 "Intrinsic first argument's type must be larger than result type",
7323 "Intrinsic first argument's type must be smaller than result type",
7339 "invalid exception behavior argument", &FPI);
7340 if (HasRoundingMD) {
7346void Verifier::verifyFragmentExpression(
const DbgVariableRecord &DVR) {
7351 if (!V || !
E || !
E->isValid())
7355 auto Fragment =
E->getFragmentInfo();
7365 if (
V->isArtificial())
7368 verifyFragmentExpression(*V, *Fragment, &DVR);
7371template <
typename ValueOrMetadata>
7372void Verifier::verifyFragmentExpression(
const DIVariable &V,
7374 ValueOrMetadata *
Desc) {
7377 auto VarSize =
V.getSizeInBits();
7383 CheckDI(FragSize + FragOffset <= *VarSize,
7384 "fragment is larger than or outside of variable",
Desc, &V);
7385 CheckDI(FragSize != *VarSize,
"fragment covers entire variable",
Desc, &V);
7388void Verifier::verifyFnArgs(
const DbgVariableRecord &DVR) {
7400 CheckDI(Var,
"#dbg record without variable");
7402 unsigned ArgNo = Var->
getArg();
7408 if (DebugFnArgs.
size() < ArgNo)
7409 DebugFnArgs.
resize(ArgNo,
nullptr);
7411 auto *Prev = DebugFnArgs[ArgNo - 1];
7412 DebugFnArgs[ArgNo - 1] = Var;
7413 CheckDI(!Prev || (Prev == Var),
"conflicting debug info for argument", &DVR,
7417void Verifier::verifyNotEntryValue(
const DbgVariableRecord &DVR) {
7421 if (!
E || !
E->isValid())
7431 ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
7436 "Entry values are only allowed in MIR unless they target a "
7437 "swiftasync Argument",
7441void Verifier::verifyCompileUnits() {
7445 if (
M.getContext().isODRUniquingDebugTypes())
7447 auto *CUs =
M.getNamedMetadata(
"llvm.dbg.cu");
7448 SmallPtrSet<const Metadata *, 2> Listed;
7451 for (
const auto *CU : CUVisited)
7452 CheckDI(Listed.
count(CU),
"DICompileUnit not listed in llvm.dbg.cu", CU);
7456void Verifier::verifyDeoptimizeCallingConvs() {
7457 if (DeoptimizeDeclarations.
empty())
7461 for (
const auto *
F :
ArrayRef(DeoptimizeDeclarations).slice(1)) {
7462 Check(
First->getCallingConv() ==
F->getCallingConv(),
7463 "All llvm.experimental.deoptimize declarations must have the same "
7464 "calling convention",
7469void Verifier::verifyAttachedCallBundle(
const CallBase &
Call,
7470 const OperandBundleUse &BU) {
7473 Check((FTy->getReturnType()->isPointerTy() ||
7475 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
7476 "function returning a pointer or a non-returning function that has a "
7481 "operand bundle \"clang.arc.attachedcall\" requires one function as "
7489 Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
7490 IID == Intrinsic::objc_claimAutoreleasedReturnValue ||
7491 IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
7492 "invalid function argument",
Call);
7494 StringRef FnName = Fn->
getName();
7495 Check((FnName ==
"objc_retainAutoreleasedReturnValue" ||
7496 FnName ==
"objc_claimAutoreleasedReturnValue" ||
7497 FnName ==
"objc_unsafeClaimAutoreleasedReturnValue"),
7498 "invalid function argument",
Call);
7502void Verifier::verifyNoAliasScopeDecl() {
7503 if (NoAliasScopeDecls.
empty())
7507 for (
auto *
II : NoAliasScopeDecls) {
7508 assert(
II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
7509 "Not a llvm.experimental.noalias.scope.decl ?");
7512 Check(ScopeListMV !=
nullptr,
7513 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
7518 Check(ScopeListMD !=
nullptr,
"!id.scope.list must point to an MDNode",
II);
7519 Check(ScopeListMD->getNumOperands() == 1,
7520 "!id.scope.list must point to a list with a single scope",
II);
7521 visitAliasScopeListMetadata(ScopeListMD);
7531 auto GetScope = [](IntrinsicInst *
II) {
7534 return &
cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
7539 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
7540 return GetScope(Lhs) < GetScope(Rhs);
7547 auto ItCurrent = NoAliasScopeDecls.begin();
7548 while (ItCurrent != NoAliasScopeDecls.end()) {
7549 auto CurScope = GetScope(*ItCurrent);
7550 auto ItNext = ItCurrent;
7553 }
while (ItNext != NoAliasScopeDecls.end() &&
7554 GetScope(*ItNext) == CurScope);
7559 if (ItNext - ItCurrent < 32)
7563 Check(!DT.dominates(
I, J),
7564 "llvm.experimental.noalias.scope.decl dominates another one "
7565 "with the same scope",
7579 Verifier V(OS,
true, *f.getParent());
7583 return !V.verify(
F);
7587 bool *BrokenDebugInfo) {
7589 Verifier V(OS, !BrokenDebugInfo, M);
7591 bool Broken =
false;
7593 Broken |= !V.verify(
F);
7595 Broken |= !V.verify();
7596 if (BrokenDebugInfo)
7597 *BrokenDebugInfo = V.hasBrokenDebugInfo();
7608 std::unique_ptr<Verifier> V;
7609 bool FatalErrors =
true;
7612 explicit VerifierLegacyPass(
bool FatalErrors)
7613 : FunctionPass(
ID), FatalErrors(FatalErrors) {}
7615 bool doInitialization(
Module &M)
override {
7616 V = std::make_unique<Verifier>(
7622 if (!
V->verify(
F) && FatalErrors) {
7623 errs() <<
"in function " <<
F.getName() <<
'\n';
7629 bool doFinalization(
Module &M)
override {
7630 bool HasErrors =
false;
7631 for (Function &
F : M)
7632 if (
F.isDeclaration())
7633 HasErrors |= !
V->verify(
F);
7635 HasErrors |= !
V->verify();
7636 if (FatalErrors && (HasErrors ||
V->hasBrokenDebugInfo()))
7641 void getAnalysisUsage(AnalysisUsage &AU)
const override {
7649template <
typename... Tys>
void TBAAVerifier::CheckFailed(Tys &&... Args) {
7651 return Diagnostic->CheckFailed(
Args...);
7654#define CheckTBAA(C, ...) \
7657 CheckFailed(__VA_ARGS__); \
7665TBAAVerifier::TBAABaseNodeSummary
7669 CheckFailed(
"Base nodes must have at least two operands",
I, BaseNode);
7673 auto Itr = TBAABaseNodes.find(BaseNode);
7674 if (Itr != TBAABaseNodes.end())
7677 auto Result = verifyTBAABaseNodeImpl(
I, BaseNode, IsNewFormat);
7678 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
7680 assert(InsertResult.second &&
"We just checked!");
7684TBAAVerifier::TBAABaseNodeSummary
7685TBAAVerifier::verifyTBAABaseNodeImpl(
const Instruction *
I,
7686 const MDNode *BaseNode,
bool IsNewFormat) {
7687 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {
true, ~0
u};
7691 return isValidScalarTBAANode(BaseNode)
7692 ? TBAAVerifier::TBAABaseNodeSummary({
false, 0})
7698 CheckFailed(
"Access tag nodes must have the number of operands that is a "
7699 "multiple of 3!", BaseNode);
7704 CheckFailed(
"Struct tag nodes must have an odd number of operands!",
7714 if (!TypeSizeNode) {
7715 CheckFailed(
"Type size nodes must be constants!",
I, BaseNode);
7722 CheckFailed(
"Struct tag nodes have a string as their first operand",
7729 std::optional<APInt> PrevOffset;
7734 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
7735 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
7736 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
7737 Idx += NumOpsPerField) {
7738 const MDOperand &FieldTy = BaseNode->
getOperand(Idx);
7739 const MDOperand &FieldOffset = BaseNode->
getOperand(Idx + 1);
7741 CheckFailed(
"Incorrect field entry in struct type node!",
I, BaseNode);
7746 auto *OffsetEntryCI =
7748 if (!OffsetEntryCI) {
7749 CheckFailed(
"Offset entries must be constants!",
I, BaseNode);
7755 BitWidth = OffsetEntryCI->getBitWidth();
7757 if (OffsetEntryCI->getBitWidth() !=
BitWidth) {
7759 "Bitwidth between the offsets and struct type entries must match",
I,
7771 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
7774 CheckFailed(
"Offsets must be increasing!",
I, BaseNode);
7778 PrevOffset = OffsetEntryCI->getValue();
7783 if (!MemberSizeNode) {
7784 CheckFailed(
"Member size entries must be constants!",
I, BaseNode);
7791 return Failed ? InvalidNode
7792 : TBAAVerifier::TBAABaseNodeSummary(
false,
BitWidth);
7814 return Parent && Visited.
insert(Parent).second &&
7818bool TBAAVerifier::isValidScalarTBAANode(
const MDNode *MD) {
7819 auto ResultIt = TBAAScalarNodes.find(MD);
7820 if (ResultIt != TBAAScalarNodes.end())
7821 return ResultIt->second;
7823 SmallPtrSet<const MDNode *, 4> Visited;
7825 auto InsertResult = TBAAScalarNodes.insert({MD,
Result});
7827 assert(InsertResult.second &&
"Just checked!");
7836MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(
const Instruction *
I,
7837 const MDNode *BaseNode,
7848 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
7849 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
7850 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
7851 Idx += NumOpsPerField) {
7852 auto *OffsetEntryCI =
7854 if (OffsetEntryCI->getValue().ugt(
Offset)) {
7855 if (Idx == FirstFieldOpNo) {
7856 CheckFailed(
"Could not find TBAA parent in struct type node",
I,
7861 unsigned PrevIdx = Idx - NumOpsPerField;
7862 auto *PrevOffsetEntryCI =
7864 Offset -= PrevOffsetEntryCI->getValue();
7872 Offset -= LastOffsetEntryCI->getValue();
7877 if (!
Type ||
Type->getNumOperands() < 3)
7893 "This instruction shall not have a TBAA access tag!",
I);
7895 bool IsStructPathTBAA =
7899 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
7909 "Access tag metadata must have either 4 or 5 operands",
I, MD);
7912 "Struct tag metadata must have either 3 or 4 operands",
I, MD);
7919 CheckTBAA(AccessSizeNode,
"Access size field must be a constant",
I, MD);
7923 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
7928 "Immutability tag on struct tag metadata must be a constant",
I,
7931 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
7932 "Immutability part of the struct tag metadata must be either 0 or 1",
I,
7937 "Malformed struct tag metadata: base and access-type "
7938 "should be non-null and point to Metadata nodes",
7939 I, MD, BaseNode, AccessType);
7942 CheckTBAA(isValidScalarTBAANode(AccessType),
7943 "Access type node must be a valid scalar type",
I, MD,
7948 CheckTBAA(OffsetCI,
"Offset must be constant integer",
I, MD);
7951 bool SeenAccessTypeInPath =
false;
7957 getFieldNodeFromTBAABaseNode(
I, BaseNode,
Offset, IsNewFormat)) {
7958 if (!StructPath.
insert(BaseNode).second) {
7959 CheckFailed(
"Cycle detected in struct path",
I, MD);
7964 unsigned BaseNodeBitWidth;
7965 std::tie(
Invalid, BaseNodeBitWidth) =
7966 verifyTBAABaseNode(
I, BaseNode, IsNewFormat);
7973 SeenAccessTypeInPath |= BaseNode == AccessType;
7975 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
7980 (BaseNodeBitWidth == 0 &&
Offset == 0) ||
7981 (IsNewFormat && BaseNodeBitWidth == ~0u),
7982 "Access bit-width not the same as description bit-width",
I, MD,
7983 BaseNodeBitWidth,
Offset.getBitWidth());
7985 if (IsNewFormat && SeenAccessTypeInPath)
7989 CheckTBAA(SeenAccessTypeInPath,
"Did not see access type in access path!",
I,
7994char VerifierLegacyPass::ID = 0;
7995INITIALIZE_PASS(VerifierLegacyPass,
"verify",
"Module Verifier",
false,
false)
7998 return new VerifierLegacyPass(FatalErrors);
8016 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
8024 if (res.IRBroken && FatalErrors)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericConvergenceVerifier template.
static DISubprogram * getSubprogram(bool IsDistinct, Ts &&...Args)
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
static bool runOnFunction(Function &F, bool PostInlining)
This file contains the declarations of entities that describe floating point environment and related ...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
static constexpr Value * getValue(Ty &ValueOrUse)
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
static unsigned getNumElements(Type *Ty)
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
verify safepoint Safepoint IR Verifier
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static bool IsScalarTBAANodeImpl(const MDNode *MD, SmallPtrSetImpl< const MDNode * > &Visited)
static bool isType(const Metadata *MD)
static Instruction * getSuccPad(Instruction *Terminator)
static bool isMDTuple(const Metadata *MD)
static bool isNewFormatTBAATypeNode(llvm::MDNode *Type)
#define CheckDI(C,...)
We know that a debug info condition should be true, if not print an error message.
static void forEachUser(const Value *User, SmallPtrSet< const Value *, 32 > &Visited, llvm::function_ref< bool(const Value *)> Callback)
static bool isDINode(const Metadata *MD)
static bool isSupportedCallBrIntrinsic(Intrinsic::ID ID)
static bool isScope(const Metadata *MD)
static cl::opt< bool > VerifyNoAliasScopeDomination("verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false), cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical " "scopes are not dominating"))
static bool IsRootTBAANode(const MDNode *MD)
static Value * getParentPad(Value *EHPad)
static bool hasConflictingReferenceFlags(unsigned Flags)
Detect mutually exclusive flags.
static AttrBuilder getParameterABIAttributes(LLVMContext &C, unsigned I, AttributeList Attrs)
static const char PassName[]
static LLVM_ABI bool isValidArbitraryFPFormat(StringRef Format)
Returns true if the given string is a valid arbitrary floating-point format interpretation for llvm....
bool isFiniteNonZero() const
const fltSemantics & getSemantics() const
Class for arbitrary precision integers.
bool sgt(const APInt &RHS) const
Signed greater than comparison.
bool isMinValue() const
Determine if this is the smallest unsigned value.
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
int64_t getSExtValue() const
Get sign extended value.
bool isMaxValue() const
Determine if this is the largest unsigned value.
This class represents a conversion between pointers from one address space to another.
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
const Value * getArraySize() const
Get the number of elements allocated.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void setPreservesAll()
Set by analyses that do not transform their input at all.
bool isElementwise() const
Return true if this RMW has elementwise vector semantics.
static bool isFPOperation(BinOp Op)
BinOp getOperation() const
static LLVM_ABI StringRef getOperationName(BinOp Op)
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
LLVM_ABI const ConstantRange & getValueAsConstantRange() const
Return the attribute's value as a ConstantRange.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
bool isValid() const
Return true if the attribute is any kind of attribute.
LLVM_ABI Type * getValueAsType() const
Return the attribute's value as a Type.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
const Instruction & front() const
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
This class represents a no-op cast from one type to another.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isInlineAsm() const
Check if this call is an inline asm statement.
auto operand_bundles() const
bool hasInAllocaArgument() const
Determine if there are is an inalloca argument.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool doesNotAccessMemory(unsigned OpNo) const
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Get the attribute of a given kind from a given arg.
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Type * getParamElementType(unsigned ArgNo) const
Extract the elementtype type for a parameter.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
bool doesNotReturn() const
Determine if the call cannot return.
LLVM_ABI bool onlyAccessesArgMemory() const
Determine if the call can access memmory only using pointers based on its arguments.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
bool isMustTailCall() const
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
unsigned getNumHandlers() const
return the number of 'handlers' in this catchswitch instruction, except the default handler
Value * getParentPad() const
BasicBlock * getUnwindDest() const
handler_range handlers()
iteration adapter for range-for loops.
BasicBlock * getUnwindDest() const
bool isFPPredicate() const
bool isIntPredicate() const
static bool isIntPredicate(Predicate P)
Value * getCondition() const
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
const APInt & getValue() const
Return the constant as an APInt value reference.
Constant * getAddrDiscriminator() const
The address discriminator if any, or the null constant.
Constant * getPointer() const
The pointer that is signed in this ptrauth signed pointer.
ConstantInt * getKey() const
The Key ID, an i32 constant.
Constant * getDeactivationSymbol() const
ConstantInt * getDiscriminator() const
The integer discriminator, an i64 constant, or 0.
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI std::optional< RoundingMode > getRoundingMode() const
LLVM_ABI unsigned getNonMetadataArgCount() const
DbgVariableFragmentInfo FragmentInfo
@ FixedPointBinary
Scale factor 2^Factor.
@ FixedPointDecimal
Scale factor 10^Factor.
@ FixedPointRational
Arbitrary rational scale factor.
DIGlobalVariable * getVariable() const
DIExpression * getExpression() const
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
DILocalScope * getScope() const
Get the local scope for this variable.
Metadata * getRawScope() const
Base class for scope-like contexts.
Subprogram description. Uses SubclassData1.
static LLVM_ABI const DIScope * getRawRetainedNodeScope(const MDNode *N)
Base class for template parameters.
Base class for variables.
Metadata * getRawType() const
Metadata * getRawScope() const
uint64_t getNumOperands() const
Records a position in IR for a source label (DILabel).
MDNode * getRawLabel() const
DILabel * getLabel() const
Base class for non-instruction debug metadata records that have positions within IR.
DebugLoc getDebugLoc() const
LLVM_ABI BasicBlock * getParent()
LLVM_ABI Function * getFunction()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LocationType getType() const
MDNode * getRawExpression() const
MDNode * getRawAddressExpression() const
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
DIExpression * getExpression() const
Metadata * getRawAssignID() const
MDNode * getRawVariable() const
DILocalVariable * getVariable() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
bool isDbgDeclare() const
Metadata * getRawAddress() const
DIExpression * getAddressExpression() const
LLVM_ABI MDNode * getAsMDNode() const
Return this as a bar MDNode.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
This instruction compares its operands according to the predicate given to the constructor.
This class represents an extension of floating point types.
static bool isSupportedFloatingPointType(Type *Ty)
Returns true if Ty is a supported floating-point type for phi, select, or call FPMathOperators.
This class represents a cast from floating point to signed integer.
This class represents a cast from floating point to unsigned integer.
This class represents a truncation of floating point types.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
op_range arg_operands()
arg_operands - iteration adapter for range-for loops.
Value * getParentPad() const
Convenience accessors.
FunctionPass class - This class is used to implement most global optimizations.
Type * getReturnType() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool hasPersonalityFn() const
Check whether this function has a personality function.
const Function & getFunction() const
const std::string & getGC() const
Type * getReturnType() const
Returns the type of the ret val.
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
LLVM_ABI Value * getBasePtr() const
LLVM_ABI Value * getDerivedPtr() const
void visit(const BlockT &BB)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
const Constant * getAliasee() const
LLVM_ABI const Function * getResolverFunction() const
static bool isValidLinkage(LinkageTypes L)
const Constant * getResolver() const
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
bool hasExternalLinkage() const
bool isImplicitDSOLocal() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
bool hasValidDeclarationLinkage() const
LinkageTypes getLinkage() const
bool hasDefaultVisibility() const
bool hasPrivateLinkage() const
bool hasHiddenVisibility() const
bool hasExternalWeakLinkage() const
bool hasDLLImportStorageClass() const
bool hasDLLExportStorageClass() const
bool isDeclarationForLinker() const
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
bool hasCommonLinkage() const
bool hasGlobalUnnamedAddr() const
bool hasAppendingLinkage() const
bool hasAvailableExternallyLinkage() const
Type * getValueType() const
LLVM_ABI bool isInterposable(bool CheckNoIPA=true) const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
BasicBlock * getDestination(unsigned i)
Return the specified destination.
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
unsigned getNumSuccessors() const
This instruction inserts a single (scalar) element into a VectorType value.
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
Value * getAggregateOperand()
ArrayRef< unsigned > getIndices() const
Base class for instruction visitors.
void visit(Iterator Start, Iterator End)
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
This class represents a cast from an integer to a pointer.
static LLVM_ABI bool mayLowerToFunctionCall(Intrinsic::ID IID)
Check if the intrinsic might lower into a regular function call in the course of IR transformations.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
@ OB_clang_arc_attachedcall
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
Align getAlign() const
Return the alignment of the access that is being performed.
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
unsigned getNumOperands() const
Return number of MDNode operands.
bool isResolved() const
Check if node is fully resolved.
LLVMContext & getContext() const
bool equalsStr(StringRef Str) const
LLVM_ABI StringRef getString() const
This class implements a map that also provides access to all stored values in a deterministic order.
A Module instance is used to store all the information related to an LLVM module.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
LLVM_ABI StringRef getName() const
LLVM_ABI unsigned getNumOperands() const
iterator_range< op_iterator > operands()
op_range incoming_values()
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
This class represents a cast from a pointer to an address (non-capturing ptrtoint).
This class represents a cast from a pointer to an integer.
Value * getValue() const
Convenience accessor.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents a sign extension of integer types.
This class represents a cast from signed integer to floating point.
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
This instruction constructs a fixed permutation of two input vectors.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
static constexpr size_t npos
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
Check if the string is empty.
std::pair< typename Base::iterator, bool > insert(StringRef key)
unsigned getNumElements() const
Random access to the elements.
LLVM_ABI Type * getTypeAtIndex(const Value *V) const
Given an index value into the type, return the type of the element.
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Verify that the TBAA Metadatas are valid.
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isByteTy() const
True if this is an instance of ByteType.
bool isVectorTy() const
True if this is an instance of VectorType.
LLVM_ABI bool containsNonGlobalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a global...
bool isArrayTy() const
True if this is an instance of ArrayType.
LLVM_ABI bool containsNonLocalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a local.
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
LLVM_ABI bool isTokenLikeTy() const
Returns true if this is 'token' or a token-like target type.s.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
LLVM_ABI bool canLosslesslyBitCastTo(Type *Ty) const
Return true if this type could be converted with a lossless BitCast to type 'Ty'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
This class represents a cast unsigned integer to floating point.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
iterator_range< user_iterator > materialized_users()
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
iterator_range< user_iterator > users()
bool materialized_use_empty() const
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Check a module for errors, and report separate error states for IR and debug info errors.
LLVM_ABI Result run(Module &M, ModuleAnalysisManager &)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
This class represents zero extension of integer types.
std::pair< iterator, bool > insert(const ValueT &V)
constexpr bool isNonZero() const
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
This class implements an extremely fast bulk output stream that can only output to a stream.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
@ BasicBlock
Various leaf nodes.
LLVM_ABI 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.
std::variant< std::monostate, Loc::Single, Loc::Multi, Loc::MMI, Loc::EntryValue > Variant
Alias for the std::variant specialization base class of DbgVariable.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
LLVM_ABI std::optional< VFInfo > tryDemangleForVFABI(StringRef MangledName, const FunctionType *FTy)
Function to construct a VFInfo out of a mangled names in the following format:
@ CE
Windows NT (Windows on ARM)
LLVM_ABI AssignmentInstRange getAssignmentInsts(DIAssignID *ID)
Return a range of instructions (typically just one) that have ID as an attachment.
initializer< Ty > init(const Ty &Val)
@ DW_LLVM_LANG_DIALECT_max
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.
@ 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)
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)
auto dyn_cast_or_null(const Y &Val)
GenericConvergenceVerifier< SSAContext > ConvergenceVerifier
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
bool isModSet(const ModRefInfo MRI)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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...
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
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
TinyPtrVector< BasicBlock * > ColorVector
LLVM_ABI const char * LLVMLoopEstimatedTripCount
Profile-based loop metadata that should be accessed only by using llvm::getLoopEstimatedTripCount and...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI std::optional< RoundingMode > convertStrToRoundingMode(StringRef)
Returns a valid RoundingMode enumerator when given a string that is valid as input in constrained int...
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI std::unique_ptr< GCStrategy > getGCStrategy(const StringRef Name)
Lookup the GCStrategy object associated with the given gc name.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
bool pred_empty(const BasicBlock *BB)
bool isHexDigit(char C)
Checks if character C is a hexadecimal numeric character.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
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 * SyntheticFunctionEntryCount
static LLVM_ABI const char * UnknownBranchWeightsMarker
static LLVM_ABI const char * ValueProfile
static LLVM_ABI const char * FunctionEntryCount
static LLVM_ABI const char * BranchWeights
uint32_t getTagID() const
Return the tag of this operand bundle as an integer.