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 "
1016 "Expected one operand for llvm.loop.distribute metadata",
1022 Check(CurrentMD->
isResolved(),
"All nodes should be resolved!", CurrentMD);
1026void Verifier::visitValueAsMetadata(
const ValueAsMetadata &MD, Function *
F) {
1029 "Unexpected metadata round-trip through values", &MD, MD.
getValue());
1035 Check(
F,
"function-local metadata used outside a function", L);
1041 Check(
I->getParent(),
"function-local metadata not in basic block", L,
I);
1048 assert(ActualF &&
"Unimplemented function local metadata case!");
1050 Check(ActualF ==
F,
"function-local metadata used in wrong function", L);
1053void Verifier::visitDIArgList(
const DIArgList &AL, Function *
F) {
1054 for (
const ValueAsMetadata *VAM :
AL.getArgs())
1055 visitValueAsMetadata(*VAM,
F);
1058void Verifier::visitMetadataAsValue(
const MetadataAsValue &MDV, Function *
F) {
1061 visitMDNode(*
N, AreDebugLocsAllowed::No);
1067 if (!MDNodes.
insert(MD).second)
1071 visitValueAsMetadata(*V,
F);
1074 visitDIArgList(*AL,
F);
1082void Verifier::visitDILocation(
const DILocation &
N) {
1084 "location requires a valid scope", &
N,
N.getRawScope());
1085 if (
auto *IA =
N.getRawInlinedAt())
1088 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1091void Verifier::visitGenericDINode(
const GenericDINode &
N) {
1095void Verifier::visitDIScope(
const DIScope &
N) {
1096 if (
auto *
F =
N.getRawFile())
1100void Verifier::visitDIType(
const DIType &
N) {
1103 CheckDI(
N.getRawFile() ||
N.getLine() == 0,
"line specified with no file", &
N,
1107void Verifier::visitDISubrangeType(
const DISubrangeType &
N) {
1110 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1113 auto *LBound =
N.getRawLowerBound();
1117 "LowerBound must be signed constant or DIVariable or DIExpression or "
1120 auto *UBound =
N.getRawUpperBound();
1124 "UpperBound must be signed constant or DIVariable or DIExpression or "
1127 auto *Stride =
N.getRawStride();
1130 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1131 auto *Bias =
N.getRawBias();
1134 "Bias must be signed constant or DIVariable or DIExpression", &
N);
1136 auto *
Size =
N.getRawSizeInBits();
1138 "SizeInBits must be a constant");
1141void Verifier::visitDISubrange(
const DISubrange &
N) {
1142 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1143 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1144 "Subrange can have any one of count or upperBound", &
N);
1145 auto *CBound =
N.getRawCountNode();
1148 "Count must be signed constant or DIVariable or DIExpression", &
N);
1149 auto Count =
N.getCount();
1152 "invalid subrange count", &
N);
1153 auto *LBound =
N.getRawLowerBound();
1156 "LowerBound must be signed constant or DIVariable or DIExpression",
1158 auto *UBound =
N.getRawUpperBound();
1161 "UpperBound must be signed constant or DIVariable or DIExpression",
1163 auto *Stride =
N.getRawStride();
1166 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1169void Verifier::visitDIGenericSubrange(
const DIGenericSubrange &
N) {
1170 CheckDI(
N.getTag() == dwarf::DW_TAG_generic_subrange,
"invalid tag", &
N);
1171 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1172 "GenericSubrange can have any one of count or upperBound", &
N);
1173 auto *CBound =
N.getRawCountNode();
1175 "Count must be signed constant or DIVariable or DIExpression", &
N);
1176 auto *LBound =
N.getRawLowerBound();
1177 CheckDI(LBound,
"GenericSubrange must contain lowerBound", &
N);
1179 "LowerBound must be signed constant or DIVariable or DIExpression",
1181 auto *UBound =
N.getRawUpperBound();
1183 "UpperBound must be signed constant or DIVariable or DIExpression",
1185 auto *Stride =
N.getRawStride();
1186 CheckDI(Stride,
"GenericSubrange must contain stride", &
N);
1188 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1191void Verifier::visitDIEnumerator(
const DIEnumerator &
N) {
1192 CheckDI(
N.getTag() == dwarf::DW_TAG_enumerator,
"invalid tag", &
N);
1195void Verifier::visitDIBasicType(
const DIBasicType &
N) {
1198 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type ||
1199 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1200 N.getTag() == dwarf::DW_TAG_string_type,
1203 auto *
Size =
N.getRawSizeInBits();
1205 "SizeInBits must be a constant");
1208void Verifier::visitDIFixedPointType(
const DIFixedPointType &
N) {
1209 visitDIBasicType(
N);
1211 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type,
"invalid tag", &
N);
1212 CheckDI(
N.getEncoding() == dwarf::DW_ATE_signed_fixed ||
1213 N.getEncoding() == dwarf::DW_ATE_unsigned_fixed,
1214 "invalid encoding", &
N);
1218 "invalid kind", &
N);
1220 N.getFactorRaw() == 0,
1221 "factor should be 0 for rationals", &
N);
1223 (
N.getNumeratorRaw() == 0 &&
N.getDenominatorRaw() == 0),
1224 "numerator and denominator should be 0 for non-rationals", &
N);
1227void Verifier::visitDIStringType(
const DIStringType &
N) {
1230 CheckDI(
N.getTag() == dwarf::DW_TAG_string_type,
"invalid tag", &
N);
1231 CheckDI(!(
N.isBigEndian() &&
N.isLittleEndian()),
"has conflicting flags",
1235void Verifier::visitDIDerivedType(
const DIDerivedType &
N) {
1239 CheckDI(
N.getTag() == dwarf::DW_TAG_typedef ||
1240 N.getTag() == dwarf::DW_TAG_pointer_type ||
1241 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1242 N.getTag() == dwarf::DW_TAG_reference_type ||
1243 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1244 N.getTag() == dwarf::DW_TAG_const_type ||
1245 N.getTag() == dwarf::DW_TAG_immutable_type ||
1246 N.getTag() == dwarf::DW_TAG_volatile_type ||
1247 N.getTag() == dwarf::DW_TAG_restrict_type ||
1248 N.getTag() == dwarf::DW_TAG_atomic_type ||
1249 N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
1250 N.getTag() == dwarf::DW_TAG_member ||
1251 (
N.getTag() == dwarf::DW_TAG_variable &&
N.isStaticMember()) ||
1252 N.getTag() == dwarf::DW_TAG_inheritance ||
1253 N.getTag() == dwarf::DW_TAG_friend ||
1254 N.getTag() == dwarf::DW_TAG_set_type ||
1255 N.getTag() == dwarf::DW_TAG_template_alias,
1257 if (
N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1258 CheckDI(
isType(
N.getRawExtraData()),
"invalid pointer to member type", &
N,
1259 N.getRawExtraData());
1260 }
else if (
N.getTag() == dwarf::DW_TAG_template_alias) {
1262 N.getRawExtraData());
1263 }
else if (
N.getTag() == dwarf::DW_TAG_inheritance ||
1264 N.getTag() == dwarf::DW_TAG_member ||
1265 N.getTag() == dwarf::DW_TAG_variable) {
1266 auto *ExtraData =
N.getRawExtraData();
1267 auto IsValidExtraData = [&]() {
1268 if (ExtraData ==
nullptr)
1274 if (Tuple->getNumOperands() != 1)
1281 "extraData must be ConstantAsMetadata, MDString, DIObjCProperty, "
1282 "or MDTuple with single ConstantAsMetadata operand",
1286 if (
N.getTag() == dwarf::DW_TAG_set_type) {
1287 if (
auto *
T =
N.getRawBaseType()) {
1292 (Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1293 (Subrange &&
Subrange->getTag() == dwarf::DW_TAG_subrange_type) ||
1294 (
Basic && (
Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1295 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1296 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1297 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1298 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1299 "invalid set base type", &
N,
T);
1304 N.getRawBaseType());
1306 if (
N.getDWARFAddressSpace()) {
1307 CheckDI(
N.getTag() == dwarf::DW_TAG_pointer_type ||
1308 N.getTag() == dwarf::DW_TAG_reference_type ||
1309 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1310 "DWARF address space only applies to pointer or reference types",
1314 auto *
Size =
N.getRawSizeInBits();
1317 "SizeInBits must be a constant or DIVariable or DIExpression");
1322 return ((Flags & DINode::FlagLValueReference) &&
1323 (Flags & DINode::FlagRValueReference)) ||
1324 ((Flags & DINode::FlagTypePassByValue) &&
1325 (Flags & DINode::FlagTypePassByReference));
1328void Verifier::visitTemplateParams(
const MDNode &
N,
const Metadata &RawParams) {
1330 CheckDI(Params,
"invalid template params", &
N, &RawParams);
1337void Verifier::visitDICompositeType(
const DICompositeType &
N) {
1341 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type ||
1342 N.getTag() == dwarf::DW_TAG_structure_type ||
1343 N.getTag() == dwarf::DW_TAG_union_type ||
1344 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1345 N.getTag() == dwarf::DW_TAG_class_type ||
1346 N.getTag() == dwarf::DW_TAG_variant_part ||
1347 N.getTag() == dwarf::DW_TAG_variant ||
1348 N.getTag() == dwarf::DW_TAG_namelist,
1352 N.getRawBaseType());
1355 "invalid composite elements", &
N,
N.getRawElements());
1357 N.getRawVTableHolder());
1359 "invalid reference flags", &
N);
1360 unsigned DIBlockByRefStruct = 1 << 4;
1361 CheckDI((
N.getFlags() & DIBlockByRefStruct) == 0,
1362 "DIBlockByRefStruct on DICompositeType is no longer supported", &
N);
1364 "DISubprogram contains null entry in `elements` field", &
N);
1367 const DINodeArray
Elements =
N.getElements();
1369 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1370 "invalid vector, expected one element of type subrange", &
N);
1373 if (
auto *Params =
N.getRawTemplateParams())
1374 visitTemplateParams(
N, *Params);
1376 if (
auto *
D =
N.getRawDiscriminator()) {
1378 "discriminator can only appear on variant part");
1381 if (
N.getRawDataLocation()) {
1382 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1383 "dataLocation can only appear in array type");
1386 if (
N.getRawAssociated()) {
1387 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1388 "associated can only appear in array type");
1391 if (
N.getRawAllocated()) {
1392 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1393 "allocated can only appear in array type");
1396 if (
N.getRawRank()) {
1397 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1398 "rank can only appear in array type");
1401 if (
N.getTag() == dwarf::DW_TAG_array_type) {
1402 CheckDI(
N.getRawBaseType(),
"array types must have a base type", &
N);
1405 auto *
Size =
N.getRawSizeInBits();
1408 "SizeInBits must be a constant or DIVariable or DIExpression");
1411void Verifier::visitDISubroutineType(
const DISubroutineType &
N) {
1413 CheckDI(
N.getTag() == dwarf::DW_TAG_subroutine_type,
"invalid tag", &
N);
1414 if (
auto *Types =
N.getRawTypeArray()) {
1416 for (
Metadata *Ty :
N.getTypeArray()->operands()) {
1417 CheckDI(
isType(Ty),
"invalid subroutine type ref", &
N, Types, Ty);
1421 "invalid reference flags", &
N);
1424void Verifier::visitDIFile(
const DIFile &
N) {
1425 CheckDI(
N.getTag() == dwarf::DW_TAG_file_type,
"invalid tag", &
N);
1426 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum =
N.getChecksum();
1428 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1429 "invalid checksum kind", &
N);
1431 switch (Checksum->Kind) {
1442 CheckDI(Checksum->Value.size() ==
Size,
"invalid checksum length", &
N);
1444 "invalid checksum", &
N);
1448void Verifier::visitDICompileUnit(
const DICompileUnit &
N) {
1449 CheckDI(
N.isDistinct(),
"compile units must be distinct", &
N);
1450 CheckDI(
N.getTag() == dwarf::DW_TAG_compile_unit,
"invalid tag", &
N);
1456 CheckDI(!
N.getFile()->getFilename().empty(),
"invalid filename", &
N,
1460 "invalid emission kind", &
N);
1463 "invalid language dialect", &
N);
1465 if (
auto *Array =
N.getRawEnumTypes()) {
1467 for (
Metadata *
Op :
N.getEnumTypes()->operands()) {
1469 CheckDI(Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1470 "invalid enum type", &
N,
N.getEnumTypes(),
Op);
1472 "function-local enum in a DICompileUnit's enum list", &
N,
1473 N.getEnumTypes(),
Op);
1476 if (
auto *Array =
N.getRawRetainedTypes()) {
1478 for (
Metadata *
Op :
N.getRetainedTypes()->operands()) {
1482 "invalid retained type", &
N,
Op);
1485 if (
auto *Array =
N.getRawGlobalVariables()) {
1487 for (
Metadata *
Op :
N.getGlobalVariables()->operands()) {
1489 CheckDI(GVE,
"invalid global variable ref", &
N,
Op);
1491 "function-local variables are not allowed in a DICompileUnit's "
1492 "global variables list",
1496 if (
auto *Array =
N.getRawImportedEntities()) {
1498 for (
Metadata *
Op :
N.getImportedEntities()->operands()) {
1500 CheckDI(IE,
"invalid imported entity ref", &
N,
Op);
1502 "function-local imports are not allowed in a DICompileUnit's "
1503 "imported entities list",
1507 if (
auto *Array =
N.getRawMacros()) {
1516void Verifier::visitDISubprogram(
const DISubprogram &
N) {
1517 CheckDI(
N.getTag() == dwarf::DW_TAG_subprogram,
"invalid tag", &
N);
1519 if (
auto *
F =
N.getRawFile())
1522 CheckDI(
N.getLine() == 0,
"line specified with no file", &
N,
N.getLine());
1523 auto *
T =
N.getRawType();
1524 CheckDI(
T,
"DISubprogram requires a non-null type", &
N);
1526 CheckDI(
isType(
N.getRawContainingType()),
"invalid containing type", &
N,
1527 N.getRawContainingType());
1528 if (
auto *Params =
N.getRawTemplateParams())
1529 visitTemplateParams(
N, *Params);
1530 if (
auto *S =
N.getRawDeclaration())
1532 "invalid subprogram declaration", &
N, S);
1533 if (
auto *RawNode =
N.getRawRetainedNodes()) {
1535 CheckDI(Node,
"invalid retained nodes list", &
N, RawNode);
1537 DenseMap<unsigned, DILocalVariable *>
Args;
1539 CheckDI(
Op,
"nullptr in retained nodes", &
N, Node);
1541 auto True = [](
const Metadata *) {
return true; };
1542 auto False = [](
const Metadata *) {
return false; };
1543 bool IsTypeCorrect = DISubprogram::visitRetainedNode<bool>(
1544 Op, True, True, True, True, True, False);
1546 "invalid retained nodes, expected DILocalVariable, DILabel, "
1547 "DIImportedEntity, DIType or DIGlobalVariableExpression",
1554 "invalid retained nodes, retained node is not local", &
N, Node,
1557 DISubprogram *RetainedNodeSP = RetainedNodeScope->getSubprogram();
1558 DICompileUnit *RetainedNodeUnit =
1559 RetainedNodeSP ? RetainedNodeSP->getUnit() :
nullptr;
1561 RetainedNodeSP == &
N,
1562 "invalid retained nodes, retained node does not belong to subprogram",
1563 &
N, Node, RetainedNode, RetainedNodeScope, RetainedNodeSP,
1569 if (
unsigned ArgNum = DV->getArg()) {
1571 CheckDI(Inserted || DV == ArgI->second,
1572 "invalid retained nodes, more than one local variable with the "
1573 "same argument index",
1574 &
N,
N.getUnit(), Node, RetainedNode, Args[ArgNum]);
1579 "invalid reference flags", &
N);
1581 auto *
Unit =
N.getRawUnit();
1582 if (
N.isDefinition()) {
1584 CheckDI(
N.isDistinct(),
"subprogram definitions must be distinct", &
N);
1585 CheckDI(Unit,
"subprogram definitions must have a compile unit", &
N);
1590 if (CT && CT->getRawIdentifier() &&
1591 M.getContext().isODRUniquingDebugTypes())
1593 "definition subprograms cannot be nested within DICompositeType "
1594 "when enabling ODR",
1598 CheckDI(!Unit,
"subprogram declarations must not have a compile unit", &
N);
1600 "subprogram declaration must not have a declaration field");
1603 if (
auto *RawThrownTypes =
N.getRawThrownTypes()) {
1605 CheckDI(ThrownTypes,
"invalid thrown types list", &
N, RawThrownTypes);
1611 if (
N.areAllCallsDescribed())
1613 "DIFlagAllCallsDescribed must be attached to a definition");
1616void Verifier::visitDILexicalBlockBase(
const DILexicalBlockBase &
N) {
1617 CheckDI(
N.getTag() == dwarf::DW_TAG_lexical_block,
"invalid tag", &
N);
1619 "invalid local scope", &
N,
N.getRawScope());
1621 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1624void Verifier::visitDILexicalBlock(
const DILexicalBlock &
N) {
1625 visitDILexicalBlockBase(
N);
1628 "cannot have column info without line info", &
N);
1631void Verifier::visitDILexicalBlockFile(
const DILexicalBlockFile &
N) {
1632 visitDILexicalBlockBase(
N);
1635void Verifier::visitDICommonBlock(
const DICommonBlock &
N) {
1636 CheckDI(
N.getTag() == dwarf::DW_TAG_common_block,
"invalid tag", &
N);
1637 if (
auto *S =
N.getRawScope())
1639 if (
auto *S =
N.getRawDecl())
1643void Verifier::visitDINamespace(
const DINamespace &
N) {
1644 CheckDI(
N.getTag() == dwarf::DW_TAG_namespace,
"invalid tag", &
N);
1645 if (
auto *S =
N.getRawScope())
1649void Verifier::visitDIMacro(
const DIMacro &
N) {
1652 "invalid macinfo type", &
N);
1653 CheckDI(!
N.getName().empty(),
"anonymous macro", &
N);
1654 if (!
N.getValue().empty()) {
1655 assert(
N.getValue().data()[0] !=
' ' &&
"Macro value has a space prefix");
1659void Verifier::visitDIMacroFile(
const DIMacroFile &
N) {
1661 "invalid macinfo type", &
N);
1662 if (
auto *
F =
N.getRawFile())
1665 if (
auto *Array =
N.getRawElements()) {
1667 for (
Metadata *
Op :
N.getElements()->operands()) {
1673void Verifier::visitDIModule(
const DIModule &
N) {
1674 CheckDI(
N.getTag() == dwarf::DW_TAG_module,
"invalid tag", &
N);
1675 CheckDI(!
N.getName().empty(),
"anonymous module", &
N);
1678void Verifier::visitDITemplateParameter(
const DITemplateParameter &
N) {
1682void Verifier::visitDITemplateTypeParameter(
const DITemplateTypeParameter &
N) {
1683 visitDITemplateParameter(
N);
1685 CheckDI(
N.getTag() == dwarf::DW_TAG_template_type_parameter,
"invalid tag",
1689void Verifier::visitDITemplateValueParameter(
1690 const DITemplateValueParameter &
N) {
1691 visitDITemplateParameter(
N);
1693 CheckDI(
N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1694 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1695 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1699void Verifier::visitDIVariable(
const DIVariable &
N) {
1700 if (
auto *S =
N.getRawScope())
1702 if (
auto *
F =
N.getRawFile())
1706void Verifier::visitDIGlobalVariable(
const DIGlobalVariable &
N) {
1710 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1713 if (
N.isDefinition())
1714 CheckDI(
N.getType(),
"missing global variable type", &
N);
1715 if (
auto *Member =
N.getRawStaticDataMemberDeclaration()) {
1717 "invalid static data member declaration", &
N, Member);
1721void Verifier::visitDILocalVariable(
const DILocalVariable &
N) {
1726 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1728 "local variable requires a valid scope", &
N,
N.getRawScope());
1729 if (
auto Ty =
N.getType())
1733void Verifier::visitDIAssignID(
const DIAssignID &
N) {
1734 CheckDI(!
N.getNumOperands(),
"DIAssignID has no arguments", &
N);
1735 CheckDI(
N.isDistinct(),
"DIAssignID must be distinct", &
N);
1738void Verifier::visitDILabel(
const DILabel &
N) {
1739 if (
auto *S =
N.getRawScope())
1741 if (
auto *
F =
N.getRawFile())
1744 CheckDI(
N.getTag() == dwarf::DW_TAG_label,
"invalid tag", &
N);
1746 "label requires a valid scope", &
N,
N.getRawScope());
1749void Verifier::visitDIExpression(
const DIExpression &
N) {
1750 CheckDI(
N.isValid(),
"invalid expression", &
N);
1753void Verifier::visitDIGlobalVariableExpression(
1754 const DIGlobalVariableExpression &GVE) {
1757 visitDIGlobalVariable(*Var);
1759 visitDIExpression(*Expr);
1760 if (
auto Fragment = Expr->getFragmentInfo())
1761 verifyFragmentExpression(*GVE.
getVariable(), *Fragment, &GVE);
1765void Verifier::visitDIObjCProperty(
const DIObjCProperty &
N) {
1766 CheckDI(
N.getTag() == dwarf::DW_TAG_APPLE_property,
"invalid tag", &
N);
1767 if (
auto *
T =
N.getRawType())
1769 if (
auto *
F =
N.getRawFile())
1773void Verifier::visitDIImportedEntity(
const DIImportedEntity &
N) {
1774 CheckDI(
N.getTag() == dwarf::DW_TAG_imported_module ||
1775 N.getTag() == dwarf::DW_TAG_imported_declaration,
1777 if (
auto *S =
N.getRawScope())
1783void Verifier::visitComdat(
const Comdat &
C) {
1786 if (
TT.isOSBinFormatCOFF())
1787 if (
const GlobalValue *GV =
M.getNamedValue(
C.getName()))
1792void Verifier::visitModuleIdents() {
1793 const NamedMDNode *Idents =
M.getNamedMetadata(
"llvm.ident");
1799 for (
const MDNode *
N : Idents->
operands()) {
1800 Check(
N->getNumOperands() == 1,
1801 "incorrect number of operands in llvm.ident metadata",
N);
1803 (
"invalid value for llvm.ident metadata entry operand"
1804 "(the operand should be a string)"),
1809void Verifier::visitModuleCommandLines() {
1810 const NamedMDNode *CommandLines =
M.getNamedMetadata(
"llvm.commandline");
1817 for (
const MDNode *
N : CommandLines->
operands()) {
1818 Check(
N->getNumOperands() == 1,
1819 "incorrect number of operands in llvm.commandline metadata",
N);
1821 (
"invalid value for llvm.commandline metadata entry operand"
1822 "(the operand should be a string)"),
1827void Verifier::visitModuleErrnoTBAA() {
1828 const NamedMDNode *ErrnoTBAA =
M.getNamedMetadata(
"llvm.errno.tbaa");
1833 "llvm.errno.tbaa must have at least one operand", ErrnoTBAA);
1835 for (
const MDNode *
N : ErrnoTBAA->
operands())
1839void Verifier::visitModuleFlags() {
1840 const NamedMDNode *
Flags =
M.getModuleFlagsMetadata();
1844 DenseMap<const MDString*, const MDNode*> SeenIDs;
1848 std::optional<uint64_t> PAuthABIPlatform;
1849 std::optional<uint64_t> PAuthABIVersion;
1851 uint64_t HasPtrauthInitFini = 0;
1852 uint64_t HasPtrauthInitFiniAddr = 0;
1854 for (
const MDNode *MDN :
Flags->operands()) {
1855 visitModuleFlag(MDN, SeenIDs, Requirements);
1856 if (MDN->getNumOperands() != 3)
1860 auto GetFlagNamed = [&](StringRef
Name) -> std::optional<uint64_t> {
1861 if (FlagName->getString() != Name)
1862 return std::nullopt;
1863 if (
const auto *FlagValue =
1865 return FlagValue->getZExtValue();
1867 CheckFailed(Name +
": module flag expects integer value");
1868 return std::nullopt;
1871 if (
auto Value = GetFlagNamed(
"aarch64-elf-pauthabi-platform"))
1872 PAuthABIPlatform = *
Value;
1873 else if (
auto Value = GetFlagNamed(
"aarch64-elf-pauthabi-version"))
1874 PAuthABIVersion = *
Value;
1875 else if (
auto Value = GetFlagNamed(
"ptrauth-init-fini"))
1876 HasPtrauthInitFini = *
Value;
1877 else if (
auto Value =
1878 GetFlagNamed(
"ptrauth-init-fini-address-discrimination"))
1879 HasPtrauthInitFiniAddr = *
Value;
1884 "ptrauth-init-fini must be 0 or 1");
1886 "ptrauth-init-fini-address-discrimination must be 0 or 1, if set");
1887 if (HasPtrauthInitFiniAddr)
1888 Check(HasPtrauthInitFini,
"ptrauth-init-fini-address-discrimination module "
1889 "flag requires ptrauth-init-fini");
1891 if (PAuthABIPlatform.has_value() != PAuthABIVersion.has_value())
1892 CheckFailed(
"either both or no 'aarch64-elf-pauthabi-platform' and "
1893 "'aarch64-elf-pauthabi-version' module flags must be present");
1896 for (
const MDNode *Requirement : Requirements) {
1898 const Metadata *ReqValue = Requirement->getOperand(1);
1900 const MDNode *
Op = SeenIDs.
lookup(Flag);
1902 CheckFailed(
"invalid requirement on flag, flag is not present in module",
1907 if (
Op->getOperand(2) != ReqValue) {
1908 CheckFailed((
"invalid requirement on flag, "
1909 "flag does not have the required value"),
1917Verifier::visitModuleFlag(
const MDNode *
Op,
1918 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1919 SmallVectorImpl<const MDNode *> &Requirements) {
1923 "incorrect number of operands in module flag",
Op);
1924 Module::ModFlagBehavior MFB;
1925 if (!Module::isValidModFlagBehavior(
Op->getOperand(0), MFB)) {
1927 "invalid behavior operand in module flag (expected constant integer)",
1930 "invalid behavior operand in module flag (unexpected constant)",
1934 Check(
ID,
"invalid ID operand in module flag (expected metadata string)",
1940 case Module::Warning:
1941 case Module::Override:
1947 Check(V &&
V->getValue().isNonNegative(),
1948 "invalid value for 'min' module flag (expected constant non-negative "
1956 "invalid value for 'max' module flag (expected constant integer)",
1961 case Module::Require: {
1966 "invalid value for 'require' module flag (expected metadata pair)",
1969 (
"invalid value for 'require' module flag "
1970 "(first value operand should be a string)"),
1971 Value->getOperand(0));
1979 case Module::Append:
1980 case Module::AppendUnique: {
1983 "invalid value for 'append'-type module flag "
1984 "(expected a metadata node)",
1991 if (MFB != Module::Require) {
1994 "module flag identifiers must be unique (or of 'require' type)",
ID);
1997 if (
ID->getString() ==
"wchar_size") {
2000 Check(
Value,
"wchar_size metadata requires constant integer argument");
2003 if (
ID->getString() ==
"Linker Options") {
2007 Check(
M.getNamedMetadata(
"llvm.linker.options"),
2008 "'Linker Options' named metadata no longer supported");
2011 if (
ID->getString() ==
"SemanticInterposition") {
2012 ConstantInt *
Value =
2015 "SemanticInterposition metadata requires constant integer argument");
2018 if (
ID->getString() ==
"CG Profile") {
2019 for (
const MDOperand &MDO :
cast<MDNode>(
Op->getOperand(2))->operands())
2020 visitModuleFlagCGProfileEntry(MDO);
2027void Verifier::visitModuleFlagCGProfileEntry(
const MDOperand &MDO) {
2028 auto CheckFunction = [&](
const MDOperand &FuncMDO) {
2033 "expected a Function or null", FuncMDO);
2036 Check(Node &&
Node->getNumOperands() == 3,
"expected a MDNode triple", MDO);
2037 CheckFunction(
Node->getOperand(0));
2038 CheckFunction(
Node->getOperand(1));
2041 "expected an integer constant",
Node->getOperand(2));
2044void Verifier::verifyAttributeTypes(AttributeSet Attrs,
const Value *V) {
2047 if (
A.isStringAttribute()) {
2048#define GET_ATTR_NAMES
2049#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
2050#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
2051 if (A.getKindAsString() == #DISPLAY_NAME) { \
2052 auto V = A.getValueAsString(); \
2053 if (!(V.empty() || V == "true" || V == "false")) \
2054 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
2058#include "llvm/IR/Attributes.inc"
2062 if (
A.isIntAttribute() != Attribute::isIntAttrKind(
A.getKindAsEnum())) {
2063 CheckFailed(
"Attribute '" +
A.getAsString() +
"' should have an Argument",
2072void Verifier::verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
2074 if (!
Attrs.hasAttributes())
2077 verifyAttributeTypes(Attrs, V);
2080 Check(Attr.isStringAttribute() ||
2081 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
2082 "Attribute '" + Attr.getAsString() +
"' does not apply to parameters",
2085 if (
Attrs.hasAttribute(Attribute::ImmArg)) {
2086 unsigned AttrCount =
2087 Attrs.getNumAttributes() -
Attrs.hasAttribute(Attribute::Range);
2088 Check(AttrCount == 1,
2089 "Attribute 'immarg' is incompatible with other attributes except the "
2090 "'range' attribute",
2096 unsigned AttrCount = 0;
2097 AttrCount +=
Attrs.hasAttribute(Attribute::ByVal);
2098 AttrCount +=
Attrs.hasAttribute(Attribute::InAlloca);
2099 AttrCount +=
Attrs.hasAttribute(Attribute::Preallocated);
2100 AttrCount +=
Attrs.hasAttribute(Attribute::StructRet) ||
2101 Attrs.hasAttribute(Attribute::InReg);
2102 AttrCount +=
Attrs.hasAttribute(Attribute::Nest);
2103 AttrCount +=
Attrs.hasAttribute(Attribute::ByRef);
2104 Check(AttrCount <= 1,
2105 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
2106 "'byref', and 'sret' are incompatible!",
2109 Check(!(
Attrs.hasAttribute(Attribute::InAlloca) &&
2110 Attrs.hasAttribute(Attribute::ReadOnly)),
2112 "'inalloca and readonly' are incompatible!",
2115 Check(!(
Attrs.hasAttribute(Attribute::StructRet) &&
2116 Attrs.hasAttribute(Attribute::Returned)),
2118 "'sret and returned' are incompatible!",
2121 Check(!(
Attrs.hasAttribute(Attribute::ZExt) &&
2122 Attrs.hasAttribute(Attribute::SExt)),
2124 "'zeroext and signext' are incompatible!",
2127 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2128 Attrs.hasAttribute(Attribute::ReadOnly)),
2130 "'readnone and readonly' are incompatible!",
2133 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2134 Attrs.hasAttribute(Attribute::WriteOnly)),
2136 "'readnone and writeonly' are incompatible!",
2139 Check(!(
Attrs.hasAttribute(Attribute::ReadOnly) &&
2140 Attrs.hasAttribute(Attribute::WriteOnly)),
2142 "'readonly and writeonly' are incompatible!",
2145 Check(!(
Attrs.hasAttribute(Attribute::NoInline) &&
2146 Attrs.hasAttribute(Attribute::AlwaysInline)),
2148 "'noinline and alwaysinline' are incompatible!",
2151 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2152 Attrs.hasAttribute(Attribute::ReadNone)),
2153 "Attributes writable and readnone are incompatible!", V);
2155 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2156 Attrs.hasAttribute(Attribute::ReadOnly)),
2157 "Attributes writable and readonly are incompatible!", V);
2159 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty, Attrs);
2161 if (!Attr.isStringAttribute() &&
2162 IncompatibleAttrs.
contains(Attr.getKindAsEnum())) {
2163 CheckFailed(
"Attribute '" + Attr.getAsString() +
2164 "' applied to incompatible type!", V);
2170 if (
Attrs.hasAttribute(Attribute::Alignment)) {
2171 Align AttrAlign =
Attrs.getAlignment().valueOrOne();
2172 Check(AttrAlign.
value() <= Value::MaximumAlignment,
2173 "huge alignment values are unsupported", V);
2175 if (
Attrs.hasAttribute(Attribute::ByVal)) {
2177 SmallPtrSet<Type *, 4> Visited;
2179 "Attribute 'byval' does not support unsized types!", V);
2183 "'byval' argument has illegal target extension type", V);
2184 Check(
DL.getTypeAllocSize(ByValTy).getKnownMinValue() < (1ULL << 32),
2185 "huge 'byval' arguments are unsupported", V);
2187 if (
Attrs.hasAttribute(Attribute::ByRef)) {
2188 SmallPtrSet<Type *, 4> Visited;
2189 Check(
Attrs.getByRefType()->isSized(&Visited),
2190 "Attribute 'byref' does not support unsized types!", V);
2191 Check(
DL.getTypeAllocSize(
Attrs.getByRefType()).getKnownMinValue() <
2193 "huge 'byref' arguments are unsupported", V);
2195 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
2196 SmallPtrSet<Type *, 4> Visited;
2197 Check(
Attrs.getInAllocaType()->isSized(&Visited),
2198 "Attribute 'inalloca' does not support unsized types!", V);
2199 Check(
DL.getTypeAllocSize(
Attrs.getInAllocaType()).getKnownMinValue() <
2201 "huge 'inalloca' arguments are unsupported", V);
2203 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
2204 SmallPtrSet<Type *, 4> Visited;
2205 Check(
Attrs.getPreallocatedType()->isSized(&Visited),
2206 "Attribute 'preallocated' does not support unsized types!", V);
2208 DL.getTypeAllocSize(
Attrs.getPreallocatedType()).getKnownMinValue() <
2210 "huge 'preallocated' arguments are unsupported", V);
2214 if (
Attrs.hasAttribute(Attribute::Initializes)) {
2215 auto Inits =
Attrs.getAttribute(Attribute::Initializes).getInitializes();
2216 Check(!Inits.empty(),
"Attribute 'initializes' does not support empty list",
2219 "Attribute 'initializes' does not support unordered ranges", V);
2222 if (
Attrs.hasAttribute(Attribute::NoFPClass)) {
2223 uint64_t Val =
Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
2224 Check(Val != 0,
"Attribute 'nofpclass' must have at least one test bit set",
2227 "Invalid value for 'nofpclass' test mask", V);
2229 if (
Attrs.hasAttribute(Attribute::Range)) {
2230 const ConstantRange &CR =
2231 Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2233 "Range bit width must match type bit width!", V);
2237void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
2239 if (
Attrs.hasFnAttr(Attr)) {
2240 StringRef S =
Attrs.getFnAttr(Attr).getValueAsString();
2243 CheckFailed(
"\"" + Attr +
"\" takes an unsigned integer: " + S, V);
2249void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
2250 const Value *V,
bool IsIntrinsic,
2252 if (
Attrs.isEmpty())
2255 if (AttributeListsVisited.
insert(
Attrs.getRawPointer()).second) {
2257 "Attribute list does not match Module context!", &Attrs, V);
2258 for (
const auto &AttrSet : Attrs) {
2259 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(
Context),
2260 "Attribute set does not match Module context!", &AttrSet, V);
2261 for (
const auto &
A : AttrSet) {
2263 "Attribute does not match Module context!", &
A, V);
2268 bool SawNest =
false;
2269 bool SawReturned =
false;
2270 bool SawSRet =
false;
2271 bool SawSwiftSelf =
false;
2272 bool SawSwiftAsync =
false;
2273 bool SawSwiftError =
false;
2276 AttributeSet RetAttrs =
Attrs.getRetAttrs();
2279 Attribute::canUseAsRetAttr(
RetAttr.getKindAsEnum()),
2280 "Attribute '" +
RetAttr.getAsString() +
2281 "' does not apply to function return values",
2284 unsigned MaxParameterWidth = 0;
2285 auto GetMaxParameterWidth = [&MaxParameterWidth](
Type *Ty) {
2288 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2289 if (
Size > MaxParameterWidth)
2290 MaxParameterWidth =
Size;
2294 GetMaxParameterWidth(FT->getReturnType());
2295 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2298 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2299 Type *Ty = FT->getParamType(i);
2300 AttributeSet ArgAttrs =
Attrs.getParamAttrs(i);
2304 "immarg attribute only applies to intrinsics", V);
2307 "Attribute 'elementtype' can only be applied to intrinsics"
2312 verifyParameterAttrs(ArgAttrs, Ty, V);
2313 GetMaxParameterWidth(Ty);
2316 Check(!SawNest,
"More than one parameter has attribute nest!", V);
2321 Check(!SawReturned,
"More than one parameter has attribute returned!", V);
2323 "Incompatible argument and return types for 'returned' attribute",
2329 Check(!SawSRet,
"Cannot have multiple 'sret' parameters!", V);
2330 Check(i == 0 || i == 1,
2331 "Attribute 'sret' is not on first or second parameter!", V);
2336 Check(!SawSwiftSelf,
"Cannot have multiple 'swiftself' parameters!", V);
2337 SawSwiftSelf =
true;
2341 Check(!SawSwiftAsync,
"Cannot have multiple 'swiftasync' parameters!", V);
2342 SawSwiftAsync =
true;
2346 Check(!SawSwiftError,
"Cannot have multiple 'swifterror' parameters!", V);
2347 SawSwiftError =
true;
2351 Check(i == FT->getNumParams() - 1,
2352 "inalloca isn't on the last parameter!", V);
2356 if (!
Attrs.hasFnAttrs())
2359 verifyAttributeTypes(
Attrs.getFnAttrs(), V);
2362 Attribute::canUseAsFnAttr(
FnAttr.getKindAsEnum()),
2363 "Attribute '" +
FnAttr.getAsString() +
2364 "' does not apply to functions!",
2367 Check(!(
Attrs.hasFnAttr(Attribute::NoInline) &&
2368 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2369 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2371 if (
Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2373 "Attribute 'optnone' requires 'noinline'!", V);
2375 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2376 "Attributes 'optsize and optnone' are incompatible!", V);
2379 "Attributes 'minsize and optnone' are incompatible!", V);
2381 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
2382 "Attributes 'optdebug and optnone' are incompatible!", V);
2385 Check(!(
Attrs.hasFnAttr(Attribute::SanitizeRealtime) &&
2386 Attrs.hasFnAttr(Attribute::SanitizeRealtimeBlocking)),
2388 "'sanitize_realtime and sanitize_realtime_blocking' are incompatible!",
2391 if (
Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
2392 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2393 "Attributes 'optsize and optdebug' are incompatible!", V);
2396 "Attributes 'minsize and optdebug' are incompatible!", V);
2399 Check(!
Attrs.hasAttrSomewhere(Attribute::Writable) ||
2400 isModSet(
Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
2401 "Attribute writable and memory without argmem: write are incompatible!",
2404 if (
Attrs.hasFnAttr(
"aarch64_pstate_sm_enabled")) {
2405 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_sm_compatible"),
2406 "Attributes 'aarch64_pstate_sm_enabled and "
2407 "aarch64_pstate_sm_compatible' are incompatible!",
2411 Check((
Attrs.hasFnAttr(
"aarch64_new_za") +
Attrs.hasFnAttr(
"aarch64_in_za") +
2412 Attrs.hasFnAttr(
"aarch64_inout_za") +
2413 Attrs.hasFnAttr(
"aarch64_out_za") +
2414 Attrs.hasFnAttr(
"aarch64_preserves_za") +
2415 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2416 "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2417 "'aarch64_inout_za', 'aarch64_preserves_za' and "
2418 "'aarch64_za_state_agnostic' are mutually exclusive",
2422 Attrs.hasFnAttr(
"aarch64_in_zt0") +
2423 Attrs.hasFnAttr(
"aarch64_inout_zt0") +
2424 Attrs.hasFnAttr(
"aarch64_out_zt0") +
2425 Attrs.hasFnAttr(
"aarch64_preserves_zt0") +
2426 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2427 "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
2428 "'aarch64_inout_zt0', 'aarch64_preserves_zt0' and "
2429 "'aarch64_za_state_agnostic' are mutually exclusive",
2432 if (
Attrs.hasFnAttr(Attribute::JumpTable)) {
2435 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2438 if (
auto Args =
Attrs.getFnAttrs().getAllocSizeArgs()) {
2439 auto CheckParam = [&](StringRef
Name,
unsigned ParamNo) {
2440 if (ParamNo >= FT->getNumParams()) {
2441 CheckFailed(
"'allocsize' " + Name +
" argument is out of bounds", V);
2445 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2446 CheckFailed(
"'allocsize' " + Name +
2447 " argument must refer to an integer parameter",
2455 if (!CheckParam(
"element size",
Args->first))
2458 if (
Args->second && !CheckParam(
"number of elements", *
Args->second))
2462 if (
Attrs.hasFnAttr(Attribute::AllocKind)) {
2465 K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
2467 {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
2470 "'allockind()' requires exactly one of alloc, realloc, and free");
2471 if ((
Type == AllocFnKind::Free) &&
2472 ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
2473 AllocFnKind::Aligned)) != AllocFnKind::Unknown))
2474 CheckFailed(
"'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2475 "or aligned modifiers.");
2476 AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
2477 if ((K & ZeroedUninit) == ZeroedUninit)
2478 CheckFailed(
"'allockind()' can't be both zeroed and uninitialized");
2482 StringRef S =
A.getValueAsString();
2483 Check(!S.
empty(),
"'alloc-variant-zeroed' must not be empty");
2491 "'alloc-variant-zeroed' must name a function belonging to the "
2492 "same 'alloc-family'");
2495 (
Variant->getFnAttribute(Attribute::AllocKind).getAllocKind() &
2496 AllocFnKind::Zeroed) != AllocFnKind::Unknown,
2497 "'alloc-variant-zeroed' must name a function with "
2498 "'allockind(\"zeroed\")'");
2501 "'alloc-variant-zeroed' must name a function with the same "
2506 "'alloc-variant-zeroed' must name a function with the same "
2507 "calling convention");
2511 if (
Attrs.hasFnAttr(Attribute::VScaleRange)) {
2512 unsigned VScaleMin =
Attrs.getFnAttrs().getVScaleRangeMin();
2514 CheckFailed(
"'vscale_range' minimum must be greater than 0", V);
2516 CheckFailed(
"'vscale_range' minimum must be power-of-two value", V);
2517 std::optional<unsigned> VScaleMax =
Attrs.getFnAttrs().getVScaleRangeMax();
2518 if (VScaleMax && VScaleMin > VScaleMax)
2519 CheckFailed(
"'vscale_range' minimum cannot be greater than maximum", V);
2521 CheckFailed(
"'vscale_range' maximum must be power-of-two value", V);
2524 if (
Attribute FPAttr =
Attrs.getFnAttr(
"frame-pointer"); FPAttr.isValid()) {
2525 StringRef
FP = FPAttr.getValueAsString();
2526 if (
FP !=
"all" &&
FP !=
"non-leaf" &&
FP !=
"none" &&
FP !=
"reserved" &&
2527 FP !=
"non-leaf-no-reserve")
2528 CheckFailed(
"invalid value for 'frame-pointer' attribute: " +
FP, V);
2531 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-prefix", V);
2532 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-entry", V);
2533 if (
Attrs.hasFnAttr(
"patchable-function-entry-section"))
2534 Check(!
Attrs.getFnAttr(
"patchable-function-entry-section")
2537 "\"patchable-function-entry-section\" must not be empty");
2538 checkUnsignedBaseTenFuncAttr(Attrs,
"warn-stack-size", V);
2540 if (
auto A =
Attrs.getFnAttr(
"sign-return-address");
A.isValid()) {
2541 StringRef S =
A.getValueAsString();
2542 if (S !=
"none" && S !=
"all" && S !=
"non-leaf")
2543 CheckFailed(
"invalid value for 'sign-return-address' attribute: " + S, V);
2546 if (
auto A =
Attrs.getFnAttr(
"sign-return-address-key");
A.isValid()) {
2547 StringRef S =
A.getValueAsString();
2548 if (S !=
"a_key" && S !=
"b_key")
2549 CheckFailed(
"invalid value for 'sign-return-address-key' attribute: " + S,
2551 if (
auto AA =
Attrs.getFnAttr(
"sign-return-address"); !AA.isValid()) {
2553 "'sign-return-address-key' present without `sign-return-address`");
2557 if (
auto A =
Attrs.getFnAttr(
"branch-target-enforcement");
A.isValid()) {
2558 StringRef S =
A.getValueAsString();
2559 if (S !=
"" && S !=
"true" && S !=
"false")
2561 "invalid value for 'branch-target-enforcement' attribute: " + S, V);
2564 if (
auto A =
Attrs.getFnAttr(
"branch-protection-pauth-lr");
A.isValid()) {
2565 StringRef S =
A.getValueAsString();
2566 if (S !=
"" && S !=
"true" && S !=
"false")
2568 "invalid value for 'branch-protection-pauth-lr' attribute: " + S, V);
2571 if (
auto A =
Attrs.getFnAttr(
"guarded-control-stack");
A.isValid()) {
2572 StringRef S =
A.getValueAsString();
2573 if (S !=
"" && S !=
"true" && S !=
"false")
2574 CheckFailed(
"invalid value for 'guarded-control-stack' attribute: " + S,
2578 if (
auto A =
Attrs.getFnAttr(
"vector-function-abi-variant");
A.isValid()) {
2579 StringRef S =
A.getValueAsString();
2582 CheckFailed(
"invalid name for a VFABI variant: " + S, V);
2585 if (
auto A =
Attrs.getFnAttr(
"modular-format");
A.isValid()) {
2586 StringRef S =
A.getValueAsString();
2590 "modular-format attribute requires at least 5 arguments", V);
2591 unsigned UpperBound = FT->getNumParams() + (FT->isVarArg() ? 1 : 0);
2593 Check(!Args[1].getAsInteger(10, FormatIdx),
2594 "modular-format attribute format string index is not an integer", V);
2595 Check(FormatIdx > 0,
2596 "modular-format attribute format string index must be greater than 0",
2598 Check(FormatIdx <= UpperBound,
2599 "modular-format attribute format string index is out of bounds", V);
2600 unsigned FirstArgIdx;
2601 Check(!Args[2].getAsInteger(10, FirstArgIdx),
2602 "modular-format attribute first arg index is not an integer", V);
2603 Check(FirstArgIdx <= UpperBound,
2604 "modular-format attribute first arg index is out of bounds", V);
2606 "modular-format attribute modular implementation function name "
2610 "modular-format attribute implementation name cannot be empty", V);
2613 if (
auto A =
Attrs.getFnAttr(
"target-features");
A.isValid()) {
2614 StringRef S =
A.getValueAsString();
2616 for (
auto FeatureFlag :
split(S,
',')) {
2617 if (FeatureFlag.empty())
2619 "target-features attribute should not contain an empty string");
2621 Check(FeatureFlag[0] ==
'+' || FeatureFlag[0] ==
'-',
2622 "target feature '" + FeatureFlag +
2623 "' must start with a '+' or '-'",
2629void Verifier::verifyUnknownProfileMetadata(MDNode *MD) {
2631 "'unknown' !prof should have a single additional operand", MD);
2634 "'unknown' !prof should have an additional operand of type "
2637 "the 'unknown' !prof operand should not be an empty string");
2640void Verifier::verifyFunctionMetadata(
2641 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2642 for (
const auto &Pair : MDs) {
2643 if (Pair.first == LLVMContext::MD_prof) {
2644 MDNode *MD = Pair.second;
2646 "!prof annotations should have no less than 2 operands", MD);
2651 verifyUnknownProfileMetadata(MD);
2656 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null",
2659 "expected string with name of the !prof annotation", MD);
2664 "first operand should be 'function_entry_count'"
2665 " or 'synthetic_function_entry_count'",
2669 Check(MD->
getOperand(1) !=
nullptr,
"second operand should not be null",
2672 "expected integer argument to function_entry_count", MD);
2673 }
else if (Pair.first == LLVMContext::MD_kcfi_type) {
2674 MDNode *MD = Pair.second;
2676 "!kcfi_type must have exactly one operand", MD);
2677 Check(MD->
getOperand(0) !=
nullptr,
"!kcfi_type operand must not be null",
2680 "expected a constant operand for !kcfi_type", MD);
2683 "expected a constant integer operand for !kcfi_type", MD);
2685 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2686 }
else if (Pair.first ==
Context.getMDKindID(
"reqd_work_group_size")) {
2687 MDNode *MD = Pair.second;
2689 "reqd_work_group_size must have exactly three operands", MD);
2693 uint64_t Product = 1;
2694 for (
unsigned I = 0;
I != 3; ++
I) {
2696 Check(
C,
"reqd_work_group_size operands must be integer constants", MD);
2700 const APInt &
Value =
C->getValue();
2702 "reqd_work_group_size operands must fit in 64 bits", MD);
2703 if (
Value.getActiveBits() > 64)
2706 uint64_t Dim =
Value.getZExtValue();
2707 Check(Dim == 0 || Product <= std::numeric_limits<uint64_t>::max() / Dim,
2708 "reqd_work_group_size product must fit in 64 bits", MD);
2709 if (Dim != 0 && Product > std::numeric_limits<uint64_t>::max() / Dim)
2717void Verifier::visitConstantExprsRecursively(
const Constant *EntryC) {
2721 if (!ConstantExprVisited.
insert(EntryC).second)
2725 Stack.push_back(EntryC);
2727 while (!
Stack.empty()) {
2732 visitConstantExpr(CE);
2735 visitConstantPtrAuth(CPA);
2740 Check(GV->
getParent() == &M,
"Referencing global in another module!",
2746 for (
const Use &U :
C->operands()) {
2750 if (!ConstantExprVisited.
insert(OpC).second)
2752 Stack.push_back(OpC);
2757void Verifier::visitConstantExpr(
const ConstantExpr *CE) {
2758 if (
CE->getOpcode() == Instruction::BitCast)
2761 "Invalid bitcast", CE);
2762 else if (
CE->getOpcode() == Instruction::PtrToAddr)
2763 checkPtrToAddr(
CE->getOperand(0)->getType(),
CE->getType(), *CE);
2766void Verifier::visitConstantPtrAuth(
const ConstantPtrAuth *CPA) {
2768 "signed ptrauth constant base pointer must have pointer type");
2771 "signed ptrauth constant must have same type as its base pointer");
2774 "signed ptrauth constant key must be i32 constant integer");
2777 "signed ptrauth constant address discriminator must be a pointer");
2780 "signed ptrauth constant discriminator must be i64 constant integer");
2783 "signed ptrauth constant deactivation symbol must be a pointer");
2787 "signed ptrauth constant deactivation symbol must be a global value "
2791bool Verifier::verifyAttributeCount(AttributeList Attrs,
unsigned Params) {
2794 return Attrs.getNumAttrSets() <= Params + 2;
2797void Verifier::verifyInlineAsmCall(
const CallBase &
Call) {
2800 unsigned LabelNo = 0;
2801 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
2811 if (CI.isIndirect) {
2814 "Operand for indirect constraint must have pointer type", &
Call);
2817 "Operand for indirect constraint must have elementtype attribute",
2821 "Elementtype attribute can only be applied for indirect "
2830 Check(LabelNo == CallBr->getNumIndirectDests(),
2831 "Number of label constraints does not match number of callbr dests",
2834 Check(LabelNo == 0,
"Label constraints can only be used with callbr",
2840void Verifier::verifyStatepoint(
const CallBase &
Call) {
2845 "gc.statepoint must read and write all memory to preserve "
2846 "reordering restrictions required by safepoint semantics",
2849 const int64_t NumPatchBytes =
2852 Check(NumPatchBytes >= 0,
2853 "gc.statepoint number of patchable bytes must be "
2858 Check(TargetElemType,
2859 "gc.statepoint callee argument must have elementtype attribute",
Call);
2861 Check(TargetFuncType,
2862 "gc.statepoint callee elementtype must be function type",
Call);
2865 Check(NumCallArgs >= 0,
2866 "gc.statepoint number of arguments to underlying call "
2869 const int NumParams = (int)TargetFuncType->getNumParams();
2870 if (TargetFuncType->isVarArg()) {
2871 Check(NumCallArgs >= NumParams,
2872 "gc.statepoint mismatch in number of vararg call args",
Call);
2875 Check(TargetFuncType->getReturnType()->isVoidTy(),
2876 "gc.statepoint doesn't support wrapping non-void "
2877 "vararg functions yet",
2880 Check(NumCallArgs == NumParams,
2881 "gc.statepoint mismatch in number of call args",
Call);
2883 const uint64_t
Flags
2885 Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
2886 "unknown flag used in gc.statepoint flags argument",
Call);
2891 for (
int i = 0; i < NumParams; i++) {
2892 Type *ParamType = TargetFuncType->getParamType(i);
2894 Check(ArgType == ParamType,
2895 "gc.statepoint call argument does not match wrapped "
2899 if (TargetFuncType->isVarArg()) {
2900 AttributeSet ArgAttrs =
Attrs.getParamAttrs(5 + i);
2902 "Attribute 'sret' cannot be used for vararg call arguments!",
Call);
2906 const int EndCallArgsInx = 4 + NumCallArgs;
2910 "gc.statepoint number of transition arguments "
2911 "must be constant integer",
2913 const int NumTransitionArgs =
2915 Check(NumTransitionArgs == 0,
2916 "gc.statepoint w/inline transition bundle is deprecated",
Call);
2917 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2921 "gc.statepoint number of deoptimization arguments "
2922 "must be constant integer",
2925 Check(NumDeoptArgs == 0,
2926 "gc.statepoint w/inline deopt operands is deprecated",
Call);
2928 const int ExpectedNumArgs = 7 + NumCallArgs;
2930 "gc.statepoint too many arguments",
Call);
2937 Check(UserCall,
"illegal use of statepoint token",
Call, U);
2941 "gc.result or gc.relocate are the only value uses "
2942 "of a gc.statepoint",
2945 Check(UserCall->getArgOperand(0) == &
Call,
2946 "gc.result connected to wrong gc.statepoint",
Call, UserCall);
2948 Check(UserCall->getArgOperand(0) == &
Call,
2949 "gc.relocate connected to wrong gc.statepoint",
Call, UserCall);
2963void Verifier::verifyFrameRecoverIndices() {
2964 for (
auto &Counts : FrameEscapeInfo) {
2966 unsigned EscapedObjectCount = Counts.second.first;
2967 unsigned MaxRecoveredIndex = Counts.second.second;
2968 Check(MaxRecoveredIndex <= EscapedObjectCount,
2969 "all indices passed to llvm.localrecover must be less than the "
2970 "number of arguments passed to llvm.localescape in the parent "
2979 UnwindDest =
II->getUnwindDest();
2981 UnwindDest = CSI->getUnwindDest();
2987void Verifier::verifySiblingFuncletUnwinds() {
2988 llvm::TimeTraceScope timeScope(
"Verifier verify sibling funclet unwinds");
2989 SmallPtrSet<Instruction *, 8> Visited;
2990 SmallPtrSet<Instruction *, 8>
Active;
2991 for (
const auto &Pair : SiblingFuncletInfo) {
2993 if (Visited.
count(PredPad))
2999 if (
Active.count(SuccPad)) {
3002 SmallVector<Instruction *, 8> CycleNodes;
3005 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
3006 if (CycleTerminator != CyclePad)
3009 }
while (CyclePad != SuccPad);
3010 Check(
false,
"EH pads can't handle each other's exceptions",
3014 if (!Visited.
insert(SuccPad).second)
3018 auto TermI = SiblingFuncletInfo.find(PredPad);
3019 if (TermI == SiblingFuncletInfo.end())
3032void Verifier::visitFunction(
const Function &
F) {
3033 visitGlobalValue(
F);
3036 FunctionType *FT =
F.getFunctionType();
3037 unsigned NumArgs =
F.arg_size();
3040 "Function context does not match Module context!", &
F);
3042 Check(!
F.hasCommonLinkage(),
"Functions may not have common linkage", &
F);
3043 Check(FT->getNumParams() == NumArgs,
3044 "# formal arguments must match # of arguments for function type!", &
F,
3046 Check(
F.getReturnType()->isFirstClassType() ||
3047 F.getReturnType()->isVoidTy() ||
F.getReturnType()->isStructTy(),
3048 "Functions cannot return aggregate values!", &
F);
3050 Check(!
F.hasStructRetAttr() ||
F.getReturnType()->isVoidTy(),
3051 "Invalid struct return type!", &
F);
3053 if (MaybeAlign
A =
F.getAlign()) {
3054 Check(
A->value() <= Value::MaximumAlignment,
3055 "huge alignment values are unsupported", &
F);
3058 AttributeList
Attrs =
F.getAttributes();
3060 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
3061 "Attribute after last parameter!", &
F);
3063 bool IsIntrinsic =
F.isIntrinsic();
3066 verifyFunctionAttrs(FT, Attrs, &
F, IsIntrinsic,
false);
3072 "Attribute 'builtin' can only be applied to a callsite.", &
F);
3074 Check(!
Attrs.hasAttrSomewhere(Attribute::ElementType),
3075 "Attribute 'elementtype' can only be applied to a callsite.", &
F);
3077 if (
Attrs.hasFnAttr(Attribute::Naked))
3078 for (
const Argument &Arg :
F.args())
3079 Check(Arg.use_empty(),
"cannot use argument of naked function", &Arg);
3084 switch (
F.getCallingConv()) {
3086 case CallingConv::C:
3088 case CallingConv::X86_INTR: {
3089 Check(
F.arg_empty() ||
Attrs.hasParamAttr(0, Attribute::ByVal),
3090 "Calling convention parameter requires byval", &
F);
3093 case CallingConv::AMDGPU_KERNEL:
3094 case CallingConv::SPIR_KERNEL:
3095 case CallingConv::AMDGPU_CS_Chain:
3096 case CallingConv::AMDGPU_CS_ChainPreserve:
3097 Check(
F.getReturnType()->isVoidTy(),
3098 "Calling convention requires void return type", &
F);
3100 case CallingConv::AMDGPU_VS:
3101 case CallingConv::AMDGPU_HS:
3102 case CallingConv::AMDGPU_GS:
3103 case CallingConv::AMDGPU_PS:
3104 case CallingConv::AMDGPU_CS:
3105 Check(!
F.hasStructRetAttr(),
"Calling convention does not allow sret", &
F);
3106 if (
F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3107 const unsigned StackAS =
DL.getAllocaAddrSpace();
3109 for (
const Argument &Arg :
F.args()) {
3110 Check(!
Attrs.hasParamAttr(i, Attribute::ByVal),
3111 "Calling convention disallows byval", &
F);
3112 Check(!
Attrs.hasParamAttr(i, Attribute::Preallocated),
3113 "Calling convention disallows preallocated", &
F);
3114 Check(!
Attrs.hasParamAttr(i, Attribute::InAlloca),
3115 "Calling convention disallows inalloca", &
F);
3117 if (
Attrs.hasParamAttr(i, Attribute::ByRef)) {
3120 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
3121 "Calling convention disallows stack byref", &
F);
3129 case CallingConv::Fast:
3130 case CallingConv::Cold:
3131 case CallingConv::Intel_OCL_BI:
3132 case CallingConv::PTX_Kernel:
3133 case CallingConv::PTX_Device:
3135 "Calling convention does not support varargs or "
3136 "perfect forwarding!",
3139 case CallingConv::AMDGPU_Gfx_WholeWave:
3140 Check(!
F.arg_empty() &&
F.arg_begin()->getType()->isIntegerTy(1),
3141 "Calling convention requires first argument to be i1", &
F);
3142 Check(!
F.arg_begin()->hasInRegAttr(),
3143 "Calling convention requires first argument to not be inreg", &
F);
3145 "Calling convention does not support varargs or "
3146 "perfect forwarding!",
3153 for (
const Argument &Arg :
F.args()) {
3154 Check(Arg.getType() == FT->getParamType(i),
3155 "Argument value does not match function argument type!", &Arg,
3156 FT->getParamType(i));
3157 Check(Arg.getType()->isFirstClassType(),
3158 "Function arguments must have first-class types!", &Arg);
3160 Check(!Arg.getType()->isMetadataTy(),
3161 "Function takes metadata but isn't an intrinsic", &Arg, &
F);
3162 Check(!Arg.getType()->isTokenLikeTy(),
3163 "Function takes token but isn't an intrinsic", &Arg, &
F);
3164 Check(!Arg.getType()->isX86_AMXTy(),
3165 "Function takes x86_amx but isn't an intrinsic", &Arg, &
F);
3169 if (
Attrs.hasParamAttr(i, Attribute::SwiftError)) {
3170 verifySwiftErrorValue(&Arg);
3176 Check(!
F.getReturnType()->isTokenLikeTy(),
3177 "Function returns a token but isn't an intrinsic", &
F);
3178 Check(!
F.getReturnType()->isX86_AMXTy(),
3179 "Function returns a x86_amx but isn't an intrinsic", &
F);
3184 F.getAllMetadata(MDs);
3185 assert(
F.hasMetadata() != MDs.
empty() &&
"Bit out-of-sync");
3186 verifyFunctionMetadata(MDs);
3192 if (
F.hasPersonalityFn()) {
3195 Check(Per->getParent() ==
F.getParent(),
3196 "Referencing personality function in another module!", &
F,
3197 F.getParent(), Per, Per->getParent());
3201 BlockEHFuncletColors.
clear();
3203 if (
F.isMaterializable()) {
3205 Check(MDs.
empty(),
"unmaterialized function cannot have metadata", &
F,
3207 }
else if (
F.isDeclaration()) {
3208 for (
const auto &
I : MDs) {
3210 CheckDI(
I.first != LLVMContext::MD_dbg ||
3212 "function declaration may only have a unique !dbg attachment",
3214 Check(
I.first != LLVMContext::MD_prof,
3215 "function declaration may not have a !prof attachment", &
F);
3218 visitMDNode(*
I.second, AreDebugLocsAllowed::Yes);
3220 Check(!
F.hasPersonalityFn(),
3221 "Function declaration shouldn't have a personality routine", &
F);
3225 Check(!IsIntrinsic,
"llvm intrinsics cannot be defined!", &
F);
3230 "Entry block to function must not have predecessors!", Entry);
3233 if (
Entry->hasAddressTaken()) {
3235 "blockaddress may not be used with the entry block!", Entry);
3238 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
3239 NumKCFIAttachments = 0;
3241 for (
const auto &
I : MDs) {
3243 auto AllowLocs = AreDebugLocsAllowed::No;
3247 case LLVMContext::MD_dbg: {
3248 ++NumDebugAttachments;
3249 CheckDI(NumDebugAttachments == 1,
3250 "function must have a single !dbg attachment", &
F,
I.second);
3252 "function !dbg attachment must be a subprogram", &
F,
I.second);
3254 "function definition may only have a distinct !dbg attachment",
3258 const Function *&AttachedTo = DISubprogramAttachments[
SP];
3259 CheckDI(!AttachedTo || AttachedTo == &
F,
3260 "DISubprogram attached to more than one function", SP, &
F);
3262 AllowLocs = AreDebugLocsAllowed::Yes;
3265 case LLVMContext::MD_prof:
3266 ++NumProfAttachments;
3267 Check(NumProfAttachments == 1,
3268 "function must have a single !prof attachment", &
F,
I.second);
3270 case LLVMContext::MD_kcfi_type:
3271 ++NumKCFIAttachments;
3272 Check(NumKCFIAttachments == 1,
3273 "function must have a single !kcfi_type attachment", &
F,
3279 visitMDNode(*
I.second, AllowLocs);
3287 bool isMaterialized =
F.getParent()->isMaterialized();
3288 if (
F.isIntrinsic() && isMaterialized) {
3290 if (
F.hasAddressTaken(&U,
false,
true,
false,
3292 Check(
false,
"Invalid user of intrinsic instruction!", U);
3299 if (IID && (isMaterialized || !
F.materialized_use_empty())) {
3303 raw_string_ostream ErrOS(ErrMsg);
3306 Printable PrintDecl([&
F](raw_ostream &OS) {
F.print(OS); });
3307 Check(IsValid, ErrMsg, PrintDecl);
3314 IID, OverloadTys,
const_cast<Module *
>(
F.getParent()), FT);
3315 Check(ExpectedName ==
F.getName(),
3316 "Intrinsic name not mangled correctly for type arguments! "
3322 auto *
N =
F.getSubprogram();
3323 HasDebugInfo = (
N !=
nullptr);
3331 SmallPtrSet<const MDNode *, 32> Seen;
3343 "DILocation's scope must be a DILocalScope",
N, &
F, &
I,
DL, Parent);
3345 DILocalScope *
Scope =
DL->getInlinedAtScope();
3346 Check(Scope,
"Failed to find DILocalScope",
DL);
3348 if (!Seen.
insert(Scope).second)
3351 DISubprogram *
SP =
Scope->getSubprogram();
3355 if ((Scope != SP) && !Seen.
insert(SP).second)
3359 "!dbg attachment points at wrong subprogram for function",
N, &
F,
3363 for (
auto &
I : BB) {
3364 VisitDebugLoc(
I,
I.getDebugLoc().getAsMDNode());
3366 if (
auto MD =
I.getMetadata(LLVMContext::MD_loop))
3369 if (BrokenDebugInfo)
3376void Verifier::visitBasicBlock(BasicBlock &BB) {
3377 InstsInThisBlock.
clear();
3378 ConvergenceVerifyHelper.
visit(BB);
3389 for (
const PHINode &PN : BB.
phis()) {
3390 Check(PN.getNumIncomingValues() == Preds.size(),
3391 "PHINode should have one entry for each predecessor of its "
3392 "parent basic block!",
3397 Values.reserve(PN.getNumIncomingValues());
3398 for (
unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3400 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3403 for (
unsigned i = 0, e =
Values.size(); i != e; ++i) {
3410 "PHI node has multiple entries for the same basic block with "
3411 "different incoming values!",
3417 "PHI node entries do not match predecessors!", &PN,
3418 Values[i].first, Preds[i]);
3426 Check(
I.getParent() == &BB,
"Instruction has bogus parent pointer!");
3430 CheckDI(!BB.getTrailingDbgRecords(),
"Basic Block has trailing DbgRecords!",
3434void Verifier::visitTerminator(Instruction &
I) {
3436 Check(&
I ==
I.getParent()->getTerminator(),
3437 "Terminator found in the middle of a basic block!",
I.getParent());
3438 visitInstruction(
I);
3441void Verifier::visitCondBrInst(CondBrInst &BI) {
3443 "Branch condition is not 'i1' type!", &BI, BI.
getCondition());
3444 visitTerminator(BI);
3447void Verifier::visitReturnInst(ReturnInst &RI) {
3450 if (
F->getReturnType()->isVoidTy())
3452 "Found return instr that returns non-void in Function of void "
3454 &RI,
F->getReturnType());
3457 "Function return type does not match operand "
3458 "type of return inst!",
3459 &RI,
F->getReturnType());
3463 visitTerminator(RI);
3466void Verifier::visitSwitchInst(SwitchInst &SI) {
3467 Check(
SI.getType()->isVoidTy(),
"Switch must have void result type!", &SI);
3470 Type *SwitchTy =
SI.getCondition()->getType();
3471 SmallPtrSet<ConstantInt*, 32>
Constants;
3472 for (
auto &Case :
SI.cases()) {
3474 "Case value is not a constant integer.", &SI);
3475 Check(Case.getCaseValue()->getType() == SwitchTy,
3476 "Switch constants must all be same type as switch value!", &SI);
3478 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3481 visitTerminator(SI);
3484void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
3486 "Indirectbr operand must have pointer type!", &BI);
3489 "Indirectbr destinations must all have pointer type!", &BI);
3491 visitTerminator(BI);
3500void Verifier::visitCallBrInst(CallBrInst &CBI) {
3503 "callbr: indirect function / invalid signature");
3505 "callbr for intrinsics currently doesn't support operand bundles");
3509 "callbr currently only supports asm-goto and selected intrinsics");
3514 Check(!
IA->canThrow(),
"Unwinding from Callbr is not allowed");
3516 verifyInlineAsmCall(CBI);
3518 visitTerminator(CBI);
3521void Verifier::visitSelectInst(SelectInst &SI) {
3524 "Invalid operands for select instruction!", &SI);
3526 Check(
SI.getTrueValue()->getType() ==
SI.getType(),
3527 "Select values must have same type as select instruction!", &SI);
3528 visitInstruction(SI);
3534void Verifier::visitUserOp1(Instruction &
I) {
3535 Check(
false,
"User-defined operators should not live outside of a pass!", &
I);
3538void Verifier::visitTruncInst(TruncInst &
I) {
3540 Type *SrcTy =
I.getOperand(0)->getType();
3541 Type *DestTy =
I.getType();
3550 "trunc source and destination must both be a vector or neither", &
I);
3551 Check(SrcBitSize > DestBitSize,
"DestTy too big for Trunc", &
I);
3553 visitInstruction(
I);
3556void Verifier::visitZExtInst(ZExtInst &
I) {
3558 Type *SrcTy =
I.getOperand(0)->getType();
3559 Type *DestTy =
I.getType();
3565 "zext source and destination must both be a vector or neither", &
I);
3569 Check(SrcBitSize < DestBitSize,
"Type too small for ZExt", &
I);
3571 visitInstruction(
I);
3574void Verifier::visitSExtInst(SExtInst &
I) {
3576 Type *SrcTy =
I.getOperand(0)->getType();
3577 Type *DestTy =
I.getType();
3586 "sext source and destination must both be a vector or neither", &
I);
3587 Check(SrcBitSize < DestBitSize,
"Type too small for SExt", &
I);
3589 visitInstruction(
I);
3592void Verifier::visitFPTruncInst(FPTruncInst &
I) {
3594 Type *SrcTy =
I.getOperand(0)->getType();
3595 Type *DestTy =
I.getType();
3603 "fptrunc source and destination must both be a vector or neither", &
I);
3604 Check(SrcBitSize > DestBitSize,
"DestTy too big for FPTrunc", &
I);
3606 visitInstruction(
I);
3609void Verifier::visitFPExtInst(FPExtInst &
I) {
3611 Type *SrcTy =
I.getOperand(0)->getType();
3612 Type *DestTy =
I.getType();
3621 "fpext source and destination must both be a vector or neither", &
I);
3622 Check(SrcBitSize < DestBitSize,
"DestTy too small for FPExt", &
I);
3624 visitInstruction(
I);
3627void Verifier::visitUIToFPInst(UIToFPInst &
I) {
3629 Type *SrcTy =
I.getOperand(0)->getType();
3630 Type *DestTy =
I.getType();
3635 Check(SrcVec == DstVec,
3636 "UIToFP source and dest must both be vector or scalar", &
I);
3638 "UIToFP source must be integer or integer vector", &
I);
3642 if (SrcVec && DstVec)
3645 "UIToFP source and dest vector length mismatch", &
I);
3647 visitInstruction(
I);
3650void Verifier::visitSIToFPInst(SIToFPInst &
I) {
3652 Type *SrcTy =
I.getOperand(0)->getType();
3653 Type *DestTy =
I.getType();
3658 Check(SrcVec == DstVec,
3659 "SIToFP source and dest must both be vector or scalar", &
I);
3661 "SIToFP source must be integer or integer vector", &
I);
3665 if (SrcVec && DstVec)
3668 "SIToFP source and dest vector length mismatch", &
I);
3670 visitInstruction(
I);
3673void Verifier::visitFPToUIInst(FPToUIInst &
I) {
3675 Type *SrcTy =
I.getOperand(0)->getType();
3676 Type *DestTy =
I.getType();
3681 Check(SrcVec == DstVec,
3682 "FPToUI source and dest must both be vector or scalar", &
I);
3685 "FPToUI result must be integer or integer vector", &
I);
3687 if (SrcVec && DstVec)
3690 "FPToUI source and dest vector length mismatch", &
I);
3692 visitInstruction(
I);
3695void Verifier::visitFPToSIInst(FPToSIInst &
I) {
3697 Type *SrcTy =
I.getOperand(0)->getType();
3698 Type *DestTy =
I.getType();
3703 Check(SrcVec == DstVec,
3704 "FPToSI source and dest must both be vector or scalar", &
I);
3707 "FPToSI result must be integer or integer vector", &
I);
3709 if (SrcVec && DstVec)
3712 "FPToSI source and dest vector length mismatch", &
I);
3714 visitInstruction(
I);
3717void Verifier::checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V) {
3726 Check(VSrc->getElementCount() == VDest->getElementCount(),
3727 "PtrToAddr vector length mismatch", V);
3730 Type *AddrTy =
DL.getAddressType(SrcTy);
3731 Check(AddrTy == DestTy,
"PtrToAddr result must be address width", V);
3734void Verifier::visitPtrToAddrInst(PtrToAddrInst &
I) {
3735 checkPtrToAddr(
I.getOperand(0)->getType(),
I.getType(),
I);
3736 visitInstruction(
I);
3739void Verifier::visitPtrToIntInst(PtrToIntInst &
I) {
3741 Type *SrcTy =
I.getOperand(0)->getType();
3742 Type *DestTy =
I.getType();
3753 Check(VSrc->getElementCount() == VDest->getElementCount(),
3754 "PtrToInt Vector length mismatch", &
I);
3757 visitInstruction(
I);
3760void Verifier::visitIntToPtrInst(IntToPtrInst &
I) {
3762 Type *SrcTy =
I.getOperand(0)->getType();
3763 Type *DestTy =
I.getType();
3773 Check(VSrc->getElementCount() == VDest->getElementCount(),
3774 "IntToPtr Vector length mismatch", &
I);
3776 visitInstruction(
I);
3779void Verifier::visitBitCastInst(BitCastInst &
I) {
3782 "Invalid bitcast", &
I);
3783 visitInstruction(
I);
3786void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &
I) {
3787 Type *SrcTy =
I.getOperand(0)->getType();
3788 Type *DestTy =
I.getType();
3795 "AddrSpaceCast must be between different address spaces", &
I);
3797 Check(SrcVTy->getElementCount() ==
3799 "AddrSpaceCast vector pointer number of elements mismatch", &
I);
3800 visitInstruction(
I);
3805void Verifier::visitPHINode(PHINode &PN) {
3812 "PHI nodes not grouped at top of basic block!", &PN, PN.
getParent());
3821 "PHI node operands are not the same type as the result!", &PN);
3826 visitInstruction(PN);
3829void Verifier::visitCallBase(CallBase &
Call) {
3831 "Called function must be a pointer!",
Call);
3835 if (FTy->isVarArg())
3837 "Called function requires more parameters than were provided!",
Call);
3840 "Incorrect number of arguments passed to called function!",
Call);
3843 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3845 "Call parameter type does not match function signature!",
3851 "Attribute after last parameter!",
Call);
3858 "Intrinsic called with incompatible signature",
Call);
3862 "calling convention does not permit calls",
Call);
3868 auto VerifyTypeAlign = [&](
Type *Ty,
const Twine &Message) {
3871 Align ABIAlign =
DL.getABITypeAlign(Ty);
3872 Check(ABIAlign.
value() <= Value::MaximumAlignment,
3873 "Incorrect alignment of " + Message +
" to called function!",
Call);
3877 VerifyTypeAlign(FTy->getReturnType(),
"return type");
3878 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3879 Type *Ty = FTy->getParamType(i);
3880 VerifyTypeAlign(Ty,
"argument passed");
3884 if (
Attrs.hasFnAttr(Attribute::Speculatable)) {
3888 "speculatable attribute may not apply to call sites",
Call);
3891 if (
Attrs.hasFnAttr(Attribute::Preallocated)) {
3893 "preallocated as a call site attribute can only be on "
3894 "llvm.call.preallocated.arg");
3897 Check(!
Attrs.hasFnAttr(Attribute::DenormalFPEnv),
3898 "denormal_fpenv attribute may not apply to call sites",
Call);
3909 Check(AI->isUsedWithInAlloca(),
3910 "inalloca argument for call has mismatched alloca", AI,
Call);
3916 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3920 Check(AI->isSwiftError(),
3921 "swifterror argument for call has mismatched alloca", AI,
Call);
3925 Check(ArgI,
"swifterror argument should come from an alloca or parameter",
3926 SwiftErrorArg,
Call);
3927 Check(ArgI->hasSwiftErrorAttr(),
3928 "swifterror argument for call has mismatched parameter", ArgI,
3932 if (
Attrs.hasParamAttr(i, Attribute::ImmArg)) {
3935 Check(Callee &&
Callee->hasParamAttribute(i, Attribute::ImmArg),
3944 "immarg operand has non-immediate parameter", ArgVal,
Call);
3950 const ConstantRange &CR =
3953 formatv(
"immarg value {} for arg {} out of range {}",
3954 CI->getValue(), i, CR),
3965 Check(hasOB != isMustTail,
3966 "preallocated operand either requires a preallocated bundle or "
3967 "the call to be musttail (but not both)",
3972 if (FTy->isVarArg()) {
3974 bool SawNest =
false;
3975 bool SawReturned =
false;
3977 for (
unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3978 if (
Attrs.hasParamAttr(Idx, Attribute::Nest))
3980 if (
Attrs.hasParamAttr(Idx, Attribute::Returned))
3985 for (
unsigned Idx = FTy->getNumParams(); Idx <
Call.
arg_size(); ++Idx) {
3987 AttributeSet ArgAttrs =
Attrs.getParamAttrs(Idx);
3988 verifyParameterAttrs(ArgAttrs, Ty, &
Call);
3991 Check(!SawNest,
"More than one parameter has attribute nest!",
Call);
3996 Check(!SawReturned,
"More than one parameter has attribute returned!",
3999 "Incompatible argument and return types for 'returned' "
4009 "Attribute 'sret' cannot be used for vararg call arguments!",
4014 "inalloca isn't on the last argument!",
Call);
4020 for (
Type *ParamTy : FTy->params()) {
4021 Check(!ParamTy->isMetadataTy(),
4022 "Function has metadata parameter but isn't an intrinsic",
Call);
4023 Check(!ParamTy->isTokenLikeTy(),
4024 "Function has token parameter but isn't an intrinsic",
Call);
4030 Check(!FTy->getReturnType()->isTokenLikeTy(),
4031 "Return type cannot be token for indirect call!");
4032 Check(!FTy->getReturnType()->isX86_AMXTy(),
4033 "Return type cannot be x86_amx for indirect call!");
4037 visitIntrinsicCall(
ID,
Call);
4042 bool FoundDeoptBundle =
false, FoundFuncletBundle =
false,
4043 FoundGCTransitionBundle =
false, FoundCFGuardTargetBundle =
false,
4044 FoundPreallocatedBundle =
false, FoundGCLiveBundle =
false,
4045 FoundPtrauthBundle =
false, FoundKCFIBundle =
false,
4046 FoundAttachedCallBundle =
false;
4051 Check(!FoundDeoptBundle,
"Multiple deopt operand bundles",
Call);
4052 FoundDeoptBundle =
true;
4054 Check(!FoundGCTransitionBundle,
"Multiple gc-transition operand bundles",
4056 FoundGCTransitionBundle =
true;
4058 Check(!FoundFuncletBundle,
"Multiple funclet operand bundles",
Call);
4059 FoundFuncletBundle =
true;
4061 "Expected exactly one funclet bundle operand",
Call);
4063 "Funclet bundle operands should correspond to a FuncletPadInst",
4066 Check(!FoundCFGuardTargetBundle,
"Multiple CFGuardTarget operand bundles",
4068 FoundCFGuardTargetBundle =
true;
4070 "Expected exactly one cfguardtarget bundle operand",
Call);
4072 Check(!FoundPtrauthBundle,
"Multiple ptrauth operand bundles",
Call);
4073 FoundPtrauthBundle =
true;
4075 "Expected exactly two ptrauth bundle operands",
Call);
4077 BU.
Inputs[0]->getType()->isIntegerTy(32),
4078 "Ptrauth bundle key operand must be an i32 constant",
Call);
4080 "Ptrauth bundle discriminator operand must be an i64",
Call);
4082 Check(!FoundKCFIBundle,
"Multiple kcfi operand bundles",
Call);
4083 FoundKCFIBundle =
true;
4084 Check(BU.
Inputs.size() == 1,
"Expected exactly one kcfi bundle operand",
4087 BU.
Inputs[0]->getType()->isIntegerTy(32),
4088 "Kcfi bundle operand must be an i32 constant",
Call);
4090 Check(!FoundPreallocatedBundle,
"Multiple preallocated operand bundles",
4092 FoundPreallocatedBundle =
true;
4094 "Expected exactly one preallocated bundle operand",
Call);
4097 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
4098 "\"preallocated\" argument must be a token from "
4099 "llvm.call.preallocated.setup",
4102 Check(!FoundGCLiveBundle,
"Multiple gc-live operand bundles",
Call);
4103 FoundGCLiveBundle =
true;
4105 Check(!FoundAttachedCallBundle,
4106 "Multiple \"clang.arc.attachedcall\" operand bundles",
Call);
4107 FoundAttachedCallBundle =
true;
4108 verifyAttachedCallBundle(
Call, BU);
4114 "Direct call cannot have a ptrauth bundle",
Call);
4126 "inlinable function call in a function with "
4127 "debug info must have a !dbg location",
4131 verifyInlineAsmCall(
Call);
4135 visitInstruction(
Call);
4138void Verifier::verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs,
4141 Twine(
"inalloca attribute not allowed in ") +
Context);
4143 Twine(
"inreg attribute not allowed in ") +
Context);
4144 Check(!
Attrs.contains(Attribute::SwiftError),
4145 Twine(
"swifterror attribute not allowed in ") +
Context);
4146 Check(!
Attrs.contains(Attribute::Preallocated),
4147 Twine(
"preallocated attribute not allowed in ") +
Context);
4149 Twine(
"byref attribute not allowed in ") +
Context);
4154 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
4155 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
4156 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
4158 AttrBuilder Copy(
C);
4159 for (
auto AK : ABIAttrs) {
4160 Attribute Attr = Attrs.getParamAttrs(
I).getAttribute(AK);
4162 Copy.addAttribute(Attr);
4166 if (Attrs.hasParamAttr(
I, Attribute::Alignment) &&
4167 (Attrs.hasParamAttr(
I, Attribute::ByVal) ||
4168 Attrs.hasParamAttr(
I, Attribute::ByRef)))
4169 Copy.addAlignmentAttr(Attrs.getParamAlignment(
I));
4173void Verifier::verifyMustTailCall(CallInst &CI) {
4177 FunctionType *CallerTy =
F->getFunctionType();
4179 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
4180 "cannot guarantee tail call due to mismatched varargs", &CI);
4181 Check(CallerTy->getReturnType() == CalleeTy->getReturnType(),
4182 "cannot guarantee tail call due to mismatched return types", &CI);
4186 "cannot guarantee tail call due to mismatched calling conv", &CI);
4194 Check(Ret,
"musttail call must precede a ret", &CI);
4197 "musttail call result must be returned", Ret);
4199 AttributeList CallerAttrs =
F->getAttributes();
4204 CI.
getCallingConv() == CallingConv::Tail ?
"tailcc" :
"swifttailcc";
4208 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4210 SmallString<32>
Context{CCName, StringRef(
" musttail caller")};
4211 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4213 for (
unsigned I = 0,
E = CalleeTy->getNumParams();
I !=
E; ++
I) {
4215 SmallString<32>
Context{CCName, StringRef(
" musttail callee")};
4216 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4219 Check(!CallerTy->isVarArg(), Twine(
"cannot guarantee ") + CCName +
4220 " tail call for varargs function");
4226 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
4227 "cannot guarantee tail call due to mismatched parameter counts", &CI);
4228 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4229 Check(CallerTy->getParamType(
I) == CalleeTy->getParamType(
I),
4230 "cannot guarantee tail call due to mismatched parameter types",
4237 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4240 Check(CallerABIAttrs == CalleeABIAttrs,
4241 "cannot guarantee tail call due to mismatched ABI impacting "
4242 "function attributes",
4247void Verifier::visitCallInst(CallInst &CI) {
4251 verifyMustTailCall(CI);
4254void Verifier::visitInvokeInst(InvokeInst &
II) {
4260 II.getUnwindDest()->isEHPad(),
4261 "The unwind destination does not have an exception handling instruction!",
4264 visitTerminator(
II);
4269void Verifier::visitUnaryOperator(UnaryOperator &U) {
4270 Check(
U.getType() ==
U.getOperand(0)->getType(),
4271 "Unary operators must have same type for"
4272 "operands and result!",
4275 switch (
U.getOpcode()) {
4278 case Instruction::FNeg:
4279 Check(
U.getType()->isFPOrFPVectorTy(),
4280 "FNeg operator only works with float types!", &U);
4286 visitInstruction(U);
4292void Verifier::visitBinaryOperator(BinaryOperator &
B) {
4293 Check(
B.getOperand(0)->getType() ==
B.getOperand(1)->getType(),
4294 "Both operands to a binary operator are not of the same type!", &
B);
4296 switch (
B.getOpcode()) {
4299 case Instruction::Add:
4300 case Instruction::Sub:
4301 case Instruction::Mul:
4302 case Instruction::SDiv:
4303 case Instruction::UDiv:
4304 case Instruction::SRem:
4305 case Instruction::URem:
4306 Check(
B.getType()->isIntOrIntVectorTy(),
4307 "Integer arithmetic operators only work with integral types!", &
B);
4308 Check(
B.getType() ==
B.getOperand(0)->getType(),
4309 "Integer arithmetic operators must have same type "
4310 "for operands and result!",
4315 case Instruction::FAdd:
4316 case Instruction::FSub:
4317 case Instruction::FMul:
4318 case Instruction::FDiv:
4319 case Instruction::FRem:
4320 Check(
B.getType()->isFPOrFPVectorTy(),
4321 "Floating-point arithmetic operators only work with "
4322 "floating-point types!",
4324 Check(
B.getType() ==
B.getOperand(0)->getType(),
4325 "Floating-point arithmetic operators must have same type "
4326 "for operands and result!",
4330 case Instruction::And:
4331 case Instruction::Or:
4332 case Instruction::Xor:
4333 Check(
B.getType()->isIntOrIntVectorTy(),
4334 "Logical operators only work with integral types!", &
B);
4335 Check(
B.getType() ==
B.getOperand(0)->getType(),
4336 "Logical operators must have same type for operands and result!", &
B);
4338 case Instruction::Shl:
4339 case Instruction::LShr:
4340 case Instruction::AShr:
4341 Check(
B.getType()->isIntOrIntVectorTy(),
4342 "Shifts only work with integral types!", &
B);
4343 Check(
B.getType() ==
B.getOperand(0)->getType(),
4344 "Shift return type must be same as operands!", &
B);
4350 visitInstruction(
B);
4353void Verifier::visitICmpInst(ICmpInst &IC) {
4357 Check(Op0Ty == Op1Ty,
4358 "Both operands to ICmp instruction are not of the same type!", &IC);
4361 "Invalid operand types for ICmp instruction", &IC);
4365 visitInstruction(IC);
4368void Verifier::visitFCmpInst(FCmpInst &FC) {
4370 Type *Op0Ty =
FC.getOperand(0)->getType();
4371 Type *Op1Ty =
FC.getOperand(1)->getType();
4372 Check(Op0Ty == Op1Ty,
4373 "Both operands to FCmp instruction are not of the same type!", &FC);
4378 Check(
FC.isFPPredicate(),
"Invalid predicate in FCmp instruction!", &FC);
4380 visitInstruction(FC);
4383void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
4385 "Invalid extractelement operands!", &EI);
4386 visitInstruction(EI);
4389void Verifier::visitInsertElementInst(InsertElementInst &IE) {
4392 "Invalid insertelement operands!", &IE);
4393 visitInstruction(IE);
4396void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
4399 "Invalid shufflevector operands!", &SV);
4400 visitInstruction(SV);
4403void Verifier::visitGetElementPtrInst(GetElementPtrInst &
GEP) {
4405 GEP.getModule()->getModuleFlag(
"require-logical-pointer")))
4406 Check(!MD->getZExtValue(),
4407 "Non-logical getelementptr disallowed for this module.");
4409 Type *TargetTy =
GEP.getPointerOperandType()->getScalarType();
4412 "GEP base pointer is not a vector or a vector of pointers", &
GEP);
4413 Check(
GEP.getSourceElementType()->isSized(),
"GEP into unsized type!", &
GEP);
4416 Check(!STy->isScalableTy(),
4417 "getelementptr cannot target structure that contains scalable vector"
4422 SmallVector<Value *, 16> Idxs(
GEP.indices());
4424 all_of(Idxs, [](
Value *V) {
return V->getType()->isIntOrIntVectorTy(); }),
4425 "GEP indexes must be integers", &
GEP);
4428 Check(ElTy,
"Invalid indices for GEP pointer type!", &
GEP);
4432 Check(PtrTy &&
GEP.getResultElementType() == ElTy,
4433 "GEP is not of right type for indices!", &
GEP, ElTy);
4437 ElementCount GEPWidth = GEPVTy->getElementCount();
4438 if (
GEP.getPointerOperandType()->isVectorTy())
4442 "Vector GEP result width doesn't match operand's", &
GEP);
4443 for (
Value *Idx : Idxs) {
4444 Type *IndexTy = Idx->getType();
4446 ElementCount IndexWidth = IndexVTy->getElementCount();
4447 Check(IndexWidth == GEPWidth,
"Invalid GEP index vector width", &
GEP);
4450 "All GEP indices should be of integer type");
4457 GTI != GTE; ++GTI) {
4458 if (GTI.isVector()) {
4459 Type *ElemTy = GTI.getIndexedType();
4460 Check(
DL.typeSizeEqualsStoreSize(ElemTy),
4461 "GEP into vector with non-byte-addressable element type", &
GEP);
4465 Check(
GEP.getAddressSpace() == PtrTy->getAddressSpace(),
4466 "GEP address space doesn't match type", &
GEP);
4468 visitInstruction(
GEP);
4472 return A.getUpper() ==
B.getLower() ||
A.getLower() ==
B.getUpper();
4477void Verifier::verifyRangeLikeMetadata(
const Value &
I,
const MDNode *
Range,
4478 Type *Ty, RangeLikeMetadataKind Kind) {
4479 unsigned NumOperands =
Range->getNumOperands();
4480 Check(NumOperands % 2 == 0,
"Unfinished range!",
Range);
4481 unsigned NumRanges = NumOperands / 2;
4482 Check(NumRanges >= 1,
"It should have at least one range!",
Range);
4484 ConstantRange LastRange(1,
true);
4485 for (
unsigned i = 0; i < NumRanges; ++i) {
4488 Check(
Low,
"The lower limit must be an integer!",
Low);
4493 Check(
High->getType() ==
Low->getType(),
"Range pair types must match!",
4496 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4498 "noalias.addrspace type must be i32!", &
I);
4501 "Range types must match instruction type!", &
I);
4504 APInt HighV =
High->getValue();
4505 APInt LowV =
Low->getValue();
4510 "The upper and lower limits cannot be the same value", &
I);
4512 ConstantRange CurRange(LowV, HighV);
4513 Check(!CurRange.isEmptySet() &&
4514 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
4515 !CurRange.isFullSet()),
4516 "Range must not be empty!",
Range);
4518 Check(CurRange.intersectWith(LastRange).isEmptySet(),
4519 "Intervals are overlapping",
Range);
4520 Check(LowV.
sgt(LastRange.getLower()),
"Intervals are not in order",
4525 LastRange = ConstantRange(LowV, HighV);
4527 if (NumRanges > 2) {
4532 ConstantRange FirstRange(FirstLow, FirstHigh);
4533 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
4534 "Intervals are overlapping",
Range);
4540void Verifier::visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty) {
4542 "precondition violation");
4543 verifyRangeLikeMetadata(
I,
Range, Ty, RangeLikeMetadataKind::Range);
4546void Verifier::visitNoFPClassMetadata(Instruction &
I, MDNode *NoFPClass,
4548 Check(AttributeFuncs::isNoFPClassCompatibleType(Ty),
4549 "nofpclass only applies to floating-point typed loads",
I);
4552 "nofpclass must have exactly one entry", NoFPClass);
4553 ConstantInt *MaskVal =
4556 "nofpclass entry must be a constant i32", NoFPClass);
4558 Check(Val != 0,
"'nofpclass' must have at least one test bit set", NoFPClass,
4562 "Invalid value for 'nofpclass' test mask", NoFPClass,
I);
4565void Verifier::visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
4568 "precondition violation");
4569 verifyRangeLikeMetadata(
I,
Range, Ty,
4570 RangeLikeMetadataKind::NoaliasAddrspace);
4573void Verifier::checkAtomicMemAccessSize(
Type *Ty,
const Instruction *
I) {
4574 unsigned Size =
DL.getTypeSizeInBits(Ty).getFixedValue();
4575 Check(
Size >= 8,
"atomic memory access' size must be byte-sized", Ty,
I);
4577 "atomic memory access' operand must have a power-of-two size", Ty,
I);
4580void Verifier::visitLoadInst(LoadInst &LI) {
4582 Check(PTy,
"Load operand must be a pointer.", &LI);
4585 Check(
A->value() <= Value::MaximumAlignment,
4586 "huge alignment values are unsupported", &LI);
4588 Check(ElTy->
isSized(),
"loading unsized types is not allowed", &LI);
4591 LI.
getOrdering() != AtomicOrdering::AcquireRelease,
4592 "Load cannot have Release ordering", &LI);
4594 Type *ScalarTy = ElTy;
4598 "atomic elementwise load operand must have fixed vector type!", &LI,
4601 checkAtomicMemAccessSize(ScalarTy, &LI);
4602 ScalarTy = VecTy->getElementType();
4609 "atomic load operand must have integer, byte, pointer, floating "
4610 "point, or vector type!",
4613 checkAtomicMemAccessSize(ScalarTy, &LI);
4617 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4620 visitInstruction(LI);
4623void Verifier::visitStoreInst(StoreInst &SI) {
4625 Check(PTy,
"Store operand must be a pointer.", &SI);
4626 Type *ElTy =
SI.getOperand(0)->getType();
4627 if (MaybeAlign
A =
SI.getAlign()) {
4628 Check(
A->value() <= Value::MaximumAlignment,
4629 "huge alignment values are unsupported", &SI);
4631 Check(ElTy->
isSized(),
"storing unsized types is not allowed", &SI);
4632 if (
SI.isAtomic()) {
4633 Check(
SI.getOrdering() != AtomicOrdering::Acquire &&
4634 SI.getOrdering() != AtomicOrdering::AcquireRelease,
4635 "Store cannot have Acquire ordering", &SI);
4639 "atomic store operand must have integer, byte, pointer, floating "
4640 "point, or vector type!",
4642 checkAtomicMemAccessSize(ElTy, &SI);
4645 "Non-atomic store cannot have SynchronizationScope specified", &SI);
4647 visitInstruction(SI);
4651void Verifier::verifySwiftErrorCall(CallBase &
Call,
4652 const Value *SwiftErrorVal) {
4654 if (
I.value() == SwiftErrorVal) {
4656 "swifterror value when used in a callsite should be marked "
4657 "with swifterror attribute",
4658 SwiftErrorVal,
Call);
4663void Verifier::verifySwiftErrorValue(
const Value *SwiftErrorVal) {
4666 for (
const User *U : SwiftErrorVal->
users()) {
4669 "swifterror value can only be loaded and stored from, or "
4670 "as a swifterror argument!",
4674 Check(StoreI->getOperand(1) == SwiftErrorVal,
4675 "swifterror value should be the second operand when used "
4679 verifySwiftErrorCall(*
const_cast<CallBase *
>(
Call), SwiftErrorVal);
4683void Verifier::visitAllocaInst(AllocaInst &AI) {
4686 Check(!MD->getZExtValue(),
4687 "Non-logical alloca disallowed for this module.");
4690 SmallPtrSet<Type*, 4> Visited;
4691 Check(Ty->
isSized(&Visited),
"Cannot allocate unsized type", &AI);
4695 "Alloca has illegal target extension type", &AI);
4697 "Alloca array size must have integer type", &AI);
4699 Check(
A->value() <= Value::MaximumAlignment,
4700 "huge alignment values are unsupported", &AI);
4706 "swifterror alloca must not be array allocation", &AI);
4707 verifySwiftErrorValue(&AI);
4710 visitInstruction(AI);
4716void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4719 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4720 checkAtomicMemAccessSize(ElTy, &CXI);
4721 visitInstruction(CXI);
4724void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
4726 "atomicrmw instructions cannot be unordered.", &RMWI);
4729 Type *ScalarTy = ElTy;
4732 Check(VecTy,
"atomicrmw elementwise operand must have fixed vector type!",
4735 ScalarTy = VecTy->getElementType();
4742 " operand must have integer or floating point type!",
4747 " operand must have floating-point or fixed vector of "
4754 " operand must have integer or fixed vector of integer type!",
4757 checkAtomicMemAccessSize(ElTy, &RMWI);
4759 "Invalid binary operation!", &RMWI);
4760 visitInstruction(RMWI);
4763void Verifier::visitFenceInst(FenceInst &FI) {
4765 Check(Ordering == AtomicOrdering::Acquire ||
4766 Ordering == AtomicOrdering::Release ||
4767 Ordering == AtomicOrdering::AcquireRelease ||
4768 Ordering == AtomicOrdering::SequentiallyConsistent,
4769 "fence instructions may only have acquire, release, acq_rel, or "
4770 "seq_cst ordering.",
4772 visitInstruction(FI);
4775void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
4778 "Invalid ExtractValueInst operands!", &EVI);
4780 visitInstruction(EVI);
4783void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
4787 "Invalid InsertValueInst operands!", &IVI);
4789 visitInstruction(IVI);
4794 return FPI->getParentPad();
4799void Verifier::visitEHPadPredecessors(Instruction &
I) {
4805 Check(BB != &
F->getEntryBlock(),
"EH pad cannot be in entry block.", &
I);
4813 Check(
II &&
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4814 "Block containing LandingPadInst must be jumped to "
4815 "only by the unwind edge of an invoke.",
4823 "Block containg CatchPadInst must be jumped to "
4824 "only by its catchswitch.",
4826 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4827 "Catchswitch cannot unwind to one of its catchpads",
4828 CPI->getCatchSwitch(), CPI);
4840 Check(
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4841 "EH pad must be jumped to via an unwind edge", ToPad,
II);
4844 if (CalledFn && CalledFn->isIntrinsic() &&
II->doesNotThrow() &&
4848 FromPad = Bundle->Inputs[0];
4852 FromPad = CRI->getOperand(0);
4853 Check(FromPad != ToPadParent,
"A cleanupret must exit its cleanup", CRI);
4857 Check(
false,
"EH pad must be jumped to via an unwind edge", ToPad, TI);
4861 SmallPtrSet<Value *, 8> Seen;
4863 Check(FromPad != ToPad,
4864 "EH pad cannot handle exceptions raised within it", FromPad, TI);
4865 if (FromPad == ToPadParent) {
4870 "A single unwind edge may only enter one EH pad", TI);
4871 Check(Seen.
insert(FromPad).second,
"EH pad jumps through a cycle of pads",
4877 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
4882void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
4886 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
4888 visitEHPadPredecessors(LPI);
4890 if (!LandingPadResultTy)
4891 LandingPadResultTy = LPI.
getType();
4894 "The landingpad instruction should have a consistent result type "
4895 "inside a function.",
4899 Check(
F->hasPersonalityFn(),
4900 "LandingPadInst needs to be in a function with a personality.", &LPI);
4905 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
4911 "Catch operand does not have pointer type!", &LPI);
4913 Check(LPI.
isFilter(i),
"Clause is neither catch nor filter!", &LPI);
4915 "Filter operand is not an array of constants!", &LPI);
4919 visitInstruction(LPI);
4922void Verifier::visitResumeInst(ResumeInst &RI) {
4924 "ResumeInst needs to be in a function with a personality.", &RI);
4926 if (!LandingPadResultTy)
4930 "The resume instruction should have a consistent result type "
4931 "inside a function.",
4934 visitTerminator(RI);
4937void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
4941 Check(
F->hasPersonalityFn(),
4942 "CatchPadInst needs to be in a function with a personality.", &CPI);
4945 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4951 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
4956 return isa<Constant>(V) || isa<AllocaInst>(V);
4958 "Argument operand must be alloca or constant.", &CPI);
4960 visitEHPadPredecessors(CPI);
4961 visitFuncletPadInst(CPI);
4964void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
4966 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
4969 visitTerminator(CatchReturn);
4972void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
4976 Check(
F->hasPersonalityFn(),
4977 "CleanupPadInst needs to be in a function with a personality.", &CPI);
4982 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
4986 "CleanupPadInst has an invalid parent.", &CPI);
4988 visitEHPadPredecessors(CPI);
4989 visitFuncletPadInst(CPI);
4992void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
4993 User *FirstUser =
nullptr;
4994 Value *FirstUnwindPad =
nullptr;
4996 SmallPtrSet<FuncletPadInst *, 8> Seen;
4998 while (!Worklist.empty()) {
4999 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
5001 "FuncletPadInst must not be nested within itself", CurrentPad);
5002 Value *UnresolvedAncestorPad =
nullptr;
5003 for (User *U : CurrentPad->
users()) {
5006 UnwindDest = CRI->getUnwindDest();
5012 if (CSI->unwindsToCaller())
5014 UnwindDest = CSI->getUnwindDest();
5016 UnwindDest =
II->getUnwindDest();
5026 Worklist.push_back(CPI);
5041 if (UnwindParent == CurrentPad)
5047 Value *ExitedPad = CurrentPad;
5050 if (ExitedPad == &FPI) {
5055 UnresolvedAncestorPad = &FPI;
5059 if (ExitedParent == UnwindParent) {
5063 UnresolvedAncestorPad = ExitedParent;
5066 ExitedPad = ExitedParent;
5072 UnresolvedAncestorPad = &FPI;
5079 Check(UnwindPad == FirstUnwindPad,
5080 "Unwind edges out of a funclet "
5081 "pad must have the same unwind "
5083 &FPI, U, FirstUser);
5086 FirstUnwindPad = UnwindPad;
5095 if (CurrentPad != &FPI)
5098 if (UnresolvedAncestorPad) {
5099 if (CurrentPad == UnresolvedAncestorPad) {
5103 assert(CurrentPad == &FPI);
5111 Value *ResolvedPad = CurrentPad;
5112 while (!Worklist.empty()) {
5113 Value *UnclePad = Worklist.back();
5117 while (ResolvedPad != AncestorPad) {
5119 if (ResolvedParent == UnresolvedAncestorPad) {
5122 ResolvedPad = ResolvedParent;
5126 if (ResolvedPad != AncestorPad)
5129 Worklist.pop_back();
5134 if (FirstUnwindPad) {
5136 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
5137 Value *SwitchUnwindPad;
5138 if (SwitchUnwindDest)
5142 Check(SwitchUnwindPad == FirstUnwindPad,
5143 "Unwind edges out of a catch must have the same unwind dest as "
5144 "the parent catchswitch",
5145 &FPI, FirstUser, CatchSwitch);
5149 visitInstruction(FPI);
5152void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
5156 Check(
F->hasPersonalityFn(),
5157 "CatchSwitchInst needs to be in a function with a personality.",
5163 "CatchSwitchInst not the first non-PHI instruction in the block.",
5168 "CatchSwitchInst has an invalid parent.", ParentPad);
5173 "CatchSwitchInst must unwind to an EH block which is not a "
5179 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
5183 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
5185 for (BasicBlock *Handler : CatchSwitch.
handlers()) {
5187 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
5190 visitEHPadPredecessors(CatchSwitch);
5191 visitTerminator(CatchSwitch);
5194void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
5196 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
5202 "CleanupReturnInst must unwind to an EH block which is not a "
5207 visitTerminator(CRI);
5210void Verifier::verifyDominatesUse(Instruction &
I,
unsigned i) {
5216 if (
II->getNormalDest() ==
II->getUnwindDest())
5230 const Use &
U =
I.getOperandUse(i);
5231 Check(DT.dominates(
Op, U),
"Instruction does not dominate all uses!",
Op, &
I);
5234void Verifier::visitDereferenceableMetadata(Instruction&
I, MDNode* MD) {
5235 Check(
I.getType()->isPointerTy(),
5236 "dereferenceable, dereferenceable_or_null "
5237 "apply only to pointer types",
5240 "dereferenceable, dereferenceable_or_null apply only to load"
5241 " and inttoptr instructions, use attributes for calls or invokes",
5244 "dereferenceable, dereferenceable_or_null "
5245 "take one operand!",
5250 "dereferenceable_or_null metadata value must be an i64!",
5254void Verifier::visitNofreeMetadata(Instruction &
I, MDNode *MD) {
5255 Check(
I.getType()->isPointerTy(),
"nofree applies only to pointer types", &
I);
5261void Verifier::visitProfMetadata(Instruction &
I, MDNode *MD) {
5262 auto GetBranchingTerminatorNumOperands = [&]() {
5263 unsigned ExpectedNumOperands = 0;
5267 ExpectedNumOperands =
SI->getNumSuccessors();
5269 ExpectedNumOperands = 1;
5271 ExpectedNumOperands = IBI->getNumDestinations();
5273 ExpectedNumOperands = 2;
5276 return ExpectedNumOperands;
5279 "!prof annotations should have at least 1 operand", MD);
5281 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null", MD);
5283 "expected string with name of the !prof annotation", MD);
5289 "'unknown' !prof should only appear on instructions on which "
5290 "'branch_weights' would",
5292 verifyUnknownProfileMetadata(MD);
5297 "!prof annotations should have no less than 2 operands", MD);
5303 Check(NumBranchWeights == 1 || NumBranchWeights == 2,
5304 "Wrong number of InvokeInst branch_weights operands", MD);
5306 const unsigned ExpectedNumOperands = GetBranchingTerminatorNumOperands();
5307 if (ExpectedNumOperands == 0)
5308 CheckFailed(
"!prof branch_weights are not allowed for this instruction",
5311 Check(NumBranchWeights == ExpectedNumOperands,
"Wrong number of operands",
5317 Check(MDO,
"second operand should not be null", MD);
5319 "!prof brunch_weights operand is not a const int");
5324 Check(KindInt,
"VP !prof missing kind argument", MD);
5327 Check(Kind >= InstrProfValueKind::IPVK_First &&
5328 Kind <= InstrProfValueKind::IPVK_Last,
5329 "Invalid VP !prof kind", MD);
5331 "VP !prof should have an even number "
5332 "of arguments after 'VP'",
5334 if (Kind == InstrProfValueKind::IPVK_IndirectCallTarget ||
5335 Kind == InstrProfValueKind::IPVK_MemOPSize)
5337 "VP !prof indirect call or memop size expected to be applied to "
5338 "CallBase instructions only",
5341 DenseSet<uint64_t> ProfileValues;
5343 ConstantInt *ProfileValue =
5345 Check(ProfileValue,
"VP !prof value operand is not a const int", MD);
5346 uint64_t ProfileValueInt = ProfileValue->
getZExtValue();
5347 auto [ValueIt,
Inserted] = ProfileValues.
insert(ProfileValueInt);
5348 Check(Inserted,
"VP !prof should not have duplicate profile values", MD);
5351 CheckFailed(
"expected either branch_weights or VP profile name", MD);
5355void Verifier::visitDIAssignIDMetadata(Instruction &
I, MDNode *MD) {
5356 assert(
I.hasMetadata(LLVMContext::MD_DIAssignID));
5361 bool ExpectedInstTy =
5363 CheckDI(ExpectedInstTy,
"!DIAssignID attached to unexpected instruction kind",
5368 for (
auto *User : AsValue->users()) {
5370 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
5374 CheckDI(DAI->getFunction() ==
I.getFunction(),
5375 "dbg.assign not in same function as inst", DAI, &
I);
5378 for (DbgVariableRecord *DVR :
5381 "!DIAssignID should only be used by Assign DVRs.", MD, DVR);
5382 CheckDI(DVR->getFunction() ==
I.getFunction(),
5383 "DVRAssign not in same function as inst", DVR, &
I);
5387void Verifier::visitMMRAMetadata(Instruction &
I, MDNode *MD) {
5389 "!mmra metadata attached to unexpected instruction kind",
I, MD);
5400 for (
const MDOperand &MDOp : MD->
operands())
5402 "!mmra metadata tuple operand is not an MMRA tag",
I, MDOp.get());
5405void Verifier::visitCallStackMetadata(MDNode *MD) {
5409 "call stack metadata should have at least 1 operand", MD);
5413 "call stack metadata operand should be constant integer",
Op);
5416void Verifier::visitMemProfMetadata(Instruction &
I, MDNode *MD) {
5419 Check(
I.hasMetadata(LLVMContext::MD_callsite),
5420 "!memprof metadata requires !callsite metadata", &
I, MD);
5422 "!memprof annotations should have at least 1 metadata operand "
5427 for (
auto &MIBOp : MD->
operands()) {
5432 Check(MIB->getNumOperands() >= 2,
5433 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
5436 Check(MIB->getOperand(0) !=
nullptr,
5437 "!memprof MemInfoBlock first operand should not be null", MIB);
5439 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
5441 visitCallStackMetadata(StackMD);
5445 "!memprof MemInfoBlock second operand should be an MDString", MIB);
5448 for (
unsigned I = 2;
I < MIB->getNumOperands(); ++
I) {
5450 Check(OpNode,
"Not all !memprof MemInfoBlock operands 2 to N are MDNode",
5452 Check(OpNode->getNumOperands() == 2,
5453 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with 2 "
5458 [](
const MDOperand &
Op) {
5459 return mdconst::hasa<ConstantInt>(Op);
5461 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with "
5462 "ConstantInt operands",
5468void Verifier::visitCallsiteMetadata(Instruction &
I, MDNode *MD) {
5472 visitCallStackMetadata(MD);
5475void Verifier::visitCalleeTypeMetadata(Instruction &
I, MDNode *MD) {
5480 "The callee_type metadata must be a list of callgraph metadata nodes",
5483 Check(CallgraphMD->getNumOperands() == 1,
5484 "Well-formed callgraph metadata must contain exactly one "
5488 "The operand of callgraph metadata for functions must be an MDString",
5493void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
5496 "annotation must have at least one operand");
5498 bool TupleOfStrings =
5504 "operands must be a string or a tuple of strings");
5508void Verifier::visitAliasScopeMetadata(
const MDNode *MD) {
5513 "first scope operand must be self-referential or string", MD);
5516 "third scope operand must be string (if used)", MD);
5519 Check(
Domain !=
nullptr,
"second scope operand must be MDNode", MD);
5521 unsigned NumDomainOps =
Domain->getNumOperands();
5522 Check(NumDomainOps >= 1 && NumDomainOps <= 2,
5523 "domain must have one or two operands",
Domain);
5526 "first domain operand must be self-referential or string",
Domain);
5527 if (NumDomainOps == 2)
5529 "second domain operand must be string (if used)",
Domain);
5532void Verifier::visitAliasScopeListMetadata(
const MDNode *MD) {
5535 Check(OpMD !=
nullptr,
"scope list must consist of MDNodes", MD);
5536 visitAliasScopeMetadata(OpMD);
5540void Verifier::visitAccessGroupMetadata(
const MDNode *MD) {
5541 auto IsValidAccessScope = [](
const MDNode *MD) {
5546 if (IsValidAccessScope(MD))
5552 Check(OpMD !=
nullptr,
"Access scope list must consist of MDNodes", MD);
5553 Check(IsValidAccessScope(OpMD),
5554 "Access scope list contains invalid access scope", MD);
5558void Verifier::visitCapturesMetadata(Instruction &
I,
const MDNode *Captures) {
5559 static const char *ValidArgs[] = {
"address_is_null",
"address",
5560 "read_provenance",
"provenance"};
5563 Check(SI,
"!captures metadata can only be applied to store instructions", &
I);
5564 Check(
SI->getValueOperand()->getType()->isPointerTy(),
5565 "!captures metadata can only be applied to store with value operand of "
5573 Check(Str,
"!captures metadata must be a list of strings", &
I);
5575 "invalid entry in !captures metadata", &
I, Str);
5579void Verifier::visitAllocTokenMetadata(Instruction &
I, MDNode *MD) {
5584 "expected integer constant", MD);
5587void Verifier::visitInlineHistoryMetadata(Instruction &
I, MDNode *MD) {
5596 ->stripPointerCastsAndAliases()),
5597 "!inline_history operands must be functions or null", MD);
5601void Verifier::visitMemCacheHintMetadata(Instruction &
I, MDNode *MD) {
5602 Check(
I.mayReadOrWriteMemory(),
5603 "!mem.cache_hint is only valid on memory operations", &
I);
5606 "!mem.cache_hint must have even number of operands "
5607 "(operand_no, hint_node pairs)",
5613 "!mem.cache_hint is not supported on non-intrinsic calls", &
I);
5615 unsigned NumOperands = CB ? CB->arg_size() :
I.getNumOperands();
5617 SmallDenseSet<unsigned, 4> SeenOperandNos;
5618 std::optional<uint64_t> LastOperandNo;
5624 "!mem.cache_hint must alternate between i32 operand numbers and "
5625 "metadata hint nodes",
5628 Check(OpNoCI->getValue().isNonNegative(),
5629 "!mem.cache_hint operand number must be non-negative", MD);
5631 uint64_t OperandNo = OpNoCI->getZExtValue();
5632 Check(OperandNo < NumOperands,
5633 "!mem.cache_hint operand number is out of range", &
I);
5636 CB ? CB->getArgOperand(OperandNo) :
I.getOperand(OperandNo);
5638 "!mem.cache_hint operand number must refer to a pointer operand", &
I);
5641 Check(Inserted,
"!mem.cache_hint contains duplicate operand number", MD);
5643 Check(!Inserted || !LastOperandNo || OperandNo > *LastOperandNo,
5644 "!mem.cache_hint operand numbers must be in increasing order", MD);
5645 LastOperandNo = OperandNo;
5649 "!mem.cache_hint must alternate between i32 operand numbers and "
5650 "metadata hint nodes",
5654 "!mem.cache_hint hint node must have even number of operands "
5655 "(key-value pairs)",
5658 StringSet<> SeenKeys;
5659 for (
unsigned K = 0;
K + 1 <
Node->getNumOperands();
K += 2) {
5661 Check(
Key,
"!mem.cache_hint key must be a string", Node);
5663 StringRef KeyStr =
Key->getString();
5665 "!mem.cache_hint hint node contains duplicate key", Node);
5670 "!mem.cache_hint value must be a string or integer", Node);
5677void Verifier::visitInstruction(Instruction &
I) {
5679 Check(BB,
"Instruction not embedded in basic block!", &
I);
5682 for (User *U :
I.users()) {
5683 Check(U != (User *)&
I || !DT.isReachableFromEntry(BB),
5684 "Only PHI nodes may reference their own value!", &
I);
5689 Check(!
I.getType()->isVoidTy() || !
I.hasName(),
5690 "Instruction has a name, but provides a void value!", &
I);
5694 Check(
I.getType()->isVoidTy() ||
I.getType()->isFirstClassType(),
5695 "Instruction returns a non-scalar type!", &
I);
5700 "Invalid use of metadata!", &
I);
5705 for (Use &U :
I.uses()) {
5708 "Instruction referencing"
5709 " instruction not embedded in a basic block!",
5712 CheckFailed(
"Use of instruction is not an instruction!", U);
5721 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i) {
5722 Check(
I.getOperand(i) !=
nullptr,
"Instruction has null operand!", &
I);
5726 if (!
I.getOperand(i)->getType()->isFirstClassType()) {
5727 Check(
false,
"Instruction operands must be first-class values!", &
I);
5733 auto IsAttachedCallOperand = [](
Function *
F,
const CallBase *CBI,
5735 return CBI && CBI->isOperandBundleOfType(
5743 Check((!
F->isIntrinsic() ||
5744 (CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i)) ||
5745 IsAttachedCallOperand(
F, CBI, i)),
5746 "Cannot take the address of an intrinsic!", &
I);
5748 F->getIntrinsicID() == Intrinsic::donothing ||
5749 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
5750 F->getIntrinsicID() == Intrinsic::seh_try_end ||
5751 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
5752 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
5753 F->getIntrinsicID() == Intrinsic::coro_resume ||
5754 F->getIntrinsicID() == Intrinsic::coro_destroy ||
5755 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
5756 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
5757 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
5758 F->getIntrinsicID() ==
5759 Intrinsic::experimental_patchpoint_void ||
5760 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
5761 F->getIntrinsicID() == Intrinsic::fake_use ||
5762 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
5763 F->getIntrinsicID() == Intrinsic::wasm_throw ||
5764 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
5765 IsAttachedCallOperand(
F, CBI, i),
5766 "Cannot invoke an intrinsic other than donothing, patchpoint, "
5767 "statepoint, coro_resume, coro_destroy, clang.arc.attachedcall or "
5770 Check(
F->getParent() == &M,
"Referencing function in another module!", &
I,
5771 &M,
F,
F->getParent());
5774 "Referring to a basic block in another function!", &
I);
5777 "Referring to an argument in another function!", &
I);
5779 Check(GV->
getParent() == &M,
"Referencing global in another module!", &
I,
5783 "Referring to an instruction in another function!", &
I);
5784 verifyDominatesUse(
I, i);
5786 Check(CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i),
5787 "Cannot take the address of an inline asm!", &
I);
5789 visitConstantExprsRecursively(
C);
5793 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_fpmath)) {
5795 "fpmath requires a floating point result!", &
I);
5797 if (ConstantFP *CFP0 =
5799 const APFloat &Accuracy = CFP0->getValueAPF();
5801 "fpmath accuracy must have float type", &
I);
5803 "fpmath accuracy not a positive number!", &
I);
5805 Check(
false,
"invalid fpmath accuracy!", &
I);
5809 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_range)) {
5811 "Ranges are only for loads, calls and invokes!", &
I);
5812 visitRangeMetadata(
I,
Range,
I.getType());
5815 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofpclass)) {
5817 visitNoFPClassMetadata(
I, MD,
I.getType());
5820 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_noalias_addrspace)) {
5823 "noalias.addrspace are only for memory operations!", &
I);
5824 visitNoaliasAddrspaceMetadata(
I,
Range,
I.getType());
5827 if (
I.hasMetadata(LLVMContext::MD_invariant_group)) {
5829 "invariant.group metadata is only for loads and stores", &
I);
5832 if (
I.hasMetadata(LLVMContext::MD_invariant_load)) {
5835 "invariant.load metadata is only for loads and readonly "
5840 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nonnull)) {
5841 Check(
I.getType()->isPointerTy(),
"nonnull applies only to pointer types",
5844 "nonnull applies only to load instructions, use attributes"
5845 " for calls or invokes",
5850 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noundef)) {
5855 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable))
5856 visitDereferenceableMetadata(
I, MD);
5858 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
5859 visitDereferenceableMetadata(
I, MD);
5861 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofree))
5862 visitNofreeMetadata(
I, MD);
5864 if (MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa))
5867 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noalias))
5868 visitAliasScopeListMetadata(MD);
5869 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alias_scope))
5870 visitAliasScopeListMetadata(MD);
5872 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_access_group))
5873 visitAccessGroupMetadata(MD);
5875 if (MDNode *AlignMD =
I.getMetadata(LLVMContext::MD_align)) {
5876 Check(
I.getType()->isPointerTy(),
"align applies only to pointer types",
5879 "align applies only to load instructions, "
5880 "use attributes for calls or invokes",
5882 Check(AlignMD->getNumOperands() == 1,
"align takes one operand!", &
I);
5885 "align metadata value must be an i64!", &
I);
5889 Check(Align <= Value::MaximumAlignment,
5890 "alignment is larger that implementation defined limit", &
I);
5893 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_prof))
5894 visitProfMetadata(
I, MD);
5896 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_memprof))
5897 visitMemProfMetadata(
I, MD);
5899 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callsite))
5900 visitCallsiteMetadata(
I, MD);
5902 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callee_type))
5903 visitCalleeTypeMetadata(
I, MD);
5905 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_DIAssignID))
5906 visitDIAssignIDMetadata(
I, MD);
5908 if (MDNode *MMRA =
I.getMetadata(LLVMContext::MD_mmra))
5909 visitMMRAMetadata(
I, MMRA);
5911 if (MDNode *Annotation =
I.getMetadata(LLVMContext::MD_annotation))
5912 visitAnnotationMetadata(Annotation);
5914 if (MDNode *Captures =
I.getMetadata(LLVMContext::MD_captures))
5915 visitCapturesMetadata(
I, Captures);
5917 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alloc_token))
5918 visitAllocTokenMetadata(
I, MD);
5920 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_inline_history))
5921 visitInlineHistoryMetadata(
I, MD);
5923 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_mem_cache_hint))
5924 visitMemCacheHintMetadata(
I, MD);
5926 if (MDNode *MD =
I.getMetadata(
"amdgpu.expected.active.lanes")) {
5928 "!amdgpu.expected.active.lanes must have exactly one operand", &
I,
5933 "!amdgpu.expected.active.lanes operand must be an i32 constant", &
I,
5937 if (MDNode *
N =
I.getDebugLoc().getAsMDNode()) {
5939 visitMDNode(*
N, AreDebugLocsAllowed::Yes);
5942 if (
DL->getAtomGroup()) {
5943 CheckDI(
DL->getScope()->getSubprogram()->getKeyInstructionsEnabled(),
5944 "DbgLoc uses atomGroup but DISubprogram doesn't have Key "
5945 "Instructions enabled",
5946 DL,
DL->getScope()->getSubprogram());
5952 I.getAllMetadata(MDs);
5953 for (
auto Attachment : MDs) {
5954 unsigned Kind = Attachment.first;
5956 (
Kind == LLVMContext::MD_dbg ||
Kind == LLVMContext::MD_loop)
5957 ? AreDebugLocsAllowed::Yes
5958 : AreDebugLocsAllowed::
No;
5959 visitMDNode(*Attachment.second, AllowLocs);
5976 "const x86_amx is not allowed in argument!");
5982 case Intrinsic::assume: {
5986 "assume with operand bundles must have i1 true condition",
Call);
5992 auto GetTypeAt = [&](
unsigned Index) {
5993 return OBU.Inputs[
Index]->getType();
5998 CheckFailed(
"tags must be valid attribute names",
Call);
6000 case BundleAttr::Align:
6001 Check(OBU.Inputs.size() >= 2 && OBU.Inputs.size() <= 3,
6002 "alignment assumptions should have 2 or 3 arguments",
Call);
6005 Check(GetTypeAt(1)->isIntegerTy() &&
6006 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6007 "second argument should be an integer with a maximum width of 64 "
6010 Check(OBU.Inputs.size() < 3 ||
6011 (GetTypeAt(2)->isIntegerTy() &&
6012 GetTypeAt(2)->getIntegerBitWidth() <= 64),
6013 "third argument should be an integer with a maximum width of 64 "
6017 case BundleAttr::Cold:
6018 Check(OBU.Inputs.size() == 0,
6019 "cold assumptions should have no arguments",
Call);
6021 case BundleAttr::Dereferenceable:
6022 case BundleAttr::DereferenceableOrNull:
6023 Check(OBU.Inputs.size() == 2,
6024 "dereferenceable assumptions should have 2 arguments",
Call);
6027 Check(GetTypeAt(1)->isIntegerTy() &&
6028 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6029 "second argument should be an integer with a maximum width of 64 "
6033 case BundleAttr::Ignore:
6035 case BundleAttr::NonNull:
6036 Check(OBU.Inputs.size() == 1,
6037 "nonnull assumptions should have 1 argument",
Call);
6041 case BundleAttr::NoUndef:
6042 Check(OBU.Inputs.size() == 1,
6043 "noundef assumptions should have 1 argument",
Call);
6045 case BundleAttr::SeparateStorage:
6046 Check(OBU.Inputs.size() == 2,
6047 "separate_storage assumptions should have 2 arguments",
Call);
6049 "arguments to separate_storage assumptions should be pointers",
6056 case Intrinsic::ucmp:
6057 case Intrinsic::scmp: {
6062 "result type must be at least 2 bits wide",
Call);
6064 bool IsDestTypeVector = DestTy->
isVectorTy();
6066 "ucmp/scmp argument and result types must both be either vector or "
6069 if (IsDestTypeVector) {
6072 Check(SrcVecLen == DestVecLen,
6073 "return type and arguments must have the same number of "
6079 case Intrinsic::coro_begin:
6080 case Intrinsic::coro_begin_custom_abi:
6082 "id argument of llvm.coro.begin must refer to coro.id");
6084 case Intrinsic::coro_id: {
6086 "align argument only accepts constants");
6089 "promise argument must refer to an alloca");
6094 "coro argument must refer to a function");
6098 if (BeforeCoroSplit)
6101 Check(!BeforeCoroEarly,
"cannot run CoroSplit before CoroEarly");
6104 "info argument of llvm.coro.id must refer to an initialized "
6108 "info argument of llvm.coro.id must refer to either a struct or "
6112 case Intrinsic::is_fpclass: {
6115 "unsupported bits for llvm.is.fpclass test mask");
6118 case Intrinsic::fptrunc_round: {
6123 MD = MAV->getMetadata();
6125 Check(MD !=
nullptr,
"missing rounding mode argument",
Call);
6128 (
"invalid value for llvm.fptrunc.round metadata operand"
6129 " (the operand should be a string)"),
6132 std::optional<RoundingMode> RoundMode =
6134 Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
6135 "unsupported rounding mode argument",
Call);
6138 case Intrinsic::convert_to_arbitrary_fp: {
6146 "if floating-point operand is a vector, integer operand must also "
6149 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6150 "floating-point and integer vector operands must have the same "
6157 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6159 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6160 StringRef Interp = InterpStr->getString();
6162 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6167 "unsupported interpretation metadata string",
Call);
6170 if (
unsigned FormatBits =
6173 "integer type bit width must equal the arbitrary FP format width",
6178 Check(RoundingMAV,
"missing rounding mode metadata operand",
Call);
6180 Check(RoundingStr,
"rounding mode metadata operand must be a string",
Call);
6182 std::optional<RoundingMode>
RM =
6184 Check(RM && *RM != RoundingMode::Dynamic,
6185 "unsupported rounding mode argument",
Call);
6188 case Intrinsic::convert_from_arbitrary_fp: {
6196 "if floating-point operand is a vector, integer operand must also "
6199 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6200 "floating-point and integer vector operands must have the same "
6207 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6209 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6210 StringRef Interp = InterpStr->getString();
6212 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6217 "unsupported interpretation metadata string",
Call);
6220 if (
unsigned FormatBits =
6223 "integer type bit width must equal the arbitrary FP format width",
6227#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6228#include "llvm/IR/VPIntrinsics.def"
6229#undef BEGIN_REGISTER_VP_INTRINSIC
6232#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
6233 case Intrinsic::INTRINSIC:
6234#include "llvm/IR/ConstrainedOps.def"
6238 case Intrinsic::dbg_declare:
6239 case Intrinsic::dbg_value:
6240 case Intrinsic::dbg_assign:
6241 case Intrinsic::dbg_label:
6248 case Intrinsic::memcpy:
6249 case Intrinsic::memcpy_inline:
6250 case Intrinsic::memmove:
6251 case Intrinsic::memset:
6252 case Intrinsic::memset_inline:
6254 case Intrinsic::experimental_memset_pattern: {
6256 Check(Memset->getValue()->getType()->isSized(),
6257 "unsized types cannot be used as memset patterns",
Call);
6260 case Intrinsic::memcpy_element_unordered_atomic:
6261 case Intrinsic::memmove_element_unordered_atomic:
6262 case Intrinsic::memset_element_unordered_atomic: {
6265 ConstantInt *ElementSizeCI =
6267 const APInt &ElementSizeVal = ElementSizeCI->
getValue();
6269 "element size of the element-wise atomic memory intrinsic "
6270 "must be a power of 2",
6273 auto IsValidAlignment = [&](MaybeAlign Alignment) {
6274 return Alignment && ElementSizeVal.
ule(Alignment->value());
6276 Check(IsValidAlignment(AMI->getDestAlign()),
6277 "incorrect alignment of the destination argument",
Call);
6279 Check(IsValidAlignment(AMT->getSourceAlign()),
6280 "incorrect alignment of the source argument",
Call);
6284 case Intrinsic::call_preallocated_setup: {
6286 bool FoundCall =
false;
6289 Check(UseCall !=
nullptr,
6290 "Uses of llvm.call.preallocated.setup must be calls");
6292 if (IID == Intrinsic::call_preallocated_arg) {
6294 Check(AllocArgIndex !=
nullptr,
6295 "llvm.call.preallocated.alloc arg index must be a constant");
6296 auto AllocArgIndexInt = AllocArgIndex->getValue();
6297 Check(AllocArgIndexInt.sge(0) &&
6298 AllocArgIndexInt.slt(NumArgs->getValue()),
6299 "llvm.call.preallocated.alloc arg index must be between 0 and "
6301 "llvm.call.preallocated.setup's argument count");
6302 }
else if (IID == Intrinsic::call_preallocated_teardown) {
6305 Check(!FoundCall,
"Can have at most one call corresponding to a "
6306 "llvm.call.preallocated.setup");
6308 size_t NumPreallocatedArgs = 0;
6309 for (
unsigned i = 0; i < UseCall->arg_size(); i++) {
6310 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
6311 ++NumPreallocatedArgs;
6314 Check(NumPreallocatedArgs != 0,
6315 "cannot use preallocated intrinsics on a call without "
6316 "preallocated arguments");
6317 Check(NumArgs->equalsInt(NumPreallocatedArgs),
6318 "llvm.call.preallocated.setup arg size must be equal to number "
6319 "of preallocated arguments "
6329 auto PreallocatedBundle =
6331 Check(PreallocatedBundle,
6332 "Use of llvm.call.preallocated.setup outside intrinsics "
6333 "must be in \"preallocated\" operand bundle");
6334 Check(PreallocatedBundle->Inputs.front().get() == &
Call,
6335 "preallocated bundle must have token from corresponding "
6336 "llvm.call.preallocated.setup");
6341 case Intrinsic::call_preallocated_arg: {
6344 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6345 "llvm.call.preallocated.arg token argument must be a "
6346 "llvm.call.preallocated.setup");
6348 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
6349 "call site attribute");
6352 case Intrinsic::call_preallocated_teardown: {
6355 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6356 "llvm.call.preallocated.teardown token argument must be a "
6357 "llvm.call.preallocated.setup");
6360 case Intrinsic::gcroot:
6361 case Intrinsic::gcwrite:
6362 case Intrinsic::gcread:
6363 if (
ID == Intrinsic::gcroot) {
6366 Check(AI,
"llvm.gcroot parameter #1 must be an alloca.",
Call);
6368 "llvm.gcroot parameter #2 must be a constant.",
Call);
6371 "llvm.gcroot parameter #1 must either be a pointer alloca, "
6372 "or argument #2 must be a non-null constant.",
6378 "Enclosing function does not use GC.",
Call);
6380 case Intrinsic::init_trampoline:
6382 "llvm.init_trampoline parameter #2 must resolve to a function.",
6385 case Intrinsic::reloc_none: {
6388 "llvm.reloc.none argument must be a metadata string", &
Call);
6391 case Intrinsic::stackprotector:
6393 "llvm.stackprotector parameter #2 must resolve to an alloca.",
Call);
6395 case Intrinsic::localescape: {
6399 Check(!SawFrameEscape,
"multiple calls to llvm.localescape in one function",
6406 "llvm.localescape only accepts static allocas",
Call);
6409 SawFrameEscape =
true;
6412 case Intrinsic::localrecover: {
6415 Check(Fn && !Fn->isDeclaration(),
6416 "llvm.localrecover first "
6417 "argument must be function defined in this module",
6420 auto &
Entry = FrameEscapeInfo[Fn];
6421 Entry.second = unsigned(
6422 std::max(uint64_t(
Entry.second), IdxArg->getLimitedValue(~0U) + 1));
6426 case Intrinsic::experimental_gc_statepoint:
6428 Check(!CI->isInlineAsm(),
6429 "gc.statepoint support for inline assembly unimplemented", CI);
6431 "Enclosing function does not use GC.",
Call);
6433 verifyStatepoint(
Call);
6435 case Intrinsic::experimental_gc_result: {
6437 "Enclosing function does not use GC.",
Call);
6445 Check(StatepointCall && StatepointCall->getIntrinsicID() ==
6446 Intrinsic::experimental_gc_statepoint,
6447 "gc.result operand #1 must be from a statepoint",
Call,
6451 auto *TargetFuncType =
6454 "gc.result result type does not match wrapped callee",
Call);
6457 case Intrinsic::experimental_gc_relocate: {
6461 "gc.relocate must return a pointer or a vector of pointers",
Call);
6469 LandingPad->getParent()->getUniquePredecessor();
6473 Check(InvokeBB,
"safepoints should have unique landingpads",
6474 LandingPad->getParent());
6478 "gc relocate should be linked to a statepoint", InvokeBB);
6485 "gc relocate is incorrectly tied to the statepoint",
Call, Token);
6494 "gc.relocate operand #2 must be integer offset",
Call);
6498 "gc.relocate operand #3 must be integer offset",
Call);
6508 Check(BaseIndex < Opt->Inputs.size(),
6509 "gc.relocate: statepoint base index out of bounds",
Call);
6510 Check(DerivedIndex < Opt->Inputs.size(),
6511 "gc.relocate: statepoint derived index out of bounds",
Call);
6524 "gc.relocate: relocated value must be a pointer",
Call);
6525 Check(DerivedType->isPtrOrPtrVectorTy(),
6526 "gc.relocate: relocated value must be a pointer",
Call);
6528 Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
6529 "gc.relocate: vector relocates to vector and pointer to pointer",
6532 ResultType->getPointerAddressSpace() ==
6533 DerivedType->getPointerAddressSpace(),
6534 "gc.relocate: relocating a pointer shouldn't change its address space",
6538 Check(GC,
"gc.relocate: calling function must have GCStrategy",
6541 auto isGCPtr = [&
GC](
Type *PTy) {
6542 return GC->isGCManagedPointer(PTy->getScalarType()).value_or(
true);
6544 Check(isGCPtr(ResultType),
"gc.relocate: must return gc pointer",
Call);
6546 "gc.relocate: relocated value must be a gc pointer",
Call);
6547 Check(isGCPtr(DerivedType),
6548 "gc.relocate: relocated value must be a gc pointer",
Call);
6552 case Intrinsic::experimental_patchpoint: {
6555 "patchpoint: invalid return type used with anyregcc",
Call);
6559 case Intrinsic::eh_exceptioncode:
6560 case Intrinsic::eh_exceptionpointer: {
6562 "eh.exceptionpointer argument must be a catchpad",
Call);
6565 case Intrinsic::get_active_lane_mask: {
6568 "get_active_lane_mask: element type is not i1",
Call);
6571 case Intrinsic::experimental_get_vector_length: {
6573 Check(!VF->isNegative() && !VF->isZero(),
6574 "get_vector_length: VF must be positive",
Call);
6577 case Intrinsic::experimental_guard: {
6580 "experimental_guard must have exactly one "
6581 "\"deopt\" operand bundle");
6585 case Intrinsic::experimental_deoptimize: {
6589 "experimental_deoptimize must have exactly one "
6590 "\"deopt\" operand bundle");
6592 "experimental_deoptimize return type must match caller return type");
6597 "calls to experimental_deoptimize must be followed by a return");
6601 "calls to experimental_deoptimize must be followed by a return "
6602 "of the value computed by experimental_deoptimize");
6607 case Intrinsic::vastart: {
6609 "va_start called in a non-varargs function");
6612 case Intrinsic::get_dynamic_area_offset: {
6614 Check(IntTy &&
DL.getPointerSizeInBits(
DL.getAllocaAddrSpace()) ==
6615 IntTy->getBitWidth(),
6616 "get_dynamic_area_offset result type must be scalar integer matching "
6617 "alloca address space width",
6621 case Intrinsic::smul_fix:
6622 case Intrinsic::smul_fix_sat:
6623 case Intrinsic::umul_fix:
6624 case Intrinsic::umul_fix_sat:
6625 case Intrinsic::sdiv_fix:
6626 case Intrinsic::sdiv_fix_sat:
6627 case Intrinsic::udiv_fix:
6628 case Intrinsic::udiv_fix_sat: {
6632 if (
ID == Intrinsic::smul_fix ||
ID == Intrinsic::smul_fix_sat ||
6633 ID == Intrinsic::sdiv_fix ||
ID == Intrinsic::sdiv_fix_sat) {
6635 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
6639 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
6640 "to the width of the operands");
6644 case Intrinsic::lrint:
6645 case Intrinsic::llrint:
6646 case Intrinsic::lround:
6647 case Intrinsic::llround: {
6651 IF->
getName() +
": argument and result disagree on vector use",
6655 Check(VTy->getElementCount() == RTy->getElementCount(),
6656 IF->
getName() +
": argument must be same length as result", &
Call);
6660 case Intrinsic::bswap: {
6663 Check(
Size % 16 == 0,
"bswap must be an even number of bytes", &
Call);
6666 case Intrinsic::invariant_start: {
6668 Check(InvariantSize &&
6669 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
6670 "invariant_start parameter must be -1, 0 or a positive number",
6674 case Intrinsic::matrix_multiply:
6675 case Intrinsic::matrix_transpose:
6676 case Intrinsic::matrix_column_major_load:
6677 case Intrinsic::matrix_column_major_store: {
6679 Value *Stride =
nullptr;
6680 ConstantInt *NumRows;
6681 ConstantInt *NumColumns;
6683 Type *Op0ElemTy =
nullptr;
6684 Type *Op1ElemTy =
nullptr;
6686 case Intrinsic::matrix_multiply: {
6691 ->getNumElements() ==
6693 "First argument of a matrix operation does not match specified "
6696 ->getNumElements() ==
6698 "Second argument of a matrix operation does not match specified "
6708 case Intrinsic::matrix_transpose:
6715 case Intrinsic::matrix_column_major_load: {
6722 case Intrinsic::matrix_column_major_store: {
6735 Check(ResultTy->getElementType()->isIntegerTy() ||
6736 ResultTy->getElementType()->isFloatingPointTy(),
6737 "Result type must be an integer or floating-point type!", IF);
6740 Check(ResultTy->getElementType() == Op0ElemTy,
6741 "Vector element type mismatch of the result and first operand "
6746 Check(ResultTy->getElementType() == Op1ElemTy,
6747 "Vector element type mismatch of the result and second operand "
6753 "Result of a matrix operation does not fit in the returned vector!");
6757 "Stride bitwidth cannot exceed 64!", IF);
6761 case Intrinsic::stepvector: {
6763 Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
6764 VecTy->getScalarSizeInBits() >= 8,
6765 "stepvector only supported for vectors of integers "
6766 "with a bitwidth of at least 8.",
6770 case Intrinsic::experimental_vector_match: {
6779 Check(Op1Ty && Op2Ty && MaskTy,
"Operands must be vectors.", &
Call);
6781 "Second operand must be a fixed length vector.", &
Call);
6783 "First operand must be a vector of integers.", &
Call);
6784 Check(Op1Ty->getElementType() == Op2Ty->getElementType(),
6785 "First two operands must have the same element type.", &
Call);
6786 Check(Op1Ty->getElementCount() == MaskTy->getElementCount(),
6787 "First operand and mask must have the same number of elements.",
6789 Check(MaskTy->getElementType()->isIntegerTy(1),
6790 "Mask must be a vector of i1's.", &
Call);
6795 case Intrinsic::vector_insert: {
6804 ElementCount VecEC = VecTy->getElementCount();
6805 ElementCount SubVecEC = SubVecTy->getElementCount();
6806 Check(VecTy->getElementType() == SubVecTy->getElementType(),
6807 "vector_insert parameters must have the same element "
6811 "vector_insert index must be a constant multiple of "
6812 "the subvector's known minimum vector length.");
6820 "subvector operand of vector_insert would overrun the "
6821 "vector being inserted into.");
6825 case Intrinsic::vector_extract: {
6833 ElementCount VecEC = VecTy->getElementCount();
6834 ElementCount ResultEC = ResultTy->getElementCount();
6836 Check(ResultTy->getElementType() == VecTy->getElementType(),
6837 "vector_extract result must have the same element "
6838 "type as the input vector.",
6841 "vector_extract index must be a constant multiple of "
6842 "the result type's known minimum vector length.");
6850 "vector_extract would overrun.");
6854 case Intrinsic::vector_partial_reduce_fadd:
6855 case Intrinsic::vector_partial_reduce_add: {
6859 unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
6860 unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
6862 Check((VecWidth % AccWidth) == 0,
6863 "Invalid vector widths for partial "
6864 "reduction. The width of the input vector "
6865 "must be a positive integer multiple of "
6866 "the width of the accumulator vector.");
6869 case Intrinsic::experimental_noalias_scope_decl: {
6873 case Intrinsic::preserve_array_access_index:
6874 case Intrinsic::preserve_struct_access_index:
6875 case Intrinsic::aarch64_ldaxr:
6876 case Intrinsic::aarch64_ldxr:
6877 case Intrinsic::arm_ldaex:
6878 case Intrinsic::arm_ldrex: {
6880 Check(ElemTy,
"Intrinsic requires elementtype attribute on first argument.",
6884 case Intrinsic::aarch64_stlxr:
6885 case Intrinsic::aarch64_stxr:
6886 case Intrinsic::arm_stlex:
6887 case Intrinsic::arm_strex: {
6890 "Intrinsic requires elementtype attribute on second argument.",
6894 case Intrinsic::aarch64_prefetch: {
6896 "write argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6898 "target argument to llvm.aarch64.prefetch must be 0-3",
Call);
6900 "stream argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6902 "isdata argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6905 case Intrinsic::aarch64_range_prefetch: {
6907 "write argument to llvm.aarch64.range.prefetch must be 0 or 1",
Call);
6909 "stream argument to llvm.aarch64.range.prefetch must be 0 or 1",
6913 case Intrinsic::callbr_landingpad: {
6915 Check(CBR,
"intrinstic requires callbr operand", &
Call);
6922 CheckFailed(
"Intrinsic in block must have 1 unique predecessor", &
Call);
6926 CheckFailed(
"Intrinsic must have corresponding callbr in predecessor",
6931 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
6932 "block in indirect destination list",
6935 Check(&
First == &
Call,
"No other instructions may proceed intrinsic",
6939 case Intrinsic::structured_gep: {
6945 "Intrinsic first parameter is missing an ElementType attribute",
6953 "Index operand type must be an integer", &
Call);
6956 T = AT->getElementType();
6958 Check(CI,
"Indexing into a struct requires a constant int", &
Call);
6960 "Indexing in a struct should be inbounds", &
Call);
6963 T = VT->getElementType();
6965 CheckFailed(
"Reached a non-composite type with more indices to process",
6971 case Intrinsic::structured_alloca:
6973 "@llvm.structured.alloca calls require elementtype attribute.",
6976 case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
6977 case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
6980 Check(RegCount % 8 == 0,
6981 "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
6984 case Intrinsic::experimental_convergence_entry:
6985 case Intrinsic::experimental_convergence_anchor:
6987 case Intrinsic::experimental_convergence_loop:
6989 case Intrinsic::ptrmask: {
6993 "llvm.ptrmask intrinsic first argument must be pointer or vector "
6998 "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
7003 "llvm.ptrmask intrinsic arguments must have the same number of "
7007 "llvm.ptrmask intrinsic second argument bitwidth must match "
7008 "pointer index type size of first argument",
7012 case Intrinsic::thread_pointer: {
7014 DL.getDefaultGlobalsAddressSpace(),
7015 "llvm.thread.pointer intrinsic return type must be for the globals "
7020 case Intrinsic::threadlocal_address: {
7023 "llvm.threadlocal.address first argument must be a GlobalValue");
7025 "llvm.threadlocal.address operand isThreadLocal() must be true");
7028 case Intrinsic::lifetime_start:
7029 case Intrinsic::lifetime_end: {
7033 (
II &&
II->getIntrinsicID() == Intrinsic::structured_alloca),
7034 "llvm.lifetime.start/end can only be used on alloca or poison",
7038 case Intrinsic::sponentry: {
7039 const unsigned StackAS =
DL.getAllocaAddrSpace();
7042 "llvm.sponentry must return a pointer to the stack", &
Call);
7045 case Intrinsic::write_volatile_register: {
7049 "llvm.write_volatile_register metadata must be a single MDString",
7053 case Intrinsic::ptrauth_auth_with_pc_and_resign: {
7056 uint64_t
Key = AuthKey->getZExtValue();
7058 "ptrauth.auth.with.pc.and.resign key must be IA (0) or IB (1)",
7067 if (
F->hasPersonalityFn() &&
7071 if (BlockEHFuncletColors.
empty())
7075 bool InEHFunclet =
false;
7079 for (BasicBlock *ColorFirstBB : CV)
7080 if (
auto It = ColorFirstBB->getFirstNonPHIIt();
7081 It != ColorFirstBB->end())
7086 bool HasToken =
false;
7093 Check(HasToken,
"Missing funclet token on intrinsic call", &
Call);
7120void Verifier::visit(DbgLabelRecord &DLR) {
7122 "invalid #dbg_label intrinsic variable", &DLR, DLR.
getRawLabel());
7135 CheckDI(Loc,
"#dbg_label record requires a !dbg attachment", &DLR, BB,
F);
7139 if (!LabelSP || !LocSP)
7143 "mismatched subprogram between #dbg_label label and !dbg attachment",
7144 &DLR, BB,
F, Label,
Label->getScope()->getSubprogram(), Loc,
7145 Loc->getScope()->getSubprogram());
7148void Verifier::visit(DbgVariableRecord &DVR) {
7152 CheckDI(DVR.
getType() == DbgVariableRecord::LocationType::Value ||
7153 DVR.
getType() == DbgVariableRecord::LocationType::Declare ||
7154 DVR.
getType() == DbgVariableRecord::LocationType::DeclareValue ||
7155 DVR.
getType() == DbgVariableRecord::LocationType::Assign,
7156 "invalid #dbg record type", &DVR, DVR.
getType(), BB,
F);
7164 "invalid #dbg record address/value", &DVR, MD, BB,
F);
7166 visitValueAsMetadata(*VAM,
F);
7169 Type *Ty = VAM->getValue()->getType();
7171 "location of #dbg_declare must be a pointer or int", &DVR, MD, BB,
7175 visitDIArgList(*AL,
F);
7189 "invalid #dbg_assign DIAssignID", &DVR, DVR.
getRawAssignID(), BB,
7192 AreDebugLocsAllowed::No);
7201 "invalid #dbg_assign address", &DVR, DVR.
getRawAddress(), BB,
F);
7203 visitValueAsMetadata(*VAM,
F);
7206 "invalid #dbg_assign address expression", &DVR,
7213 "inst not in same function as #dbg_assign",
I, &DVR, BB,
F);
7223 &DVR, DLNode, BB,
F);
7229 if (!VarSP || !LocSP)
7233 "mismatched subprogram between #dbg record variable and DILocation",
7235 Loc->getScope()->getSubprogram(), BB,
F);
7240void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
7244 Check(RetTy->getElementCount() == ValTy->getElementCount(),
7245 "VP cast intrinsic first argument and result vector lengths must be "
7249 switch (VPCast->getIntrinsicID()) {
7250 case Intrinsic::vp_trunc:
7252 "llvm.vp.trunc intrinsic the bit size of first argument must be "
7253 "larger than the bit size of the return type",
7256 case Intrinsic::vp_zext:
7257 case Intrinsic::vp_sext:
7259 "llvm.vp.zext or llvm.vp.sext intrinsic the bit size of first "
7260 "argument must be smaller than the bit size of the return type",
7263 case Intrinsic::vp_fptrunc:
7265 "llvm.vp.fptrunc intrinsic the bit size of first argument must be "
7266 "larger than the bit size of the return type",
7269 case Intrinsic::vp_fpext:
7271 "llvm.vp.fpext intrinsic the bit size of first argument must be "
7272 "smaller than the bit size of the return type",
7281 case Intrinsic::vp_fcmp: {
7284 "invalid predicate for VP FP comparison intrinsic", &VPI);
7287 case Intrinsic::vp_icmp: {
7290 "invalid predicate for VP integer comparison intrinsic", &VPI);
7293 case Intrinsic::vp_is_fpclass: {
7296 "unsupported bits for llvm.vp.is.fpclass test mask");
7299 case Intrinsic::experimental_vp_splice: {
7302 int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
7304 AttributeList
Attrs = VPI.
getParent()->getParent()->getAttributes();
7305 if (
Attrs.hasFnAttr(Attribute::VScaleRange))
7306 KnownMinNumElements *=
Attrs.getFnAttrs().getVScaleRangeMin();
7308 Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
7309 (Idx >= 0 && Idx < KnownMinNumElements),
7310 "The splice index exceeds the range [-VL, VL-1] where VL is the "
7311 "known minimum number of elements in the vector. For scalable "
7312 "vectors the minimum number of elements is determined from "
7320void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
7322 bool HasRoundingMD =
7326 NumOperands += (1 + HasRoundingMD);
7332 "invalid arguments for constrained FP intrinsic", &FPI);
7335 case Intrinsic::experimental_constrained_fcmp:
7336 case Intrinsic::experimental_constrained_fcmps: {
7339 "invalid predicate for constrained FP comparison intrinsic", &FPI);
7343 case Intrinsic::experimental_constrained_fptosi:
7344 case Intrinsic::experimental_constrained_fptoui: {
7348 "Intrinsic first argument must be floating point", &FPI);
7355 "Intrinsic first argument and result disagree on vector use", &FPI);
7357 "Intrinsic result must be an integer", &FPI);
7360 "Intrinsic first argument and result vector lengths must be equal",
7366 case Intrinsic::experimental_constrained_sitofp:
7367 case Intrinsic::experimental_constrained_uitofp: {
7371 "Intrinsic first argument must be integer", &FPI);
7378 "Intrinsic first argument and result disagree on vector use", &FPI);
7380 "Intrinsic result must be a floating point", &FPI);
7383 "Intrinsic first argument and result vector lengths must be equal",
7389 case Intrinsic::experimental_constrained_fptrunc:
7390 case Intrinsic::experimental_constrained_fpext: {
7396 "Intrinsic first argument must be FP or FP vector", &FPI);
7398 "Intrinsic result must be FP or FP vector", &FPI);
7400 "Intrinsic first argument and result disagree on vector use", &FPI);
7404 "Intrinsic first argument and result vector lengths must be equal",
7407 if (FPI.
getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
7409 "Intrinsic first argument's type must be larger than result type",
7413 "Intrinsic first argument's type must be smaller than result type",
7429 "invalid exception behavior argument", &FPI);
7430 if (HasRoundingMD) {
7436void Verifier::verifyFragmentExpression(
const DbgVariableRecord &DVR) {
7441 if (!V || !
E || !
E->isValid())
7445 auto Fragment =
E->getFragmentInfo();
7455 if (
V->isArtificial())
7458 verifyFragmentExpression(*V, *Fragment, &DVR);
7461template <
typename ValueOrMetadata>
7462void Verifier::verifyFragmentExpression(
const DIVariable &V,
7464 ValueOrMetadata *
Desc) {
7467 auto VarSize =
V.getSizeInBits();
7473 CheckDI(FragSize + FragOffset <= *VarSize,
7474 "fragment is larger than or outside of variable",
Desc, &V);
7475 CheckDI(FragSize != *VarSize,
"fragment covers entire variable",
Desc, &V);
7478void Verifier::verifyFnArgs(
const DbgVariableRecord &DVR) {
7490 CheckDI(Var,
"#dbg record without variable");
7492 unsigned ArgNo = Var->
getArg();
7498 if (DebugFnArgs.
size() < ArgNo)
7499 DebugFnArgs.
resize(ArgNo,
nullptr);
7501 auto *Prev = DebugFnArgs[ArgNo - 1];
7502 DebugFnArgs[ArgNo - 1] = Var;
7503 CheckDI(!Prev || (Prev == Var),
"conflicting debug info for argument", &DVR,
7507void Verifier::verifyNotEntryValue(
const DbgVariableRecord &DVR) {
7511 if (!
E || !
E->isValid())
7521 ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
7526 "Entry values are only allowed in MIR unless they target a "
7527 "swiftasync Argument",
7531void Verifier::verifyCompileUnits() {
7535 if (
M.getContext().isODRUniquingDebugTypes())
7537 auto *CUs =
M.getNamedMetadata(
"llvm.dbg.cu");
7538 SmallPtrSet<const Metadata *, 2> Listed;
7541 for (
const auto *CU : CUVisited)
7542 CheckDI(Listed.
count(CU),
"DICompileUnit not listed in llvm.dbg.cu", CU);
7546void Verifier::verifyDeoptimizeCallingConvs() {
7547 if (DeoptimizeDeclarations.
empty())
7551 for (
const auto *
F :
ArrayRef(DeoptimizeDeclarations).slice(1)) {
7552 Check(
First->getCallingConv() ==
F->getCallingConv(),
7553 "All llvm.experimental.deoptimize declarations must have the same "
7554 "calling convention",
7559void Verifier::verifyAttachedCallBundle(
const CallBase &
Call,
7560 const OperandBundleUse &BU) {
7563 Check((FTy->getReturnType()->isPointerTy() ||
7565 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
7566 "function returning a pointer or a non-returning function that has a "
7571 "operand bundle \"clang.arc.attachedcall\" requires one function as "
7579 Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
7580 IID == Intrinsic::objc_claimAutoreleasedReturnValue ||
7581 IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
7582 "invalid function argument",
Call);
7584 StringRef FnName = Fn->getName();
7585 Check((FnName ==
"objc_retainAutoreleasedReturnValue" ||
7586 FnName ==
"objc_claimAutoreleasedReturnValue" ||
7587 FnName ==
"objc_unsafeClaimAutoreleasedReturnValue"),
7588 "invalid function argument",
Call);
7592void Verifier::verifyNoAliasScopeDecl() {
7593 if (NoAliasScopeDecls.
empty())
7597 for (
auto *
II : NoAliasScopeDecls) {
7598 assert(
II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
7599 "Not a llvm.experimental.noalias.scope.decl ?");
7602 Check(ScopeListMV !=
nullptr,
7603 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
7608 Check(ScopeListMD !=
nullptr,
"!id.scope.list must point to an MDNode",
II);
7609 Check(ScopeListMD->getNumOperands() == 1,
7610 "!id.scope.list must point to a list with a single scope",
II);
7611 visitAliasScopeListMetadata(ScopeListMD);
7621 auto GetScope = [](IntrinsicInst *
II) {
7624 return &
cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
7629 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
7630 return GetScope(Lhs) < GetScope(Rhs);
7637 auto ItCurrent = NoAliasScopeDecls.begin();
7638 while (ItCurrent != NoAliasScopeDecls.end()) {
7639 auto CurScope = GetScope(*ItCurrent);
7640 auto ItNext = ItCurrent;
7643 }
while (ItNext != NoAliasScopeDecls.end() &&
7644 GetScope(*ItNext) == CurScope);
7649 if (ItNext - ItCurrent < 32)
7653 Check(!DT.dominates(
I, J),
7654 "llvm.experimental.noalias.scope.decl dominates another one "
7655 "with the same scope",
7669 Verifier V(OS,
true, *f.getParent());
7673 return !V.verify(
F);
7677 bool *BrokenDebugInfo) {
7679 Verifier V(OS, !BrokenDebugInfo, M);
7681 bool Broken =
false;
7683 Broken |= !V.verify(
F);
7685 Broken |= !V.verify();
7686 if (BrokenDebugInfo)
7687 *BrokenDebugInfo = V.hasBrokenDebugInfo();
7698 std::unique_ptr<Verifier> V;
7699 bool FatalErrors =
true;
7702 explicit VerifierLegacyPass(
bool FatalErrors)
7703 : FunctionPass(
ID), FatalErrors(FatalErrors) {}
7705 bool doInitialization(
Module &M)
override {
7706 V = std::make_unique<Verifier>(
7712 if (!
V->verify(
F) && FatalErrors) {
7713 errs() <<
"in function " <<
F.getName() <<
'\n';
7719 bool doFinalization(
Module &M)
override {
7720 bool HasErrors =
false;
7721 for (Function &
F : M)
7722 if (
F.isDeclaration())
7723 HasErrors |= !
V->verify(
F);
7725 HasErrors |= !
V->verify();
7726 if (FatalErrors && (HasErrors ||
V->hasBrokenDebugInfo()))
7731 void getAnalysisUsage(AnalysisUsage &AU)
const override {
7739template <
typename... Tys>
void TBAAVerifier::CheckFailed(Tys &&... Args) {
7741 return Diagnostic->CheckFailed(
Args...);
7744#define CheckTBAA(C, ...) \
7747 CheckFailed(__VA_ARGS__); \
7755TBAAVerifier::TBAABaseNodeSummary
7759 CheckFailed(
"Base nodes must have at least two operands",
I, BaseNode);
7763 auto Itr = TBAABaseNodes.find(BaseNode);
7764 if (Itr != TBAABaseNodes.end())
7767 auto Result = verifyTBAABaseNodeImpl(
I, BaseNode, IsNewFormat);
7768 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
7770 assert(InsertResult.second &&
"We just checked!");
7774TBAAVerifier::TBAABaseNodeSummary
7775TBAAVerifier::verifyTBAABaseNodeImpl(
const Instruction *
I,
7776 const MDNode *BaseNode,
bool IsNewFormat) {
7777 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {
true, ~0
u};
7781 return isValidScalarTBAANode(BaseNode)
7782 ? TBAAVerifier::TBAABaseNodeSummary({
false, 0})
7788 CheckFailed(
"Access tag nodes must have the number of operands that is a "
7789 "multiple of 3!", BaseNode);
7794 CheckFailed(
"Struct tag nodes must have an odd number of operands!",
7804 if (!TypeSizeNode) {
7805 CheckFailed(
"Type size nodes must be constants!",
I, BaseNode);
7812 CheckFailed(
"Struct tag nodes have a string as their first operand",
7819 std::optional<APInt> PrevOffset;
7824 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
7825 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
7826 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
7827 Idx += NumOpsPerField) {
7828 const MDOperand &FieldTy = BaseNode->
getOperand(Idx);
7829 const MDOperand &FieldOffset = BaseNode->
getOperand(Idx + 1);
7831 CheckFailed(
"Incorrect field entry in struct type node!",
I, BaseNode);
7836 auto *OffsetEntryCI =
7838 if (!OffsetEntryCI) {
7839 CheckFailed(
"Offset entries must be constants!",
I, BaseNode);
7845 BitWidth = OffsetEntryCI->getBitWidth();
7847 if (OffsetEntryCI->getBitWidth() !=
BitWidth) {
7849 "Bitwidth between the offsets and struct type entries must match",
I,
7861 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
7864 CheckFailed(
"Offsets must be increasing!",
I, BaseNode);
7868 PrevOffset = OffsetEntryCI->getValue();
7873 if (!MemberSizeNode) {
7874 CheckFailed(
"Member size entries must be constants!",
I, BaseNode);
7881 return Failed ? InvalidNode
7882 : TBAAVerifier::TBAABaseNodeSummary(
false,
BitWidth);
7904 return Parent && Visited.
insert(Parent).second &&
7908bool TBAAVerifier::isValidScalarTBAANode(
const MDNode *MD) {
7909 auto ResultIt = TBAAScalarNodes.find(MD);
7910 if (ResultIt != TBAAScalarNodes.end())
7911 return ResultIt->second;
7913 SmallPtrSet<const MDNode *, 4> Visited;
7915 auto InsertResult = TBAAScalarNodes.insert({MD,
Result});
7917 assert(InsertResult.second &&
"Just checked!");
7926MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(
const Instruction *
I,
7927 const MDNode *BaseNode,
7938 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
7939 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
7940 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
7941 Idx += NumOpsPerField) {
7942 auto *OffsetEntryCI =
7944 if (OffsetEntryCI->getValue().ugt(
Offset)) {
7945 if (Idx == FirstFieldOpNo) {
7946 CheckFailed(
"Could not find TBAA parent in struct type node",
I,
7951 unsigned PrevIdx = Idx - NumOpsPerField;
7952 auto *PrevOffsetEntryCI =
7954 Offset -= PrevOffsetEntryCI->getValue();
7962 Offset -= LastOffsetEntryCI->getValue();
7967 if (!
Type ||
Type->getNumOperands() < 3)
7983 "This instruction shall not have a TBAA access tag!",
I);
7985 bool IsStructPathTBAA =
7989 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
7999 "Access tag metadata must have either 4 or 5 operands",
I, MD);
8002 "Struct tag metadata must have either 3 or 4 operands",
I, MD);
8009 CheckTBAA(AccessSizeNode,
"Access size field must be a constant",
I, MD);
8013 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
8018 "Immutability tag on struct tag metadata must be a constant",
I,
8021 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
8022 "Immutability part of the struct tag metadata must be either 0 or 1",
I,
8027 "Malformed struct tag metadata: base and access-type "
8028 "should be non-null and point to Metadata nodes",
8029 I, MD, BaseNode, AccessType);
8032 CheckTBAA(isValidScalarTBAANode(AccessType),
8033 "Access type node must be a valid scalar type",
I, MD,
8038 CheckTBAA(OffsetCI,
"Offset must be constant integer",
I, MD);
8041 bool SeenAccessTypeInPath =
false;
8047 getFieldNodeFromTBAABaseNode(
I, BaseNode,
Offset, IsNewFormat)) {
8048 if (!StructPath.
insert(BaseNode).second) {
8049 CheckFailed(
"Cycle detected in struct path",
I, MD);
8054 unsigned BaseNodeBitWidth;
8055 std::tie(
Invalid, BaseNodeBitWidth) =
8056 verifyTBAABaseNode(
I, BaseNode, IsNewFormat);
8063 SeenAccessTypeInPath |= BaseNode == AccessType;
8065 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
8070 (BaseNodeBitWidth == 0 &&
Offset == 0) ||
8071 (IsNewFormat && BaseNodeBitWidth == ~0u),
8072 "Access bit-width not the same as description bit-width",
I, MD,
8073 BaseNodeBitWidth,
Offset.getBitWidth());
8075 if (IsNewFormat && SeenAccessTypeInPath)
8079 CheckTBAA(SeenAccessTypeInPath,
"Did not see access type in access path!",
I,
8084char VerifierLegacyPass::ID = 0;
8085INITIALIZE_PASS(VerifierLegacyPass,
"verify",
"Module Verifier",
false,
false)
8088 return new VerifierLegacyPass(FatalErrors);
8106 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
8114 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.
bool isElementwise() const
Return true if this is an elementwise atomic load.
Align getAlign() const
Return the alignment of the access that is being performed.
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
unsigned getNumOperands() const
Return number of MDNode operands.
bool isResolved() const
Check if node is fully resolved.
LLVMContext & getContext() const
bool equalsStr(StringRef Str) const
LLVM_ABI StringRef getString() const
This class implements a map that also provides access to all stored values in a deterministic order.
A Module instance is used to store all the information related to an LLVM module.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
LLVM_ABI StringRef getName() const
LLVM_ABI unsigned getNumOperands() const
iterator_range< op_iterator > operands()
op_range incoming_values()
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
This class represents a cast from a pointer to an address (non-capturing ptrtoint).
This class represents a cast from a pointer to an integer.
Value * getValue() const
Convenience accessor.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents a sign extension of integer types.
This class represents a cast from signed integer to floating point.
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
This instruction constructs a fixed permutation of two input vectors.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
static constexpr size_t npos
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
Check if the string is empty.
std::pair< typename Base::iterator, bool > insert(StringRef key)
Verify that the TBAA Metadatas are valid.
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI unsigned getIntegerBitWidth() const
bool isByteTy() const
True if this is an instance of ByteType.
bool isVectorTy() const
True if this is an instance of VectorType.
LLVM_ABI bool containsNonGlobalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a global...
LLVM_ABI bool containsNonLocalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a local.
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
LLVM_ABI bool isTokenLikeTy() const
Returns true if this is 'token' or a token-like target type.s.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
LLVM_ABI bool canLosslesslyBitCastTo(Type *Ty) const
Return true if this type could be converted with a lossless BitCast to type 'Ty'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
This class represents a cast unsigned integer to floating point.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
iterator_range< user_iterator > materialized_users()
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
iterator_range< user_iterator > users()
bool materialized_use_empty() const
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Check a module for errors, and report separate error states for IR and debug info errors.
LLVM_ABI Result run(Module &M, ModuleAnalysisManager &)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
This class represents zero extension of integer types.
std::pair< iterator, bool > insert(const ValueT &V)
constexpr bool isNonZero() const
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
This class implements an extremely fast bulk output stream that can only output to a stream.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
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.