98#include "llvm/IR/IntrinsicsAArch64.h"
99#include "llvm/IR/IntrinsicsARM.h"
100#include "llvm/IR/IntrinsicsNVPTX.h"
101#include "llvm/IR/IntrinsicsWebAssembly.h"
143 cl::desc(
"Ensure that llvm.experimental.noalias.scope.decl for identical "
144 "scopes are not dominating"));
169 Type *LandingPadResultTy;
176 bool HasDebugInfo =
false;
219 SawFrameEscape(
false), TBAAVerifyHelper(this) {
220 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
223 bool hasBrokenDebugInfo()
const {
return BrokenDebugInfo; }
225 bool verify(
const Function &
F) {
226 llvm::TimeTraceScope timeScope(
"Verifier");
228 "An instance of this class only works with a specific module!");
238 for (
const BasicBlock &BB :
F) {
239 if (!BB.empty() && BB.back().isTerminator())
243 *OS <<
"Basic Block in function '" <<
F.getName()
244 <<
"' does not have terminator!\n";
245 BB.printAsOperand(*OS,
true, MST);
253 DT.recalculate(
const_cast<Function &
>(
F));
255 auto FailureCB = [
this](
const Twine &Message) {
256 this->CheckFailed(Message);
258 ConvergenceVerifyHelper.initialize(OS, FailureCB,
F);
263 verifySiblingFuncletUnwinds();
265 if (ConvergenceVerifyHelper.sawTokens())
266 ConvergenceVerifyHelper.verify(DT);
268 InstsInThisBlock.clear();
270 LandingPadResultTy =
nullptr;
271 SawFrameEscape =
false;
272 SiblingFuncletInfo.clear();
273 verifyNoAliasScopeDecl();
274 NoAliasScopeDecls.clear();
284 for (
const Function &
F : M)
285 if (
F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
286 DeoptimizeDeclarations.push_back(&
F);
290 verifyFrameRecoverIndices();
291 for (
const GlobalVariable &GV :
M.globals())
292 visitGlobalVariable(GV);
294 for (
const GlobalAlias &GA :
M.aliases())
295 visitGlobalAlias(GA);
297 for (
const GlobalIFunc &GI :
M.ifuncs())
298 visitGlobalIFunc(GI);
300 for (
const NamedMDNode &NMD :
M.named_metadata())
301 visitNamedMDNode(NMD);
303 for (
const StringMapEntry<Comdat> &SMEC :
M.getComdatSymbolTable())
304 visitComdat(SMEC.getValue());
308 visitModuleCommandLines();
309 visitModuleErrnoTBAA();
311 verifyCompileUnits();
313 verifyDeoptimizeCallingConvs();
314 DISubprogramAttachments.clear();
320 enum class AreDebugLocsAllowed {
No,
Yes };
324 enum class RangeLikeMetadataKind {
331 void visitGlobalValue(
const GlobalValue &GV);
332 void visitGlobalVariable(
const GlobalVariable &GV);
333 void visitGlobalAlias(
const GlobalAlias &GA);
334 void visitGlobalIFunc(
const GlobalIFunc &GI);
335 void visitAliaseeSubExpr(
const GlobalAlias &
A,
const Constant &
C);
336 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
337 const GlobalAlias &
A,
const Constant &
C);
338 void visitNamedMDNode(
const NamedMDNode &NMD);
339 void visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs);
340 void visitMetadataAsValue(
const MetadataAsValue &MD, Function *
F);
341 void visitValueAsMetadata(
const ValueAsMetadata &MD, Function *
F);
342 void visitDIArgList(
const DIArgList &AL, Function *
F);
343 void visitComdat(
const Comdat &
C);
344 void visitModuleIdents();
345 void visitModuleCommandLines();
346 void visitModuleErrnoTBAA();
347 void visitModuleFlags();
348 void visitModuleFlag(
const MDNode *
Op,
349 DenseMap<const MDString *, const MDNode *> &SeenIDs,
350 SmallVectorImpl<const MDNode *> &Requirements);
351 void visitModuleFlagCGProfileEntry(
const MDOperand &MDO);
352 void visitFunction(
const Function &
F);
353 void visitBasicBlock(BasicBlock &BB);
354 void verifyRangeLikeMetadata(
const Value &V,
const MDNode *
Range,
Type *Ty,
355 RangeLikeMetadataKind Kind);
356 void visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
357 void visitNoFPClassMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
358 void visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
359 void visitDereferenceableMetadata(Instruction &
I, MDNode *MD);
360 void visitNofreeMetadata(Instruction &
I, MDNode *MD);
361 void visitProfMetadata(Instruction &
I, MDNode *MD);
362 void visitCallStackMetadata(MDNode *MD);
363 void visitMemProfMetadata(Instruction &
I, MDNode *MD);
364 void visitCallsiteMetadata(Instruction &
I, MDNode *MD);
365 void visitCalleeTypeMetadata(Instruction &
I, MDNode *MD);
366 void visitDIAssignIDMetadata(Instruction &
I, MDNode *MD);
367 void visitMMRAMetadata(Instruction &
I, MDNode *MD);
368 void visitAnnotationMetadata(MDNode *Annotation);
369 void visitAliasScopeMetadata(
const MDNode *MD);
370 void visitAliasScopeListMetadata(
const MDNode *MD);
371 void visitAccessGroupMetadata(
const MDNode *MD);
372 void visitCapturesMetadata(Instruction &
I,
const MDNode *Captures);
373 void visitAllocTokenMetadata(Instruction &
I, MDNode *MD);
374 void visitInlineHistoryMetadata(Instruction &
I, MDNode *MD);
375 void visitMemCacheHintMetadata(Instruction &
I, MDNode *MD);
377#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
378#include "llvm/IR/Metadata.def"
379 void visitDIType(
const DIType &
N);
380 void visitDIScope(
const DIScope &
N);
404 void checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V);
409 void visitPHINode(
PHINode &PN);
418 void visitVAArgInst(
VAArgInst &VAA) { visitInstruction(VAA); }
419 void visitCallInst(CallInst &CI);
420 void visitInvokeInst(InvokeInst &
II);
421 void visitGetElementPtrInst(GetElementPtrInst &
GEP);
422 void visitLoadInst(LoadInst &LI);
423 void visitStoreInst(StoreInst &SI);
424 void verifyDominatesUse(Instruction &
I,
unsigned i);
425 void visitInstruction(Instruction &
I);
426 void visitTerminator(Instruction &
I);
427 void visitCondBrInst(CondBrInst &BI);
428 void visitReturnInst(ReturnInst &RI);
429 void visitSwitchInst(SwitchInst &SI);
430 void visitIndirectBrInst(IndirectBrInst &BI);
431 void visitCallBrInst(CallBrInst &CBI);
432 void visitSelectInst(SelectInst &SI);
433 void visitUserOp1(Instruction &
I);
434 void visitUserOp2(Instruction &
I) { visitUserOp1(
I); }
436 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
437 void visitVPIntrinsic(VPIntrinsic &VPI);
438 void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
439 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
440 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
441 void visitFenceInst(FenceInst &FI);
442 void visitAllocaInst(AllocaInst &AI);
443 void visitExtractValueInst(ExtractValueInst &EVI);
444 void visitInsertValueInst(InsertValueInst &IVI);
445 void visitEHPadPredecessors(Instruction &
I);
446 void visitLandingPadInst(LandingPadInst &LPI);
447 void visitResumeInst(ResumeInst &RI);
448 void visitCatchPadInst(CatchPadInst &CPI);
449 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
450 void visitCleanupPadInst(CleanupPadInst &CPI);
451 void visitFuncletPadInst(FuncletPadInst &FPI);
452 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
453 void visitCleanupReturnInst(CleanupReturnInst &CRI);
455 void verifySwiftErrorCall(CallBase &
Call,
const Value *SwiftErrorVal);
456 void verifySwiftErrorValue(
const Value *SwiftErrorVal);
457 void verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs, StringRef
Context);
458 void verifyMustTailCall(CallInst &CI);
459 bool verifyAttributeCount(AttributeList Attrs,
unsigned Params);
460 void verifyAttributeTypes(AttributeSet Attrs,
const Value *V);
461 void verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
const Value *V);
462 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
464 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
465 const Value *V,
bool IsIntrinsic,
bool IsInlineAsm);
466 void verifyFunctionMetadata(
ArrayRef<std::pair<unsigned, MDNode *>> MDs);
467 void verifyUnknownProfileMetadata(MDNode *MD);
468 void visitConstantExprsRecursively(
const Constant *EntryC);
469 void visitConstantExpr(
const ConstantExpr *CE);
470 void visitConstantPtrAuth(
const ConstantPtrAuth *CPA);
471 void verifyInlineAsmCall(
const CallBase &
Call);
472 void verifyStatepoint(
const CallBase &
Call);
473 void verifyFrameRecoverIndices();
474 void verifySiblingFuncletUnwinds();
476 void verifyFragmentExpression(
const DbgVariableRecord &
I);
477 template <
typename ValueOrMetadata>
478 void verifyFragmentExpression(
const DIVariable &V,
480 ValueOrMetadata *
Desc);
481 void verifyFnArgs(
const DbgVariableRecord &DVR);
482 void verifyNotEntryValue(
const DbgVariableRecord &
I);
485 void verifyCompileUnits();
489 void verifyDeoptimizeCallingConvs();
491 void verifyAttachedCallBundle(
const CallBase &
Call,
492 const OperandBundleUse &BU);
495 void verifyNoAliasScopeDecl();
501#define Check(C, ...) \
504 CheckFailed(__VA_ARGS__); \
511#define CheckDI(C, ...) \
514 DebugInfoCheckFailed(__VA_ARGS__); \
522 CheckDI(
I.DebugMarker->MarkedInstr == &
I,
523 "Instruction has invalid DebugMarker", &
I);
525 "PHI Node must not have any attached DbgRecords", &
I);
527 CheckDI(DR.getMarker() ==
I.DebugMarker,
528 "DbgRecord had invalid DebugMarker", &
I, &DR);
531 visitMDNode(*
Loc, AreDebugLocsAllowed::Yes);
536 verifyFragmentExpression(*DVR);
537 verifyNotEntryValue(*DVR);
544void Verifier::visit(Instruction &
I) {
546 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i)
547 Check(
I.getOperand(i) !=
nullptr,
"Operand is null", &
I);
559 while (!WorkList.
empty()) {
561 if (!Visited.
insert(Cur).second)
568void Verifier::visitGlobalValue(
const GlobalValue &GV) {
570 "Global is external, but doesn't have external or weak linkage!", &GV);
573 if (
const MDNode *Associated =
574 GO->getMetadata(LLVMContext::MD_associated)) {
575 Check(Associated->getNumOperands() == 1,
576 "associated metadata must have one operand", &GV, Associated);
577 const Metadata *
Op = Associated->getOperand(0).get();
578 Check(
Op,
"associated metadata must have a global value", GO, Associated);
581 Check(VM,
"associated metadata must be ValueAsMetadata", GO, Associated);
584 "associated value must be pointer typed", GV, Associated);
586 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
588 "associated metadata must point to a GlobalObject", GO, Stripped);
589 Check(Stripped != GO,
590 "global values should not associate to themselves", GO,
596 if (
const MDNode *AbsoluteSymbol =
597 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
598 verifyRangeLikeMetadata(*GO, AbsoluteSymbol,
599 DL.getIntPtrType(GO->getType()),
600 RangeLikeMetadataKind::AbsoluteSymbol);
603 if (GO->hasMetadata(LLVMContext::MD_implicit_ref)) {
604 Check(!GO->isDeclaration(),
605 "ref metadata must not be placed on a declaration", GO);
608 GO->getMetadata(LLVMContext::MD_implicit_ref, MDs);
609 for (
const MDNode *MD : MDs) {
610 Check(MD->getNumOperands() == 1,
"ref metadata must have one operand",
614 Check(VM,
"ref metadata must be ValueAsMetadata", GO, MD);
617 "ref value must be pointer typed", GV, MD);
621 "ref metadata must point to a GlobalObject", GO, Stripped);
622 Check(Stripped != GO,
"values should not reference themselves", GO,
628 if (
auto *Props = GO->getMetadata(LLVMContext::MD_elf_section_properties)) {
629 Check(Props->getNumOperands() == 2,
630 "elf_section_properties metadata must have two operands", GO,
632 if (Props->getNumOperands() == 2) {
634 Check(
Type,
"type field must be ConstantAsMetadata", GO, Props);
636 Check(TypeInt,
"type field must be ConstantInt", GO, Props);
639 Check(Entsize,
"entsize field must be ConstantAsMetadata", GO, Props);
641 Check(EntsizeInt,
"entsize field must be ConstantInt", GO, Props);
647 "Only global variables can have appending linkage!", &GV);
651 Check(GVar && GVar->getValueType()->isArrayTy(),
652 "Only global arrays can have appending linkage!", GVar);
656 Check(!GV.
hasComdat(),
"Declaration may not be in a Comdat!", &GV);
660 "dllexport GlobalValue must have default or protected visibility",
665 "dllimport GlobalValue must have default visibility", &GV);
666 Check(!GV.
isDSOLocal(),
"GlobalValue with DLLImport Storage is dso_local!",
672 "Global is marked as dllimport, but not external", &GV);
677 "GlobalValue with local linkage or non-default "
678 "visibility must be dso_local!",
683 if (!
I->getParent() || !
I->getParent()->getParent())
684 CheckFailed(
"Global is referenced by parentless instruction!", &GV, &M,
686 else if (
I->getParent()->getParent()->getParent() != &M)
687 CheckFailed(
"Global is referenced in a different module!", &GV, &M,
I,
688 I->getParent()->getParent(),
689 I->getParent()->getParent()->getParent());
692 if (
F->getParent() != &M)
693 CheckFailed(
"Global is used by function in a different module", &GV, &M,
701void Verifier::visitGlobalVariable(
const GlobalVariable &GV) {
705 Check(
A->value() <= Value::MaximumAlignment,
706 "huge alignment values are unsupported", &GV);
711 "Global variable initializer type does not match global "
715 "Global variable initializer must be sized", &GV);
721 "'common' global must have a zero initializer!", &GV);
724 Check(!GV.
hasComdat(),
"'common' global may not be in a Comdat!", &GV);
729 GV.
getName() ==
"llvm.global_dtors")) {
731 "invalid linkage for intrinsic global variable", &GV);
733 "invalid uses of intrinsic global variable", &GV);
740 PointerType::get(
Context,
DL.getProgramAddressSpace());
741 Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
742 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
743 STy->getTypeAtIndex(1) == FuncPtrTy,
744 "wrong type for intrinsic global variable", &GV);
745 Check(STy->getNumElements() == 3,
746 "the third field of the element type is mandatory, "
747 "specify ptr null to migrate from the obsoleted 2-field form");
748 Type *ETy = STy->getTypeAtIndex(2);
757 for (
const Use &U : Init->operands()) {
759 if (!Structor || Structor->getNumOperands() != 3)
762 "signing of ctors/dtors should be requested via module flags");
768 GV.
getName() ==
"llvm.compiler.used")) {
770 "invalid linkage for intrinsic global variable", &GV);
772 "invalid uses of intrinsic global variable", &GV);
776 Check(PTy,
"wrong type for intrinsic global variable", &GV);
780 Check(InitArray,
"wrong initializer for intrinsic global variable",
782 for (
Value *
Op : InitArray->operands()) {
786 Twine(
"invalid ") + GV.
getName() +
" member", V);
788 Twine(
"members of ") + GV.
getName() +
" must be named", V);
797 for (MDNode *MD : MDs) {
799 visitDIGlobalVariableExpression(*GVE);
801 CheckDI(
false,
"!dbg attachment of global variable must be a "
802 "DIGlobalVariableExpression");
812 "Global @" + GV.
getName() +
" has illegal target extension type",
821 "Global variable is too large to fit into the address space", &GV,
825 visitGlobalValue(GV);
832 visitGlobalValue(GV);
835void Verifier::visitAliaseeSubExpr(
const GlobalAlias &GA,
const Constant &
C) {
836 SmallPtrSet<const GlobalAlias*, 4> Visited;
838 visitAliaseeSubExpr(Visited, GA,
C);
841void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
842 const GlobalAlias &GA,
const Constant &
C) {
846 "available_externally alias must point to available_externally "
857 Check(Visited.
insert(GA2).second,
"Aliases cannot form a cycle", &GA);
859 Check(!GA2->isInterposable(),
860 "Alias cannot point to an interposable alias", &GA);
869 visitConstantExprsRecursively(CE);
871 for (
const Use &U :
C.operands()) {
874 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
876 visitAliaseeSubExpr(Visited, GA, *C2);
880void Verifier::visitGlobalAlias(
const GlobalAlias &GA) {
882 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
883 "weak_odr, external, or available_externally linkage!",
886 Check(Aliasee,
"Aliasee cannot be NULL!", &GA);
888 "Alias and aliasee types should match!", &GA);
891 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
893 visitAliaseeSubExpr(GA, *Aliasee);
895 visitGlobalValue(GA);
898void Verifier::visitGlobalIFunc(
const GlobalIFunc &GI) {
899 visitGlobalValue(GI);
903 for (
const auto &
I : MDs) {
904 CheckDI(
I.first != LLVMContext::MD_dbg,
905 "an ifunc may not have a !dbg attachment", &GI);
906 Check(
I.first != LLVMContext::MD_prof,
907 "an ifunc may not have a !prof attachment", &GI);
908 visitMDNode(*
I.second, AreDebugLocsAllowed::No);
912 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
913 "weak_odr, or external linkage!",
918 Check(Resolver,
"IFunc must have a Function resolver", &GI);
920 "IFunc resolver must be a definition", &GI);
927 "IFunc resolver must return a pointer", &GI);
930 "IFunc resolver has incorrect type", &GI);
933void Verifier::visitNamedMDNode(
const NamedMDNode &NMD) {
938 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
939 for (
const MDNode *MD : NMD.
operands()) {
940 if (NMD.
getName() ==
"llvm.dbg.cu")
946 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
950void Verifier::visitMDNode(
const MDNode &BaseMD,
951 AreDebugLocsAllowed AllowLocs) {
954 if (!MDNodes.
insert(&BaseMD).second)
957 std::queue<const MDNode *> Worklist;
958 Worklist.push(&BaseMD);
960 while (!Worklist.empty()) {
961 const MDNode *CurrentMD = Worklist.front();
964 "MDNode context does not match Module context!", CurrentMD);
969 case Metadata::MDTupleKind:
971#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
972 case Metadata::CLASS##Kind: \
973 visit##CLASS(cast<CLASS>(*CurrentMD)); \
975#include "llvm/IR/Metadata.def"
984 "DILocation not allowed within this metadata node", CurrentMD,
992 visitValueAsMetadata(*V,
nullptr);
1006 "Expected second operand to be an integer constant of type i32 or "
1014 Check(CurrentMD->
isResolved(),
"All nodes should be resolved!", CurrentMD);
1018void Verifier::visitValueAsMetadata(
const ValueAsMetadata &MD, Function *
F) {
1021 "Unexpected metadata round-trip through values", &MD, MD.
getValue());
1027 Check(
F,
"function-local metadata used outside a function", L);
1033 Check(
I->getParent(),
"function-local metadata not in basic block", L,
I);
1040 assert(ActualF &&
"Unimplemented function local metadata case!");
1042 Check(ActualF ==
F,
"function-local metadata used in wrong function", L);
1045void Verifier::visitDIArgList(
const DIArgList &AL, Function *
F) {
1046 for (
const ValueAsMetadata *VAM :
AL.getArgs())
1047 visitValueAsMetadata(*VAM,
F);
1050void Verifier::visitMetadataAsValue(
const MetadataAsValue &MDV, Function *
F) {
1053 visitMDNode(*
N, AreDebugLocsAllowed::No);
1059 if (!MDNodes.
insert(MD).second)
1063 visitValueAsMetadata(*V,
F);
1066 visitDIArgList(*AL,
F);
1074void Verifier::visitDILocation(
const DILocation &
N) {
1076 "location requires a valid scope", &
N,
N.getRawScope());
1077 if (
auto *IA =
N.getRawInlinedAt())
1080 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1083void Verifier::visitGenericDINode(
const GenericDINode &
N) {
1087void Verifier::visitDIScope(
const DIScope &
N) {
1088 if (
auto *
F =
N.getRawFile())
1092void Verifier::visitDIType(
const DIType &
N) {
1095 CheckDI(
N.getRawFile() ||
N.getLine() == 0,
"line specified with no file", &
N,
1099void Verifier::visitDISubrangeType(
const DISubrangeType &
N) {
1102 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1105 auto *LBound =
N.getRawLowerBound();
1109 "LowerBound must be signed constant or DIVariable or DIExpression or "
1112 auto *UBound =
N.getRawUpperBound();
1116 "UpperBound must be signed constant or DIVariable or DIExpression or "
1119 auto *Stride =
N.getRawStride();
1122 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1123 auto *Bias =
N.getRawBias();
1126 "Bias must be signed constant or DIVariable or DIExpression", &
N);
1128 auto *
Size =
N.getRawSizeInBits();
1130 "SizeInBits must be a constant");
1133void Verifier::visitDISubrange(
const DISubrange &
N) {
1134 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1135 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1136 "Subrange can have any one of count or upperBound", &
N);
1137 auto *CBound =
N.getRawCountNode();
1140 "Count must be signed constant or DIVariable or DIExpression", &
N);
1141 auto Count =
N.getCount();
1144 "invalid subrange count", &
N);
1145 auto *LBound =
N.getRawLowerBound();
1148 "LowerBound must be signed constant or DIVariable or DIExpression",
1150 auto *UBound =
N.getRawUpperBound();
1153 "UpperBound must be signed constant or DIVariable or DIExpression",
1155 auto *Stride =
N.getRawStride();
1158 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1161void Verifier::visitDIGenericSubrange(
const DIGenericSubrange &
N) {
1162 CheckDI(
N.getTag() == dwarf::DW_TAG_generic_subrange,
"invalid tag", &
N);
1163 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1164 "GenericSubrange can have any one of count or upperBound", &
N);
1165 auto *CBound =
N.getRawCountNode();
1167 "Count must be signed constant or DIVariable or DIExpression", &
N);
1168 auto *LBound =
N.getRawLowerBound();
1169 CheckDI(LBound,
"GenericSubrange must contain lowerBound", &
N);
1171 "LowerBound must be signed constant or DIVariable or DIExpression",
1173 auto *UBound =
N.getRawUpperBound();
1175 "UpperBound must be signed constant or DIVariable or DIExpression",
1177 auto *Stride =
N.getRawStride();
1178 CheckDI(Stride,
"GenericSubrange must contain stride", &
N);
1180 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1183void Verifier::visitDIEnumerator(
const DIEnumerator &
N) {
1184 CheckDI(
N.getTag() == dwarf::DW_TAG_enumerator,
"invalid tag", &
N);
1187void Verifier::visitDIBasicType(
const DIBasicType &
N) {
1190 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type ||
1191 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1192 N.getTag() == dwarf::DW_TAG_string_type,
1195 auto *
Size =
N.getRawSizeInBits();
1197 "SizeInBits must be a constant");
1200void Verifier::visitDIFixedPointType(
const DIFixedPointType &
N) {
1201 visitDIBasicType(
N);
1203 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type,
"invalid tag", &
N);
1204 CheckDI(
N.getEncoding() == dwarf::DW_ATE_signed_fixed ||
1205 N.getEncoding() == dwarf::DW_ATE_unsigned_fixed,
1206 "invalid encoding", &
N);
1210 "invalid kind", &
N);
1212 N.getFactorRaw() == 0,
1213 "factor should be 0 for rationals", &
N);
1215 (
N.getNumeratorRaw() == 0 &&
N.getDenominatorRaw() == 0),
1216 "numerator and denominator should be 0 for non-rationals", &
N);
1219void Verifier::visitDIStringType(
const DIStringType &
N) {
1222 CheckDI(
N.getTag() == dwarf::DW_TAG_string_type,
"invalid tag", &
N);
1223 CheckDI(!(
N.isBigEndian() &&
N.isLittleEndian()),
"has conflicting flags",
1227void Verifier::visitDIDerivedType(
const DIDerivedType &
N) {
1231 CheckDI(
N.getTag() == dwarf::DW_TAG_typedef ||
1232 N.getTag() == dwarf::DW_TAG_pointer_type ||
1233 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1234 N.getTag() == dwarf::DW_TAG_reference_type ||
1235 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1236 N.getTag() == dwarf::DW_TAG_const_type ||
1237 N.getTag() == dwarf::DW_TAG_immutable_type ||
1238 N.getTag() == dwarf::DW_TAG_volatile_type ||
1239 N.getTag() == dwarf::DW_TAG_restrict_type ||
1240 N.getTag() == dwarf::DW_TAG_atomic_type ||
1241 N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
1242 N.getTag() == dwarf::DW_TAG_member ||
1243 (
N.getTag() == dwarf::DW_TAG_variable &&
N.isStaticMember()) ||
1244 N.getTag() == dwarf::DW_TAG_inheritance ||
1245 N.getTag() == dwarf::DW_TAG_friend ||
1246 N.getTag() == dwarf::DW_TAG_set_type ||
1247 N.getTag() == dwarf::DW_TAG_template_alias,
1249 if (
N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1250 CheckDI(
isType(
N.getRawExtraData()),
"invalid pointer to member type", &
N,
1251 N.getRawExtraData());
1252 }
else if (
N.getTag() == dwarf::DW_TAG_template_alias) {
1254 N.getRawExtraData());
1255 }
else if (
N.getTag() == dwarf::DW_TAG_inheritance ||
1256 N.getTag() == dwarf::DW_TAG_member ||
1257 N.getTag() == dwarf::DW_TAG_variable) {
1258 auto *ExtraData =
N.getRawExtraData();
1259 auto IsValidExtraData = [&]() {
1260 if (ExtraData ==
nullptr)
1266 if (Tuple->getNumOperands() != 1)
1273 "extraData must be ConstantAsMetadata, MDString, DIObjCProperty, "
1274 "or MDTuple with single ConstantAsMetadata operand",
1278 if (
N.getTag() == dwarf::DW_TAG_set_type) {
1279 if (
auto *
T =
N.getRawBaseType()) {
1284 (Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1285 (Subrange &&
Subrange->getTag() == dwarf::DW_TAG_subrange_type) ||
1286 (
Basic && (
Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1287 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1288 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1289 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1290 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1291 "invalid set base type", &
N,
T);
1296 N.getRawBaseType());
1298 if (
N.getDWARFAddressSpace()) {
1299 CheckDI(
N.getTag() == dwarf::DW_TAG_pointer_type ||
1300 N.getTag() == dwarf::DW_TAG_reference_type ||
1301 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1302 "DWARF address space only applies to pointer or reference types",
1306 auto *
Size =
N.getRawSizeInBits();
1309 "SizeInBits must be a constant or DIVariable or DIExpression");
1314 return ((Flags & DINode::FlagLValueReference) &&
1315 (Flags & DINode::FlagRValueReference)) ||
1316 ((Flags & DINode::FlagTypePassByValue) &&
1317 (Flags & DINode::FlagTypePassByReference));
1320void Verifier::visitTemplateParams(
const MDNode &
N,
const Metadata &RawParams) {
1322 CheckDI(Params,
"invalid template params", &
N, &RawParams);
1329void Verifier::visitDICompositeType(
const DICompositeType &
N) {
1333 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type ||
1334 N.getTag() == dwarf::DW_TAG_structure_type ||
1335 N.getTag() == dwarf::DW_TAG_union_type ||
1336 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1337 N.getTag() == dwarf::DW_TAG_class_type ||
1338 N.getTag() == dwarf::DW_TAG_variant_part ||
1339 N.getTag() == dwarf::DW_TAG_variant ||
1340 N.getTag() == dwarf::DW_TAG_namelist,
1344 N.getRawBaseType());
1347 "invalid composite elements", &
N,
N.getRawElements());
1349 N.getRawVTableHolder());
1351 "invalid reference flags", &
N);
1352 unsigned DIBlockByRefStruct = 1 << 4;
1353 CheckDI((
N.getFlags() & DIBlockByRefStruct) == 0,
1354 "DIBlockByRefStruct on DICompositeType is no longer supported", &
N);
1356 "DISubprogram contains null entry in `elements` field", &
N);
1359 const DINodeArray
Elements =
N.getElements();
1361 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1362 "invalid vector, expected one element of type subrange", &
N);
1365 if (
auto *Params =
N.getRawTemplateParams())
1366 visitTemplateParams(
N, *Params);
1368 if (
auto *
D =
N.getRawDiscriminator()) {
1370 "discriminator can only appear on variant part");
1373 if (
N.getRawDataLocation()) {
1374 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1375 "dataLocation can only appear in array type");
1378 if (
N.getRawAssociated()) {
1379 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1380 "associated can only appear in array type");
1383 if (
N.getRawAllocated()) {
1384 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1385 "allocated can only appear in array type");
1388 if (
N.getRawRank()) {
1389 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1390 "rank can only appear in array type");
1393 if (
N.getTag() == dwarf::DW_TAG_array_type) {
1394 CheckDI(
N.getRawBaseType(),
"array types must have a base type", &
N);
1397 auto *
Size =
N.getRawSizeInBits();
1400 "SizeInBits must be a constant or DIVariable or DIExpression");
1403void Verifier::visitDISubroutineType(
const DISubroutineType &
N) {
1405 CheckDI(
N.getTag() == dwarf::DW_TAG_subroutine_type,
"invalid tag", &
N);
1406 if (
auto *Types =
N.getRawTypeArray()) {
1408 for (
Metadata *Ty :
N.getTypeArray()->operands()) {
1409 CheckDI(
isType(Ty),
"invalid subroutine type ref", &
N, Types, Ty);
1413 "invalid reference flags", &
N);
1416void Verifier::visitDIFile(
const DIFile &
N) {
1417 CheckDI(
N.getTag() == dwarf::DW_TAG_file_type,
"invalid tag", &
N);
1418 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum =
N.getChecksum();
1420 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1421 "invalid checksum kind", &
N);
1423 switch (Checksum->Kind) {
1434 CheckDI(Checksum->Value.size() ==
Size,
"invalid checksum length", &
N);
1436 "invalid checksum", &
N);
1440void Verifier::visitDICompileUnit(
const DICompileUnit &
N) {
1441 CheckDI(
N.isDistinct(),
"compile units must be distinct", &
N);
1442 CheckDI(
N.getTag() == dwarf::DW_TAG_compile_unit,
"invalid tag", &
N);
1448 CheckDI(!
N.getFile()->getFilename().empty(),
"invalid filename", &
N,
1452 "invalid emission kind", &
N);
1455 "invalid language dialect", &
N);
1457 if (
auto *Array =
N.getRawEnumTypes()) {
1459 for (
Metadata *
Op :
N.getEnumTypes()->operands()) {
1461 CheckDI(Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1462 "invalid enum type", &
N,
N.getEnumTypes(),
Op);
1464 "function-local enum in a DICompileUnit's enum list", &
N,
1465 N.getEnumTypes(),
Op);
1468 if (
auto *Array =
N.getRawRetainedTypes()) {
1470 for (
Metadata *
Op :
N.getRetainedTypes()->operands()) {
1474 "invalid retained type", &
N,
Op);
1477 if (
auto *Array =
N.getRawGlobalVariables()) {
1479 for (
Metadata *
Op :
N.getGlobalVariables()->operands()) {
1481 CheckDI(GVE,
"invalid global variable ref", &
N,
Op);
1483 "function-local variables are not allowed in a DICompileUnit's "
1484 "global variables list",
1488 if (
auto *Array =
N.getRawImportedEntities()) {
1490 for (
Metadata *
Op :
N.getImportedEntities()->operands()) {
1492 CheckDI(IE,
"invalid imported entity ref", &
N,
Op);
1494 "function-local imports are not allowed in a DICompileUnit's "
1495 "imported entities list",
1499 if (
auto *Array =
N.getRawMacros()) {
1508void Verifier::visitDISubprogram(
const DISubprogram &
N) {
1509 CheckDI(
N.getTag() == dwarf::DW_TAG_subprogram,
"invalid tag", &
N);
1511 if (
auto *
F =
N.getRawFile())
1514 CheckDI(
N.getLine() == 0,
"line specified with no file", &
N,
N.getLine());
1515 auto *
T =
N.getRawType();
1516 CheckDI(
T,
"DISubprogram requires a non-null type", &
N);
1518 CheckDI(
isType(
N.getRawContainingType()),
"invalid containing type", &
N,
1519 N.getRawContainingType());
1520 if (
auto *Params =
N.getRawTemplateParams())
1521 visitTemplateParams(
N, *Params);
1522 if (
auto *S =
N.getRawDeclaration())
1524 "invalid subprogram declaration", &
N, S);
1525 if (
auto *RawNode =
N.getRawRetainedNodes()) {
1527 CheckDI(Node,
"invalid retained nodes list", &
N, RawNode);
1529 DenseMap<unsigned, DILocalVariable *>
Args;
1531 CheckDI(
Op,
"nullptr in retained nodes", &
N, Node);
1533 auto True = [](
const Metadata *) {
return true; };
1534 auto False = [](
const Metadata *) {
return false; };
1535 bool IsTypeCorrect = DISubprogram::visitRetainedNode<bool>(
1536 Op, True, True, True, True, True, False);
1538 "invalid retained nodes, expected DILocalVariable, DILabel, "
1539 "DIImportedEntity, DIType or DIGlobalVariableExpression",
1546 "invalid retained nodes, retained node is not local", &
N, Node,
1549 DISubprogram *RetainedNodeSP = RetainedNodeScope->getSubprogram();
1550 DICompileUnit *RetainedNodeUnit =
1551 RetainedNodeSP ? RetainedNodeSP->getUnit() :
nullptr;
1553 RetainedNodeSP == &
N,
1554 "invalid retained nodes, retained node does not belong to subprogram",
1555 &
N, Node, RetainedNode, RetainedNodeScope, RetainedNodeSP,
1561 if (
unsigned ArgNum = DV->getArg()) {
1563 CheckDI(Inserted || DV == ArgI->second,
1564 "invalid retained nodes, more than one local variable with the "
1565 "same argument index",
1566 &
N,
N.getUnit(), Node, RetainedNode, Args[ArgNum]);
1571 "invalid reference flags", &
N);
1573 auto *
Unit =
N.getRawUnit();
1574 if (
N.isDefinition()) {
1576 CheckDI(
N.isDistinct(),
"subprogram definitions must be distinct", &
N);
1577 CheckDI(Unit,
"subprogram definitions must have a compile unit", &
N);
1582 if (CT && CT->getRawIdentifier() &&
1583 M.getContext().isODRUniquingDebugTypes())
1585 "definition subprograms cannot be nested within DICompositeType "
1586 "when enabling ODR",
1590 CheckDI(!Unit,
"subprogram declarations must not have a compile unit", &
N);
1592 "subprogram declaration must not have a declaration field");
1595 if (
auto *RawThrownTypes =
N.getRawThrownTypes()) {
1597 CheckDI(ThrownTypes,
"invalid thrown types list", &
N, RawThrownTypes);
1603 if (
N.areAllCallsDescribed())
1605 "DIFlagAllCallsDescribed must be attached to a definition");
1608void Verifier::visitDILexicalBlockBase(
const DILexicalBlockBase &
N) {
1609 CheckDI(
N.getTag() == dwarf::DW_TAG_lexical_block,
"invalid tag", &
N);
1611 "invalid local scope", &
N,
N.getRawScope());
1613 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1616void Verifier::visitDILexicalBlock(
const DILexicalBlock &
N) {
1617 visitDILexicalBlockBase(
N);
1620 "cannot have column info without line info", &
N);
1623void Verifier::visitDILexicalBlockFile(
const DILexicalBlockFile &
N) {
1624 visitDILexicalBlockBase(
N);
1627void Verifier::visitDICommonBlock(
const DICommonBlock &
N) {
1628 CheckDI(
N.getTag() == dwarf::DW_TAG_common_block,
"invalid tag", &
N);
1629 if (
auto *S =
N.getRawScope())
1631 if (
auto *S =
N.getRawDecl())
1635void Verifier::visitDINamespace(
const DINamespace &
N) {
1636 CheckDI(
N.getTag() == dwarf::DW_TAG_namespace,
"invalid tag", &
N);
1637 if (
auto *S =
N.getRawScope())
1641void Verifier::visitDIMacro(
const DIMacro &
N) {
1644 "invalid macinfo type", &
N);
1645 CheckDI(!
N.getName().empty(),
"anonymous macro", &
N);
1646 if (!
N.getValue().empty()) {
1647 assert(
N.getValue().data()[0] !=
' ' &&
"Macro value has a space prefix");
1651void Verifier::visitDIMacroFile(
const DIMacroFile &
N) {
1653 "invalid macinfo type", &
N);
1654 if (
auto *
F =
N.getRawFile())
1657 if (
auto *Array =
N.getRawElements()) {
1659 for (
Metadata *
Op :
N.getElements()->operands()) {
1665void Verifier::visitDIModule(
const DIModule &
N) {
1666 CheckDI(
N.getTag() == dwarf::DW_TAG_module,
"invalid tag", &
N);
1667 CheckDI(!
N.getName().empty(),
"anonymous module", &
N);
1670void Verifier::visitDITemplateParameter(
const DITemplateParameter &
N) {
1674void Verifier::visitDITemplateTypeParameter(
const DITemplateTypeParameter &
N) {
1675 visitDITemplateParameter(
N);
1677 CheckDI(
N.getTag() == dwarf::DW_TAG_template_type_parameter,
"invalid tag",
1681void Verifier::visitDITemplateValueParameter(
1682 const DITemplateValueParameter &
N) {
1683 visitDITemplateParameter(
N);
1685 CheckDI(
N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1686 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1687 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1691void Verifier::visitDIVariable(
const DIVariable &
N) {
1692 if (
auto *S =
N.getRawScope())
1694 if (
auto *
F =
N.getRawFile())
1698void Verifier::visitDIGlobalVariable(
const DIGlobalVariable &
N) {
1702 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1705 if (
N.isDefinition())
1706 CheckDI(
N.getType(),
"missing global variable type", &
N);
1707 if (
auto *Member =
N.getRawStaticDataMemberDeclaration()) {
1709 "invalid static data member declaration", &
N, Member);
1713void Verifier::visitDILocalVariable(
const DILocalVariable &
N) {
1718 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1720 "local variable requires a valid scope", &
N,
N.getRawScope());
1721 if (
auto Ty =
N.getType())
1725void Verifier::visitDIAssignID(
const DIAssignID &
N) {
1726 CheckDI(!
N.getNumOperands(),
"DIAssignID has no arguments", &
N);
1727 CheckDI(
N.isDistinct(),
"DIAssignID must be distinct", &
N);
1730void Verifier::visitDILabel(
const DILabel &
N) {
1731 if (
auto *S =
N.getRawScope())
1733 if (
auto *
F =
N.getRawFile())
1736 CheckDI(
N.getTag() == dwarf::DW_TAG_label,
"invalid tag", &
N);
1738 "label requires a valid scope", &
N,
N.getRawScope());
1741void Verifier::visitDIExpression(
const DIExpression &
N) {
1742 CheckDI(
N.isValid(),
"invalid expression", &
N);
1745void Verifier::visitDIGlobalVariableExpression(
1746 const DIGlobalVariableExpression &GVE) {
1749 visitDIGlobalVariable(*Var);
1751 visitDIExpression(*Expr);
1752 if (
auto Fragment = Expr->getFragmentInfo())
1753 verifyFragmentExpression(*GVE.
getVariable(), *Fragment, &GVE);
1757void Verifier::visitDIObjCProperty(
const DIObjCProperty &
N) {
1758 CheckDI(
N.getTag() == dwarf::DW_TAG_APPLE_property,
"invalid tag", &
N);
1759 if (
auto *
T =
N.getRawType())
1761 if (
auto *
F =
N.getRawFile())
1765void Verifier::visitDIImportedEntity(
const DIImportedEntity &
N) {
1766 CheckDI(
N.getTag() == dwarf::DW_TAG_imported_module ||
1767 N.getTag() == dwarf::DW_TAG_imported_declaration,
1769 if (
auto *S =
N.getRawScope())
1775void Verifier::visitComdat(
const Comdat &
C) {
1778 if (
TT.isOSBinFormatCOFF())
1779 if (
const GlobalValue *GV =
M.getNamedValue(
C.getName()))
1784void Verifier::visitModuleIdents() {
1785 const NamedMDNode *Idents =
M.getNamedMetadata(
"llvm.ident");
1791 for (
const MDNode *
N : Idents->
operands()) {
1792 Check(
N->getNumOperands() == 1,
1793 "incorrect number of operands in llvm.ident metadata",
N);
1795 (
"invalid value for llvm.ident metadata entry operand"
1796 "(the operand should be a string)"),
1801void Verifier::visitModuleCommandLines() {
1802 const NamedMDNode *CommandLines =
M.getNamedMetadata(
"llvm.commandline");
1809 for (
const MDNode *
N : CommandLines->
operands()) {
1810 Check(
N->getNumOperands() == 1,
1811 "incorrect number of operands in llvm.commandline metadata",
N);
1813 (
"invalid value for llvm.commandline metadata entry operand"
1814 "(the operand should be a string)"),
1819void Verifier::visitModuleErrnoTBAA() {
1820 const NamedMDNode *ErrnoTBAA =
M.getNamedMetadata(
"llvm.errno.tbaa");
1825 "llvm.errno.tbaa must have at least one operand", ErrnoTBAA);
1827 for (
const MDNode *
N : ErrnoTBAA->
operands())
1831void Verifier::visitModuleFlags() {
1832 const NamedMDNode *
Flags =
M.getModuleFlagsMetadata();
1836 DenseMap<const MDString*, const MDNode*> SeenIDs;
1840 std::optional<uint64_t> PAuthABIPlatform;
1841 std::optional<uint64_t> PAuthABIVersion;
1843 uint64_t HasPtrauthInitFini = 0;
1844 uint64_t HasPtrauthInitFiniAddr = 0;
1846 for (
const MDNode *MDN :
Flags->operands()) {
1847 visitModuleFlag(MDN, SeenIDs, Requirements);
1848 if (MDN->getNumOperands() != 3)
1852 auto GetFlagNamed = [&](StringRef
Name) -> std::optional<uint64_t> {
1853 if (FlagName->getString() != Name)
1854 return std::nullopt;
1855 if (
const auto *FlagValue =
1857 return FlagValue->getZExtValue();
1859 CheckFailed(Name +
": module flag expects integer value");
1860 return std::nullopt;
1863 if (
auto Value = GetFlagNamed(
"aarch64-elf-pauthabi-platform"))
1864 PAuthABIPlatform = *
Value;
1865 else if (
auto Value = GetFlagNamed(
"aarch64-elf-pauthabi-version"))
1866 PAuthABIVersion = *
Value;
1867 else if (
auto Value = GetFlagNamed(
"ptrauth-init-fini"))
1868 HasPtrauthInitFini = *
Value;
1869 else if (
auto Value =
1870 GetFlagNamed(
"ptrauth-init-fini-address-discrimination"))
1871 HasPtrauthInitFiniAddr = *
Value;
1876 "ptrauth-init-fini must be 0 or 1");
1878 "ptrauth-init-fini-address-discrimination must be 0 or 1, if set");
1879 if (HasPtrauthInitFiniAddr)
1880 Check(HasPtrauthInitFini,
"ptrauth-init-fini-address-discrimination module "
1881 "flag requires ptrauth-init-fini");
1883 if (PAuthABIPlatform.has_value() != PAuthABIVersion.has_value())
1884 CheckFailed(
"either both or no 'aarch64-elf-pauthabi-platform' and "
1885 "'aarch64-elf-pauthabi-version' module flags must be present");
1888 for (
const MDNode *Requirement : Requirements) {
1890 const Metadata *ReqValue = Requirement->getOperand(1);
1892 const MDNode *
Op = SeenIDs.
lookup(Flag);
1894 CheckFailed(
"invalid requirement on flag, flag is not present in module",
1899 if (
Op->getOperand(2) != ReqValue) {
1900 CheckFailed((
"invalid requirement on flag, "
1901 "flag does not have the required value"),
1909Verifier::visitModuleFlag(
const MDNode *
Op,
1910 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1911 SmallVectorImpl<const MDNode *> &Requirements) {
1915 "incorrect number of operands in module flag",
Op);
1916 Module::ModFlagBehavior MFB;
1917 if (!Module::isValidModFlagBehavior(
Op->getOperand(0), MFB)) {
1919 "invalid behavior operand in module flag (expected constant integer)",
1922 "invalid behavior operand in module flag (unexpected constant)",
1926 Check(
ID,
"invalid ID operand in module flag (expected metadata string)",
1932 case Module::Warning:
1933 case Module::Override:
1939 Check(V &&
V->getValue().isNonNegative(),
1940 "invalid value for 'min' module flag (expected constant non-negative "
1948 "invalid value for 'max' module flag (expected constant integer)",
1953 case Module::Require: {
1958 "invalid value for 'require' module flag (expected metadata pair)",
1961 (
"invalid value for 'require' module flag "
1962 "(first value operand should be a string)"),
1963 Value->getOperand(0));
1971 case Module::Append:
1972 case Module::AppendUnique: {
1975 "invalid value for 'append'-type module flag "
1976 "(expected a metadata node)",
1983 if (MFB != Module::Require) {
1986 "module flag identifiers must be unique (or of 'require' type)",
ID);
1989 if (
ID->getString() ==
"wchar_size") {
1992 Check(
Value,
"wchar_size metadata requires constant integer argument");
1995 if (
ID->getString() ==
"Linker Options") {
1999 Check(
M.getNamedMetadata(
"llvm.linker.options"),
2000 "'Linker Options' named metadata no longer supported");
2003 if (
ID->getString() ==
"SemanticInterposition") {
2004 ConstantInt *
Value =
2007 "SemanticInterposition metadata requires constant integer argument");
2010 if (
ID->getString() ==
"CG Profile") {
2011 for (
const MDOperand &MDO :
cast<MDNode>(
Op->getOperand(2))->operands())
2012 visitModuleFlagCGProfileEntry(MDO);
2019void Verifier::visitModuleFlagCGProfileEntry(
const MDOperand &MDO) {
2020 auto CheckFunction = [&](
const MDOperand &FuncMDO) {
2025 "expected a Function or null", FuncMDO);
2028 Check(Node &&
Node->getNumOperands() == 3,
"expected a MDNode triple", MDO);
2029 CheckFunction(
Node->getOperand(0));
2030 CheckFunction(
Node->getOperand(1));
2033 "expected an integer constant",
Node->getOperand(2));
2036void Verifier::verifyAttributeTypes(AttributeSet Attrs,
const Value *V) {
2039 if (
A.isStringAttribute()) {
2040#define GET_ATTR_NAMES
2041#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
2042#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
2043 if (A.getKindAsString() == #DISPLAY_NAME) { \
2044 auto V = A.getValueAsString(); \
2045 if (!(V.empty() || V == "true" || V == "false")) \
2046 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
2050#include "llvm/IR/Attributes.inc"
2054 if (
A.isIntAttribute() != Attribute::isIntAttrKind(
A.getKindAsEnum())) {
2055 CheckFailed(
"Attribute '" +
A.getAsString() +
"' should have an Argument",
2064void Verifier::verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
2066 if (!
Attrs.hasAttributes())
2069 verifyAttributeTypes(Attrs, V);
2072 Check(Attr.isStringAttribute() ||
2073 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
2074 "Attribute '" + Attr.getAsString() +
"' does not apply to parameters",
2077 if (
Attrs.hasAttribute(Attribute::ImmArg)) {
2078 unsigned AttrCount =
2079 Attrs.getNumAttributes() -
Attrs.hasAttribute(Attribute::Range);
2080 Check(AttrCount == 1,
2081 "Attribute 'immarg' is incompatible with other attributes except the "
2082 "'range' attribute",
2088 unsigned AttrCount = 0;
2089 AttrCount +=
Attrs.hasAttribute(Attribute::ByVal);
2090 AttrCount +=
Attrs.hasAttribute(Attribute::InAlloca);
2091 AttrCount +=
Attrs.hasAttribute(Attribute::Preallocated);
2092 AttrCount +=
Attrs.hasAttribute(Attribute::StructRet) ||
2093 Attrs.hasAttribute(Attribute::InReg);
2094 AttrCount +=
Attrs.hasAttribute(Attribute::Nest);
2095 AttrCount +=
Attrs.hasAttribute(Attribute::ByRef);
2096 Check(AttrCount <= 1,
2097 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
2098 "'byref', and 'sret' are incompatible!",
2101 Check(!(
Attrs.hasAttribute(Attribute::InAlloca) &&
2102 Attrs.hasAttribute(Attribute::ReadOnly)),
2104 "'inalloca and readonly' are incompatible!",
2107 Check(!(
Attrs.hasAttribute(Attribute::StructRet) &&
2108 Attrs.hasAttribute(Attribute::Returned)),
2110 "'sret and returned' are incompatible!",
2113 Check(!(
Attrs.hasAttribute(Attribute::ZExt) &&
2114 Attrs.hasAttribute(Attribute::SExt)),
2116 "'zeroext and signext' are incompatible!",
2119 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2120 Attrs.hasAttribute(Attribute::ReadOnly)),
2122 "'readnone and readonly' are incompatible!",
2125 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2126 Attrs.hasAttribute(Attribute::WriteOnly)),
2128 "'readnone and writeonly' are incompatible!",
2131 Check(!(
Attrs.hasAttribute(Attribute::ReadOnly) &&
2132 Attrs.hasAttribute(Attribute::WriteOnly)),
2134 "'readonly and writeonly' are incompatible!",
2137 Check(!(
Attrs.hasAttribute(Attribute::NoInline) &&
2138 Attrs.hasAttribute(Attribute::AlwaysInline)),
2140 "'noinline and alwaysinline' are incompatible!",
2143 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2144 Attrs.hasAttribute(Attribute::ReadNone)),
2145 "Attributes writable and readnone are incompatible!", V);
2147 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2148 Attrs.hasAttribute(Attribute::ReadOnly)),
2149 "Attributes writable and readonly are incompatible!", V);
2151 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty, Attrs);
2153 if (!Attr.isStringAttribute() &&
2154 IncompatibleAttrs.
contains(Attr.getKindAsEnum())) {
2155 CheckFailed(
"Attribute '" + Attr.getAsString() +
2156 "' applied to incompatible type!", V);
2162 if (
Attrs.hasAttribute(Attribute::Alignment)) {
2163 Align AttrAlign =
Attrs.getAlignment().valueOrOne();
2164 Check(AttrAlign.
value() <= Value::MaximumAlignment,
2165 "huge alignment values are unsupported", V);
2167 if (
Attrs.hasAttribute(Attribute::ByVal)) {
2169 SmallPtrSet<Type *, 4> Visited;
2171 "Attribute 'byval' does not support unsized types!", V);
2175 "'byval' argument has illegal target extension type", V);
2176 Check(
DL.getTypeAllocSize(ByValTy).getKnownMinValue() < (1ULL << 32),
2177 "huge 'byval' arguments are unsupported", V);
2179 if (
Attrs.hasAttribute(Attribute::ByRef)) {
2180 SmallPtrSet<Type *, 4> Visited;
2181 Check(
Attrs.getByRefType()->isSized(&Visited),
2182 "Attribute 'byref' does not support unsized types!", V);
2183 Check(
DL.getTypeAllocSize(
Attrs.getByRefType()).getKnownMinValue() <
2185 "huge 'byref' arguments are unsupported", V);
2187 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
2188 SmallPtrSet<Type *, 4> Visited;
2189 Check(
Attrs.getInAllocaType()->isSized(&Visited),
2190 "Attribute 'inalloca' does not support unsized types!", V);
2191 Check(
DL.getTypeAllocSize(
Attrs.getInAllocaType()).getKnownMinValue() <
2193 "huge 'inalloca' arguments are unsupported", V);
2195 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
2196 SmallPtrSet<Type *, 4> Visited;
2197 Check(
Attrs.getPreallocatedType()->isSized(&Visited),
2198 "Attribute 'preallocated' does not support unsized types!", V);
2200 DL.getTypeAllocSize(
Attrs.getPreallocatedType()).getKnownMinValue() <
2202 "huge 'preallocated' arguments are unsupported", V);
2206 if (
Attrs.hasAttribute(Attribute::Initializes)) {
2207 auto Inits =
Attrs.getAttribute(Attribute::Initializes).getInitializes();
2208 Check(!Inits.empty(),
"Attribute 'initializes' does not support empty list",
2211 "Attribute 'initializes' does not support unordered ranges", V);
2214 if (
Attrs.hasAttribute(Attribute::NoFPClass)) {
2215 uint64_t Val =
Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
2216 Check(Val != 0,
"Attribute 'nofpclass' must have at least one test bit set",
2219 "Invalid value for 'nofpclass' test mask", V);
2221 if (
Attrs.hasAttribute(Attribute::Range)) {
2222 const ConstantRange &CR =
2223 Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2225 "Range bit width must match type bit width!", V);
2229void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
2231 if (
Attrs.hasFnAttr(Attr)) {
2232 StringRef S =
Attrs.getFnAttr(Attr).getValueAsString();
2235 CheckFailed(
"\"" + Attr +
"\" takes an unsigned integer: " + S, V);
2241void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
2242 const Value *V,
bool IsIntrinsic,
2244 if (
Attrs.isEmpty())
2247 if (AttributeListsVisited.
insert(
Attrs.getRawPointer()).second) {
2249 "Attribute list does not match Module context!", &Attrs, V);
2250 for (
const auto &AttrSet : Attrs) {
2251 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(
Context),
2252 "Attribute set does not match Module context!", &AttrSet, V);
2253 for (
const auto &
A : AttrSet) {
2255 "Attribute does not match Module context!", &
A, V);
2260 bool SawNest =
false;
2261 bool SawReturned =
false;
2262 bool SawSRet =
false;
2263 bool SawSwiftSelf =
false;
2264 bool SawSwiftAsync =
false;
2265 bool SawSwiftError =
false;
2268 AttributeSet RetAttrs =
Attrs.getRetAttrs();
2271 Attribute::canUseAsRetAttr(
RetAttr.getKindAsEnum()),
2272 "Attribute '" +
RetAttr.getAsString() +
2273 "' does not apply to function return values",
2276 unsigned MaxParameterWidth = 0;
2277 auto GetMaxParameterWidth = [&MaxParameterWidth](
Type *Ty) {
2280 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2281 if (
Size > MaxParameterWidth)
2282 MaxParameterWidth =
Size;
2286 GetMaxParameterWidth(FT->getReturnType());
2287 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2290 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2291 Type *Ty = FT->getParamType(i);
2292 AttributeSet ArgAttrs =
Attrs.getParamAttrs(i);
2296 "immarg attribute only applies to intrinsics", V);
2299 "Attribute 'elementtype' can only be applied to intrinsics"
2304 verifyParameterAttrs(ArgAttrs, Ty, V);
2305 GetMaxParameterWidth(Ty);
2308 Check(!SawNest,
"More than one parameter has attribute nest!", V);
2313 Check(!SawReturned,
"More than one parameter has attribute returned!", V);
2315 "Incompatible argument and return types for 'returned' attribute",
2321 Check(!SawSRet,
"Cannot have multiple 'sret' parameters!", V);
2322 Check(i == 0 || i == 1,
2323 "Attribute 'sret' is not on first or second parameter!", V);
2328 Check(!SawSwiftSelf,
"Cannot have multiple 'swiftself' parameters!", V);
2329 SawSwiftSelf =
true;
2333 Check(!SawSwiftAsync,
"Cannot have multiple 'swiftasync' parameters!", V);
2334 SawSwiftAsync =
true;
2338 Check(!SawSwiftError,
"Cannot have multiple 'swifterror' parameters!", V);
2339 SawSwiftError =
true;
2343 Check(i == FT->getNumParams() - 1,
2344 "inalloca isn't on the last parameter!", V);
2348 if (!
Attrs.hasFnAttrs())
2351 verifyAttributeTypes(
Attrs.getFnAttrs(), V);
2354 Attribute::canUseAsFnAttr(
FnAttr.getKindAsEnum()),
2355 "Attribute '" +
FnAttr.getAsString() +
2356 "' does not apply to functions!",
2359 Check(!(
Attrs.hasFnAttr(Attribute::NoInline) &&
2360 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2361 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2363 if (
Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2365 "Attribute 'optnone' requires 'noinline'!", V);
2367 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2368 "Attributes 'optsize and optnone' are incompatible!", V);
2371 "Attributes 'minsize and optnone' are incompatible!", V);
2373 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
2374 "Attributes 'optdebug and optnone' are incompatible!", V);
2377 Check(!(
Attrs.hasFnAttr(Attribute::SanitizeRealtime) &&
2378 Attrs.hasFnAttr(Attribute::SanitizeRealtimeBlocking)),
2380 "'sanitize_realtime and sanitize_realtime_blocking' are incompatible!",
2383 if (
Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
2384 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2385 "Attributes 'optsize and optdebug' are incompatible!", V);
2388 "Attributes 'minsize and optdebug' are incompatible!", V);
2391 Check(!
Attrs.hasAttrSomewhere(Attribute::Writable) ||
2392 isModSet(
Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
2393 "Attribute writable and memory without argmem: write are incompatible!",
2396 if (
Attrs.hasFnAttr(
"aarch64_pstate_sm_enabled")) {
2397 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_sm_compatible"),
2398 "Attributes 'aarch64_pstate_sm_enabled and "
2399 "aarch64_pstate_sm_compatible' are incompatible!",
2403 Check((
Attrs.hasFnAttr(
"aarch64_new_za") +
Attrs.hasFnAttr(
"aarch64_in_za") +
2404 Attrs.hasFnAttr(
"aarch64_inout_za") +
2405 Attrs.hasFnAttr(
"aarch64_out_za") +
2406 Attrs.hasFnAttr(
"aarch64_preserves_za") +
2407 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2408 "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2409 "'aarch64_inout_za', 'aarch64_preserves_za' and "
2410 "'aarch64_za_state_agnostic' are mutually exclusive",
2414 Attrs.hasFnAttr(
"aarch64_in_zt0") +
2415 Attrs.hasFnAttr(
"aarch64_inout_zt0") +
2416 Attrs.hasFnAttr(
"aarch64_out_zt0") +
2417 Attrs.hasFnAttr(
"aarch64_preserves_zt0") +
2418 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2419 "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
2420 "'aarch64_inout_zt0', 'aarch64_preserves_zt0' and "
2421 "'aarch64_za_state_agnostic' are mutually exclusive",
2424 if (
Attrs.hasFnAttr(Attribute::JumpTable)) {
2427 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2430 if (
auto Args =
Attrs.getFnAttrs().getAllocSizeArgs()) {
2431 auto CheckParam = [&](StringRef
Name,
unsigned ParamNo) {
2432 if (ParamNo >= FT->getNumParams()) {
2433 CheckFailed(
"'allocsize' " + Name +
" argument is out of bounds", V);
2437 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2438 CheckFailed(
"'allocsize' " + Name +
2439 " argument must refer to an integer parameter",
2447 if (!CheckParam(
"element size",
Args->first))
2450 if (
Args->second && !CheckParam(
"number of elements", *
Args->second))
2454 if (
Attrs.hasFnAttr(Attribute::AllocKind)) {
2457 K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
2459 {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
2462 "'allockind()' requires exactly one of alloc, realloc, and free");
2463 if ((
Type == AllocFnKind::Free) &&
2464 ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
2465 AllocFnKind::Aligned)) != AllocFnKind::Unknown))
2466 CheckFailed(
"'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2467 "or aligned modifiers.");
2468 AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
2469 if ((K & ZeroedUninit) == ZeroedUninit)
2470 CheckFailed(
"'allockind()' can't be both zeroed and uninitialized");
2474 StringRef S =
A.getValueAsString();
2475 Check(!S.
empty(),
"'alloc-variant-zeroed' must not be empty");
2483 "'alloc-variant-zeroed' must name a function belonging to the "
2484 "same 'alloc-family'");
2487 (
Variant->getFnAttribute(Attribute::AllocKind).getAllocKind() &
2488 AllocFnKind::Zeroed) != AllocFnKind::Unknown,
2489 "'alloc-variant-zeroed' must name a function with "
2490 "'allockind(\"zeroed\")'");
2493 "'alloc-variant-zeroed' must name a function with the same "
2498 "'alloc-variant-zeroed' must name a function with the same "
2499 "calling convention");
2503 if (
Attrs.hasFnAttr(Attribute::VScaleRange)) {
2504 unsigned VScaleMin =
Attrs.getFnAttrs().getVScaleRangeMin();
2506 CheckFailed(
"'vscale_range' minimum must be greater than 0", V);
2508 CheckFailed(
"'vscale_range' minimum must be power-of-two value", V);
2509 std::optional<unsigned> VScaleMax =
Attrs.getFnAttrs().getVScaleRangeMax();
2510 if (VScaleMax && VScaleMin > VScaleMax)
2511 CheckFailed(
"'vscale_range' minimum cannot be greater than maximum", V);
2513 CheckFailed(
"'vscale_range' maximum must be power-of-two value", V);
2516 if (
Attribute FPAttr =
Attrs.getFnAttr(
"frame-pointer"); FPAttr.isValid()) {
2517 StringRef
FP = FPAttr.getValueAsString();
2518 if (
FP !=
"all" &&
FP !=
"non-leaf" &&
FP !=
"none" &&
FP !=
"reserved" &&
2519 FP !=
"non-leaf-no-reserve")
2520 CheckFailed(
"invalid value for 'frame-pointer' attribute: " +
FP, V);
2523 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-prefix", V);
2524 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-entry", V);
2525 if (
Attrs.hasFnAttr(
"patchable-function-entry-section"))
2526 Check(!
Attrs.getFnAttr(
"patchable-function-entry-section")
2529 "\"patchable-function-entry-section\" must not be empty");
2530 checkUnsignedBaseTenFuncAttr(Attrs,
"warn-stack-size", V);
2532 if (
auto A =
Attrs.getFnAttr(
"sign-return-address");
A.isValid()) {
2533 StringRef S =
A.getValueAsString();
2534 if (S !=
"none" && S !=
"all" && S !=
"non-leaf")
2535 CheckFailed(
"invalid value for 'sign-return-address' attribute: " + S, V);
2538 if (
auto A =
Attrs.getFnAttr(
"sign-return-address-key");
A.isValid()) {
2539 StringRef S =
A.getValueAsString();
2540 if (S !=
"a_key" && S !=
"b_key")
2541 CheckFailed(
"invalid value for 'sign-return-address-key' attribute: " + S,
2543 if (
auto AA =
Attrs.getFnAttr(
"sign-return-address"); !AA.isValid()) {
2545 "'sign-return-address-key' present without `sign-return-address`");
2549 if (
auto A =
Attrs.getFnAttr(
"branch-target-enforcement");
A.isValid()) {
2550 StringRef S =
A.getValueAsString();
2551 if (S !=
"" && S !=
"true" && S !=
"false")
2553 "invalid value for 'branch-target-enforcement' attribute: " + S, V);
2556 if (
auto A =
Attrs.getFnAttr(
"branch-protection-pauth-lr");
A.isValid()) {
2557 StringRef S =
A.getValueAsString();
2558 if (S !=
"" && S !=
"true" && S !=
"false")
2560 "invalid value for 'branch-protection-pauth-lr' attribute: " + S, V);
2563 if (
auto A =
Attrs.getFnAttr(
"guarded-control-stack");
A.isValid()) {
2564 StringRef S =
A.getValueAsString();
2565 if (S !=
"" && S !=
"true" && S !=
"false")
2566 CheckFailed(
"invalid value for 'guarded-control-stack' attribute: " + S,
2570 if (
auto A =
Attrs.getFnAttr(
"vector-function-abi-variant");
A.isValid()) {
2571 StringRef S =
A.getValueAsString();
2574 CheckFailed(
"invalid name for a VFABI variant: " + S, V);
2577 if (
auto A =
Attrs.getFnAttr(
"modular-format");
A.isValid()) {
2578 StringRef S =
A.getValueAsString();
2582 "modular-format attribute requires at least 5 arguments", V);
2583 unsigned UpperBound = FT->getNumParams() + (FT->isVarArg() ? 1 : 0);
2585 Check(!Args[1].getAsInteger(10, FormatIdx),
2586 "modular-format attribute format string index is not an integer", V);
2587 Check(FormatIdx > 0,
2588 "modular-format attribute format string index must be greater than 0",
2590 Check(FormatIdx <= UpperBound,
2591 "modular-format attribute format string index is out of bounds", V);
2592 unsigned FirstArgIdx;
2593 Check(!Args[2].getAsInteger(10, FirstArgIdx),
2594 "modular-format attribute first arg index is not an integer", V);
2595 Check(FirstArgIdx <= UpperBound,
2596 "modular-format attribute first arg index is out of bounds", V);
2598 "modular-format attribute modular implementation function name "
2602 "modular-format attribute implementation name cannot be empty", V);
2605 if (
auto A =
Attrs.getFnAttr(
"target-features");
A.isValid()) {
2606 StringRef S =
A.getValueAsString();
2608 for (
auto FeatureFlag :
split(S,
',')) {
2609 if (FeatureFlag.empty())
2611 "target-features attribute should not contain an empty string");
2613 Check(FeatureFlag[0] ==
'+' || FeatureFlag[0] ==
'-',
2614 "target feature '" + FeatureFlag +
2615 "' must start with a '+' or '-'",
2621void Verifier::verifyUnknownProfileMetadata(MDNode *MD) {
2623 "'unknown' !prof should have a single additional operand", MD);
2626 "'unknown' !prof should have an additional operand of type "
2629 "the 'unknown' !prof operand should not be an empty string");
2632void Verifier::verifyFunctionMetadata(
2633 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2634 for (
const auto &Pair : MDs) {
2635 if (Pair.first == LLVMContext::MD_prof) {
2636 MDNode *MD = Pair.second;
2638 "!prof annotations should have no less than 2 operands", MD);
2643 verifyUnknownProfileMetadata(MD);
2648 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null",
2651 "expected string with name of the !prof annotation", MD);
2656 "first operand should be 'function_entry_count'"
2657 " or 'synthetic_function_entry_count'",
2661 Check(MD->
getOperand(1) !=
nullptr,
"second operand should not be null",
2664 "expected integer argument to function_entry_count", MD);
2665 }
else if (Pair.first == LLVMContext::MD_kcfi_type) {
2666 MDNode *MD = Pair.second;
2668 "!kcfi_type must have exactly one operand", MD);
2669 Check(MD->
getOperand(0) !=
nullptr,
"!kcfi_type operand must not be null",
2672 "expected a constant operand for !kcfi_type", MD);
2675 "expected a constant integer operand for !kcfi_type", MD);
2677 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2678 }
else if (Pair.first ==
Context.getMDKindID(
"reqd_work_group_size")) {
2679 MDNode *MD = Pair.second;
2681 "reqd_work_group_size must have exactly three operands", MD);
2685 uint64_t Product = 1;
2686 for (
unsigned I = 0;
I != 3; ++
I) {
2688 Check(
C,
"reqd_work_group_size operands must be integer constants", MD);
2692 const APInt &
Value =
C->getValue();
2694 "reqd_work_group_size operands must fit in 64 bits", MD);
2695 if (
Value.getActiveBits() > 64)
2698 uint64_t Dim =
Value.getZExtValue();
2699 Check(Dim == 0 || Product <= std::numeric_limits<uint64_t>::max() / Dim,
2700 "reqd_work_group_size product must fit in 64 bits", MD);
2701 if (Dim != 0 && Product > std::numeric_limits<uint64_t>::max() / Dim)
2709void Verifier::visitConstantExprsRecursively(
const Constant *EntryC) {
2713 if (!ConstantExprVisited.
insert(EntryC).second)
2717 Stack.push_back(EntryC);
2719 while (!
Stack.empty()) {
2724 visitConstantExpr(CE);
2727 visitConstantPtrAuth(CPA);
2732 Check(GV->
getParent() == &M,
"Referencing global in another module!",
2738 for (
const Use &U :
C->operands()) {
2742 if (!ConstantExprVisited.
insert(OpC).second)
2744 Stack.push_back(OpC);
2749void Verifier::visitConstantExpr(
const ConstantExpr *CE) {
2750 if (
CE->getOpcode() == Instruction::BitCast)
2753 "Invalid bitcast", CE);
2754 else if (
CE->getOpcode() == Instruction::PtrToAddr)
2755 checkPtrToAddr(
CE->getOperand(0)->getType(),
CE->getType(), *CE);
2758void Verifier::visitConstantPtrAuth(
const ConstantPtrAuth *CPA) {
2760 "signed ptrauth constant base pointer must have pointer type");
2763 "signed ptrauth constant must have same type as its base pointer");
2766 "signed ptrauth constant key must be i32 constant integer");
2769 "signed ptrauth constant address discriminator must be a pointer");
2772 "signed ptrauth constant discriminator must be i64 constant integer");
2775 "signed ptrauth constant deactivation symbol must be a pointer");
2779 "signed ptrauth constant deactivation symbol must be a global value "
2783bool Verifier::verifyAttributeCount(AttributeList Attrs,
unsigned Params) {
2786 return Attrs.getNumAttrSets() <= Params + 2;
2789void Verifier::verifyInlineAsmCall(
const CallBase &
Call) {
2792 unsigned LabelNo = 0;
2793 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
2803 if (CI.isIndirect) {
2806 "Operand for indirect constraint must have pointer type", &
Call);
2809 "Operand for indirect constraint must have elementtype attribute",
2813 "Elementtype attribute can only be applied for indirect "
2822 Check(LabelNo == CallBr->getNumIndirectDests(),
2823 "Number of label constraints does not match number of callbr dests",
2826 Check(LabelNo == 0,
"Label constraints can only be used with callbr",
2832void Verifier::verifyStatepoint(
const CallBase &
Call) {
2837 "gc.statepoint must read and write all memory to preserve "
2838 "reordering restrictions required by safepoint semantics",
2841 const int64_t NumPatchBytes =
2844 Check(NumPatchBytes >= 0,
2845 "gc.statepoint number of patchable bytes must be "
2850 Check(TargetElemType,
2851 "gc.statepoint callee argument must have elementtype attribute",
Call);
2853 Check(TargetFuncType,
2854 "gc.statepoint callee elementtype must be function type",
Call);
2857 Check(NumCallArgs >= 0,
2858 "gc.statepoint number of arguments to underlying call "
2861 const int NumParams = (int)TargetFuncType->getNumParams();
2862 if (TargetFuncType->isVarArg()) {
2863 Check(NumCallArgs >= NumParams,
2864 "gc.statepoint mismatch in number of vararg call args",
Call);
2867 Check(TargetFuncType->getReturnType()->isVoidTy(),
2868 "gc.statepoint doesn't support wrapping non-void "
2869 "vararg functions yet",
2872 Check(NumCallArgs == NumParams,
2873 "gc.statepoint mismatch in number of call args",
Call);
2875 const uint64_t
Flags
2877 Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
2878 "unknown flag used in gc.statepoint flags argument",
Call);
2883 for (
int i = 0; i < NumParams; i++) {
2884 Type *ParamType = TargetFuncType->getParamType(i);
2886 Check(ArgType == ParamType,
2887 "gc.statepoint call argument does not match wrapped "
2891 if (TargetFuncType->isVarArg()) {
2892 AttributeSet ArgAttrs =
Attrs.getParamAttrs(5 + i);
2894 "Attribute 'sret' cannot be used for vararg call arguments!",
Call);
2898 const int EndCallArgsInx = 4 + NumCallArgs;
2902 "gc.statepoint number of transition arguments "
2903 "must be constant integer",
2905 const int NumTransitionArgs =
2907 Check(NumTransitionArgs == 0,
2908 "gc.statepoint w/inline transition bundle is deprecated",
Call);
2909 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2913 "gc.statepoint number of deoptimization arguments "
2914 "must be constant integer",
2917 Check(NumDeoptArgs == 0,
2918 "gc.statepoint w/inline deopt operands is deprecated",
Call);
2920 const int ExpectedNumArgs = 7 + NumCallArgs;
2922 "gc.statepoint too many arguments",
Call);
2929 Check(UserCall,
"illegal use of statepoint token",
Call, U);
2933 "gc.result or gc.relocate are the only value uses "
2934 "of a gc.statepoint",
2937 Check(UserCall->getArgOperand(0) == &
Call,
2938 "gc.result connected to wrong gc.statepoint",
Call, UserCall);
2940 Check(UserCall->getArgOperand(0) == &
Call,
2941 "gc.relocate connected to wrong gc.statepoint",
Call, UserCall);
2955void Verifier::verifyFrameRecoverIndices() {
2956 for (
auto &Counts : FrameEscapeInfo) {
2958 unsigned EscapedObjectCount = Counts.second.first;
2959 unsigned MaxRecoveredIndex = Counts.second.second;
2960 Check(MaxRecoveredIndex <= EscapedObjectCount,
2961 "all indices passed to llvm.localrecover must be less than the "
2962 "number of arguments passed to llvm.localescape in the parent "
2971 UnwindDest =
II->getUnwindDest();
2973 UnwindDest = CSI->getUnwindDest();
2979void Verifier::verifySiblingFuncletUnwinds() {
2980 llvm::TimeTraceScope timeScope(
"Verifier verify sibling funclet unwinds");
2981 SmallPtrSet<Instruction *, 8> Visited;
2982 SmallPtrSet<Instruction *, 8>
Active;
2983 for (
const auto &Pair : SiblingFuncletInfo) {
2985 if (Visited.
count(PredPad))
2991 if (
Active.count(SuccPad)) {
2994 SmallVector<Instruction *, 8> CycleNodes;
2997 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
2998 if (CycleTerminator != CyclePad)
3001 }
while (CyclePad != SuccPad);
3002 Check(
false,
"EH pads can't handle each other's exceptions",
3006 if (!Visited.
insert(SuccPad).second)
3010 auto TermI = SiblingFuncletInfo.find(PredPad);
3011 if (TermI == SiblingFuncletInfo.end())
3024void Verifier::visitFunction(
const Function &
F) {
3025 visitGlobalValue(
F);
3028 FunctionType *FT =
F.getFunctionType();
3029 unsigned NumArgs =
F.arg_size();
3032 "Function context does not match Module context!", &
F);
3034 Check(!
F.hasCommonLinkage(),
"Functions may not have common linkage", &
F);
3035 Check(FT->getNumParams() == NumArgs,
3036 "# formal arguments must match # of arguments for function type!", &
F,
3038 Check(
F.getReturnType()->isFirstClassType() ||
3039 F.getReturnType()->isVoidTy() ||
F.getReturnType()->isStructTy(),
3040 "Functions cannot return aggregate values!", &
F);
3042 Check(!
F.hasStructRetAttr() ||
F.getReturnType()->isVoidTy(),
3043 "Invalid struct return type!", &
F);
3045 if (MaybeAlign
A =
F.getAlign()) {
3046 Check(
A->value() <= Value::MaximumAlignment,
3047 "huge alignment values are unsupported", &
F);
3050 AttributeList
Attrs =
F.getAttributes();
3052 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
3053 "Attribute after last parameter!", &
F);
3055 bool IsIntrinsic =
F.isIntrinsic();
3058 verifyFunctionAttrs(FT, Attrs, &
F, IsIntrinsic,
false);
3064 "Attribute 'builtin' can only be applied to a callsite.", &
F);
3066 Check(!
Attrs.hasAttrSomewhere(Attribute::ElementType),
3067 "Attribute 'elementtype' can only be applied to a callsite.", &
F);
3069 if (
Attrs.hasFnAttr(Attribute::Naked))
3070 for (
const Argument &Arg :
F.args())
3071 Check(Arg.use_empty(),
"cannot use argument of naked function", &Arg);
3076 switch (
F.getCallingConv()) {
3078 case CallingConv::C:
3080 case CallingConv::X86_INTR: {
3081 Check(
F.arg_empty() ||
Attrs.hasParamAttr(0, Attribute::ByVal),
3082 "Calling convention parameter requires byval", &
F);
3085 case CallingConv::AMDGPU_KERNEL:
3086 case CallingConv::SPIR_KERNEL:
3087 case CallingConv::AMDGPU_CS_Chain:
3088 case CallingConv::AMDGPU_CS_ChainPreserve:
3089 Check(
F.getReturnType()->isVoidTy(),
3090 "Calling convention requires void return type", &
F);
3092 case CallingConv::AMDGPU_VS:
3093 case CallingConv::AMDGPU_HS:
3094 case CallingConv::AMDGPU_GS:
3095 case CallingConv::AMDGPU_PS:
3096 case CallingConv::AMDGPU_CS:
3097 Check(!
F.hasStructRetAttr(),
"Calling convention does not allow sret", &
F);
3098 if (
F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3099 const unsigned StackAS =
DL.getAllocaAddrSpace();
3101 for (
const Argument &Arg :
F.args()) {
3102 Check(!
Attrs.hasParamAttr(i, Attribute::ByVal),
3103 "Calling convention disallows byval", &
F);
3104 Check(!
Attrs.hasParamAttr(i, Attribute::Preallocated),
3105 "Calling convention disallows preallocated", &
F);
3106 Check(!
Attrs.hasParamAttr(i, Attribute::InAlloca),
3107 "Calling convention disallows inalloca", &
F);
3109 if (
Attrs.hasParamAttr(i, Attribute::ByRef)) {
3112 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
3113 "Calling convention disallows stack byref", &
F);
3121 case CallingConv::Fast:
3122 case CallingConv::Cold:
3123 case CallingConv::Intel_OCL_BI:
3124 case CallingConv::PTX_Kernel:
3125 case CallingConv::PTX_Device:
3127 "Calling convention does not support varargs or "
3128 "perfect forwarding!",
3131 case CallingConv::AMDGPU_Gfx_WholeWave:
3132 Check(!
F.arg_empty() &&
F.arg_begin()->getType()->isIntegerTy(1),
3133 "Calling convention requires first argument to be i1", &
F);
3134 Check(!
F.arg_begin()->hasInRegAttr(),
3135 "Calling convention requires first argument to not be inreg", &
F);
3137 "Calling convention does not support varargs or "
3138 "perfect forwarding!",
3145 for (
const Argument &Arg :
F.args()) {
3146 Check(Arg.getType() == FT->getParamType(i),
3147 "Argument value does not match function argument type!", &Arg,
3148 FT->getParamType(i));
3149 Check(Arg.getType()->isFirstClassType(),
3150 "Function arguments must have first-class types!", &Arg);
3152 Check(!Arg.getType()->isMetadataTy(),
3153 "Function takes metadata but isn't an intrinsic", &Arg, &
F);
3154 Check(!Arg.getType()->isTokenLikeTy(),
3155 "Function takes token but isn't an intrinsic", &Arg, &
F);
3156 Check(!Arg.getType()->isX86_AMXTy(),
3157 "Function takes x86_amx but isn't an intrinsic", &Arg, &
F);
3161 if (
Attrs.hasParamAttr(i, Attribute::SwiftError)) {
3162 verifySwiftErrorValue(&Arg);
3168 Check(!
F.getReturnType()->isTokenLikeTy(),
3169 "Function returns a token but isn't an intrinsic", &
F);
3170 Check(!
F.getReturnType()->isX86_AMXTy(),
3171 "Function returns a x86_amx but isn't an intrinsic", &
F);
3176 F.getAllMetadata(MDs);
3177 assert(
F.hasMetadata() != MDs.
empty() &&
"Bit out-of-sync");
3178 verifyFunctionMetadata(MDs);
3184 if (
F.hasPersonalityFn()) {
3187 Check(Per->getParent() ==
F.getParent(),
3188 "Referencing personality function in another module!", &
F,
3189 F.getParent(), Per, Per->getParent());
3193 BlockEHFuncletColors.
clear();
3195 if (
F.isMaterializable()) {
3197 Check(MDs.
empty(),
"unmaterialized function cannot have metadata", &
F,
3199 }
else if (
F.isDeclaration()) {
3200 for (
const auto &
I : MDs) {
3202 CheckDI(
I.first != LLVMContext::MD_dbg ||
3204 "function declaration may only have a unique !dbg attachment",
3206 Check(
I.first != LLVMContext::MD_prof,
3207 "function declaration may not have a !prof attachment", &
F);
3210 visitMDNode(*
I.second, AreDebugLocsAllowed::Yes);
3212 Check(!
F.hasPersonalityFn(),
3213 "Function declaration shouldn't have a personality routine", &
F);
3217 Check(!IsIntrinsic,
"llvm intrinsics cannot be defined!", &
F);
3222 "Entry block to function must not have predecessors!", Entry);
3225 if (
Entry->hasAddressTaken()) {
3227 "blockaddress may not be used with the entry block!", Entry);
3230 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
3231 NumKCFIAttachments = 0;
3233 for (
const auto &
I : MDs) {
3235 auto AllowLocs = AreDebugLocsAllowed::No;
3239 case LLVMContext::MD_dbg: {
3240 ++NumDebugAttachments;
3241 CheckDI(NumDebugAttachments == 1,
3242 "function must have a single !dbg attachment", &
F,
I.second);
3244 "function !dbg attachment must be a subprogram", &
F,
I.second);
3246 "function definition may only have a distinct !dbg attachment",
3250 const Function *&AttachedTo = DISubprogramAttachments[
SP];
3251 CheckDI(!AttachedTo || AttachedTo == &
F,
3252 "DISubprogram attached to more than one function", SP, &
F);
3254 AllowLocs = AreDebugLocsAllowed::Yes;
3257 case LLVMContext::MD_prof:
3258 ++NumProfAttachments;
3259 Check(NumProfAttachments == 1,
3260 "function must have a single !prof attachment", &
F,
I.second);
3262 case LLVMContext::MD_kcfi_type:
3263 ++NumKCFIAttachments;
3264 Check(NumKCFIAttachments == 1,
3265 "function must have a single !kcfi_type attachment", &
F,
3271 visitMDNode(*
I.second, AllowLocs);
3279 bool isMaterialized =
F.getParent()->isMaterialized();
3280 if (
F.isIntrinsic() && isMaterialized) {
3282 if (
F.hasAddressTaken(&U,
false,
true,
false,
3284 Check(
false,
"Invalid user of intrinsic instruction!", U);
3291 if (IID && (isMaterialized || !
F.materialized_use_empty())) {
3295 raw_string_ostream ErrOS(ErrMsg);
3298 Printable PrintDecl([&
F](raw_ostream &OS) {
F.print(OS); });
3299 Check(IsValid, ErrMsg, PrintDecl);
3306 IID, OverloadTys,
const_cast<Module *
>(
F.getParent()), FT);
3307 Check(ExpectedName ==
F.getName(),
3308 "Intrinsic name not mangled correctly for type arguments! "
3314 auto *
N =
F.getSubprogram();
3315 HasDebugInfo = (
N !=
nullptr);
3323 SmallPtrSet<const MDNode *, 32> Seen;
3335 "DILocation's scope must be a DILocalScope",
N, &
F, &
I,
DL, Parent);
3337 DILocalScope *
Scope =
DL->getInlinedAtScope();
3338 Check(Scope,
"Failed to find DILocalScope",
DL);
3340 if (!Seen.
insert(Scope).second)
3343 DISubprogram *
SP =
Scope->getSubprogram();
3347 if ((Scope != SP) && !Seen.
insert(SP).second)
3351 "!dbg attachment points at wrong subprogram for function",
N, &
F,
3355 for (
auto &
I : BB) {
3356 VisitDebugLoc(
I,
I.getDebugLoc().getAsMDNode());
3358 if (
auto MD =
I.getMetadata(LLVMContext::MD_loop))
3361 if (BrokenDebugInfo)
3368void Verifier::visitBasicBlock(BasicBlock &BB) {
3369 InstsInThisBlock.
clear();
3370 ConvergenceVerifyHelper.
visit(BB);
3381 for (
const PHINode &PN : BB.
phis()) {
3382 Check(PN.getNumIncomingValues() == Preds.size(),
3383 "PHINode should have one entry for each predecessor of its "
3384 "parent basic block!",
3389 Values.reserve(PN.getNumIncomingValues());
3390 for (
unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3392 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3395 for (
unsigned i = 0, e =
Values.size(); i != e; ++i) {
3402 "PHI node has multiple entries for the same basic block with "
3403 "different incoming values!",
3409 "PHI node entries do not match predecessors!", &PN,
3410 Values[i].first, Preds[i]);
3418 Check(
I.getParent() == &BB,
"Instruction has bogus parent pointer!");
3422 CheckDI(!BB.getTrailingDbgRecords(),
"Basic Block has trailing DbgRecords!",
3426void Verifier::visitTerminator(Instruction &
I) {
3428 Check(&
I ==
I.getParent()->getTerminator(),
3429 "Terminator found in the middle of a basic block!",
I.getParent());
3430 visitInstruction(
I);
3433void Verifier::visitCondBrInst(CondBrInst &BI) {
3435 "Branch condition is not 'i1' type!", &BI, BI.
getCondition());
3436 visitTerminator(BI);
3439void Verifier::visitReturnInst(ReturnInst &RI) {
3442 if (
F->getReturnType()->isVoidTy())
3444 "Found return instr that returns non-void in Function of void "
3446 &RI,
F->getReturnType());
3449 "Function return type does not match operand "
3450 "type of return inst!",
3451 &RI,
F->getReturnType());
3455 visitTerminator(RI);
3458void Verifier::visitSwitchInst(SwitchInst &SI) {
3459 Check(
SI.getType()->isVoidTy(),
"Switch must have void result type!", &SI);
3462 Type *SwitchTy =
SI.getCondition()->getType();
3463 SmallPtrSet<ConstantInt*, 32>
Constants;
3464 for (
auto &Case :
SI.cases()) {
3466 "Case value is not a constant integer.", &SI);
3467 Check(Case.getCaseValue()->getType() == SwitchTy,
3468 "Switch constants must all be same type as switch value!", &SI);
3470 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3473 visitTerminator(SI);
3476void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
3478 "Indirectbr operand must have pointer type!", &BI);
3481 "Indirectbr destinations must all have pointer type!", &BI);
3483 visitTerminator(BI);
3492void Verifier::visitCallBrInst(CallBrInst &CBI) {
3495 "callbr: indirect function / invalid signature");
3497 "callbr for intrinsics currently doesn't support operand bundles");
3501 "callbr currently only supports asm-goto and selected intrinsics");
3506 Check(!
IA->canThrow(),
"Unwinding from Callbr is not allowed");
3508 verifyInlineAsmCall(CBI);
3510 visitTerminator(CBI);
3513void Verifier::visitSelectInst(SelectInst &SI) {
3516 "Invalid operands for select instruction!", &SI);
3518 Check(
SI.getTrueValue()->getType() ==
SI.getType(),
3519 "Select values must have same type as select instruction!", &SI);
3520 visitInstruction(SI);
3526void Verifier::visitUserOp1(Instruction &
I) {
3527 Check(
false,
"User-defined operators should not live outside of a pass!", &
I);
3530void Verifier::visitTruncInst(TruncInst &
I) {
3532 Type *SrcTy =
I.getOperand(0)->getType();
3533 Type *DestTy =
I.getType();
3542 "trunc source and destination must both be a vector or neither", &
I);
3543 Check(SrcBitSize > DestBitSize,
"DestTy too big for Trunc", &
I);
3545 visitInstruction(
I);
3548void Verifier::visitZExtInst(ZExtInst &
I) {
3550 Type *SrcTy =
I.getOperand(0)->getType();
3551 Type *DestTy =
I.getType();
3557 "zext source and destination must both be a vector or neither", &
I);
3561 Check(SrcBitSize < DestBitSize,
"Type too small for ZExt", &
I);
3563 visitInstruction(
I);
3566void Verifier::visitSExtInst(SExtInst &
I) {
3568 Type *SrcTy =
I.getOperand(0)->getType();
3569 Type *DestTy =
I.getType();
3578 "sext source and destination must both be a vector or neither", &
I);
3579 Check(SrcBitSize < DestBitSize,
"Type too small for SExt", &
I);
3581 visitInstruction(
I);
3584void Verifier::visitFPTruncInst(FPTruncInst &
I) {
3586 Type *SrcTy =
I.getOperand(0)->getType();
3587 Type *DestTy =
I.getType();
3595 "fptrunc source and destination must both be a vector or neither", &
I);
3596 Check(SrcBitSize > DestBitSize,
"DestTy too big for FPTrunc", &
I);
3598 visitInstruction(
I);
3601void Verifier::visitFPExtInst(FPExtInst &
I) {
3603 Type *SrcTy =
I.getOperand(0)->getType();
3604 Type *DestTy =
I.getType();
3613 "fpext source and destination must both be a vector or neither", &
I);
3614 Check(SrcBitSize < DestBitSize,
"DestTy too small for FPExt", &
I);
3616 visitInstruction(
I);
3619void Verifier::visitUIToFPInst(UIToFPInst &
I) {
3621 Type *SrcTy =
I.getOperand(0)->getType();
3622 Type *DestTy =
I.getType();
3627 Check(SrcVec == DstVec,
3628 "UIToFP source and dest must both be vector or scalar", &
I);
3630 "UIToFP source must be integer or integer vector", &
I);
3634 if (SrcVec && DstVec)
3637 "UIToFP source and dest vector length mismatch", &
I);
3639 visitInstruction(
I);
3642void Verifier::visitSIToFPInst(SIToFPInst &
I) {
3644 Type *SrcTy =
I.getOperand(0)->getType();
3645 Type *DestTy =
I.getType();
3650 Check(SrcVec == DstVec,
3651 "SIToFP source and dest must both be vector or scalar", &
I);
3653 "SIToFP source must be integer or integer vector", &
I);
3657 if (SrcVec && DstVec)
3660 "SIToFP source and dest vector length mismatch", &
I);
3662 visitInstruction(
I);
3665void Verifier::visitFPToUIInst(FPToUIInst &
I) {
3667 Type *SrcTy =
I.getOperand(0)->getType();
3668 Type *DestTy =
I.getType();
3673 Check(SrcVec == DstVec,
3674 "FPToUI source and dest must both be vector or scalar", &
I);
3677 "FPToUI result must be integer or integer vector", &
I);
3679 if (SrcVec && DstVec)
3682 "FPToUI source and dest vector length mismatch", &
I);
3684 visitInstruction(
I);
3687void Verifier::visitFPToSIInst(FPToSIInst &
I) {
3689 Type *SrcTy =
I.getOperand(0)->getType();
3690 Type *DestTy =
I.getType();
3695 Check(SrcVec == DstVec,
3696 "FPToSI source and dest must both be vector or scalar", &
I);
3699 "FPToSI result must be integer or integer vector", &
I);
3701 if (SrcVec && DstVec)
3704 "FPToSI source and dest vector length mismatch", &
I);
3706 visitInstruction(
I);
3709void Verifier::checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V) {
3718 Check(VSrc->getElementCount() == VDest->getElementCount(),
3719 "PtrToAddr vector length mismatch", V);
3722 Type *AddrTy =
DL.getAddressType(SrcTy);
3723 Check(AddrTy == DestTy,
"PtrToAddr result must be address width", V);
3726void Verifier::visitPtrToAddrInst(PtrToAddrInst &
I) {
3727 checkPtrToAddr(
I.getOperand(0)->getType(),
I.getType(),
I);
3728 visitInstruction(
I);
3731void Verifier::visitPtrToIntInst(PtrToIntInst &
I) {
3733 Type *SrcTy =
I.getOperand(0)->getType();
3734 Type *DestTy =
I.getType();
3745 Check(VSrc->getElementCount() == VDest->getElementCount(),
3746 "PtrToInt Vector length mismatch", &
I);
3749 visitInstruction(
I);
3752void Verifier::visitIntToPtrInst(IntToPtrInst &
I) {
3754 Type *SrcTy =
I.getOperand(0)->getType();
3755 Type *DestTy =
I.getType();
3765 Check(VSrc->getElementCount() == VDest->getElementCount(),
3766 "IntToPtr Vector length mismatch", &
I);
3768 visitInstruction(
I);
3771void Verifier::visitBitCastInst(BitCastInst &
I) {
3774 "Invalid bitcast", &
I);
3775 visitInstruction(
I);
3778void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &
I) {
3779 Type *SrcTy =
I.getOperand(0)->getType();
3780 Type *DestTy =
I.getType();
3787 "AddrSpaceCast must be between different address spaces", &
I);
3789 Check(SrcVTy->getElementCount() ==
3791 "AddrSpaceCast vector pointer number of elements mismatch", &
I);
3792 visitInstruction(
I);
3797void Verifier::visitPHINode(PHINode &PN) {
3804 "PHI nodes not grouped at top of basic block!", &PN, PN.
getParent());
3813 "PHI node operands are not the same type as the result!", &PN);
3818 visitInstruction(PN);
3821void Verifier::visitCallBase(CallBase &
Call) {
3823 "Called function must be a pointer!",
Call);
3827 if (FTy->isVarArg())
3829 "Called function requires more parameters than were provided!",
Call);
3832 "Incorrect number of arguments passed to called function!",
Call);
3835 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3837 "Call parameter type does not match function signature!",
3843 "Attribute after last parameter!",
Call);
3850 "Intrinsic called with incompatible signature",
Call);
3854 "calling convention does not permit calls",
Call);
3860 auto VerifyTypeAlign = [&](
Type *Ty,
const Twine &Message) {
3863 Align ABIAlign =
DL.getABITypeAlign(Ty);
3864 Check(ABIAlign.
value() <= Value::MaximumAlignment,
3865 "Incorrect alignment of " + Message +
" to called function!",
Call);
3869 VerifyTypeAlign(FTy->getReturnType(),
"return type");
3870 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3871 Type *Ty = FTy->getParamType(i);
3872 VerifyTypeAlign(Ty,
"argument passed");
3876 if (
Attrs.hasFnAttr(Attribute::Speculatable)) {
3880 "speculatable attribute may not apply to call sites",
Call);
3883 if (
Attrs.hasFnAttr(Attribute::Preallocated)) {
3885 "preallocated as a call site attribute can only be on "
3886 "llvm.call.preallocated.arg");
3889 Check(!
Attrs.hasFnAttr(Attribute::DenormalFPEnv),
3890 "denormal_fpenv attribute may not apply to call sites",
Call);
3901 Check(AI->isUsedWithInAlloca(),
3902 "inalloca argument for call has mismatched alloca", AI,
Call);
3908 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3912 Check(AI->isSwiftError(),
3913 "swifterror argument for call has mismatched alloca", AI,
Call);
3917 Check(ArgI,
"swifterror argument should come from an alloca or parameter",
3918 SwiftErrorArg,
Call);
3919 Check(ArgI->hasSwiftErrorAttr(),
3920 "swifterror argument for call has mismatched parameter", ArgI,
3924 if (
Attrs.hasParamAttr(i, Attribute::ImmArg)) {
3927 Check(Callee &&
Callee->hasParamAttribute(i, Attribute::ImmArg),
3936 "immarg operand has non-immediate parameter", ArgVal,
Call);
3942 const ConstantRange &CR =
3945 formatv(
"immarg value {} for arg {} out of range {}",
3946 CI->getValue(), i, CR),
3957 Check(hasOB != isMustTail,
3958 "preallocated operand either requires a preallocated bundle or "
3959 "the call to be musttail (but not both)",
3964 if (FTy->isVarArg()) {
3966 bool SawNest =
false;
3967 bool SawReturned =
false;
3969 for (
unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3970 if (
Attrs.hasParamAttr(Idx, Attribute::Nest))
3972 if (
Attrs.hasParamAttr(Idx, Attribute::Returned))
3977 for (
unsigned Idx = FTy->getNumParams(); Idx <
Call.
arg_size(); ++Idx) {
3979 AttributeSet ArgAttrs =
Attrs.getParamAttrs(Idx);
3980 verifyParameterAttrs(ArgAttrs, Ty, &
Call);
3983 Check(!SawNest,
"More than one parameter has attribute nest!",
Call);
3988 Check(!SawReturned,
"More than one parameter has attribute returned!",
3991 "Incompatible argument and return types for 'returned' "
4001 "Attribute 'sret' cannot be used for vararg call arguments!",
4006 "inalloca isn't on the last argument!",
Call);
4012 for (
Type *ParamTy : FTy->params()) {
4013 Check(!ParamTy->isMetadataTy(),
4014 "Function has metadata parameter but isn't an intrinsic",
Call);
4015 Check(!ParamTy->isTokenLikeTy(),
4016 "Function has token parameter but isn't an intrinsic",
Call);
4022 Check(!FTy->getReturnType()->isTokenLikeTy(),
4023 "Return type cannot be token for indirect call!");
4024 Check(!FTy->getReturnType()->isX86_AMXTy(),
4025 "Return type cannot be x86_amx for indirect call!");
4029 visitIntrinsicCall(
ID,
Call);
4034 bool FoundDeoptBundle =
false, FoundFuncletBundle =
false,
4035 FoundGCTransitionBundle =
false, FoundCFGuardTargetBundle =
false,
4036 FoundPreallocatedBundle =
false, FoundGCLiveBundle =
false,
4037 FoundPtrauthBundle =
false, FoundKCFIBundle =
false,
4038 FoundAttachedCallBundle =
false;
4043 Check(!FoundDeoptBundle,
"Multiple deopt operand bundles",
Call);
4044 FoundDeoptBundle =
true;
4046 Check(!FoundGCTransitionBundle,
"Multiple gc-transition operand bundles",
4048 FoundGCTransitionBundle =
true;
4050 Check(!FoundFuncletBundle,
"Multiple funclet operand bundles",
Call);
4051 FoundFuncletBundle =
true;
4053 "Expected exactly one funclet bundle operand",
Call);
4055 "Funclet bundle operands should correspond to a FuncletPadInst",
4058 Check(!FoundCFGuardTargetBundle,
"Multiple CFGuardTarget operand bundles",
4060 FoundCFGuardTargetBundle =
true;
4062 "Expected exactly one cfguardtarget bundle operand",
Call);
4064 Check(!FoundPtrauthBundle,
"Multiple ptrauth operand bundles",
Call);
4065 FoundPtrauthBundle =
true;
4067 "Expected exactly two ptrauth bundle operands",
Call);
4069 BU.
Inputs[0]->getType()->isIntegerTy(32),
4070 "Ptrauth bundle key operand must be an i32 constant",
Call);
4072 "Ptrauth bundle discriminator operand must be an i64",
Call);
4074 Check(!FoundKCFIBundle,
"Multiple kcfi operand bundles",
Call);
4075 FoundKCFIBundle =
true;
4076 Check(BU.
Inputs.size() == 1,
"Expected exactly one kcfi bundle operand",
4079 BU.
Inputs[0]->getType()->isIntegerTy(32),
4080 "Kcfi bundle operand must be an i32 constant",
Call);
4082 Check(!FoundPreallocatedBundle,
"Multiple preallocated operand bundles",
4084 FoundPreallocatedBundle =
true;
4086 "Expected exactly one preallocated bundle operand",
Call);
4089 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
4090 "\"preallocated\" argument must be a token from "
4091 "llvm.call.preallocated.setup",
4094 Check(!FoundGCLiveBundle,
"Multiple gc-live operand bundles",
Call);
4095 FoundGCLiveBundle =
true;
4097 Check(!FoundAttachedCallBundle,
4098 "Multiple \"clang.arc.attachedcall\" operand bundles",
Call);
4099 FoundAttachedCallBundle =
true;
4100 verifyAttachedCallBundle(
Call, BU);
4106 "Direct call cannot have a ptrauth bundle",
Call);
4118 "inlinable function call in a function with "
4119 "debug info must have a !dbg location",
4123 verifyInlineAsmCall(
Call);
4127 visitInstruction(
Call);
4130void Verifier::verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs,
4133 Twine(
"inalloca attribute not allowed in ") +
Context);
4135 Twine(
"inreg attribute not allowed in ") +
Context);
4136 Check(!
Attrs.contains(Attribute::SwiftError),
4137 Twine(
"swifterror attribute not allowed in ") +
Context);
4138 Check(!
Attrs.contains(Attribute::Preallocated),
4139 Twine(
"preallocated attribute not allowed in ") +
Context);
4141 Twine(
"byref attribute not allowed in ") +
Context);
4146 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
4147 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
4148 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
4150 AttrBuilder Copy(
C);
4151 for (
auto AK : ABIAttrs) {
4152 Attribute Attr = Attrs.getParamAttrs(
I).getAttribute(AK);
4154 Copy.addAttribute(Attr);
4158 if (Attrs.hasParamAttr(
I, Attribute::Alignment) &&
4159 (Attrs.hasParamAttr(
I, Attribute::ByVal) ||
4160 Attrs.hasParamAttr(
I, Attribute::ByRef)))
4161 Copy.addAlignmentAttr(Attrs.getParamAlignment(
I));
4165void Verifier::verifyMustTailCall(CallInst &CI) {
4169 FunctionType *CallerTy =
F->getFunctionType();
4171 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
4172 "cannot guarantee tail call due to mismatched varargs", &CI);
4173 Check(CallerTy->getReturnType() == CalleeTy->getReturnType(),
4174 "cannot guarantee tail call due to mismatched return types", &CI);
4178 "cannot guarantee tail call due to mismatched calling conv", &CI);
4186 Check(Ret,
"musttail call must precede a ret", &CI);
4189 "musttail call result must be returned", Ret);
4191 AttributeList CallerAttrs =
F->getAttributes();
4196 CI.
getCallingConv() == CallingConv::Tail ?
"tailcc" :
"swifttailcc";
4200 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4202 SmallString<32>
Context{CCName, StringRef(
" musttail caller")};
4203 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4205 for (
unsigned I = 0,
E = CalleeTy->getNumParams();
I !=
E; ++
I) {
4207 SmallString<32>
Context{CCName, StringRef(
" musttail callee")};
4208 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4211 Check(!CallerTy->isVarArg(), Twine(
"cannot guarantee ") + CCName +
4212 " tail call for varargs function");
4218 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
4219 "cannot guarantee tail call due to mismatched parameter counts", &CI);
4220 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4221 Check(CallerTy->getParamType(
I) == CalleeTy->getParamType(
I),
4222 "cannot guarantee tail call due to mismatched parameter types",
4229 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4232 Check(CallerABIAttrs == CalleeABIAttrs,
4233 "cannot guarantee tail call due to mismatched ABI impacting "
4234 "function attributes",
4239void Verifier::visitCallInst(CallInst &CI) {
4243 verifyMustTailCall(CI);
4246void Verifier::visitInvokeInst(InvokeInst &
II) {
4252 II.getUnwindDest()->isEHPad(),
4253 "The unwind destination does not have an exception handling instruction!",
4256 visitTerminator(
II);
4261void Verifier::visitUnaryOperator(UnaryOperator &U) {
4262 Check(
U.getType() ==
U.getOperand(0)->getType(),
4263 "Unary operators must have same type for"
4264 "operands and result!",
4267 switch (
U.getOpcode()) {
4270 case Instruction::FNeg:
4271 Check(
U.getType()->isFPOrFPVectorTy(),
4272 "FNeg operator only works with float types!", &U);
4278 visitInstruction(U);
4284void Verifier::visitBinaryOperator(BinaryOperator &
B) {
4285 Check(
B.getOperand(0)->getType() ==
B.getOperand(1)->getType(),
4286 "Both operands to a binary operator are not of the same type!", &
B);
4288 switch (
B.getOpcode()) {
4291 case Instruction::Add:
4292 case Instruction::Sub:
4293 case Instruction::Mul:
4294 case Instruction::SDiv:
4295 case Instruction::UDiv:
4296 case Instruction::SRem:
4297 case Instruction::URem:
4298 Check(
B.getType()->isIntOrIntVectorTy(),
4299 "Integer arithmetic operators only work with integral types!", &
B);
4300 Check(
B.getType() ==
B.getOperand(0)->getType(),
4301 "Integer arithmetic operators must have same type "
4302 "for operands and result!",
4307 case Instruction::FAdd:
4308 case Instruction::FSub:
4309 case Instruction::FMul:
4310 case Instruction::FDiv:
4311 case Instruction::FRem:
4312 Check(
B.getType()->isFPOrFPVectorTy(),
4313 "Floating-point arithmetic operators only work with "
4314 "floating-point types!",
4316 Check(
B.getType() ==
B.getOperand(0)->getType(),
4317 "Floating-point arithmetic operators must have same type "
4318 "for operands and result!",
4322 case Instruction::And:
4323 case Instruction::Or:
4324 case Instruction::Xor:
4325 Check(
B.getType()->isIntOrIntVectorTy(),
4326 "Logical operators only work with integral types!", &
B);
4327 Check(
B.getType() ==
B.getOperand(0)->getType(),
4328 "Logical operators must have same type for operands and result!", &
B);
4330 case Instruction::Shl:
4331 case Instruction::LShr:
4332 case Instruction::AShr:
4333 Check(
B.getType()->isIntOrIntVectorTy(),
4334 "Shifts only work with integral types!", &
B);
4335 Check(
B.getType() ==
B.getOperand(0)->getType(),
4336 "Shift return type must be same as operands!", &
B);
4342 visitInstruction(
B);
4345void Verifier::visitICmpInst(ICmpInst &IC) {
4349 Check(Op0Ty == Op1Ty,
4350 "Both operands to ICmp instruction are not of the same type!", &IC);
4353 "Invalid operand types for ICmp instruction", &IC);
4357 visitInstruction(IC);
4360void Verifier::visitFCmpInst(FCmpInst &FC) {
4362 Type *Op0Ty =
FC.getOperand(0)->getType();
4363 Type *Op1Ty =
FC.getOperand(1)->getType();
4364 Check(Op0Ty == Op1Ty,
4365 "Both operands to FCmp instruction are not of the same type!", &FC);
4370 Check(
FC.isFPPredicate(),
"Invalid predicate in FCmp instruction!", &FC);
4372 visitInstruction(FC);
4375void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
4377 "Invalid extractelement operands!", &EI);
4378 visitInstruction(EI);
4381void Verifier::visitInsertElementInst(InsertElementInst &IE) {
4384 "Invalid insertelement operands!", &IE);
4385 visitInstruction(IE);
4388void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
4391 "Invalid shufflevector operands!", &SV);
4392 visitInstruction(SV);
4395void Verifier::visitGetElementPtrInst(GetElementPtrInst &
GEP) {
4397 GEP.getModule()->getModuleFlag(
"require-logical-pointer")))
4398 Check(!MD->getZExtValue(),
4399 "Non-logical getelementptr disallowed for this module.");
4401 Type *TargetTy =
GEP.getPointerOperandType()->getScalarType();
4404 "GEP base pointer is not a vector or a vector of pointers", &
GEP);
4405 Check(
GEP.getSourceElementType()->isSized(),
"GEP into unsized type!", &
GEP);
4408 Check(!STy->isScalableTy(),
4409 "getelementptr cannot target structure that contains scalable vector"
4414 SmallVector<Value *, 16> Idxs(
GEP.indices());
4416 all_of(Idxs, [](
Value *V) {
return V->getType()->isIntOrIntVectorTy(); }),
4417 "GEP indexes must be integers", &
GEP);
4420 Check(ElTy,
"Invalid indices for GEP pointer type!", &
GEP);
4424 Check(PtrTy &&
GEP.getResultElementType() == ElTy,
4425 "GEP is not of right type for indices!", &
GEP, ElTy);
4429 ElementCount GEPWidth = GEPVTy->getElementCount();
4430 if (
GEP.getPointerOperandType()->isVectorTy())
4434 "Vector GEP result width doesn't match operand's", &
GEP);
4435 for (
Value *Idx : Idxs) {
4436 Type *IndexTy = Idx->getType();
4438 ElementCount IndexWidth = IndexVTy->getElementCount();
4439 Check(IndexWidth == GEPWidth,
"Invalid GEP index vector width", &
GEP);
4442 "All GEP indices should be of integer type");
4449 GTI != GTE; ++GTI) {
4450 if (GTI.isVector()) {
4451 Type *ElemTy = GTI.getIndexedType();
4452 Check(
DL.typeSizeEqualsStoreSize(ElemTy),
4453 "GEP into vector with non-byte-addressable element type", &
GEP);
4457 Check(
GEP.getAddressSpace() == PtrTy->getAddressSpace(),
4458 "GEP address space doesn't match type", &
GEP);
4460 visitInstruction(
GEP);
4464 return A.getUpper() ==
B.getLower() ||
A.getLower() ==
B.getUpper();
4469void Verifier::verifyRangeLikeMetadata(
const Value &
I,
const MDNode *
Range,
4470 Type *Ty, RangeLikeMetadataKind Kind) {
4471 unsigned NumOperands =
Range->getNumOperands();
4472 Check(NumOperands % 2 == 0,
"Unfinished range!",
Range);
4473 unsigned NumRanges = NumOperands / 2;
4474 Check(NumRanges >= 1,
"It should have at least one range!",
Range);
4476 ConstantRange LastRange(1,
true);
4477 for (
unsigned i = 0; i < NumRanges; ++i) {
4480 Check(
Low,
"The lower limit must be an integer!",
Low);
4485 Check(
High->getType() ==
Low->getType(),
"Range pair types must match!",
4488 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4490 "noalias.addrspace type must be i32!", &
I);
4493 "Range types must match instruction type!", &
I);
4496 APInt HighV =
High->getValue();
4497 APInt LowV =
Low->getValue();
4502 "The upper and lower limits cannot be the same value", &
I);
4504 ConstantRange CurRange(LowV, HighV);
4505 Check(!CurRange.isEmptySet() &&
4506 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
4507 !CurRange.isFullSet()),
4508 "Range must not be empty!",
Range);
4510 Check(CurRange.intersectWith(LastRange).isEmptySet(),
4511 "Intervals are overlapping",
Range);
4512 Check(LowV.
sgt(LastRange.getLower()),
"Intervals are not in order",
4517 LastRange = ConstantRange(LowV, HighV);
4519 if (NumRanges > 2) {
4524 ConstantRange FirstRange(FirstLow, FirstHigh);
4525 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
4526 "Intervals are overlapping",
Range);
4532void Verifier::visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty) {
4534 "precondition violation");
4535 verifyRangeLikeMetadata(
I,
Range, Ty, RangeLikeMetadataKind::Range);
4538void Verifier::visitNoFPClassMetadata(Instruction &
I, MDNode *NoFPClass,
4540 Check(AttributeFuncs::isNoFPClassCompatibleType(Ty),
4541 "nofpclass only applies to floating-point typed loads",
I);
4544 "nofpclass must have exactly one entry", NoFPClass);
4545 ConstantInt *MaskVal =
4548 "nofpclass entry must be a constant i32", NoFPClass);
4550 Check(Val != 0,
"'nofpclass' must have at least one test bit set", NoFPClass,
4554 "Invalid value for 'nofpclass' test mask", NoFPClass,
I);
4557void Verifier::visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
4560 "precondition violation");
4561 verifyRangeLikeMetadata(
I,
Range, Ty,
4562 RangeLikeMetadataKind::NoaliasAddrspace);
4565void Verifier::checkAtomicMemAccessSize(
Type *Ty,
const Instruction *
I) {
4566 unsigned Size =
DL.getTypeSizeInBits(Ty).getFixedValue();
4567 Check(
Size >= 8,
"atomic memory access' size must be byte-sized", Ty,
I);
4569 "atomic memory access' operand must have a power-of-two size", Ty,
I);
4572void Verifier::visitLoadInst(LoadInst &LI) {
4574 Check(PTy,
"Load operand must be a pointer.", &LI);
4577 Check(
A->value() <= Value::MaximumAlignment,
4578 "huge alignment values are unsupported", &LI);
4580 Check(ElTy->
isSized(),
"loading unsized types is not allowed", &LI);
4583 LI.
getOrdering() != AtomicOrdering::AcquireRelease,
4584 "Load cannot have Release ordering", &LI);
4588 "atomic load operand must have integer, byte, pointer, floating "
4589 "point, or vector type!",
4592 checkAtomicMemAccessSize(ElTy, &LI);
4595 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4598 visitInstruction(LI);
4601void Verifier::visitStoreInst(StoreInst &SI) {
4603 Check(PTy,
"Store operand must be a pointer.", &SI);
4604 Type *ElTy =
SI.getOperand(0)->getType();
4605 if (MaybeAlign
A =
SI.getAlign()) {
4606 Check(
A->value() <= Value::MaximumAlignment,
4607 "huge alignment values are unsupported", &SI);
4609 Check(ElTy->
isSized(),
"storing unsized types is not allowed", &SI);
4610 if (
SI.isAtomic()) {
4611 Check(
SI.getOrdering() != AtomicOrdering::Acquire &&
4612 SI.getOrdering() != AtomicOrdering::AcquireRelease,
4613 "Store cannot have Acquire ordering", &SI);
4617 "atomic store operand must have integer, byte, pointer, floating "
4618 "point, or vector type!",
4620 checkAtomicMemAccessSize(ElTy, &SI);
4623 "Non-atomic store cannot have SynchronizationScope specified", &SI);
4625 visitInstruction(SI);
4629void Verifier::verifySwiftErrorCall(CallBase &
Call,
4630 const Value *SwiftErrorVal) {
4632 if (
I.value() == SwiftErrorVal) {
4634 "swifterror value when used in a callsite should be marked "
4635 "with swifterror attribute",
4636 SwiftErrorVal,
Call);
4641void Verifier::verifySwiftErrorValue(
const Value *SwiftErrorVal) {
4644 for (
const User *U : SwiftErrorVal->
users()) {
4647 "swifterror value can only be loaded and stored from, or "
4648 "as a swifterror argument!",
4652 Check(StoreI->getOperand(1) == SwiftErrorVal,
4653 "swifterror value should be the second operand when used "
4657 verifySwiftErrorCall(*
const_cast<CallBase *
>(
Call), SwiftErrorVal);
4661void Verifier::visitAllocaInst(AllocaInst &AI) {
4664 Check(!MD->getZExtValue(),
4665 "Non-logical alloca disallowed for this module.");
4668 SmallPtrSet<Type*, 4> Visited;
4669 Check(Ty->
isSized(&Visited),
"Cannot allocate unsized type", &AI);
4673 "Alloca has illegal target extension type", &AI);
4675 "Alloca array size must have integer type", &AI);
4677 Check(
A->value() <= Value::MaximumAlignment,
4678 "huge alignment values are unsupported", &AI);
4684 "swifterror alloca must not be array allocation", &AI);
4685 verifySwiftErrorValue(&AI);
4688 visitInstruction(AI);
4694void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4697 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4698 checkAtomicMemAccessSize(ElTy, &CXI);
4699 visitInstruction(CXI);
4702void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
4704 "atomicrmw instructions cannot be unordered.", &RMWI);
4707 Type *ScalarTy = ElTy;
4710 Check(VecTy,
"atomicrmw elementwise operand must have fixed vector type!",
4713 ScalarTy = VecTy->getElementType();
4720 " operand must have integer or floating point type!",
4725 " operand must have floating-point or fixed vector of "
4732 " operand must have integer or fixed vector of integer type!",
4735 checkAtomicMemAccessSize(ElTy, &RMWI);
4737 "Invalid binary operation!", &RMWI);
4738 visitInstruction(RMWI);
4741void Verifier::visitFenceInst(FenceInst &FI) {
4743 Check(Ordering == AtomicOrdering::Acquire ||
4744 Ordering == AtomicOrdering::Release ||
4745 Ordering == AtomicOrdering::AcquireRelease ||
4746 Ordering == AtomicOrdering::SequentiallyConsistent,
4747 "fence instructions may only have acquire, release, acq_rel, or "
4748 "seq_cst ordering.",
4750 visitInstruction(FI);
4753void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
4756 "Invalid ExtractValueInst operands!", &EVI);
4758 visitInstruction(EVI);
4761void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
4765 "Invalid InsertValueInst operands!", &IVI);
4767 visitInstruction(IVI);
4772 return FPI->getParentPad();
4777void Verifier::visitEHPadPredecessors(Instruction &
I) {
4783 Check(BB != &
F->getEntryBlock(),
"EH pad cannot be in entry block.", &
I);
4791 Check(
II &&
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4792 "Block containing LandingPadInst must be jumped to "
4793 "only by the unwind edge of an invoke.",
4801 "Block containg CatchPadInst must be jumped to "
4802 "only by its catchswitch.",
4804 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4805 "Catchswitch cannot unwind to one of its catchpads",
4806 CPI->getCatchSwitch(), CPI);
4818 Check(
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4819 "EH pad must be jumped to via an unwind edge", ToPad,
II);
4822 if (CalledFn && CalledFn->isIntrinsic() &&
II->doesNotThrow() &&
4826 FromPad = Bundle->Inputs[0];
4830 FromPad = CRI->getOperand(0);
4831 Check(FromPad != ToPadParent,
"A cleanupret must exit its cleanup", CRI);
4835 Check(
false,
"EH pad must be jumped to via an unwind edge", ToPad, TI);
4839 SmallPtrSet<Value *, 8> Seen;
4841 Check(FromPad != ToPad,
4842 "EH pad cannot handle exceptions raised within it", FromPad, TI);
4843 if (FromPad == ToPadParent) {
4848 "A single unwind edge may only enter one EH pad", TI);
4849 Check(Seen.
insert(FromPad).second,
"EH pad jumps through a cycle of pads",
4855 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
4860void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
4864 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
4866 visitEHPadPredecessors(LPI);
4868 if (!LandingPadResultTy)
4869 LandingPadResultTy = LPI.
getType();
4872 "The landingpad instruction should have a consistent result type "
4873 "inside a function.",
4877 Check(
F->hasPersonalityFn(),
4878 "LandingPadInst needs to be in a function with a personality.", &LPI);
4883 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
4889 "Catch operand does not have pointer type!", &LPI);
4891 Check(LPI.
isFilter(i),
"Clause is neither catch nor filter!", &LPI);
4893 "Filter operand is not an array of constants!", &LPI);
4897 visitInstruction(LPI);
4900void Verifier::visitResumeInst(ResumeInst &RI) {
4902 "ResumeInst needs to be in a function with a personality.", &RI);
4904 if (!LandingPadResultTy)
4908 "The resume instruction should have a consistent result type "
4909 "inside a function.",
4912 visitTerminator(RI);
4915void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
4919 Check(
F->hasPersonalityFn(),
4920 "CatchPadInst needs to be in a function with a personality.", &CPI);
4923 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4929 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
4934 return isa<Constant>(V) || isa<AllocaInst>(V);
4936 "Argument operand must be alloca or constant.", &CPI);
4938 visitEHPadPredecessors(CPI);
4939 visitFuncletPadInst(CPI);
4942void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
4944 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
4947 visitTerminator(CatchReturn);
4950void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
4954 Check(
F->hasPersonalityFn(),
4955 "CleanupPadInst needs to be in a function with a personality.", &CPI);
4960 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
4964 "CleanupPadInst has an invalid parent.", &CPI);
4966 visitEHPadPredecessors(CPI);
4967 visitFuncletPadInst(CPI);
4970void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
4971 User *FirstUser =
nullptr;
4972 Value *FirstUnwindPad =
nullptr;
4974 SmallPtrSet<FuncletPadInst *, 8> Seen;
4976 while (!Worklist.empty()) {
4977 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
4979 "FuncletPadInst must not be nested within itself", CurrentPad);
4980 Value *UnresolvedAncestorPad =
nullptr;
4981 for (User *U : CurrentPad->
users()) {
4984 UnwindDest = CRI->getUnwindDest();
4990 if (CSI->unwindsToCaller())
4992 UnwindDest = CSI->getUnwindDest();
4994 UnwindDest =
II->getUnwindDest();
5004 Worklist.push_back(CPI);
5019 if (UnwindParent == CurrentPad)
5025 Value *ExitedPad = CurrentPad;
5028 if (ExitedPad == &FPI) {
5033 UnresolvedAncestorPad = &FPI;
5037 if (ExitedParent == UnwindParent) {
5041 UnresolvedAncestorPad = ExitedParent;
5044 ExitedPad = ExitedParent;
5050 UnresolvedAncestorPad = &FPI;
5057 Check(UnwindPad == FirstUnwindPad,
5058 "Unwind edges out of a funclet "
5059 "pad must have the same unwind "
5061 &FPI, U, FirstUser);
5064 FirstUnwindPad = UnwindPad;
5073 if (CurrentPad != &FPI)
5076 if (UnresolvedAncestorPad) {
5077 if (CurrentPad == UnresolvedAncestorPad) {
5081 assert(CurrentPad == &FPI);
5089 Value *ResolvedPad = CurrentPad;
5090 while (!Worklist.empty()) {
5091 Value *UnclePad = Worklist.back();
5095 while (ResolvedPad != AncestorPad) {
5097 if (ResolvedParent == UnresolvedAncestorPad) {
5100 ResolvedPad = ResolvedParent;
5104 if (ResolvedPad != AncestorPad)
5107 Worklist.pop_back();
5112 if (FirstUnwindPad) {
5114 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
5115 Value *SwitchUnwindPad;
5116 if (SwitchUnwindDest)
5120 Check(SwitchUnwindPad == FirstUnwindPad,
5121 "Unwind edges out of a catch must have the same unwind dest as "
5122 "the parent catchswitch",
5123 &FPI, FirstUser, CatchSwitch);
5127 visitInstruction(FPI);
5130void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
5134 Check(
F->hasPersonalityFn(),
5135 "CatchSwitchInst needs to be in a function with a personality.",
5141 "CatchSwitchInst not the first non-PHI instruction in the block.",
5146 "CatchSwitchInst has an invalid parent.", ParentPad);
5151 "CatchSwitchInst must unwind to an EH block which is not a "
5157 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
5161 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
5163 for (BasicBlock *Handler : CatchSwitch.
handlers()) {
5165 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
5168 visitEHPadPredecessors(CatchSwitch);
5169 visitTerminator(CatchSwitch);
5172void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
5174 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
5180 "CleanupReturnInst must unwind to an EH block which is not a "
5185 visitTerminator(CRI);
5188void Verifier::verifyDominatesUse(Instruction &
I,
unsigned i) {
5194 if (
II->getNormalDest() ==
II->getUnwindDest())
5208 const Use &
U =
I.getOperandUse(i);
5209 Check(DT.dominates(
Op, U),
"Instruction does not dominate all uses!",
Op, &
I);
5212void Verifier::visitDereferenceableMetadata(Instruction&
I, MDNode* MD) {
5213 Check(
I.getType()->isPointerTy(),
5214 "dereferenceable, dereferenceable_or_null "
5215 "apply only to pointer types",
5218 "dereferenceable, dereferenceable_or_null apply only to load"
5219 " and inttoptr instructions, use attributes for calls or invokes",
5222 "dereferenceable, dereferenceable_or_null "
5223 "take one operand!",
5228 "dereferenceable_or_null metadata value must be an i64!",
5232void Verifier::visitNofreeMetadata(Instruction &
I, MDNode *MD) {
5233 Check(
I.getType()->isPointerTy(),
"nofree applies only to pointer types", &
I);
5239void Verifier::visitProfMetadata(Instruction &
I, MDNode *MD) {
5240 auto GetBranchingTerminatorNumOperands = [&]() {
5241 unsigned ExpectedNumOperands = 0;
5245 ExpectedNumOperands =
SI->getNumSuccessors();
5247 ExpectedNumOperands = 1;
5249 ExpectedNumOperands = IBI->getNumDestinations();
5251 ExpectedNumOperands = 2;
5254 return ExpectedNumOperands;
5257 "!prof annotations should have at least 1 operand", MD);
5259 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null", MD);
5261 "expected string with name of the !prof annotation", MD);
5267 "'unknown' !prof should only appear on instructions on which "
5268 "'branch_weights' would",
5270 verifyUnknownProfileMetadata(MD);
5275 "!prof annotations should have no less than 2 operands", MD);
5281 Check(NumBranchWeights == 1 || NumBranchWeights == 2,
5282 "Wrong number of InvokeInst branch_weights operands", MD);
5284 const unsigned ExpectedNumOperands = GetBranchingTerminatorNumOperands();
5285 if (ExpectedNumOperands == 0)
5286 CheckFailed(
"!prof branch_weights are not allowed for this instruction",
5289 Check(NumBranchWeights == ExpectedNumOperands,
"Wrong number of operands",
5295 Check(MDO,
"second operand should not be null", MD);
5297 "!prof brunch_weights operand is not a const int");
5302 Check(KindInt,
"VP !prof missing kind argument", MD);
5305 Check(Kind >= InstrProfValueKind::IPVK_First &&
5306 Kind <= InstrProfValueKind::IPVK_Last,
5307 "Invalid VP !prof kind", MD);
5309 "VP !prof should have an even number "
5310 "of arguments after 'VP'",
5312 if (Kind == InstrProfValueKind::IPVK_IndirectCallTarget ||
5313 Kind == InstrProfValueKind::IPVK_MemOPSize)
5315 "VP !prof indirect call or memop size expected to be applied to "
5316 "CallBase instructions only",
5319 DenseSet<uint64_t> ProfileValues;
5321 ConstantInt *ProfileValue =
5323 Check(ProfileValue,
"VP !prof value operand is not a const int", MD);
5324 uint64_t ProfileValueInt = ProfileValue->
getZExtValue();
5325 auto [ValueIt,
Inserted] = ProfileValues.
insert(ProfileValueInt);
5326 Check(Inserted,
"VP !prof should not have duplicate profile values", MD);
5329 CheckFailed(
"expected either branch_weights or VP profile name", MD);
5333void Verifier::visitDIAssignIDMetadata(Instruction &
I, MDNode *MD) {
5334 assert(
I.hasMetadata(LLVMContext::MD_DIAssignID));
5339 bool ExpectedInstTy =
5341 CheckDI(ExpectedInstTy,
"!DIAssignID attached to unexpected instruction kind",
5346 for (
auto *User : AsValue->users()) {
5348 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
5352 CheckDI(DAI->getFunction() ==
I.getFunction(),
5353 "dbg.assign not in same function as inst", DAI, &
I);
5356 for (DbgVariableRecord *DVR :
5359 "!DIAssignID should only be used by Assign DVRs.", MD, DVR);
5360 CheckDI(DVR->getFunction() ==
I.getFunction(),
5361 "DVRAssign not in same function as inst", DVR, &
I);
5365void Verifier::visitMMRAMetadata(Instruction &
I, MDNode *MD) {
5367 "!mmra metadata attached to unexpected instruction kind",
I, MD);
5378 for (
const MDOperand &MDOp : MD->
operands())
5380 "!mmra metadata tuple operand is not an MMRA tag",
I, MDOp.get());
5383void Verifier::visitCallStackMetadata(MDNode *MD) {
5387 "call stack metadata should have at least 1 operand", MD);
5391 "call stack metadata operand should be constant integer",
Op);
5394void Verifier::visitMemProfMetadata(Instruction &
I, MDNode *MD) {
5397 Check(
I.hasMetadata(LLVMContext::MD_callsite),
5398 "!memprof metadata requires !callsite metadata", &
I, MD);
5400 "!memprof annotations should have at least 1 metadata operand "
5405 for (
auto &MIBOp : MD->
operands()) {
5410 Check(MIB->getNumOperands() >= 2,
5411 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
5414 Check(MIB->getOperand(0) !=
nullptr,
5415 "!memprof MemInfoBlock first operand should not be null", MIB);
5417 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
5419 visitCallStackMetadata(StackMD);
5423 "!memprof MemInfoBlock second operand should be an MDString", MIB);
5426 for (
unsigned I = 2;
I < MIB->getNumOperands(); ++
I) {
5428 Check(OpNode,
"Not all !memprof MemInfoBlock operands 2 to N are MDNode",
5430 Check(OpNode->getNumOperands() == 2,
5431 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with 2 "
5436 [](
const MDOperand &
Op) {
5437 return mdconst::hasa<ConstantInt>(Op);
5439 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with "
5440 "ConstantInt operands",
5446void Verifier::visitCallsiteMetadata(Instruction &
I, MDNode *MD) {
5450 visitCallStackMetadata(MD);
5453void Verifier::visitCalleeTypeMetadata(Instruction &
I, MDNode *MD) {
5458 "The callee_type metadata must be a list of callgraph metadata nodes",
5461 Check(CallgraphMD->getNumOperands() == 1,
5462 "Well-formed generalized callgraph metadata must contain exactly one "
5466 "The operand of callgraph metadata for functions must be an MDString",
5470 .ends_with(
".generalized"),
5471 "Only generalized callgraph metadata can be part of the callee_type "
5477void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
5480 "annotation must have at least one operand");
5482 bool TupleOfStrings =
5488 "operands must be a string or a tuple of strings");
5492void Verifier::visitAliasScopeMetadata(
const MDNode *MD) {
5497 "first scope operand must be self-referential or string", MD);
5500 "third scope operand must be string (if used)", MD);
5503 Check(
Domain !=
nullptr,
"second scope operand must be MDNode", MD);
5505 unsigned NumDomainOps =
Domain->getNumOperands();
5506 Check(NumDomainOps >= 1 && NumDomainOps <= 2,
5507 "domain must have one or two operands",
Domain);
5510 "first domain operand must be self-referential or string",
Domain);
5511 if (NumDomainOps == 2)
5513 "second domain operand must be string (if used)",
Domain);
5516void Verifier::visitAliasScopeListMetadata(
const MDNode *MD) {
5519 Check(OpMD !=
nullptr,
"scope list must consist of MDNodes", MD);
5520 visitAliasScopeMetadata(OpMD);
5524void Verifier::visitAccessGroupMetadata(
const MDNode *MD) {
5525 auto IsValidAccessScope = [](
const MDNode *MD) {
5530 if (IsValidAccessScope(MD))
5536 Check(OpMD !=
nullptr,
"Access scope list must consist of MDNodes", MD);
5537 Check(IsValidAccessScope(OpMD),
5538 "Access scope list contains invalid access scope", MD);
5542void Verifier::visitCapturesMetadata(Instruction &
I,
const MDNode *Captures) {
5543 static const char *ValidArgs[] = {
"address_is_null",
"address",
5544 "read_provenance",
"provenance"};
5547 Check(SI,
"!captures metadata can only be applied to store instructions", &
I);
5548 Check(
SI->getValueOperand()->getType()->isPointerTy(),
5549 "!captures metadata can only be applied to store with value operand of "
5557 Check(Str,
"!captures metadata must be a list of strings", &
I);
5559 "invalid entry in !captures metadata", &
I, Str);
5563void Verifier::visitAllocTokenMetadata(Instruction &
I, MDNode *MD) {
5568 "expected integer constant", MD);
5571void Verifier::visitInlineHistoryMetadata(Instruction &
I, MDNode *MD) {
5580 ->stripPointerCastsAndAliases()),
5581 "!inline_history operands must be functions or null", MD);
5585void Verifier::visitMemCacheHintMetadata(Instruction &
I, MDNode *MD) {
5586 Check(
I.mayReadOrWriteMemory(),
5587 "!mem.cache_hint is only valid on memory operations", &
I);
5590 "!mem.cache_hint must have even number of operands "
5591 "(operand_no, hint_node pairs)",
5597 "!mem.cache_hint is not supported on non-intrinsic calls", &
I);
5599 unsigned NumOperands = CB ? CB->arg_size() :
I.getNumOperands();
5601 SmallDenseSet<unsigned, 4> SeenOperandNos;
5602 std::optional<uint64_t> LastOperandNo;
5608 "!mem.cache_hint must alternate between i32 operand numbers and "
5609 "metadata hint nodes",
5612 Check(OpNoCI->getValue().isNonNegative(),
5613 "!mem.cache_hint operand number must be non-negative", MD);
5615 uint64_t OperandNo = OpNoCI->getZExtValue();
5616 Check(OperandNo < NumOperands,
5617 "!mem.cache_hint operand number is out of range", &
I);
5620 CB ? CB->getArgOperand(OperandNo) :
I.getOperand(OperandNo);
5622 "!mem.cache_hint operand number must refer to a pointer operand", &
I);
5625 Check(Inserted,
"!mem.cache_hint contains duplicate operand number", MD);
5627 Check(!Inserted || !LastOperandNo || OperandNo > *LastOperandNo,
5628 "!mem.cache_hint operand numbers must be in increasing order", MD);
5629 LastOperandNo = OperandNo;
5633 "!mem.cache_hint must alternate between i32 operand numbers and "
5634 "metadata hint nodes",
5638 "!mem.cache_hint hint node must have even number of operands "
5639 "(key-value pairs)",
5642 StringSet<> SeenKeys;
5643 for (
unsigned K = 0;
K + 1 <
Node->getNumOperands();
K += 2) {
5645 Check(
Key,
"!mem.cache_hint key must be a string", Node);
5647 StringRef KeyStr =
Key->getString();
5649 "!mem.cache_hint hint node contains duplicate key", Node);
5654 "!mem.cache_hint value must be a string or integer", Node);
5661void Verifier::visitInstruction(Instruction &
I) {
5663 Check(BB,
"Instruction not embedded in basic block!", &
I);
5666 for (User *U :
I.users()) {
5667 Check(U != (User *)&
I || !DT.isReachableFromEntry(BB),
5668 "Only PHI nodes may reference their own value!", &
I);
5673 Check(!
I.getType()->isVoidTy() || !
I.hasName(),
5674 "Instruction has a name, but provides a void value!", &
I);
5678 Check(
I.getType()->isVoidTy() ||
I.getType()->isFirstClassType(),
5679 "Instruction returns a non-scalar type!", &
I);
5684 "Invalid use of metadata!", &
I);
5689 for (Use &U :
I.uses()) {
5692 "Instruction referencing"
5693 " instruction not embedded in a basic block!",
5696 CheckFailed(
"Use of instruction is not an instruction!", U);
5705 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i) {
5706 Check(
I.getOperand(i) !=
nullptr,
"Instruction has null operand!", &
I);
5710 if (!
I.getOperand(i)->getType()->isFirstClassType()) {
5711 Check(
false,
"Instruction operands must be first-class values!", &
I);
5717 auto IsAttachedCallOperand = [](
Function *
F,
const CallBase *CBI,
5719 return CBI && CBI->isOperandBundleOfType(
5727 Check((!
F->isIntrinsic() ||
5728 (CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i)) ||
5729 IsAttachedCallOperand(
F, CBI, i)),
5730 "Cannot take the address of an intrinsic!", &
I);
5732 F->getIntrinsicID() == Intrinsic::donothing ||
5733 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
5734 F->getIntrinsicID() == Intrinsic::seh_try_end ||
5735 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
5736 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
5737 F->getIntrinsicID() == Intrinsic::coro_resume ||
5738 F->getIntrinsicID() == Intrinsic::coro_destroy ||
5739 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
5740 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
5741 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
5742 F->getIntrinsicID() ==
5743 Intrinsic::experimental_patchpoint_void ||
5744 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
5745 F->getIntrinsicID() == Intrinsic::fake_use ||
5746 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
5747 F->getIntrinsicID() == Intrinsic::wasm_throw ||
5748 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
5749 IsAttachedCallOperand(
F, CBI, i),
5750 "Cannot invoke an intrinsic other than donothing, patchpoint, "
5751 "statepoint, coro_resume, coro_destroy, clang.arc.attachedcall or "
5754 Check(
F->getParent() == &M,
"Referencing function in another module!", &
I,
5755 &M,
F,
F->getParent());
5758 "Referring to a basic block in another function!", &
I);
5761 "Referring to an argument in another function!", &
I);
5763 Check(GV->
getParent() == &M,
"Referencing global in another module!", &
I,
5767 "Referring to an instruction in another function!", &
I);
5768 verifyDominatesUse(
I, i);
5770 Check(CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i),
5771 "Cannot take the address of an inline asm!", &
I);
5773 visitConstantExprsRecursively(
C);
5777 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_fpmath)) {
5779 "fpmath requires a floating point result!", &
I);
5781 if (ConstantFP *CFP0 =
5783 const APFloat &Accuracy = CFP0->getValueAPF();
5785 "fpmath accuracy must have float type", &
I);
5787 "fpmath accuracy not a positive number!", &
I);
5789 Check(
false,
"invalid fpmath accuracy!", &
I);
5793 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_range)) {
5795 "Ranges are only for loads, calls and invokes!", &
I);
5796 visitRangeMetadata(
I,
Range,
I.getType());
5799 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofpclass)) {
5801 visitNoFPClassMetadata(
I, MD,
I.getType());
5804 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_noalias_addrspace)) {
5807 "noalias.addrspace are only for memory operations!", &
I);
5808 visitNoaliasAddrspaceMetadata(
I,
Range,
I.getType());
5811 if (
I.hasMetadata(LLVMContext::MD_invariant_group)) {
5813 "invariant.group metadata is only for loads and stores", &
I);
5816 if (
I.hasMetadata(LLVMContext::MD_invariant_load)) {
5819 "invariant.load metadata is only for loads and readonly "
5824 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nonnull)) {
5825 Check(
I.getType()->isPointerTy(),
"nonnull applies only to pointer types",
5828 "nonnull applies only to load instructions, use attributes"
5829 " for calls or invokes",
5834 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noundef)) {
5839 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable))
5840 visitDereferenceableMetadata(
I, MD);
5842 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
5843 visitDereferenceableMetadata(
I, MD);
5845 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofree))
5846 visitNofreeMetadata(
I, MD);
5848 if (MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa))
5851 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noalias))
5852 visitAliasScopeListMetadata(MD);
5853 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alias_scope))
5854 visitAliasScopeListMetadata(MD);
5856 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_access_group))
5857 visitAccessGroupMetadata(MD);
5859 if (MDNode *AlignMD =
I.getMetadata(LLVMContext::MD_align)) {
5860 Check(
I.getType()->isPointerTy(),
"align applies only to pointer types",
5863 "align applies only to load instructions, "
5864 "use attributes for calls or invokes",
5866 Check(AlignMD->getNumOperands() == 1,
"align takes one operand!", &
I);
5869 "align metadata value must be an i64!", &
I);
5873 Check(Align <= Value::MaximumAlignment,
5874 "alignment is larger that implementation defined limit", &
I);
5877 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_prof))
5878 visitProfMetadata(
I, MD);
5880 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_memprof))
5881 visitMemProfMetadata(
I, MD);
5883 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callsite))
5884 visitCallsiteMetadata(
I, MD);
5886 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callee_type))
5887 visitCalleeTypeMetadata(
I, MD);
5889 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_DIAssignID))
5890 visitDIAssignIDMetadata(
I, MD);
5892 if (MDNode *MMRA =
I.getMetadata(LLVMContext::MD_mmra))
5893 visitMMRAMetadata(
I, MMRA);
5895 if (MDNode *Annotation =
I.getMetadata(LLVMContext::MD_annotation))
5896 visitAnnotationMetadata(Annotation);
5898 if (MDNode *Captures =
I.getMetadata(LLVMContext::MD_captures))
5899 visitCapturesMetadata(
I, Captures);
5901 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alloc_token))
5902 visitAllocTokenMetadata(
I, MD);
5904 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_inline_history))
5905 visitInlineHistoryMetadata(
I, MD);
5907 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_mem_cache_hint))
5908 visitMemCacheHintMetadata(
I, MD);
5910 if (MDNode *
N =
I.getDebugLoc().getAsMDNode()) {
5912 visitMDNode(*
N, AreDebugLocsAllowed::Yes);
5915 if (
DL->getAtomGroup()) {
5916 CheckDI(
DL->getScope()->getSubprogram()->getKeyInstructionsEnabled(),
5917 "DbgLoc uses atomGroup but DISubprogram doesn't have Key "
5918 "Instructions enabled",
5919 DL,
DL->getScope()->getSubprogram());
5925 I.getAllMetadata(MDs);
5926 for (
auto Attachment : MDs) {
5927 unsigned Kind = Attachment.first;
5929 (
Kind == LLVMContext::MD_dbg ||
Kind == LLVMContext::MD_loop)
5930 ? AreDebugLocsAllowed::Yes
5931 : AreDebugLocsAllowed::
No;
5932 visitMDNode(*Attachment.second, AllowLocs);
5949 "const x86_amx is not allowed in argument!");
5955 case Intrinsic::assume: {
5959 "assume with operand bundles must have i1 true condition",
Call);
5965 auto GetTypeAt = [&](
unsigned Index) {
5966 return OBU.Inputs[
Index]->getType();
5971 CheckFailed(
"tags must be valid attribute names",
Call);
5973 case BundleAttr::Align:
5974 Check(OBU.Inputs.size() >= 2 && OBU.Inputs.size() <= 3,
5975 "alignment assumptions should have 2 or 3 arguments",
Call);
5978 Check(GetTypeAt(1)->isIntegerTy() &&
5979 GetTypeAt(1)->getIntegerBitWidth() <= 64,
5980 "second argument should be an integer with a maximum width of 64 "
5983 Check(OBU.Inputs.size() < 3 ||
5984 (GetTypeAt(2)->isIntegerTy() &&
5985 GetTypeAt(2)->getIntegerBitWidth() <= 64),
5986 "third argument should be an integer with a maximum width of 64 "
5990 case BundleAttr::Cold:
5991 Check(OBU.Inputs.size() == 0,
5992 "cold assumptions should have no arguments",
Call);
5994 case BundleAttr::Dereferenceable:
5995 case BundleAttr::DereferenceableOrNull:
5996 Check(OBU.Inputs.size() == 2,
5997 "dereferenceable assumptions should have 2 arguments",
Call);
6000 Check(GetTypeAt(1)->isIntegerTy() &&
6001 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6002 "second argument should be an integer with a maximum width of 64 "
6006 case BundleAttr::Ignore:
6008 case BundleAttr::NonNull:
6009 Check(OBU.Inputs.size() == 1,
6010 "nonnull assumptions should have 1 argument",
Call);
6014 case BundleAttr::NoUndef:
6015 Check(OBU.Inputs.size() == 1,
6016 "noundef assumptions should have 1 argument",
Call);
6018 case BundleAttr::SeparateStorage:
6019 Check(OBU.Inputs.size() == 2,
6020 "separate_storage assumptions should have 2 arguments",
Call);
6022 "arguments to separate_storage assumptions should be pointers",
6029 case Intrinsic::ucmp:
6030 case Intrinsic::scmp: {
6035 "result type must be at least 2 bits wide",
Call);
6037 bool IsDestTypeVector = DestTy->
isVectorTy();
6039 "ucmp/scmp argument and result types must both be either vector or "
6042 if (IsDestTypeVector) {
6045 Check(SrcVecLen == DestVecLen,
6046 "return type and arguments must have the same number of "
6052 case Intrinsic::coro_begin:
6053 case Intrinsic::coro_begin_custom_abi:
6055 "id argument of llvm.coro.begin must refer to coro.id");
6057 case Intrinsic::coro_id: {
6059 "align argument only accepts constants");
6062 "promise argument must refer to an alloca");
6067 "coro argument must refer to a function");
6071 if (BeforeCoroSplit)
6074 Check(!BeforeCoroEarly,
"cannot run CoroSplit before CoroEarly");
6077 "info argument of llvm.coro.id must refer to an initialized "
6081 "info argument of llvm.coro.id must refer to either a struct or "
6085 case Intrinsic::is_fpclass: {
6088 "unsupported bits for llvm.is.fpclass test mask");
6091 case Intrinsic::fptrunc_round: {
6096 MD = MAV->getMetadata();
6098 Check(MD !=
nullptr,
"missing rounding mode argument",
Call);
6101 (
"invalid value for llvm.fptrunc.round metadata operand"
6102 " (the operand should be a string)"),
6105 std::optional<RoundingMode> RoundMode =
6107 Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
6108 "unsupported rounding mode argument",
Call);
6111 case Intrinsic::convert_to_arbitrary_fp: {
6119 "if floating-point operand is a vector, integer operand must also "
6122 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6123 "floating-point and integer vector operands must have the same "
6130 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6132 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6133 StringRef Interp = InterpStr->getString();
6135 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6140 "unsupported interpretation metadata string",
Call);
6143 if (
unsigned FormatBits =
6146 "integer type bit width must equal the arbitrary FP format width",
6151 Check(RoundingMAV,
"missing rounding mode metadata operand",
Call);
6153 Check(RoundingStr,
"rounding mode metadata operand must be a string",
Call);
6155 std::optional<RoundingMode>
RM =
6157 Check(RM && *RM != RoundingMode::Dynamic,
6158 "unsupported rounding mode argument",
Call);
6161 case Intrinsic::convert_from_arbitrary_fp: {
6169 "if floating-point operand is a vector, integer operand must also "
6172 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6173 "floating-point and integer vector operands must have the same "
6180 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6182 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6183 StringRef Interp = InterpStr->getString();
6185 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6190 "unsupported interpretation metadata string",
Call);
6193 if (
unsigned FormatBits =
6196 "integer type bit width must equal the arbitrary FP format width",
6200#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6201#include "llvm/IR/VPIntrinsics.def"
6202#undef BEGIN_REGISTER_VP_INTRINSIC
6205#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
6206 case Intrinsic::INTRINSIC:
6207#include "llvm/IR/ConstrainedOps.def"
6211 case Intrinsic::dbg_declare:
6212 case Intrinsic::dbg_value:
6213 case Intrinsic::dbg_assign:
6214 case Intrinsic::dbg_label:
6221 case Intrinsic::memcpy:
6222 case Intrinsic::memcpy_inline:
6223 case Intrinsic::memmove:
6224 case Intrinsic::memset:
6225 case Intrinsic::memset_inline:
6227 case Intrinsic::experimental_memset_pattern: {
6229 Check(Memset->getValue()->getType()->isSized(),
6230 "unsized types cannot be used as memset patterns",
Call);
6233 case Intrinsic::memcpy_element_unordered_atomic:
6234 case Intrinsic::memmove_element_unordered_atomic:
6235 case Intrinsic::memset_element_unordered_atomic: {
6238 ConstantInt *ElementSizeCI =
6240 const APInt &ElementSizeVal = ElementSizeCI->
getValue();
6242 "element size of the element-wise atomic memory intrinsic "
6243 "must be a power of 2",
6246 auto IsValidAlignment = [&](MaybeAlign Alignment) {
6247 return Alignment && ElementSizeVal.
ule(Alignment->value());
6249 Check(IsValidAlignment(AMI->getDestAlign()),
6250 "incorrect alignment of the destination argument",
Call);
6252 Check(IsValidAlignment(AMT->getSourceAlign()),
6253 "incorrect alignment of the source argument",
Call);
6257 case Intrinsic::call_preallocated_setup: {
6259 bool FoundCall =
false;
6262 Check(UseCall !=
nullptr,
6263 "Uses of llvm.call.preallocated.setup must be calls");
6265 if (IID == Intrinsic::call_preallocated_arg) {
6267 Check(AllocArgIndex !=
nullptr,
6268 "llvm.call.preallocated.alloc arg index must be a constant");
6269 auto AllocArgIndexInt = AllocArgIndex->getValue();
6270 Check(AllocArgIndexInt.sge(0) &&
6271 AllocArgIndexInt.slt(NumArgs->getValue()),
6272 "llvm.call.preallocated.alloc arg index must be between 0 and "
6274 "llvm.call.preallocated.setup's argument count");
6275 }
else if (IID == Intrinsic::call_preallocated_teardown) {
6278 Check(!FoundCall,
"Can have at most one call corresponding to a "
6279 "llvm.call.preallocated.setup");
6281 size_t NumPreallocatedArgs = 0;
6282 for (
unsigned i = 0; i < UseCall->arg_size(); i++) {
6283 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
6284 ++NumPreallocatedArgs;
6287 Check(NumPreallocatedArgs != 0,
6288 "cannot use preallocated intrinsics on a call without "
6289 "preallocated arguments");
6290 Check(NumArgs->equalsInt(NumPreallocatedArgs),
6291 "llvm.call.preallocated.setup arg size must be equal to number "
6292 "of preallocated arguments "
6302 auto PreallocatedBundle =
6304 Check(PreallocatedBundle,
6305 "Use of llvm.call.preallocated.setup outside intrinsics "
6306 "must be in \"preallocated\" operand bundle");
6307 Check(PreallocatedBundle->Inputs.front().get() == &
Call,
6308 "preallocated bundle must have token from corresponding "
6309 "llvm.call.preallocated.setup");
6314 case Intrinsic::call_preallocated_arg: {
6317 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6318 "llvm.call.preallocated.arg token argument must be a "
6319 "llvm.call.preallocated.setup");
6321 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
6322 "call site attribute");
6325 case Intrinsic::call_preallocated_teardown: {
6328 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6329 "llvm.call.preallocated.teardown token argument must be a "
6330 "llvm.call.preallocated.setup");
6333 case Intrinsic::gcroot:
6334 case Intrinsic::gcwrite:
6335 case Intrinsic::gcread:
6336 if (
ID == Intrinsic::gcroot) {
6339 Check(AI,
"llvm.gcroot parameter #1 must be an alloca.",
Call);
6341 "llvm.gcroot parameter #2 must be a constant.",
Call);
6344 "llvm.gcroot parameter #1 must either be a pointer alloca, "
6345 "or argument #2 must be a non-null constant.",
6351 "Enclosing function does not use GC.",
Call);
6353 case Intrinsic::init_trampoline:
6355 "llvm.init_trampoline parameter #2 must resolve to a function.",
6358 case Intrinsic::reloc_none: {
6361 "llvm.reloc.none argument must be a metadata string", &
Call);
6364 case Intrinsic::stackprotector:
6366 "llvm.stackprotector parameter #2 must resolve to an alloca.",
Call);
6368 case Intrinsic::localescape: {
6372 Check(!SawFrameEscape,
"multiple calls to llvm.localescape in one function",
6379 "llvm.localescape only accepts static allocas",
Call);
6382 SawFrameEscape =
true;
6385 case Intrinsic::localrecover: {
6388 Check(Fn && !Fn->isDeclaration(),
6389 "llvm.localrecover first "
6390 "argument must be function defined in this module",
6393 auto &
Entry = FrameEscapeInfo[Fn];
6394 Entry.second = unsigned(
6395 std::max(uint64_t(
Entry.second), IdxArg->getLimitedValue(~0U) + 1));
6399 case Intrinsic::experimental_gc_statepoint:
6401 Check(!CI->isInlineAsm(),
6402 "gc.statepoint support for inline assembly unimplemented", CI);
6404 "Enclosing function does not use GC.",
Call);
6406 verifyStatepoint(
Call);
6408 case Intrinsic::experimental_gc_result: {
6410 "Enclosing function does not use GC.",
Call);
6418 Check(StatepointCall && StatepointCall->getIntrinsicID() ==
6419 Intrinsic::experimental_gc_statepoint,
6420 "gc.result operand #1 must be from a statepoint",
Call,
6424 auto *TargetFuncType =
6427 "gc.result result type does not match wrapped callee",
Call);
6430 case Intrinsic::experimental_gc_relocate: {
6434 "gc.relocate must return a pointer or a vector of pointers",
Call);
6442 LandingPad->getParent()->getUniquePredecessor();
6446 Check(InvokeBB,
"safepoints should have unique landingpads",
6447 LandingPad->getParent());
6451 "gc relocate should be linked to a statepoint", InvokeBB);
6458 "gc relocate is incorrectly tied to the statepoint",
Call, Token);
6467 "gc.relocate operand #2 must be integer offset",
Call);
6471 "gc.relocate operand #3 must be integer offset",
Call);
6481 Check(BaseIndex < Opt->Inputs.size(),
6482 "gc.relocate: statepoint base index out of bounds",
Call);
6483 Check(DerivedIndex < Opt->Inputs.size(),
6484 "gc.relocate: statepoint derived index out of bounds",
Call);
6497 "gc.relocate: relocated value must be a pointer",
Call);
6498 Check(DerivedType->isPtrOrPtrVectorTy(),
6499 "gc.relocate: relocated value must be a pointer",
Call);
6501 Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
6502 "gc.relocate: vector relocates to vector and pointer to pointer",
6505 ResultType->getPointerAddressSpace() ==
6506 DerivedType->getPointerAddressSpace(),
6507 "gc.relocate: relocating a pointer shouldn't change its address space",
6511 Check(GC,
"gc.relocate: calling function must have GCStrategy",
6514 auto isGCPtr = [&
GC](
Type *PTy) {
6515 return GC->isGCManagedPointer(PTy->getScalarType()).value_or(
true);
6517 Check(isGCPtr(ResultType),
"gc.relocate: must return gc pointer",
Call);
6519 "gc.relocate: relocated value must be a gc pointer",
Call);
6520 Check(isGCPtr(DerivedType),
6521 "gc.relocate: relocated value must be a gc pointer",
Call);
6525 case Intrinsic::experimental_patchpoint: {
6528 "patchpoint: invalid return type used with anyregcc",
Call);
6532 case Intrinsic::eh_exceptioncode:
6533 case Intrinsic::eh_exceptionpointer: {
6535 "eh.exceptionpointer argument must be a catchpad",
Call);
6538 case Intrinsic::get_active_lane_mask: {
6541 "get_active_lane_mask: element type is not i1",
Call);
6544 case Intrinsic::experimental_get_vector_length: {
6546 Check(!VF->isNegative() && !VF->isZero(),
6547 "get_vector_length: VF must be positive",
Call);
6550 case Intrinsic::experimental_guard: {
6553 "experimental_guard must have exactly one "
6554 "\"deopt\" operand bundle");
6558 case Intrinsic::experimental_deoptimize: {
6562 "experimental_deoptimize must have exactly one "
6563 "\"deopt\" operand bundle");
6565 "experimental_deoptimize return type must match caller return type");
6570 "calls to experimental_deoptimize must be followed by a return");
6574 "calls to experimental_deoptimize must be followed by a return "
6575 "of the value computed by experimental_deoptimize");
6580 case Intrinsic::vastart: {
6582 "va_start called in a non-varargs function");
6585 case Intrinsic::get_dynamic_area_offset: {
6587 Check(IntTy &&
DL.getPointerSizeInBits(
DL.getAllocaAddrSpace()) ==
6588 IntTy->getBitWidth(),
6589 "get_dynamic_area_offset result type must be scalar integer matching "
6590 "alloca address space width",
6594 case Intrinsic::smul_fix:
6595 case Intrinsic::smul_fix_sat:
6596 case Intrinsic::umul_fix:
6597 case Intrinsic::umul_fix_sat:
6598 case Intrinsic::sdiv_fix:
6599 case Intrinsic::sdiv_fix_sat:
6600 case Intrinsic::udiv_fix:
6601 case Intrinsic::udiv_fix_sat: {
6605 if (
ID == Intrinsic::smul_fix ||
ID == Intrinsic::smul_fix_sat ||
6606 ID == Intrinsic::sdiv_fix ||
ID == Intrinsic::sdiv_fix_sat) {
6608 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
6612 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
6613 "to the width of the operands");
6617 case Intrinsic::lrint:
6618 case Intrinsic::llrint:
6619 case Intrinsic::lround:
6620 case Intrinsic::llround: {
6624 IF->
getName() +
": argument and result disagree on vector use",
6628 Check(VTy->getElementCount() == RTy->getElementCount(),
6629 IF->
getName() +
": argument must be same length as result", &
Call);
6633 case Intrinsic::bswap: {
6636 Check(
Size % 16 == 0,
"bswap must be an even number of bytes", &
Call);
6639 case Intrinsic::invariant_start: {
6641 Check(InvariantSize &&
6642 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
6643 "invariant_start parameter must be -1, 0 or a positive number",
6647 case Intrinsic::matrix_multiply:
6648 case Intrinsic::matrix_transpose:
6649 case Intrinsic::matrix_column_major_load:
6650 case Intrinsic::matrix_column_major_store: {
6652 ConstantInt *Stride =
nullptr;
6653 ConstantInt *NumRows;
6654 ConstantInt *NumColumns;
6656 Type *Op0ElemTy =
nullptr;
6657 Type *Op1ElemTy =
nullptr;
6659 case Intrinsic::matrix_multiply: {
6664 ->getNumElements() ==
6666 "First argument of a matrix operation does not match specified "
6669 ->getNumElements() ==
6671 "Second argument of a matrix operation does not match specified "
6681 case Intrinsic::matrix_transpose:
6688 case Intrinsic::matrix_column_major_load: {
6695 case Intrinsic::matrix_column_major_store: {
6708 Check(ResultTy->getElementType()->isIntegerTy() ||
6709 ResultTy->getElementType()->isFloatingPointTy(),
6710 "Result type must be an integer or floating-point type!", IF);
6713 Check(ResultTy->getElementType() == Op0ElemTy,
6714 "Vector element type mismatch of the result and first operand "
6719 Check(ResultTy->getElementType() == Op1ElemTy,
6720 "Vector element type mismatch of the result and second operand "
6726 "Result of a matrix operation does not fit in the returned vector!");
6732 "Stride must be greater or equal than the number of rows!", IF);
6737 case Intrinsic::stepvector: {
6739 Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
6740 VecTy->getScalarSizeInBits() >= 8,
6741 "stepvector only supported for vectors of integers "
6742 "with a bitwidth of at least 8.",
6746 case Intrinsic::experimental_vector_match: {
6755 Check(Op1Ty && Op2Ty && MaskTy,
"Operands must be vectors.", &
Call);
6757 "Second operand must be a fixed length vector.", &
Call);
6759 "First operand must be a vector of integers.", &
Call);
6760 Check(Op1Ty->getElementType() == Op2Ty->getElementType(),
6761 "First two operands must have the same element type.", &
Call);
6762 Check(Op1Ty->getElementCount() == MaskTy->getElementCount(),
6763 "First operand and mask must have the same number of elements.",
6765 Check(MaskTy->getElementType()->isIntegerTy(1),
6766 "Mask must be a vector of i1's.", &
Call);
6771 case Intrinsic::vector_insert: {
6780 ElementCount VecEC = VecTy->getElementCount();
6781 ElementCount SubVecEC = SubVecTy->getElementCount();
6782 Check(VecTy->getElementType() == SubVecTy->getElementType(),
6783 "vector_insert parameters must have the same element "
6787 "vector_insert index must be a constant multiple of "
6788 "the subvector's known minimum vector length.");
6796 "subvector operand of vector_insert would overrun the "
6797 "vector being inserted into.");
6801 case Intrinsic::vector_extract: {
6809 ElementCount VecEC = VecTy->getElementCount();
6810 ElementCount ResultEC = ResultTy->getElementCount();
6812 Check(ResultTy->getElementType() == VecTy->getElementType(),
6813 "vector_extract result must have the same element "
6814 "type as the input vector.",
6817 "vector_extract index must be a constant multiple of "
6818 "the result type's known minimum vector length.");
6826 "vector_extract would overrun.");
6830 case Intrinsic::vector_partial_reduce_fadd:
6831 case Intrinsic::vector_partial_reduce_add: {
6835 unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
6836 unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
6838 Check((VecWidth % AccWidth) == 0,
6839 "Invalid vector widths for partial "
6840 "reduction. The width of the input vector "
6841 "must be a positive integer multiple of "
6842 "the width of the accumulator vector.");
6845 case Intrinsic::experimental_noalias_scope_decl: {
6849 case Intrinsic::preserve_array_access_index:
6850 case Intrinsic::preserve_struct_access_index:
6851 case Intrinsic::aarch64_ldaxr:
6852 case Intrinsic::aarch64_ldxr:
6853 case Intrinsic::arm_ldaex:
6854 case Intrinsic::arm_ldrex: {
6856 Check(ElemTy,
"Intrinsic requires elementtype attribute on first argument.",
6860 case Intrinsic::aarch64_stlxr:
6861 case Intrinsic::aarch64_stxr:
6862 case Intrinsic::arm_stlex:
6863 case Intrinsic::arm_strex: {
6866 "Intrinsic requires elementtype attribute on second argument.",
6870 case Intrinsic::aarch64_prefetch: {
6872 "write argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6874 "target argument to llvm.aarch64.prefetch must be 0-3",
Call);
6876 "stream argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6878 "isdata argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6881 case Intrinsic::aarch64_range_prefetch: {
6883 "write argument to llvm.aarch64.range.prefetch must be 0 or 1",
Call);
6885 "stream argument to llvm.aarch64.range.prefetch must be 0 or 1",
6889 case Intrinsic::callbr_landingpad: {
6891 Check(CBR,
"intrinstic requires callbr operand", &
Call);
6898 CheckFailed(
"Intrinsic in block must have 1 unique predecessor", &
Call);
6902 CheckFailed(
"Intrinsic must have corresponding callbr in predecessor",
6907 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
6908 "block in indirect destination list",
6911 Check(&
First == &
Call,
"No other instructions may proceed intrinsic",
6915 case Intrinsic::structured_gep: {
6921 "Intrinsic first parameter is missing an ElementType attribute",
6929 "Index operand type must be an integer", &
Call);
6932 T = AT->getElementType();
6934 Check(CI,
"Indexing into a struct requires a constant int", &
Call);
6936 "Indexing in a struct should be inbounds", &
Call);
6939 T = VT->getElementType();
6941 CheckFailed(
"Reached a non-composite type with more indices to process",
6947 case Intrinsic::structured_alloca:
6949 "@llvm.structured.alloca calls require elementtype attribute.",
6952 case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
6953 case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
6956 Check(RegCount % 8 == 0,
6957 "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
6960 case Intrinsic::experimental_convergence_entry:
6961 case Intrinsic::experimental_convergence_anchor:
6963 case Intrinsic::experimental_convergence_loop:
6965 case Intrinsic::ptrmask: {
6969 "llvm.ptrmask intrinsic first argument must be pointer or vector "
6974 "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
6979 "llvm.ptrmask intrinsic arguments must have the same number of "
6983 "llvm.ptrmask intrinsic second argument bitwidth must match "
6984 "pointer index type size of first argument",
6988 case Intrinsic::thread_pointer: {
6990 DL.getDefaultGlobalsAddressSpace(),
6991 "llvm.thread.pointer intrinsic return type must be for the globals "
6996 case Intrinsic::threadlocal_address: {
6999 "llvm.threadlocal.address first argument must be a GlobalValue");
7001 "llvm.threadlocal.address operand isThreadLocal() must be true");
7004 case Intrinsic::lifetime_start:
7005 case Intrinsic::lifetime_end: {
7009 (
II &&
II->getIntrinsicID() == Intrinsic::structured_alloca),
7010 "llvm.lifetime.start/end can only be used on alloca or poison",
7014 case Intrinsic::sponentry: {
7015 const unsigned StackAS =
DL.getAllocaAddrSpace();
7018 "llvm.sponentry must return a pointer to the stack", &
Call);
7021 case Intrinsic::write_volatile_register: {
7025 "llvm.write_volatile_register metadata must be a single MDString",
7029 case Intrinsic::ptrauth_auth_with_pc_and_resign: {
7032 uint64_t
Key = AuthKey->getZExtValue();
7034 "ptrauth.auth.with.pc.and.resign key must be IA (0) or IB (1)",
7043 if (
F->hasPersonalityFn() &&
7047 if (BlockEHFuncletColors.
empty())
7051 bool InEHFunclet =
false;
7055 for (BasicBlock *ColorFirstBB : CV)
7056 if (
auto It = ColorFirstBB->getFirstNonPHIIt();
7057 It != ColorFirstBB->end())
7062 bool HasToken =
false;
7069 Check(HasToken,
"Missing funclet token on intrinsic call", &
Call);
7096void Verifier::visit(DbgLabelRecord &DLR) {
7098 "invalid #dbg_label intrinsic variable", &DLR, DLR.
getRawLabel());
7111 CheckDI(Loc,
"#dbg_label record requires a !dbg attachment", &DLR, BB,
F);
7115 if (!LabelSP || !LocSP)
7119 "mismatched subprogram between #dbg_label label and !dbg attachment",
7120 &DLR, BB,
F, Label,
Label->getScope()->getSubprogram(), Loc,
7121 Loc->getScope()->getSubprogram());
7124void Verifier::visit(DbgVariableRecord &DVR) {
7128 CheckDI(DVR.
getType() == DbgVariableRecord::LocationType::Value ||
7129 DVR.
getType() == DbgVariableRecord::LocationType::Declare ||
7130 DVR.
getType() == DbgVariableRecord::LocationType::DeclareValue ||
7131 DVR.
getType() == DbgVariableRecord::LocationType::Assign,
7132 "invalid #dbg record type", &DVR, DVR.
getType(), BB,
F);
7140 "invalid #dbg record address/value", &DVR, MD, BB,
F);
7142 visitValueAsMetadata(*VAM,
F);
7145 Type *Ty = VAM->getValue()->getType();
7147 "location of #dbg_declare must be a pointer or int", &DVR, MD, BB,
7151 visitDIArgList(*AL,
F);
7165 "invalid #dbg_assign DIAssignID", &DVR, DVR.
getRawAssignID(), BB,
7168 AreDebugLocsAllowed::No);
7177 "invalid #dbg_assign address", &DVR, DVR.
getRawAddress(), BB,
F);
7179 visitValueAsMetadata(*VAM,
F);
7182 "invalid #dbg_assign address expression", &DVR,
7189 "inst not in same function as #dbg_assign",
I, &DVR, BB,
F);
7199 &DVR, DLNode, BB,
F);
7205 if (!VarSP || !LocSP)
7209 "mismatched subprogram between #dbg record variable and DILocation",
7211 Loc->getScope()->getSubprogram(), BB,
F);
7216void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
7220 Check(RetTy->getElementCount() == ValTy->getElementCount(),
7221 "VP cast intrinsic first argument and result vector lengths must be "
7225 switch (VPCast->getIntrinsicID()) {
7226 case Intrinsic::vp_trunc:
7228 "llvm.vp.trunc intrinsic the bit size of first argument must be "
7229 "larger than the bit size of the return type",
7232 case Intrinsic::vp_zext:
7233 case Intrinsic::vp_sext:
7235 "llvm.vp.zext or llvm.vp.sext intrinsic the bit size of first "
7236 "argument must be smaller than the bit size of the return type",
7239 case Intrinsic::vp_fptrunc:
7241 "llvm.vp.fptrunc intrinsic the bit size of first argument must be "
7242 "larger than the bit size of the return type",
7245 case Intrinsic::vp_fpext:
7247 "llvm.vp.fpext intrinsic the bit size of first argument must be "
7248 "smaller than the bit size of the return type",
7257 case Intrinsic::vp_fcmp: {
7260 "invalid predicate for VP FP comparison intrinsic", &VPI);
7263 case Intrinsic::vp_icmp: {
7266 "invalid predicate for VP integer comparison intrinsic", &VPI);
7269 case Intrinsic::vp_is_fpclass: {
7272 "unsupported bits for llvm.vp.is.fpclass test mask");
7275 case Intrinsic::experimental_vp_splice: {
7278 int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
7280 AttributeList
Attrs = VPI.
getParent()->getParent()->getAttributes();
7281 if (
Attrs.hasFnAttr(Attribute::VScaleRange))
7282 KnownMinNumElements *=
Attrs.getFnAttrs().getVScaleRangeMin();
7284 Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
7285 (Idx >= 0 && Idx < KnownMinNumElements),
7286 "The splice index exceeds the range [-VL, VL-1] where VL is the "
7287 "known minimum number of elements in the vector. For scalable "
7288 "vectors the minimum number of elements is determined from "
7296void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
7298 bool HasRoundingMD =
7302 NumOperands += (1 + HasRoundingMD);
7308 "invalid arguments for constrained FP intrinsic", &FPI);
7311 case Intrinsic::experimental_constrained_fcmp:
7312 case Intrinsic::experimental_constrained_fcmps: {
7315 "invalid predicate for constrained FP comparison intrinsic", &FPI);
7319 case Intrinsic::experimental_constrained_fptosi:
7320 case Intrinsic::experimental_constrained_fptoui: {
7324 "Intrinsic first argument must be floating point", &FPI);
7331 "Intrinsic first argument and result disagree on vector use", &FPI);
7333 "Intrinsic result must be an integer", &FPI);
7336 "Intrinsic first argument and result vector lengths must be equal",
7342 case Intrinsic::experimental_constrained_sitofp:
7343 case Intrinsic::experimental_constrained_uitofp: {
7347 "Intrinsic first argument must be integer", &FPI);
7354 "Intrinsic first argument and result disagree on vector use", &FPI);
7356 "Intrinsic result must be a floating point", &FPI);
7359 "Intrinsic first argument and result vector lengths must be equal",
7365 case Intrinsic::experimental_constrained_fptrunc:
7366 case Intrinsic::experimental_constrained_fpext: {
7372 "Intrinsic first argument must be FP or FP vector", &FPI);
7374 "Intrinsic result must be FP or FP vector", &FPI);
7376 "Intrinsic first argument and result disagree on vector use", &FPI);
7380 "Intrinsic first argument and result vector lengths must be equal",
7383 if (FPI.
getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
7385 "Intrinsic first argument's type must be larger than result type",
7389 "Intrinsic first argument's type must be smaller than result type",
7405 "invalid exception behavior argument", &FPI);
7406 if (HasRoundingMD) {
7412void Verifier::verifyFragmentExpression(
const DbgVariableRecord &DVR) {
7417 if (!V || !
E || !
E->isValid())
7421 auto Fragment =
E->getFragmentInfo();
7431 if (
V->isArtificial())
7434 verifyFragmentExpression(*V, *Fragment, &DVR);
7437template <
typename ValueOrMetadata>
7438void Verifier::verifyFragmentExpression(
const DIVariable &V,
7440 ValueOrMetadata *
Desc) {
7443 auto VarSize =
V.getSizeInBits();
7449 CheckDI(FragSize + FragOffset <= *VarSize,
7450 "fragment is larger than or outside of variable",
Desc, &V);
7451 CheckDI(FragSize != *VarSize,
"fragment covers entire variable",
Desc, &V);
7454void Verifier::verifyFnArgs(
const DbgVariableRecord &DVR) {
7466 CheckDI(Var,
"#dbg record without variable");
7468 unsigned ArgNo = Var->
getArg();
7474 if (DebugFnArgs.
size() < ArgNo)
7475 DebugFnArgs.
resize(ArgNo,
nullptr);
7477 auto *Prev = DebugFnArgs[ArgNo - 1];
7478 DebugFnArgs[ArgNo - 1] = Var;
7479 CheckDI(!Prev || (Prev == Var),
"conflicting debug info for argument", &DVR,
7483void Verifier::verifyNotEntryValue(
const DbgVariableRecord &DVR) {
7487 if (!
E || !
E->isValid())
7497 ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
7502 "Entry values are only allowed in MIR unless they target a "
7503 "swiftasync Argument",
7507void Verifier::verifyCompileUnits() {
7511 if (
M.getContext().isODRUniquingDebugTypes())
7513 auto *CUs =
M.getNamedMetadata(
"llvm.dbg.cu");
7514 SmallPtrSet<const Metadata *, 2> Listed;
7517 for (
const auto *CU : CUVisited)
7518 CheckDI(Listed.
count(CU),
"DICompileUnit not listed in llvm.dbg.cu", CU);
7522void Verifier::verifyDeoptimizeCallingConvs() {
7523 if (DeoptimizeDeclarations.
empty())
7527 for (
const auto *
F :
ArrayRef(DeoptimizeDeclarations).slice(1)) {
7528 Check(
First->getCallingConv() ==
F->getCallingConv(),
7529 "All llvm.experimental.deoptimize declarations must have the same "
7530 "calling convention",
7535void Verifier::verifyAttachedCallBundle(
const CallBase &
Call,
7536 const OperandBundleUse &BU) {
7539 Check((FTy->getReturnType()->isPointerTy() ||
7541 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
7542 "function returning a pointer or a non-returning function that has a "
7547 "operand bundle \"clang.arc.attachedcall\" requires one function as "
7555 Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
7556 IID == Intrinsic::objc_claimAutoreleasedReturnValue ||
7557 IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
7558 "invalid function argument",
Call);
7560 StringRef FnName = Fn->getName();
7561 Check((FnName ==
"objc_retainAutoreleasedReturnValue" ||
7562 FnName ==
"objc_claimAutoreleasedReturnValue" ||
7563 FnName ==
"objc_unsafeClaimAutoreleasedReturnValue"),
7564 "invalid function argument",
Call);
7568void Verifier::verifyNoAliasScopeDecl() {
7569 if (NoAliasScopeDecls.
empty())
7573 for (
auto *
II : NoAliasScopeDecls) {
7574 assert(
II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
7575 "Not a llvm.experimental.noalias.scope.decl ?");
7578 Check(ScopeListMV !=
nullptr,
7579 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
7584 Check(ScopeListMD !=
nullptr,
"!id.scope.list must point to an MDNode",
II);
7585 Check(ScopeListMD->getNumOperands() == 1,
7586 "!id.scope.list must point to a list with a single scope",
II);
7587 visitAliasScopeListMetadata(ScopeListMD);
7597 auto GetScope = [](IntrinsicInst *
II) {
7600 return &
cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
7605 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
7606 return GetScope(Lhs) < GetScope(Rhs);
7613 auto ItCurrent = NoAliasScopeDecls.begin();
7614 while (ItCurrent != NoAliasScopeDecls.end()) {
7615 auto CurScope = GetScope(*ItCurrent);
7616 auto ItNext = ItCurrent;
7619 }
while (ItNext != NoAliasScopeDecls.end() &&
7620 GetScope(*ItNext) == CurScope);
7625 if (ItNext - ItCurrent < 32)
7629 Check(!DT.dominates(
I, J),
7630 "llvm.experimental.noalias.scope.decl dominates another one "
7631 "with the same scope",
7645 Verifier V(OS,
true, *f.getParent());
7649 return !V.verify(
F);
7653 bool *BrokenDebugInfo) {
7655 Verifier V(OS, !BrokenDebugInfo, M);
7657 bool Broken =
false;
7659 Broken |= !V.verify(
F);
7661 Broken |= !V.verify();
7662 if (BrokenDebugInfo)
7663 *BrokenDebugInfo = V.hasBrokenDebugInfo();
7674 std::unique_ptr<Verifier> V;
7675 bool FatalErrors =
true;
7678 explicit VerifierLegacyPass(
bool FatalErrors)
7679 : FunctionPass(
ID), FatalErrors(FatalErrors) {}
7681 bool doInitialization(
Module &M)
override {
7682 V = std::make_unique<Verifier>(
7688 if (!
V->verify(
F) && FatalErrors) {
7689 errs() <<
"in function " <<
F.getName() <<
'\n';
7695 bool doFinalization(
Module &M)
override {
7696 bool HasErrors =
false;
7697 for (Function &
F : M)
7698 if (
F.isDeclaration())
7699 HasErrors |= !
V->verify(
F);
7701 HasErrors |= !
V->verify();
7702 if (FatalErrors && (HasErrors ||
V->hasBrokenDebugInfo()))
7707 void getAnalysisUsage(AnalysisUsage &AU)
const override {
7715template <
typename... Tys>
void TBAAVerifier::CheckFailed(Tys &&... Args) {
7717 return Diagnostic->CheckFailed(
Args...);
7720#define CheckTBAA(C, ...) \
7723 CheckFailed(__VA_ARGS__); \
7731TBAAVerifier::TBAABaseNodeSummary
7735 CheckFailed(
"Base nodes must have at least two operands",
I, BaseNode);
7739 auto Itr = TBAABaseNodes.find(BaseNode);
7740 if (Itr != TBAABaseNodes.end())
7743 auto Result = verifyTBAABaseNodeImpl(
I, BaseNode, IsNewFormat);
7744 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
7746 assert(InsertResult.second &&
"We just checked!");
7750TBAAVerifier::TBAABaseNodeSummary
7751TBAAVerifier::verifyTBAABaseNodeImpl(
const Instruction *
I,
7752 const MDNode *BaseNode,
bool IsNewFormat) {
7753 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {
true, ~0
u};
7757 return isValidScalarTBAANode(BaseNode)
7758 ? TBAAVerifier::TBAABaseNodeSummary({
false, 0})
7764 CheckFailed(
"Access tag nodes must have the number of operands that is a "
7765 "multiple of 3!", BaseNode);
7770 CheckFailed(
"Struct tag nodes must have an odd number of operands!",
7780 if (!TypeSizeNode) {
7781 CheckFailed(
"Type size nodes must be constants!",
I, BaseNode);
7788 CheckFailed(
"Struct tag nodes have a string as their first operand",
7795 std::optional<APInt> PrevOffset;
7800 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
7801 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
7802 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
7803 Idx += NumOpsPerField) {
7804 const MDOperand &FieldTy = BaseNode->
getOperand(Idx);
7805 const MDOperand &FieldOffset = BaseNode->
getOperand(Idx + 1);
7807 CheckFailed(
"Incorrect field entry in struct type node!",
I, BaseNode);
7812 auto *OffsetEntryCI =
7814 if (!OffsetEntryCI) {
7815 CheckFailed(
"Offset entries must be constants!",
I, BaseNode);
7821 BitWidth = OffsetEntryCI->getBitWidth();
7823 if (OffsetEntryCI->getBitWidth() !=
BitWidth) {
7825 "Bitwidth between the offsets and struct type entries must match",
I,
7837 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
7840 CheckFailed(
"Offsets must be increasing!",
I, BaseNode);
7844 PrevOffset = OffsetEntryCI->getValue();
7849 if (!MemberSizeNode) {
7850 CheckFailed(
"Member size entries must be constants!",
I, BaseNode);
7857 return Failed ? InvalidNode
7858 : TBAAVerifier::TBAABaseNodeSummary(
false,
BitWidth);
7880 return Parent && Visited.
insert(Parent).second &&
7884bool TBAAVerifier::isValidScalarTBAANode(
const MDNode *MD) {
7885 auto ResultIt = TBAAScalarNodes.find(MD);
7886 if (ResultIt != TBAAScalarNodes.end())
7887 return ResultIt->second;
7889 SmallPtrSet<const MDNode *, 4> Visited;
7891 auto InsertResult = TBAAScalarNodes.insert({MD,
Result});
7893 assert(InsertResult.second &&
"Just checked!");
7902MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(
const Instruction *
I,
7903 const MDNode *BaseNode,
7914 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
7915 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
7916 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
7917 Idx += NumOpsPerField) {
7918 auto *OffsetEntryCI =
7920 if (OffsetEntryCI->getValue().ugt(
Offset)) {
7921 if (Idx == FirstFieldOpNo) {
7922 CheckFailed(
"Could not find TBAA parent in struct type node",
I,
7927 unsigned PrevIdx = Idx - NumOpsPerField;
7928 auto *PrevOffsetEntryCI =
7930 Offset -= PrevOffsetEntryCI->getValue();
7938 Offset -= LastOffsetEntryCI->getValue();
7943 if (!
Type ||
Type->getNumOperands() < 3)
7959 "This instruction shall not have a TBAA access tag!",
I);
7961 bool IsStructPathTBAA =
7965 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
7975 "Access tag metadata must have either 4 or 5 operands",
I, MD);
7978 "Struct tag metadata must have either 3 or 4 operands",
I, MD);
7985 CheckTBAA(AccessSizeNode,
"Access size field must be a constant",
I, MD);
7989 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
7994 "Immutability tag on struct tag metadata must be a constant",
I,
7997 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
7998 "Immutability part of the struct tag metadata must be either 0 or 1",
I,
8003 "Malformed struct tag metadata: base and access-type "
8004 "should be non-null and point to Metadata nodes",
8005 I, MD, BaseNode, AccessType);
8008 CheckTBAA(isValidScalarTBAANode(AccessType),
8009 "Access type node must be a valid scalar type",
I, MD,
8014 CheckTBAA(OffsetCI,
"Offset must be constant integer",
I, MD);
8017 bool SeenAccessTypeInPath =
false;
8023 getFieldNodeFromTBAABaseNode(
I, BaseNode,
Offset, IsNewFormat)) {
8024 if (!StructPath.
insert(BaseNode).second) {
8025 CheckFailed(
"Cycle detected in struct path",
I, MD);
8030 unsigned BaseNodeBitWidth;
8031 std::tie(
Invalid, BaseNodeBitWidth) =
8032 verifyTBAABaseNode(
I, BaseNode, IsNewFormat);
8039 SeenAccessTypeInPath |= BaseNode == AccessType;
8041 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
8046 (BaseNodeBitWidth == 0 &&
Offset == 0) ||
8047 (IsNewFormat && BaseNodeBitWidth == ~0u),
8048 "Access bit-width not the same as description bit-width",
I, MD,
8049 BaseNodeBitWidth,
Offset.getBitWidth());
8051 if (IsNewFormat && SeenAccessTypeInPath)
8055 CheckTBAA(SeenAccessTypeInPath,
"Did not see access type in access path!",
I,
8060char VerifierLegacyPass::ID = 0;
8061INITIALIZE_PASS(VerifierLegacyPass,
"verify",
"Module Verifier",
false,
false)
8064 return new VerifierLegacyPass(FatalErrors);
8082 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
8090 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 void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
verify safepoint Safepoint IR Verifier
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static bool IsScalarTBAANodeImpl(const MDNode *MD, SmallPtrSetImpl< const MDNode * > &Visited)
static bool isType(const Metadata *MD)
static Instruction * getSuccPad(Instruction *Terminator)
static bool isMDTuple(const Metadata *MD)
static bool isNewFormatTBAATypeNode(llvm::MDNode *Type)
#define CheckDI(C,...)
We know that a debug info condition should be true, if not print an error message.
static void forEachUser(const Value *User, SmallPtrSet< const Value *, 32 > &Visited, llvm::function_ref< bool(const Value *)> Callback)
static bool isDINode(const Metadata *MD)
static bool isSupportedCallBrIntrinsic(Intrinsic::ID ID)
static bool isScope(const Metadata *MD)
static cl::opt< bool > VerifyNoAliasScopeDomination("verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false), cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical " "scopes are not dominating"))
static bool IsRootTBAANode(const MDNode *MD)
static Value * getParentPad(Value *EHPad)
static bool hasConflictingReferenceFlags(unsigned Flags)
Detect mutually exclusive flags.
static AttrBuilder getParameterABIAttributes(LLVMContext &C, unsigned I, AttributeList Attrs)
static const char PassName[]
static LLVM_ABI bool isValidArbitraryFPFormat(StringRef Format)
Returns true if the given string is a valid arbitrary floating-point format interpretation for llvm....
static LLVM_ABI unsigned getArbitraryFPFormatSizeInBits(StringRef Format)
Returns the size in bits of a valid arbitrary floating-point format string, or 0 if the string is not...
bool isFiniteNonZero() const
const fltSemantics & getSemantics() const
Class for arbitrary precision integers.
bool sgt(const APInt &RHS) const
Signed greater than comparison.
bool isMinValue() const
Determine if this is the smallest unsigned value.
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
bool isMaxValue() const
Determine if this is the largest unsigned value.
This class represents a conversion between pointers from one address space to another.
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
const Value * getArraySize() const
Get the number of elements allocated.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void setPreservesAll()
Set by analyses that do not transform their input at all.
bool isElementwise() const
Return true if this RMW has elementwise vector semantics.
static bool isFPOperation(BinOp Op)
BinOp getOperation() const
static LLVM_ABI StringRef getOperationName(BinOp Op)
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
LLVM_ABI const ConstantRange & getValueAsConstantRange() const
Return the attribute's value as a ConstantRange.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
bool isValid() const
Return true if the attribute is any kind of attribute.
LLVM_ABI Type * getValueAsType() const
Return the attribute's value as a Type.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
const Instruction & front() const
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
This class represents a no-op cast from one type to another.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isInlineAsm() const
Check if this call is an inline asm statement.
auto operand_bundles() const
bool hasInAllocaArgument() const
Determine if there are is an inalloca argument.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool doesNotAccessMemory(unsigned OpNo) const
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Get the attribute of a given kind from a given arg.
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Type * getParamElementType(unsigned ArgNo) const
Extract the elementtype type for a parameter.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
bool doesNotReturn() const
Determine if the call cannot return.
LLVM_ABI bool onlyAccessesArgMemory() const
Determine if the call can access memmory only using pointers based on its arguments.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
bool isMustTailCall() const
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
unsigned getNumHandlers() const
return the number of 'handlers' in this catchswitch instruction, except the default handler
Value * getParentPad() const
BasicBlock * getUnwindDest() const
handler_range handlers()
iteration adapter for range-for loops.
BasicBlock * getUnwindDest() const
bool isFPPredicate() const
bool isIntPredicate() const
static bool isIntPredicate(Predicate P)
Value * getCondition() const
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
const APInt & getValue() const
Return the constant as an APInt value reference.
Constant * getAddrDiscriminator() const
The address discriminator if any, or the null constant.
Constant * getPointer() const
The pointer that is signed in this ptrauth signed pointer.
ConstantInt * getKey() const
The Key ID, an i32 constant.
Constant * getDeactivationSymbol() const
ConstantInt * getDiscriminator() const
The integer discriminator, an i64 constant, or 0.
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
This class represents a range of values.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI std::optional< RoundingMode > getRoundingMode() const
LLVM_ABI unsigned getNonMetadataArgCount() const
DbgVariableFragmentInfo FragmentInfo
@ FixedPointBinary
Scale factor 2^Factor.
@ FixedPointDecimal
Scale factor 10^Factor.
@ FixedPointRational
Arbitrary rational scale factor.
DIGlobalVariable * getVariable() const
DIExpression * getExpression() const
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
DILocalScope * getScope() const
Get the local scope for this variable.
Metadata * getRawScope() const
Base class for scope-like contexts.
Subprogram description. Uses SubclassData1.
static LLVM_ABI const DIScope * getRawRetainedNodeScope(const MDNode *N)
Base class for template parameters.
Base class for variables.
Metadata * getRawType() const
Metadata * getRawScope() const
uint64_t getNumOperands() const
Records a position in IR for a source label (DILabel).
MDNode * getRawLabel() const
DILabel * getLabel() const
Base class for non-instruction debug metadata records that have positions within IR.
DebugLoc getDebugLoc() const
LLVM_ABI BasicBlock * getParent()
LLVM_ABI Function * getFunction()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LocationType getType() const
MDNode * getRawExpression() const
MDNode * getRawAddressExpression() const
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
DIExpression * getExpression() const
Metadata * getRawAssignID() const
MDNode * getRawVariable() const
DILocalVariable * getVariable() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
bool isDbgDeclare() const
Metadata * getRawAddress() const
DIExpression * getAddressExpression() const
LLVM_ABI MDNode * getAsMDNode() const
Return this as a bar MDNode.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
This instruction compares its operands according to the predicate given to the constructor.
This class represents an extension of floating point types.
static bool isSupportedFloatingPointType(Type *Ty)
Returns true if Ty is a supported floating-point type for phi, select, or call FPMathOperators.
This class represents a cast from floating point to signed integer.
This class represents a cast from floating point to unsigned integer.
This class represents a truncation of floating point types.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
op_range arg_operands()
arg_operands - iteration adapter for range-for loops.
Value * getParentPad() const
Convenience accessors.
FunctionPass class - This class is used to implement most global optimizations.
Type * getReturnType() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool hasPersonalityFn() const
Check whether this function has a personality function.
const Function & getFunction() const
const std::string & getGC() const
Type * getReturnType() const
Returns the type of the ret val.
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
LLVM_ABI Value * getBasePtr() const
LLVM_ABI Value * getDerivedPtr() const
void visit(const BlockT &BB)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
const Constant * getAliasee() const
LLVM_ABI const Function * getResolverFunction() const
static bool isValidLinkage(LinkageTypes L)
const Constant * getResolver() const
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
bool hasExternalLinkage() const
bool isImplicitDSOLocal() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
bool hasValidDeclarationLinkage() const
LinkageTypes getLinkage() const
bool hasDefaultVisibility() const
bool hasPrivateLinkage() const
bool hasHiddenVisibility() const
bool hasExternalWeakLinkage() const
bool hasDLLImportStorageClass() const
bool hasDLLExportStorageClass() const
bool isDeclarationForLinker() const
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
bool hasCommonLinkage() const
bool hasGlobalUnnamedAddr() const
bool hasAppendingLinkage() const
bool hasAvailableExternallyLinkage() const
Type * getValueType() const
LLVM_ABI bool isInterposable(bool CheckNoIPA=true) const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
BasicBlock * getDestination(unsigned i)
Return the specified destination.
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
unsigned getNumSuccessors() const
This instruction inserts a single (scalar) element into a VectorType value.
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
Value * getAggregateOperand()
ArrayRef< unsigned > getIndices() const
Base class for instruction visitors.
void visit(Iterator Start, Iterator End)
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
This class represents a cast from an integer to a pointer.
static LLVM_ABI bool mayLowerToFunctionCall(Intrinsic::ID IID)
Check if the intrinsic might lower into a regular function call in the course of IR transformations.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
@ OB_clang_arc_attachedcall
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
Align getAlign() const
Return the alignment of the access that is being performed.
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
unsigned getNumOperands() const
Return number of MDNode operands.
bool isResolved() const
Check if node is fully resolved.
LLVMContext & getContext() const
bool equalsStr(StringRef Str) const
LLVM_ABI StringRef getString() const
This class implements a map that also provides access to all stored values in a deterministic order.
A Module instance is used to store all the information related to an LLVM module.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
LLVM_ABI StringRef getName() const
LLVM_ABI unsigned getNumOperands() const
iterator_range< op_iterator > operands()
op_range incoming_values()
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
This class represents a cast from a pointer to an address (non-capturing ptrtoint).
This class represents a cast from a pointer to an integer.
Value * getValue() const
Convenience accessor.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents a sign extension of integer types.
This class represents a cast from signed integer to floating point.
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
This instruction constructs a fixed permutation of two input vectors.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
static constexpr size_t npos
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
Check if the string is empty.
std::pair< typename Base::iterator, bool > insert(StringRef key)
Verify that the TBAA Metadatas are valid.
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isByteTy() const
True if this is an instance of ByteType.
bool isVectorTy() const
True if this is an instance of VectorType.
LLVM_ABI bool containsNonGlobalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a global...
LLVM_ABI bool containsNonLocalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a local.
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
LLVM_ABI bool isTokenLikeTy() const
Returns true if this is 'token' or a token-like target type.s.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
LLVM_ABI bool canLosslesslyBitCastTo(Type *Ty) const
Return true if this type could be converted with a lossless BitCast to type 'Ty'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
This class represents a cast unsigned integer to floating point.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
iterator_range< user_iterator > materialized_users()
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
iterator_range< user_iterator > users()
bool materialized_use_empty() const
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Check a module for errors, and report separate error states for IR and debug info errors.
LLVM_ABI Result run(Module &M, ModuleAnalysisManager &)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
This class represents zero extension of integer types.
std::pair< iterator, bool > insert(const ValueT &V)
constexpr bool isNonZero() const
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
This class implements an extremely fast bulk output stream that can only output to a stream.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
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.
unsigned getNumElements(Type *Ty)
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)
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
GenericConvergenceVerifier< SSAContext > ConvergenceVerifier
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
bool isModSet(const ModRefInfo MRI)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void verifyAMDGPUIntrinsicCall(VerifierSupport &VS, Intrinsic::ID ID, CallBase &Call)
bool isPointerTy(const Type *T)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
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.