99#include "llvm/IR/IntrinsicsAArch64.h"
100#include "llvm/IR/IntrinsicsARM.h"
101#include "llvm/IR/IntrinsicsNVPTX.h"
102#include "llvm/IR/IntrinsicsRISCV.h"
103#include "llvm/IR/IntrinsicsWebAssembly.h"
147 cl::desc(
"Ensure that llvm.experimental.noalias.scope.decl for identical "
148 "scopes are not dominating"));
177 Type *LandingPadResultTy;
184 bool HasDebugInfo =
false;
227 SawFrameEscape(
false), TBAAVerifyHelper(this) {
228 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
231 bool hasBrokenDebugInfo()
const {
return BrokenDebugInfo; }
234 llvm::TimeTraceScope timeScope(
"Verifier");
236 "An instance of this class only works with a specific module!");
246 for (
const BasicBlock &BB :
F) {
247 if (!BB.empty() && BB.back().isTerminator())
251 *OS <<
"Basic Block in function '" <<
F.getName()
252 <<
"' does not have terminator!\n";
253 BB.printAsOperand(*OS,
true, MST);
261 DT.recalculate(
const_cast<Function &
>(
F));
263 auto FailureCB = [
this](
const Twine &Message) {
264 this->CheckFailed(Message);
266 ConvergenceVerifyHelper.initialize(OS, FailureCB,
F);
271 verifySiblingFuncletUnwinds();
273 if (ConvergenceVerifyHelper.sawTokens())
274 ConvergenceVerifyHelper.verify(DT);
276 InstsInThisBlock.clear();
278 DIScopeChainReachesCycle.clear();
279 LandingPadResultTy =
nullptr;
280 SawFrameEscape =
false;
281 SiblingFuncletInfo.clear();
282 verifyNoAliasScopeDecl();
283 NoAliasScopeDecls.clear();
294 if (
F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
295 DeoptimizeDeclarations.push_back(&
F);
299 verifyFrameRecoverIndices();
300 for (
const GlobalVariable &GV :
M.globals())
301 visitGlobalVariable(GV);
303 for (
const GlobalAlias &GA :
M.aliases())
304 visitGlobalAlias(GA);
306 for (
const GlobalIFunc &GI :
M.ifuncs())
307 visitGlobalIFunc(GI);
309 for (
const NamedMDNode &NMD :
M.named_metadata())
310 visitNamedMDNode(NMD);
312 for (
const StringMapEntry<Comdat> &SMEC :
M.getComdatSymbolTable())
313 visitComdat(SMEC.getValue());
317 visitModuleCommandLines();
318 visitModuleErrnoTBAA();
320 verifyCompileUnits();
322 verifyDeoptimizeCallingConvs();
323 DISubprogramAttachments.clear();
324 DIScopeChainReachesCycle.clear();
330 enum class AreDebugLocsAllowed {
No,
Yes };
334 enum class RangeLikeMetadataKind {
341 void visitGlobalValue(
const GlobalValue &GV);
342 void visitGlobalVariable(
const GlobalVariable &GV);
343 void visitGlobalAlias(
const GlobalAlias &GA);
344 void visitGlobalIFunc(
const GlobalIFunc &GI);
345 void visitAliaseeSubExpr(
const GlobalAlias &
A,
const Constant &
C);
346 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
347 const GlobalAlias &
A,
const Constant &
C);
348 void visitNamedMDNode(
const NamedMDNode &NMD);
349 void visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs);
350 void visitMetadataAsValue(
const MetadataAsValue &MD,
Function *
F);
351 void visitValueAsMetadata(
const ValueAsMetadata &MD,
Function *
F);
352 void visitDIArgList(
const DIArgList &AL,
Function *
F);
353 void visitComdat(
const Comdat &
C);
354 void visitModuleIdents();
355 void visitModuleCommandLines();
356 void visitModuleErrnoTBAA();
357 void visitModuleFlags();
358 void visitModuleFlag(
const MDNode *
Op,
359 DenseMap<const MDString *, const MDNode *> &SeenIDs,
360 SmallVectorImpl<const MDNode *> &Requirements);
361 void visitModuleFlagCGProfileEntry(
const MDOperand &MDO);
363 void visitBasicBlock(BasicBlock &BB);
364 void verifyRangeLikeMetadata(
const Value &V,
const MDNode *
Range,
Type *Ty,
365 RangeLikeMetadataKind Kind);
366 void visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
367 void visitNoFPClassMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
368 void visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
369 void visitDereferenceableMetadata(Instruction &
I, MDNode *MD);
370 void visitNoFreeObjMetadata(Instruction &
I, MDNode *MD);
371 void visitProfMetadata(Instruction &
I, MDNode *MD);
372 void visitCallStackMetadata(MDNode *MD);
373 void visitMemProfMetadata(Instruction &
I, MDNode *MD);
374 void visitCallsiteMetadata(Instruction &
I, MDNode *MD);
375 void visitCalleeTypeMetadata(Instruction &
I, MDNode *MD);
376 void visitDIAssignIDMetadata(Instruction &
I, MDNode *MD);
377 void visitMMRAMetadata(Instruction &
I, MDNode *MD);
378 void visitAnnotationMetadata(MDNode *Annotation);
379 void visitAliasScopeMetadata(
const MDNode *MD);
380 void visitAliasScopeListMetadata(
const MDNode *MD);
381 void visitAccessGroupMetadata(
const MDNode *MD);
382 void visitCapturesMetadata(Instruction &
I,
const MDNode *Captures);
383 void visitAllocTokenMetadata(Instruction &
I, MDNode *MD);
384 void visitInlineHistoryMetadata(Instruction &
I, MDNode *MD);
385 void visitMemCacheHintMetadata(Instruction &
I, MDNode *MD);
387#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
388#include "llvm/IR/Metadata.def"
389 void visitDIType(
const DIType &
N);
390 void visitDIScope(
const DIScope &
N);
391 void visitDIScopeChain(
const DIScope &
N);
392 bool hasDIScopeCycle(
const Metadata *S);
417 void checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V);
422 void visitPHINode(
PHINode &PN);
431 void visitVAArgInst(
VAArgInst &VAA) { visitInstruction(VAA); }
432 void visitCallInst(CallInst &CI);
433 void visitInvokeInst(InvokeInst &
II);
434 void visitGetElementPtrInst(GetElementPtrInst &
GEP);
435 void visitLoadInst(LoadInst &LI);
436 void visitStoreInst(StoreInst &SI);
437 void verifyDominatesUse(Instruction &
I,
unsigned i);
438 void visitInstruction(Instruction &
I);
439 void visitTerminator(Instruction &
I);
440 void visitCondBrInst(CondBrInst &BI);
441 void visitReturnInst(ReturnInst &RI);
442 void visitSwitchInst(SwitchInst &SI);
443 void visitIndirectBrInst(IndirectBrInst &BI);
444 void visitCallBrInst(CallBrInst &CBI);
445 void visitSelectInst(SelectInst &SI);
446 void visitUserOp1(Instruction &
I);
447 void visitUserOp2(Instruction &
I) { visitUserOp1(
I); }
449 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
450 void visitVPIntrinsic(VPIntrinsic &VPI);
451 void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
452 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
453 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
454 void visitFenceInst(FenceInst &FI);
455 void visitAllocaInst(AllocaInst &AI);
456 void visitExtractValueInst(ExtractValueInst &EVI);
457 void visitInsertValueInst(InsertValueInst &IVI);
458 void visitEHPadPredecessors(Instruction &
I);
459 void visitLandingPadInst(LandingPadInst &LPI);
460 void visitResumeInst(ResumeInst &RI);
461 void visitCatchPadInst(CatchPadInst &CPI);
462 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
463 void visitCleanupPadInst(CleanupPadInst &CPI);
464 void visitFuncletPadInst(FuncletPadInst &FPI);
465 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
466 void visitCleanupReturnInst(CleanupReturnInst &CRI);
468 void verifySwiftErrorCall(CallBase &
Call,
const Value *SwiftErrorVal);
469 void verifySwiftErrorValue(
const Value *SwiftErrorVal);
470 void verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs, StringRef
Context);
471 void verifyMustTailCall(CallInst &CI);
472 bool verifyAttributeCount(AttributeList Attrs,
unsigned Params);
473 void verifyAttributeTypes(AttributeSet Attrs,
const Value *V);
474 void verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
const Value *V);
475 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
477 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
478 const Value *V,
bool IsIntrinsic,
bool IsInlineAsm);
479 void verifyFunctionMetadata(
ArrayRef<std::pair<unsigned, MDNode *>> MDs);
480 void verifyUnknownProfileMetadata(MDNode *MD);
481 void visitConstantExprsRecursively(
const Constant *EntryC);
482 void visitConstantExpr(
const ConstantExpr *CE);
483 void visitConstantPtrAuth(
const ConstantPtrAuth *CPA);
484 void verifyInlineAsmCall(
const CallBase &
Call);
485 void verifyStatepoint(
const CallBase &
Call);
486 void verifyFrameRecoverIndices();
487 void verifySiblingFuncletUnwinds();
489 void verifyFragmentExpression(
const DbgVariableRecord &
I);
490 template <
typename ValueOrMetadata>
491 void verifyFragmentExpression(
const DIVariable &V,
493 ValueOrMetadata *
Desc);
494 void verifyFnArgs(
const DbgVariableRecord &DVR);
495 void verifyNotEntryValue(
const DbgVariableRecord &
I);
498 void verifyCompileUnits();
502 void verifyDeoptimizeCallingConvs();
504 void verifyAttachedCallBundle(
const CallBase &
Call,
505 const OperandBundleUse &BU);
508 void verifyNoAliasScopeDecl();
514#define Check(C, ...) \
517 CheckFailed(__VA_ARGS__); \
524#define CheckDI(C, ...) \
527 DebugInfoCheckFailed(__VA_ARGS__); \
535 CheckDI(
I.DebugMarker->MarkedInstr == &
I,
536 "Instruction has invalid DebugMarker", &
I);
538 "PHI Node must not have any attached DbgRecords", &
I);
540 CheckDI(DR.getMarker() ==
I.DebugMarker,
541 "DbgRecord had invalid DebugMarker", &
I, &DR);
544 visitMDNode(*
Loc, AreDebugLocsAllowed::Yes);
549 verifyFragmentExpression(*DVR);
550 verifyNotEntryValue(*DVR);
557void Verifier::visit(Instruction &
I) {
559 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i)
560 Check(
I.getOperand(i) !=
nullptr,
"Operand is null", &
I);
572 while (!WorkList.
empty()) {
574 if (!Visited.
insert(Cur).second)
581void Verifier::visitGlobalValue(
const GlobalValue &GV) {
583 "Global is external, but doesn't have external or weak linkage!", &GV);
586 if (
const MDNode *Associated =
587 GO->getMetadata(LLVMContext::MD_associated)) {
588 Check(Associated->getNumOperands() == 1,
589 "associated metadata must have one operand", &GV, Associated);
590 const Metadata *
Op = Associated->getOperand(0).get();
591 Check(
Op,
"associated metadata must have a global value", GO, Associated);
594 Check(VM,
"associated metadata must be ValueAsMetadata", GO, Associated);
597 "associated value must be pointer typed", GV, Associated);
599 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
601 "associated metadata must point to a GlobalObject", GO, Stripped);
602 Check(Stripped != GO,
603 "global values should not associate to themselves", GO,
609 if (
const MDNode *AbsoluteSymbol =
610 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
611 verifyRangeLikeMetadata(*GO, AbsoluteSymbol,
612 DL.getIntPtrType(GO->getType()),
613 RangeLikeMetadataKind::AbsoluteSymbol);
616 if (GO->hasMetadata(LLVMContext::MD_implicit_ref)) {
617 Check(!GO->isDeclaration(),
618 "ref metadata must not be placed on a declaration", GO);
621 GO->getMetadata(LLVMContext::MD_implicit_ref, MDs);
622 for (
const MDNode *MD : MDs) {
623 Check(MD->getNumOperands() == 1,
"ref metadata must have one operand",
627 Check(VM,
"ref metadata must be ValueAsMetadata", GO, MD);
630 "ref value must be pointer typed", GV, MD);
634 "ref metadata must point to a GlobalObject", GO, Stripped);
635 Check(Stripped != GO,
"values should not reference themselves", GO,
641 if (
auto *Props = GO->getMetadata(LLVMContext::MD_elf_section_properties)) {
642 Check(Props->getNumOperands() == 2,
643 "elf_section_properties metadata must have two operands", GO,
645 if (Props->getNumOperands() == 2) {
647 Check(
Type,
"type field must be ConstantAsMetadata", GO, Props);
649 Check(TypeInt,
"type field must be ConstantInt", GO, Props);
652 Check(Entsize,
"entsize field must be ConstantAsMetadata", GO, Props);
654 Check(EntsizeInt,
"entsize field must be ConstantInt", GO, Props);
660 "Only global variables can have appending linkage!", &GV);
664 Check(GVar && GVar->getValueType()->isArrayTy(),
665 "Only global arrays can have appending linkage!", GVar);
669 Check(!GV.
hasComdat(),
"Declaration may not be in a Comdat!", &GV);
673 "dllexport GlobalValue must have default or protected visibility",
678 "dllimport GlobalValue must have default visibility", &GV);
679 Check(!GV.
isDSOLocal(),
"GlobalValue with DLLImport Storage is dso_local!",
685 "Global is marked as dllimport, but not external", &GV);
690 "GlobalValue with local linkage or non-default "
691 "visibility must be dso_local!",
696 if (!
I->getParent() || !
I->getParent()->getParent())
697 CheckFailed(
"Global is referenced by parentless instruction!", &GV, &M,
699 else if (
I->getParent()->getParent()->getParent() != &M)
700 CheckFailed(
"Global is referenced in a different module!", &GV, &M,
I,
701 I->getParent()->getParent(),
702 I->getParent()->getParent()->getParent());
705 if (
F->getParent() != &M)
706 CheckFailed(
"Global is used by function in a different module", &GV, &M,
714void Verifier::visitGlobalVariable(
const GlobalVariable &GV) {
718 Check(
A->value() <= Value::MaximumAlignment,
719 "huge alignment values are unsupported", &GV);
724 "Global variable initializer type does not match global "
728 "Global variable initializer must be sized", &GV);
734 "'common' global must have a zero initializer!", &GV);
737 Check(!GV.
hasComdat(),
"'common' global may not be in a Comdat!", &GV);
742 GV.
getName() ==
"llvm.global_dtors")) {
744 "invalid linkage for intrinsic global variable", &GV);
746 "invalid uses of intrinsic global variable", &GV);
753 PointerType::get(
Context,
DL.getProgramAddressSpace());
754 Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
755 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
756 STy->getTypeAtIndex(1) == FuncPtrTy,
757 "wrong type for intrinsic global variable", &GV);
758 Check(STy->getNumElements() == 3,
759 "the third field of the element type is mandatory, "
760 "specify ptr null to migrate from the obsoleted 2-field form");
761 Type *ETy = STy->getTypeAtIndex(2);
770 for (
const Use &U : Init->operands()) {
772 if (!Structor || Structor->getNumOperands() != 3)
775 "signing of ctors/dtors should be requested via module flags");
781 GV.
getName() ==
"llvm.compiler.used")) {
783 "invalid linkage for intrinsic global variable", &GV);
785 "invalid uses of intrinsic global variable", &GV);
789 Check(PTy,
"wrong type for intrinsic global variable", &GV);
793 Check(InitArray,
"wrong initializer for intrinsic global variable",
795 for (
Value *
Op : InitArray->operands()) {
799 Twine(
"invalid ") + GV.
getName() +
" member", V);
801 Twine(
"members of ") + GV.
getName() +
" must be named", V);
810 for (MDNode *MD : MDs) {
812 visitDIGlobalVariableExpression(*GVE);
814 CheckDI(
false,
"!dbg attachment of global variable must be a "
815 "DIGlobalVariableExpression");
825 "Global @" + GV.
getName() +
" has illegal target extension type",
834 "Global variable is too large to fit into the address space", &GV,
838 visitGlobalValue(GV);
845 visitGlobalValue(GV);
848void Verifier::visitAliaseeSubExpr(
const GlobalAlias &GA,
const Constant &
C) {
849 SmallPtrSet<const GlobalAlias*, 4> Visited;
851 visitAliaseeSubExpr(Visited, GA,
C);
854void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
855 const GlobalAlias &GA,
const Constant &
C) {
859 "available_externally alias must point to available_externally "
870 Check(Visited.
insert(GA2).second,
"Aliases cannot form a cycle", &GA);
872 Check(!GA2->isInterposable(),
873 "Alias cannot point to an interposable alias", &GA);
882 visitConstantExprsRecursively(CE);
884 for (
const Use &U :
C.operands()) {
887 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
889 visitAliaseeSubExpr(Visited, GA, *C2);
893void Verifier::visitGlobalAlias(
const GlobalAlias &GA) {
895 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
896 "weak_odr, external, or available_externally linkage!",
899 Check(Aliasee,
"Aliasee cannot be NULL!", &GA);
901 "Alias and aliasee types should match!", &GA);
904 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
906 visitAliaseeSubExpr(GA, *Aliasee);
908 visitGlobalValue(GA);
911void Verifier::visitGlobalIFunc(
const GlobalIFunc &GI) {
912 visitGlobalValue(GI);
916 for (
const auto &
I : MDs) {
917 CheckDI(
I.first != LLVMContext::MD_dbg,
918 "an ifunc may not have a !dbg attachment", &GI);
919 Check(
I.first != LLVMContext::MD_prof,
920 "an ifunc may not have a !prof attachment", &GI);
921 visitMDNode(*
I.second, AreDebugLocsAllowed::No);
925 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
926 "weak_odr, or external linkage!",
931 Check(Resolver,
"IFunc must have a Function resolver", &GI);
933 "IFunc resolver must be a definition", &GI);
940 "IFunc resolver must return a pointer", &GI);
943 "IFunc resolver has incorrect type", &GI);
946void Verifier::visitNamedMDNode(
const NamedMDNode &NMD) {
951 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
952 for (
const MDNode *MD : NMD.
operands()) {
953 if (NMD.
getName() ==
"llvm.dbg.cu")
959 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
970 return T->getRawScope();
972 return SP->getRawScope();
974 return LB->getRawScope();
976 return NS->getRawScope();
978 return CB->getRawScope();
980 return M->getRawScope();
985bool Verifier::hasDIScopeCycle(
const Metadata *S) {
986 SmallPtrSet<const Metadata *, 8> Seen;
987 auto CacheSeen = [&](
bool HasCycle) {
989 DIScopeChainReachesCycle[
M] = HasCycle;
994 auto It = DIScopeChainReachesCycle.
find(Scope);
995 bool IsInCache = It != DIScopeChainReachesCycle.
end();
997 return CacheSeen(It->second);
998 bool AlreadySeen = !Seen.
insert(Scope).second;
1000 return CacheSeen(
true);
1006 return CacheSeen(
false);
1009void Verifier::visitDIScopeChain(
const DIScope &
N) {
1010 CheckDI(!hasDIScopeCycle(&
N),
"DIScope scope chain must not contain a cycle",
1014void Verifier::visitMDNode(
const MDNode &BaseMD,
1015 AreDebugLocsAllowed AllowLocs) {
1018 if (!MDNodes.
insert(&BaseMD).second)
1021 std::queue<const MDNode *> Worklist;
1022 Worklist.push(&BaseMD);
1024 while (!Worklist.empty()) {
1025 const MDNode *CurrentMD = Worklist.front();
1028 "MDNode context does not match Module context!", CurrentMD);
1033 case Metadata::MDTupleKind:
1035#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
1036 case Metadata::CLASS##Kind: \
1037 visit##CLASS(cast<CLASS>(*CurrentMD)); \
1039#include "llvm/IR/Metadata.def"
1044 visitDIScopeChain(*S);
1052 "DILocation not allowed within this metadata node", CurrentMD,
1060 visitValueAsMetadata(*V,
nullptr);
1074 "Expected second operand to be an integer constant of type i32 or "
1086 "Expecting only the metadata name", CurrentMD);
1091 Check(CurrentMD->
isResolved(),
"All nodes should be resolved!", CurrentMD);
1095void Verifier::visitValueAsMetadata(
const ValueAsMetadata &MD,
Function *
F) {
1098 "Unexpected metadata round-trip through values", &MD, MD.
getValue());
1104 Check(
F,
"function-local metadata used outside a function", L);
1110 Check(
I->getParent(),
"function-local metadata not in basic block", L,
I);
1117 assert(ActualF &&
"Unimplemented function local metadata case!");
1119 Check(ActualF ==
F,
"function-local metadata used in wrong function", L);
1122void Verifier::visitDIArgList(
const DIArgList &AL,
Function *
F) {
1123 for (
const ValueAsMetadata *VAM :
AL.getArgs())
1124 visitValueAsMetadata(*VAM,
F);
1127void Verifier::visitMetadataAsValue(
const MetadataAsValue &MDV,
Function *
F) {
1130 visitMDNode(*
N, AreDebugLocsAllowed::No);
1136 if (!MDNodes.
insert(MD).second)
1140 visitValueAsMetadata(*V,
F);
1143 visitDIArgList(*AL,
F);
1151void Verifier::visitDILocation(
const DILocation &
N) {
1153 "location requires a valid scope", &
N,
N.getRawScope());
1154 if (
auto *IA =
N.getRawInlinedAt())
1157 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1160void Verifier::visitGenericDINode(
const GenericDINode &
N) {
1164void Verifier::visitDIScope(
const DIScope &
N) {
1165 if (
auto *
F =
N.getRawFile())
1169void Verifier::visitDIType(
const DIType &
N) {
1172 CheckDI(
N.getRawFile() ||
N.getLine() == 0,
"line specified with no file", &
N,
1176void Verifier::visitDISubrangeType(
const DISubrangeType &
N) {
1179 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1182 auto *LBound =
N.getRawLowerBound();
1186 "LowerBound must be signed constant or DIVariable or DIExpression or "
1189 auto *UBound =
N.getRawUpperBound();
1193 "UpperBound must be signed constant or DIVariable or DIExpression or "
1196 auto *Stride =
N.getRawStride();
1199 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1200 auto *Bias =
N.getRawBias();
1203 "Bias must be signed constant or DIVariable or DIExpression", &
N);
1205 auto *
Size =
N.getRawSizeInBits();
1207 "SizeInBits must be a constant");
1210void Verifier::visitDISubrange(
const DISubrange &
N) {
1211 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1212 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1213 "Subrange can have any one of count or upperBound", &
N);
1214 auto *CBound =
N.getRawCountNode();
1217 "Count must be signed constant or DIVariable or DIExpression", &
N);
1218 auto Count =
N.getCount();
1221 "invalid subrange count", &
N);
1222 auto *LBound =
N.getRawLowerBound();
1225 "LowerBound must be signed constant or DIVariable or DIExpression",
1227 auto *UBound =
N.getRawUpperBound();
1230 "UpperBound must be signed constant or DIVariable or DIExpression",
1232 auto *Stride =
N.getRawStride();
1235 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1238void Verifier::visitDIGenericSubrange(
const DIGenericSubrange &
N) {
1239 CheckDI(
N.getTag() == dwarf::DW_TAG_generic_subrange,
"invalid tag", &
N);
1240 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1241 "GenericSubrange can have any one of count or upperBound", &
N);
1242 auto *CBound =
N.getRawCountNode();
1244 "Count must be signed constant or DIVariable or DIExpression", &
N);
1245 auto *LBound =
N.getRawLowerBound();
1246 CheckDI(LBound,
"GenericSubrange must contain lowerBound", &
N);
1248 "LowerBound must be signed constant or DIVariable or DIExpression",
1250 auto *UBound =
N.getRawUpperBound();
1252 "UpperBound must be signed constant or DIVariable or DIExpression",
1254 auto *Stride =
N.getRawStride();
1255 CheckDI(Stride,
"GenericSubrange must contain stride", &
N);
1257 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1260void Verifier::visitDIEnumerator(
const DIEnumerator &
N) {
1261 CheckDI(
N.getTag() == dwarf::DW_TAG_enumerator,
"invalid tag", &
N);
1264void Verifier::visitDIBasicType(
const DIBasicType &
N) {
1267 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type ||
1268 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1269 N.getTag() == dwarf::DW_TAG_string_type,
1272 auto *
Size =
N.getRawSizeInBits();
1274 "SizeInBits must be a constant");
1277void Verifier::visitDIFixedPointType(
const DIFixedPointType &
N) {
1278 visitDIBasicType(
N);
1280 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type,
"invalid tag", &
N);
1281 CheckDI(
N.getEncoding() == dwarf::DW_ATE_signed_fixed ||
1282 N.getEncoding() == dwarf::DW_ATE_unsigned_fixed,
1283 "invalid encoding", &
N);
1287 "invalid kind", &
N);
1289 N.getFactorRaw() == 0,
1290 "factor should be 0 for rationals", &
N);
1292 (
N.getNumeratorRaw() == 0 &&
N.getDenominatorRaw() == 0),
1293 "numerator and denominator should be 0 for non-rationals", &
N);
1296void Verifier::visitDIStringType(
const DIStringType &
N) {
1299 CheckDI(
N.getTag() == dwarf::DW_TAG_string_type,
"invalid tag", &
N);
1300 CheckDI(!(
N.isBigEndian() &&
N.isLittleEndian()),
"has conflicting flags",
1304void Verifier::visitDIDerivedType(
const DIDerivedType &
N) {
1308 CheckDI(
N.getTag() == dwarf::DW_TAG_typedef ||
1309 N.getTag() == dwarf::DW_TAG_pointer_type ||
1310 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1311 N.getTag() == dwarf::DW_TAG_reference_type ||
1312 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1313 N.getTag() == dwarf::DW_TAG_const_type ||
1314 N.getTag() == dwarf::DW_TAG_immutable_type ||
1315 N.getTag() == dwarf::DW_TAG_volatile_type ||
1316 N.getTag() == dwarf::DW_TAG_restrict_type ||
1317 N.getTag() == dwarf::DW_TAG_atomic_type ||
1318 N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
1319 N.getTag() == dwarf::DW_TAG_member ||
1320 (
N.getTag() == dwarf::DW_TAG_variable &&
N.isStaticMember()) ||
1321 N.getTag() == dwarf::DW_TAG_inheritance ||
1322 N.getTag() == dwarf::DW_TAG_friend ||
1323 N.getTag() == dwarf::DW_TAG_set_type ||
1324 N.getTag() == dwarf::DW_TAG_template_alias,
1326 if (
N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1327 CheckDI(
isType(
N.getRawExtraData()),
"invalid pointer to member type", &
N,
1328 N.getRawExtraData());
1329 }
else if (
N.getTag() == dwarf::DW_TAG_template_alias) {
1331 N.getRawExtraData());
1332 }
else if (
N.getTag() == dwarf::DW_TAG_inheritance ||
1333 N.getTag() == dwarf::DW_TAG_member ||
1334 N.getTag() == dwarf::DW_TAG_variable) {
1335 auto *ExtraData =
N.getRawExtraData();
1336 auto IsValidExtraData = [&]() {
1337 if (ExtraData ==
nullptr)
1343 if (Tuple->getNumOperands() != 1)
1350 "extraData must be ConstantAsMetadata, MDString, DIObjCProperty, "
1351 "or MDTuple with single ConstantAsMetadata operand",
1355 if (
N.getTag() == dwarf::DW_TAG_set_type) {
1356 if (
auto *
T =
N.getRawBaseType()) {
1361 (Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1362 (Subrange &&
Subrange->getTag() == dwarf::DW_TAG_subrange_type) ||
1363 (
Basic && (
Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1364 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1365 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1366 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1367 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1368 "invalid set base type", &
N,
T);
1373 N.getRawBaseType());
1375 if (
N.getDWARFAddressSpace()) {
1376 CheckDI(
N.getTag() == dwarf::DW_TAG_pointer_type ||
1377 N.getTag() == dwarf::DW_TAG_reference_type ||
1378 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1379 "DWARF address space only applies to pointer or reference types",
1383 auto *
Size =
N.getRawSizeInBits();
1386 "SizeInBits must be a constant or DIVariable or DIExpression");
1391 return ((Flags & DINode::FlagLValueReference) &&
1392 (Flags & DINode::FlagRValueReference)) ||
1393 ((Flags & DINode::FlagTypePassByValue) &&
1394 (Flags & DINode::FlagTypePassByReference));
1397void Verifier::visitTemplateParams(
const MDNode &
N,
const Metadata &RawParams) {
1399 CheckDI(Params,
"invalid template params", &
N, &RawParams);
1406void Verifier::visitDICompositeType(
const DICompositeType &
N) {
1410 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type ||
1411 N.getTag() == dwarf::DW_TAG_structure_type ||
1412 N.getTag() == dwarf::DW_TAG_union_type ||
1413 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1414 N.getTag() == dwarf::DW_TAG_class_type ||
1415 N.getTag() == dwarf::DW_TAG_variant_part ||
1416 N.getTag() == dwarf::DW_TAG_variant ||
1417 N.getTag() == dwarf::DW_TAG_namelist,
1421 N.getRawBaseType());
1424 "invalid composite elements", &
N,
N.getRawElements());
1426 N.getRawVTableHolder());
1428 "invalid reference flags", &
N);
1429 unsigned DIBlockByRefStruct = 1 << 4;
1430 CheckDI((
N.getFlags() & DIBlockByRefStruct) == 0,
1431 "DIBlockByRefStruct on DICompositeType is no longer supported", &
N);
1433 "DISubprogram contains null entry in `elements` field", &
N);
1436 const DINodeArray
Elements =
N.getElements();
1438 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1439 "invalid vector, expected one element of type subrange", &
N);
1442 if (
auto *Params =
N.getRawTemplateParams())
1443 visitTemplateParams(
N, *Params);
1445 if (
auto *
D =
N.getRawDiscriminator()) {
1447 "discriminator can only appear on variant part");
1450 if (
N.getRawDataLocation()) {
1451 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1452 "dataLocation can only appear in array type");
1455 if (
N.getRawAssociated()) {
1456 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1457 "associated can only appear in array type");
1460 if (
N.getRawAllocated()) {
1461 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1462 "allocated can only appear in array type");
1465 if (
N.getRawRank()) {
1466 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1467 "rank can only appear in array type");
1470 if (
N.getTag() == dwarf::DW_TAG_array_type) {
1471 CheckDI(
N.getRawBaseType(),
"array types must have a base type", &
N);
1474 auto *
Size =
N.getRawSizeInBits();
1477 "SizeInBits must be a constant or DIVariable or DIExpression");
1480void Verifier::visitDISubroutineType(
const DISubroutineType &
N) {
1482 CheckDI(
N.getTag() == dwarf::DW_TAG_subroutine_type,
"invalid tag", &
N);
1483 if (
auto *Types =
N.getRawTypeArray()) {
1485 for (
Metadata *Ty :
N.getTypeArray()->operands()) {
1486 CheckDI(
isType(Ty),
"invalid subroutine type ref", &
N, Types, Ty);
1490 "invalid reference flags", &
N);
1493void Verifier::visitDIFile(
const DIFile &
N) {
1494 CheckDI(
N.getTag() == dwarf::DW_TAG_file_type,
"invalid tag", &
N);
1495 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum =
N.getChecksum();
1497 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1498 "invalid checksum kind", &
N);
1500 switch (Checksum->Kind) {
1511 CheckDI(Checksum->Value.size() ==
Size,
"invalid checksum length", &
N);
1513 "invalid checksum", &
N);
1517void Verifier::visitDICompileUnit(
const DICompileUnit &
N) {
1518 CheckDI(
N.isDistinct(),
"compile units must be distinct", &
N);
1519 CheckDI(
N.getTag() == dwarf::DW_TAG_compile_unit,
"invalid tag", &
N);
1525 CheckDI(!
N.getFile()->getFilename().empty(),
"invalid filename", &
N,
1529 "invalid emission kind", &
N);
1532 "invalid language dialect", &
N);
1534 if (
auto *Array =
N.getRawEnumTypes()) {
1536 for (
Metadata *
Op :
N.getEnumTypes()->operands()) {
1538 CheckDI(Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1539 "invalid enum type", &
N,
N.getEnumTypes(),
Op);
1541 "function-local enum in a DICompileUnit's enum list", &
N,
1542 N.getEnumTypes(),
Op);
1545 if (
auto *Array =
N.getRawRetainedTypes()) {
1547 for (
Metadata *
Op :
N.getRetainedTypes()->operands()) {
1551 "invalid retained type", &
N,
Op);
1554 if (
auto *Array =
N.getRawGlobalVariables()) {
1556 for (
Metadata *
Op :
N.getGlobalVariables()->operands()) {
1558 CheckDI(GVE,
"invalid global variable ref", &
N,
Op);
1560 "function-local variables are not allowed in a DICompileUnit's "
1561 "global variables list",
1565 if (
auto *Array =
N.getRawImportedEntities()) {
1567 for (
Metadata *
Op :
N.getImportedEntities()->operands()) {
1569 CheckDI(IE,
"invalid imported entity ref", &
N,
Op);
1571 "function-local imports are not allowed in a DICompileUnit's "
1572 "imported entities list",
1576 if (
auto *Array =
N.getRawMacros()) {
1585void Verifier::visitDISubprogram(
const DISubprogram &
N) {
1586 CheckDI(
N.getTag() == dwarf::DW_TAG_subprogram,
"invalid tag", &
N);
1588 if (
auto *
F =
N.getRawFile())
1591 CheckDI(
N.getLine() == 0,
"line specified with no file", &
N,
N.getLine());
1592 auto *
T =
N.getRawType();
1593 CheckDI(
T,
"DISubprogram requires a non-null type", &
N);
1595 CheckDI(
isType(
N.getRawContainingType()),
"invalid containing type", &
N,
1596 N.getRawContainingType());
1597 if (
auto *Params =
N.getRawTemplateParams())
1598 visitTemplateParams(
N, *Params);
1599 if (
auto *S =
N.getRawDeclaration())
1601 "invalid subprogram declaration", &
N, S);
1602 if (
auto *RawNode =
N.getRawRetainedNodes()) {
1604 CheckDI(Node,
"invalid retained nodes list", &
N, RawNode);
1606 DenseMap<unsigned, DILocalVariable *>
Args;
1608 CheckDI(
Op,
"nullptr in retained nodes", &
N, Node);
1610 auto True = [](
const Metadata *) {
return true; };
1611 auto False = [](
const Metadata *) {
return false; };
1612 bool IsTypeCorrect = DISubprogram::visitRetainedNode<bool>(
1613 Op, True, True, True, True, True, False);
1615 "invalid retained nodes, expected DILocalVariable, DILabel, "
1616 "DIImportedEntity, DIType or DIGlobalVariableExpression",
1623 "invalid retained nodes, retained node is not local", &
N, Node,
1626 DISubprogram *RetainedNodeSP =
getSubprogram(RetainedNodeScope);
1627 DICompileUnit *RetainedNodeUnit =
1628 RetainedNodeSP ? RetainedNodeSP->getUnit() :
nullptr;
1630 RetainedNodeSP == &
N,
1631 "invalid retained nodes, retained node does not belong to subprogram",
1632 &
N, Node, RetainedNode, RetainedNodeScope, RetainedNodeSP,
1638 if (
unsigned ArgNum = DV->getArg()) {
1640 CheckDI(Inserted || DV == ArgI->second,
1641 "invalid retained nodes, more than one local variable with the "
1642 "same argument index",
1643 &
N,
N.getUnit(), Node, RetainedNode, Args[ArgNum]);
1648 "invalid reference flags", &
N);
1650 auto *
Unit =
N.getRawUnit();
1651 if (
N.isDefinition()) {
1653 CheckDI(
N.isDistinct(),
"subprogram definitions must be distinct", &
N);
1654 CheckDI(Unit,
"subprogram definitions must have a compile unit", &
N);
1659 if (CT && CT->getRawIdentifier() &&
1660 M.getContext().isODRUniquingDebugTypes())
1662 "definition subprograms cannot be nested within DICompositeType "
1663 "when enabling ODR",
1667 CheckDI(!Unit,
"subprogram declarations must not have a compile unit", &
N);
1669 "subprogram declaration must not have a declaration field");
1672 if (
auto *RawThrownTypes =
N.getRawThrownTypes()) {
1674 CheckDI(ThrownTypes,
"invalid thrown types list", &
N, RawThrownTypes);
1680 if (
N.areAllCallsDescribed())
1682 "DIFlagAllCallsDescribed must be attached to a definition");
1685void Verifier::visitDILexicalBlockBase(
const DILexicalBlockBase &
N) {
1686 CheckDI(
N.getTag() == dwarf::DW_TAG_lexical_block,
"invalid tag", &
N);
1688 "invalid local scope", &
N,
N.getRawScope());
1690 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1693void Verifier::visitDILexicalBlock(
const DILexicalBlock &
N) {
1694 visitDILexicalBlockBase(
N);
1697 "cannot have column info without line info", &
N);
1700void Verifier::visitDILexicalBlockFile(
const DILexicalBlockFile &
N) {
1701 visitDILexicalBlockBase(
N);
1704void Verifier::visitDICommonBlock(
const DICommonBlock &
N) {
1705 CheckDI(
N.getTag() == dwarf::DW_TAG_common_block,
"invalid tag", &
N);
1706 if (
auto *S =
N.getRawScope())
1708 if (
auto *S =
N.getRawDecl())
1712void Verifier::visitDINamespace(
const DINamespace &
N) {
1713 CheckDI(
N.getTag() == dwarf::DW_TAG_namespace,
"invalid tag", &
N);
1714 if (
auto *S =
N.getRawScope())
1718void Verifier::visitDIMacro(
const DIMacro &
N) {
1721 "invalid macinfo type", &
N);
1722 CheckDI(!
N.getName().empty(),
"anonymous macro", &
N);
1723 if (!
N.getValue().empty()) {
1724 assert(
N.getValue().data()[0] !=
' ' &&
"Macro value has a space prefix");
1728void Verifier::visitDIMacroFile(
const DIMacroFile &
N) {
1730 "invalid macinfo type", &
N);
1731 if (
auto *
F =
N.getRawFile())
1734 if (
auto *Array =
N.getRawElements()) {
1736 for (
Metadata *
Op :
N.getElements()->operands()) {
1742void Verifier::visitDIModule(
const DIModule &
N) {
1743 CheckDI(
N.getTag() == dwarf::DW_TAG_module,
"invalid tag", &
N);
1744 CheckDI(!
N.getName().empty(),
"anonymous module", &
N);
1747void Verifier::visitDITemplateParameter(
const DITemplateParameter &
N) {
1751void Verifier::visitDITemplateTypeParameter(
const DITemplateTypeParameter &
N) {
1752 visitDITemplateParameter(
N);
1754 CheckDI(
N.getTag() == dwarf::DW_TAG_template_type_parameter,
"invalid tag",
1758void Verifier::visitDITemplateValueParameter(
1759 const DITemplateValueParameter &
N) {
1760 visitDITemplateParameter(
N);
1762 CheckDI(
N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1763 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1764 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1768void Verifier::visitDIVariable(
const DIVariable &
N) {
1769 if (
auto *S =
N.getRawScope())
1771 if (
auto *
F =
N.getRawFile())
1775void Verifier::visitDIGlobalVariable(
const DIGlobalVariable &
N) {
1779 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1782 if (
N.isDefinition())
1783 CheckDI(
N.getType(),
"missing global variable type", &
N);
1784 if (
auto *Member =
N.getRawStaticDataMemberDeclaration()) {
1786 "invalid static data member declaration", &
N, Member);
1790void Verifier::visitDILocalVariable(
const DILocalVariable &
N) {
1795 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1797 "local variable requires a valid scope", &
N,
N.getRawScope());
1798 if (
auto Ty =
N.getType())
1802void Verifier::visitDIAssignID(
const DIAssignID &
N) {
1803 CheckDI(!
N.getNumOperands(),
"DIAssignID has no arguments", &
N);
1804 CheckDI(
N.isDistinct(),
"DIAssignID must be distinct", &
N);
1807void Verifier::visitDILabel(
const DILabel &
N) {
1808 if (
auto *S =
N.getRawScope())
1810 if (
auto *
F =
N.getRawFile())
1813 CheckDI(
N.getTag() == dwarf::DW_TAG_label,
"invalid tag", &
N);
1815 "label requires a valid scope", &
N,
N.getRawScope());
1818void Verifier::visitDIExpression(
const DIExpression &
N) {
1819 CheckDI(
N.isValid(),
"invalid expression", &
N);
1822void Verifier::visitDIGlobalVariableExpression(
1823 const DIGlobalVariableExpression &GVE) {
1826 visitDIGlobalVariable(*Var);
1828 visitDIExpression(*Expr);
1829 if (
auto Fragment = Expr->getFragmentInfo())
1830 verifyFragmentExpression(*GVE.
getVariable(), *Fragment, &GVE);
1834void Verifier::visitDIObjCProperty(
const DIObjCProperty &
N) {
1835 CheckDI(
N.getTag() == dwarf::DW_TAG_APPLE_property,
"invalid tag", &
N);
1836 if (
auto *
T =
N.getRawType())
1838 if (
auto *
F =
N.getRawFile())
1842void Verifier::visitDIProperty(
const DIProperty &
N) {
1843 CheckDI(
N.getTag() == dwarf::DW_TAG_property,
"invalid tag", &
N);
1844 if (
auto *
T =
N.getRawType())
1846 if (
auto *
F =
N.getRawFile())
1850 if (DINode *BackingStorage =
N.getBackingStorage()) {
1852 CheckDI(DT && DT->getTag() == dwarf::DW_TAG_member,
1853 "property backing storage must be a member", &
N, BackingStorage);
1857void Verifier::visitDIImportedEntity(
const DIImportedEntity &
N) {
1858 CheckDI(
N.getTag() == dwarf::DW_TAG_imported_module ||
1859 N.getTag() == dwarf::DW_TAG_imported_declaration,
1861 if (
auto *S =
N.getRawScope())
1867void Verifier::visitComdat(
const Comdat &
C) {
1870 if (
TT.isOSBinFormatCOFF())
1871 if (
const GlobalValue *GV =
M.getNamedValue(
C.getName()))
1876void Verifier::visitModuleIdents() {
1877 const NamedMDNode *Idents =
M.getNamedMetadata(
"llvm.ident");
1883 for (
const MDNode *
N : Idents->
operands()) {
1884 Check(
N->getNumOperands() == 1,
1885 "incorrect number of operands in llvm.ident metadata",
N);
1887 (
"invalid value for llvm.ident metadata entry operand"
1888 "(the operand should be a string)"),
1893void Verifier::visitModuleCommandLines() {
1894 const NamedMDNode *CommandLines =
M.getNamedMetadata(
"llvm.commandline");
1901 for (
const MDNode *
N : CommandLines->
operands()) {
1902 Check(
N->getNumOperands() == 1,
1903 "incorrect number of operands in llvm.commandline metadata",
N);
1905 (
"invalid value for llvm.commandline metadata entry operand"
1906 "(the operand should be a string)"),
1911void Verifier::visitModuleErrnoTBAA() {
1912 const NamedMDNode *ErrnoTBAA =
M.getNamedMetadata(
"llvm.errno.tbaa");
1917 "llvm.errno.tbaa must have at least one operand", ErrnoTBAA);
1919 for (
const MDNode *
N : ErrnoTBAA->
operands())
1923void Verifier::visitModuleFlags() {
1924 const NamedMDNode *
Flags =
M.getModuleFlagsMetadata();
1928 DenseMap<const MDString*, const MDNode*> SeenIDs;
1932 std::optional<uint64_t> PAuthABIPlatform;
1933 std::optional<uint64_t> PAuthABIVersion;
1936 uint64_t HasPtrauthInitFiniAddr = 0;
1938 for (
const MDNode *MDN :
Flags->operands()) {
1939 visitModuleFlag(MDN, SeenIDs, Requirements);
1940 if (MDN->getNumOperands() != 3)
1944 auto GetFlagNamed = [&](StringRef
Name) -> std::optional<uint64_t> {
1945 if (FlagName->getString() != Name)
1946 return std::nullopt;
1947 if (
const auto *FlagValue =
1949 return FlagValue->getZExtValue();
1951 CheckFailed(Name +
": module flag expects integer value");
1952 return std::nullopt;
1955 if (
auto Value = GetFlagNamed(
"aarch64-elf-pauthabi-platform"))
1956 PAuthABIPlatform = *
Value;
1957 else if (
auto Value = GetFlagNamed(
"aarch64-elf-pauthabi-version"))
1958 PAuthABIVersion = *
Value;
1959 else if (
auto Value = GetFlagNamed(
"ptrauth-init-fini"))
1960 HasPtrauthInitFini = *
Value;
1961 else if (
auto Value =
1962 GetFlagNamed(
"ptrauth-init-fini-address-discrimination"))
1963 HasPtrauthInitFiniAddr = *
Value;
1968 "ptrauth-init-fini must be 0 or 1");
1970 "ptrauth-init-fini-address-discrimination must be 0 or 1, if set");
1971 if (HasPtrauthInitFiniAddr)
1972 Check(HasPtrauthInitFini,
"ptrauth-init-fini-address-discrimination module "
1973 "flag requires ptrauth-init-fini");
1975 if (PAuthABIPlatform.has_value() != PAuthABIVersion.has_value())
1976 CheckFailed(
"either both or no 'aarch64-elf-pauthabi-platform' and "
1977 "'aarch64-elf-pauthabi-version' module flags must be present");
1980 for (
const MDNode *Requirement : Requirements) {
1982 const Metadata *ReqValue = Requirement->getOperand(1);
1984 const MDNode *
Op = SeenIDs.
lookup(Flag);
1986 CheckFailed(
"invalid requirement on flag, flag is not present in module",
1991 if (
Op->getOperand(2) != ReqValue) {
1992 CheckFailed((
"invalid requirement on flag, "
1993 "flag does not have the required value"),
2001Verifier::visitModuleFlag(
const MDNode *
Op,
2002 DenseMap<const MDString *, const MDNode *> &SeenIDs,
2003 SmallVectorImpl<const MDNode *> &Requirements) {
2007 "incorrect number of operands in module flag",
Op);
2008 Module::ModFlagBehavior MFB;
2009 if (!Module::isValidModFlagBehavior(
Op->getOperand(0), MFB)) {
2011 "invalid behavior operand in module flag (expected constant integer)",
2014 "invalid behavior operand in module flag (unexpected constant)",
2018 Check(ID,
"invalid ID operand in module flag (expected metadata string)",
2024 case Module::Warning:
2025 case Module::Override:
2031 Check(V &&
V->getValue().isNonNegative(),
2032 "invalid value for 'min' module flag (expected constant non-negative "
2040 "invalid value for 'max' module flag (expected constant integer)",
2045 case Module::Require: {
2050 "invalid value for 'require' module flag (expected metadata pair)",
2053 (
"invalid value for 'require' module flag "
2054 "(first value operand should be a string)"),
2055 Value->getOperand(0));
2063 case Module::Append:
2064 case Module::AppendUnique: {
2067 "invalid value for 'append'-type module flag "
2068 "(expected a metadata node)",
2075 if (MFB != Module::Require) {
2078 "module flag identifiers must be unique (or of 'require' type)", ID);
2081 StringRef
Name =
ID->getString();
2082 if (Name ==
"wchar_size") {
2085 Check(
Value,
"wchar_size metadata requires constant integer argument");
2089 if (Name ==
"long-double-type") {
2090 Check(MFB == Module::Error,
2091 "long-double-type module flag must use 'error' merge behavior",
Op);
2093 Check(
Value,
"long-double-type metadata requires a string argument");
2096 "invalid long-double-type metadata value",
Op);
2100 if (Name ==
"float-abi") {
2101 Check(MFB == Module::Error,
2102 "float-abi module flag must use 'error' merge behavior",
Op);
2104 Check(
Value,
"float-abi metadata requires a string argument");
2107 "invalid float-abi metadata value",
Op);
2111 if (Name ==
"target-abi") {
2114 "target-abi metadata requires a non-empty string argument",
Op);
2118 if (Name ==
"Linker Options") {
2122 Check(
M.getNamedMetadata(
"llvm.linker.options"),
2123 "'Linker Options' named metadata no longer supported");
2127 if (Name ==
"SemanticInterposition") {
2128 ConstantInt *
Value =
2131 "SemanticInterposition metadata requires constant integer argument");
2135 if (Name ==
"CG Profile") {
2136 for (
const MDOperand &MDO :
cast<MDNode>(
Op->getOperand(2))->operands())
2137 visitModuleFlagCGProfileEntry(MDO);
2145void Verifier::visitModuleFlagCGProfileEntry(
const MDOperand &MDO) {
2146 auto CheckFunction = [&](
const MDOperand &FuncMDO) {
2151 "expected a Function or null", FuncMDO);
2154 Check(Node &&
Node->getNumOperands() == 3,
"expected a MDNode triple", MDO);
2155 CheckFunction(
Node->getOperand(0));
2156 CheckFunction(
Node->getOperand(1));
2159 "expected an integer constant",
Node->getOperand(2));
2162void Verifier::verifyAttributeTypes(AttributeSet Attrs,
const Value *V) {
2165 if (
A.isStringAttribute()) {
2166#define GET_ATTR_NAMES
2167#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
2168#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
2169 if (A.getKindAsString() == #DISPLAY_NAME) { \
2170 auto V = A.getValueAsString(); \
2171 if (!(V.empty() || V == "true" || V == "false")) \
2172 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
2176#include "llvm/IR/Attributes.inc"
2180 if (
A.isIntAttribute() != Attribute::isIntAttrKind(
A.getKindAsEnum())) {
2181 CheckFailed(
"Attribute '" +
A.getAsString() +
"' should have an Argument",
2190void Verifier::verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
2192 if (!
Attrs.hasAttributes())
2195 verifyAttributeTypes(Attrs, V);
2198 Check(Attr.isStringAttribute() ||
2199 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
2200 "Attribute '" + Attr.getAsString() +
"' does not apply to parameters",
2203 if (
Attrs.hasAttribute(Attribute::ImmArg)) {
2204 unsigned AttrCount =
2205 Attrs.getNumAttributes() -
Attrs.hasAttribute(Attribute::Range);
2206 Check(AttrCount == 1,
2207 "Attribute 'immarg' is incompatible with other attributes except the "
2208 "'range' attribute",
2214 unsigned AttrCount = 0;
2215 AttrCount +=
Attrs.hasAttribute(Attribute::ByVal);
2216 AttrCount +=
Attrs.hasAttribute(Attribute::InAlloca);
2217 AttrCount +=
Attrs.hasAttribute(Attribute::Preallocated);
2218 AttrCount +=
Attrs.hasAttribute(Attribute::StructRet) ||
2219 Attrs.hasAttribute(Attribute::InReg);
2220 AttrCount +=
Attrs.hasAttribute(Attribute::Nest);
2221 AttrCount +=
Attrs.hasAttribute(Attribute::ByRef);
2222 Check(AttrCount <= 1,
2223 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
2224 "'byref', and 'sret' are incompatible!",
2227 Check(!(
Attrs.hasAttribute(Attribute::InAlloca) &&
2228 Attrs.hasAttribute(Attribute::ReadOnly)),
2230 "'inalloca and readonly' are incompatible!",
2233 Check(!(
Attrs.hasAttribute(Attribute::StructRet) &&
2234 Attrs.hasAttribute(Attribute::Returned)),
2236 "'sret and returned' are incompatible!",
2239 Check(!(
Attrs.hasAttribute(Attribute::ZExt) &&
2240 Attrs.hasAttribute(Attribute::SExt)),
2242 "'zeroext and signext' are incompatible!",
2245 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2246 Attrs.hasAttribute(Attribute::ReadOnly)),
2248 "'readnone and readonly' are incompatible!",
2251 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2252 Attrs.hasAttribute(Attribute::WriteOnly)),
2254 "'readnone and writeonly' are incompatible!",
2257 Check(!(
Attrs.hasAttribute(Attribute::ReadOnly) &&
2258 Attrs.hasAttribute(Attribute::WriteOnly)),
2260 "'readonly and writeonly' are incompatible!",
2263 Check(!(
Attrs.hasAttribute(Attribute::NoInline) &&
2264 Attrs.hasAttribute(Attribute::AlwaysInline)),
2266 "'noinline and alwaysinline' are incompatible!",
2269 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2270 Attrs.hasAttribute(Attribute::ReadNone)),
2271 "Attributes writable and readnone are incompatible!", V);
2273 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2274 Attrs.hasAttribute(Attribute::ReadOnly)),
2275 "Attributes writable and readonly are incompatible!", V);
2277 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty, Attrs);
2279 if (!Attr.isStringAttribute() &&
2280 IncompatibleAttrs.
contains(Attr.getKindAsEnum())) {
2281 CheckFailed(
"Attribute '" + Attr.getAsString() +
2282 "' applied to incompatible type!", V);
2288 if (
Attrs.hasAttribute(Attribute::Alignment)) {
2289 Align AttrAlign =
Attrs.getAlignment().valueOrOne();
2290 Check(AttrAlign.
value() <= Value::MaximumAlignment,
2291 "huge alignment values are unsupported", V);
2293 if (
Attrs.hasAttribute(Attribute::ByVal)) {
2295 SmallPtrSet<Type *, 4> Visited;
2297 "Attribute 'byval' does not support unsized types!", V);
2301 "'byval' argument has illegal target extension type", V);
2302 Check(
DL.getTypeAllocSize(ByValTy).getKnownMinValue() < (1ULL << 32),
2303 "huge 'byval' arguments are unsupported", V);
2305 if (
Attrs.hasAttribute(Attribute::ByRef)) {
2306 SmallPtrSet<Type *, 4> Visited;
2307 Check(
Attrs.getByRefType()->isSized(&Visited),
2308 "Attribute 'byref' does not support unsized types!", V);
2309 Check(
DL.getTypeAllocSize(
Attrs.getByRefType()).getKnownMinValue() <
2311 "huge 'byref' arguments are unsupported", V);
2313 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
2314 SmallPtrSet<Type *, 4> Visited;
2315 Check(
Attrs.getInAllocaType()->isSized(&Visited),
2316 "Attribute 'inalloca' does not support unsized types!", V);
2317 Check(
DL.getTypeAllocSize(
Attrs.getInAllocaType()).getKnownMinValue() <
2319 "huge 'inalloca' arguments are unsupported", V);
2321 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
2322 SmallPtrSet<Type *, 4> Visited;
2323 Check(
Attrs.getPreallocatedType()->isSized(&Visited),
2324 "Attribute 'preallocated' does not support unsized types!", V);
2326 DL.getTypeAllocSize(
Attrs.getPreallocatedType()).getKnownMinValue() <
2328 "huge 'preallocated' arguments are unsupported", V);
2332 if (
Attrs.hasAttribute(Attribute::Initializes)) {
2333 auto Inits =
Attrs.getAttribute(Attribute::Initializes).getInitializes();
2334 Check(!Inits.empty(),
"Attribute 'initializes' does not support empty list",
2337 "Attribute 'initializes' does not support unordered ranges", V);
2340 if (
Attrs.hasAttribute(Attribute::NoFPClass)) {
2341 uint64_t Val =
Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
2342 Check(Val != 0,
"Attribute 'nofpclass' must have at least one test bit set",
2345 "Invalid value for 'nofpclass' test mask", V);
2347 if (
Attrs.hasAttribute(Attribute::Range)) {
2348 const ConstantRange &CR =
2349 Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2351 "Range bit width must match type bit width!", V);
2355void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
2357 if (
Attrs.hasFnAttr(Attr)) {
2358 StringRef S =
Attrs.getFnAttr(Attr).getValueAsString();
2361 CheckFailed(
"\"" + Attr +
"\" takes an unsigned integer: " + S, V);
2367void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
2368 const Value *V,
bool IsIntrinsic,
2370 if (
Attrs.isEmpty())
2373 if (AttributeListsVisited.
insert(
Attrs.getRawPointer()).second) {
2375 "Attribute list does not match Module context!", &Attrs, V);
2376 for (
const auto &AttrSet : Attrs) {
2377 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(
Context),
2378 "Attribute set does not match Module context!", &AttrSet, V);
2379 for (
const auto &
A : AttrSet) {
2381 "Attribute does not match Module context!", &
A, V);
2386 bool SawNest =
false;
2387 bool SawReturned =
false;
2388 bool SawSRet =
false;
2389 bool SawSwiftSelf =
false;
2390 bool SawSwiftAsync =
false;
2391 bool SawSwiftError =
false;
2394 AttributeSet RetAttrs =
Attrs.getRetAttrs();
2397 Attribute::canUseAsRetAttr(
RetAttr.getKindAsEnum()),
2398 "Attribute '" +
RetAttr.getAsString() +
2399 "' does not apply to function return values",
2402 unsigned MaxParameterWidth = 0;
2403 auto GetMaxParameterWidth = [&MaxParameterWidth](
Type *Ty) {
2406 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2407 if (
Size > MaxParameterWidth)
2408 MaxParameterWidth =
Size;
2412 GetMaxParameterWidth(FT->getReturnType());
2413 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2416 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2417 Type *Ty = FT->getParamType(i);
2418 AttributeSet ArgAttrs =
Attrs.getParamAttrs(i);
2422 "immarg attribute only applies to intrinsics", V);
2425 "Attribute 'elementtype' can only be applied to intrinsics"
2430 verifyParameterAttrs(ArgAttrs, Ty, V);
2431 GetMaxParameterWidth(Ty);
2434 Check(!SawNest,
"More than one parameter has attribute nest!", V);
2439 Check(!SawReturned,
"More than one parameter has attribute returned!", V);
2441 "Incompatible argument and return types for 'returned' attribute",
2447 Check(!SawSRet,
"Cannot have multiple 'sret' parameters!", V);
2448 Check(i == 0 || i == 1,
2449 "Attribute 'sret' is not on first or second parameter!", V);
2454 Check(!SawSwiftSelf,
"Cannot have multiple 'swiftself' parameters!", V);
2455 SawSwiftSelf =
true;
2459 Check(!SawSwiftAsync,
"Cannot have multiple 'swiftasync' parameters!", V);
2460 SawSwiftAsync =
true;
2464 Check(!SawSwiftError,
"Cannot have multiple 'swifterror' parameters!", V);
2465 SawSwiftError =
true;
2469 Check(i == FT->getNumParams() - 1,
2470 "inalloca isn't on the last parameter!", V);
2474 if (!
Attrs.hasFnAttrs())
2477 verifyAttributeTypes(
Attrs.getFnAttrs(), V);
2480 Attribute::canUseAsFnAttr(
FnAttr.getKindAsEnum()),
2481 "Attribute '" +
FnAttr.getAsString() +
2482 "' does not apply to functions!",
2485 Check(!(
Attrs.hasFnAttr(Attribute::NoInline) &&
2486 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2487 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2489 if (
Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2491 "Attribute 'optnone' requires 'noinline'!", V);
2493 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2494 "Attributes 'optsize and optnone' are incompatible!", V);
2497 "Attributes 'minsize and optnone' are incompatible!", V);
2499 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
2500 "Attributes 'optdebug and optnone' are incompatible!", V);
2503 Check(!(
Attrs.hasFnAttr(Attribute::SanitizeRealtime) &&
2504 Attrs.hasFnAttr(Attribute::SanitizeRealtimeBlocking)),
2506 "'sanitize_realtime and sanitize_realtime_blocking' are incompatible!",
2509 if (
Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
2510 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2511 "Attributes 'optsize and optdebug' are incompatible!", V);
2514 "Attributes 'minsize and optdebug' are incompatible!", V);
2517 Check(!
Attrs.hasAttrSomewhere(Attribute::Writable) ||
2518 isModSet(
Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
2519 "Attribute writable and memory without argmem: write are incompatible!",
2522 if (
Attrs.hasFnAttr(
"aarch64_pstate_sm_enabled")) {
2523 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_sm_compatible"),
2524 "Attributes 'aarch64_pstate_sm_enabled and "
2525 "aarch64_pstate_sm_compatible' are incompatible!",
2529 Check((
Attrs.hasFnAttr(
"aarch64_new_za") +
Attrs.hasFnAttr(
"aarch64_in_za") +
2530 Attrs.hasFnAttr(
"aarch64_inout_za") +
2531 Attrs.hasFnAttr(
"aarch64_out_za") +
2532 Attrs.hasFnAttr(
"aarch64_preserves_za") +
2533 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2534 "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2535 "'aarch64_inout_za', 'aarch64_preserves_za' and "
2536 "'aarch64_za_state_agnostic' are mutually exclusive",
2540 Attrs.hasFnAttr(
"aarch64_in_zt0") +
2541 Attrs.hasFnAttr(
"aarch64_inout_zt0") +
2542 Attrs.hasFnAttr(
"aarch64_out_zt0") +
2543 Attrs.hasFnAttr(
"aarch64_preserves_zt0") +
2544 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2545 "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
2546 "'aarch64_inout_zt0', 'aarch64_preserves_zt0' and "
2547 "'aarch64_za_state_agnostic' are mutually exclusive",
2550 if (
Attrs.hasFnAttr(Attribute::JumpTable)) {
2553 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2556 if (
auto Args =
Attrs.getFnAttrs().getAllocSizeArgs()) {
2557 auto CheckParam = [&](StringRef
Name,
unsigned ParamNo) {
2558 if (ParamNo >= FT->getNumParams()) {
2559 CheckFailed(
"'allocsize' " + Name +
" argument is out of bounds", V);
2563 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2564 CheckFailed(
"'allocsize' " + Name +
2565 " argument must refer to an integer parameter",
2573 if (!CheckParam(
"element size",
Args->first))
2576 if (
Args->second && !CheckParam(
"number of elements", *
Args->second))
2580 if (
Attrs.hasFnAttr(Attribute::AllocKind)) {
2583 K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
2585 {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
2588 "'allockind()' requires exactly one of alloc, realloc, and free");
2589 if ((
Type == AllocFnKind::Free) &&
2590 ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
2591 AllocFnKind::Aligned)) != AllocFnKind::Unknown))
2592 CheckFailed(
"'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2593 "or aligned modifiers.");
2594 AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
2595 if ((K & ZeroedUninit) == ZeroedUninit)
2596 CheckFailed(
"'allockind()' can't be both zeroed and uninitialized");
2600 StringRef S =
A.getValueAsString();
2601 Check(!S.
empty(),
"'alloc-variant-zeroed' must not be empty");
2609 "'alloc-variant-zeroed' must name a function belonging to the "
2610 "same 'alloc-family'");
2613 (
Variant->getFnAttribute(Attribute::AllocKind).getAllocKind() &
2614 AllocFnKind::Zeroed) != AllocFnKind::Unknown,
2615 "'alloc-variant-zeroed' must name a function with "
2616 "'allockind(\"zeroed\")'");
2619 "'alloc-variant-zeroed' must name a function with the same "
2624 "'alloc-variant-zeroed' must name a function with the same "
2625 "calling convention");
2629 if (
Attrs.hasFnAttr(Attribute::VScaleRange)) {
2630 unsigned VScaleMin =
Attrs.getFnAttrs().getVScaleRangeMin();
2632 CheckFailed(
"'vscale_range' minimum must be greater than 0", V);
2634 CheckFailed(
"'vscale_range' minimum must be power-of-two value", V);
2635 std::optional<unsigned> VScaleMax =
Attrs.getFnAttrs().getVScaleRangeMax();
2636 if (VScaleMax && VScaleMin > VScaleMax)
2637 CheckFailed(
"'vscale_range' minimum cannot be greater than maximum", V);
2639 CheckFailed(
"'vscale_range' maximum must be power-of-two value", V);
2642 if (
Attribute FPAttr =
Attrs.getFnAttr(
"frame-pointer"); FPAttr.isValid()) {
2643 StringRef
FP = FPAttr.getValueAsString();
2644 if (
FP !=
"all" &&
FP !=
"non-leaf" &&
FP !=
"none" &&
FP !=
"reserved" &&
2645 FP !=
"non-leaf-no-reserve")
2646 CheckFailed(
"invalid value for 'frame-pointer' attribute: " +
FP, V);
2649 checkUnsignedBaseTenFuncAttr(Attrs,
"tail-pad-to-size", V);
2650 checkUnsignedBaseTenFuncAttr(Attrs,
"tail-pad-value", V);
2651 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-prefix", V);
2652 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-entry", V);
2653 if (
Attrs.hasFnAttr(
"patchable-function-entry-section"))
2654 Check(!
Attrs.getFnAttr(
"patchable-function-entry-section")
2657 "\"patchable-function-entry-section\" must not be empty");
2658 checkUnsignedBaseTenFuncAttr(Attrs,
"warn-stack-size", V);
2660 if (
auto A =
Attrs.getFnAttr(
"sign-return-address");
A.isValid()) {
2661 StringRef S =
A.getValueAsString();
2662 if (S !=
"none" && S !=
"all" && S !=
"non-leaf")
2663 CheckFailed(
"invalid value for 'sign-return-address' attribute: " + S, V);
2666 if (
auto A =
Attrs.getFnAttr(
"sign-return-address-key");
A.isValid()) {
2667 StringRef S =
A.getValueAsString();
2668 if (S !=
"a_key" && S !=
"b_key")
2669 CheckFailed(
"invalid value for 'sign-return-address-key' attribute: " + S,
2671 if (
auto AA =
Attrs.getFnAttr(
"sign-return-address"); !AA.isValid()) {
2673 "'sign-return-address-key' present without `sign-return-address`");
2677 if (
auto A =
Attrs.getFnAttr(
"branch-target-enforcement");
A.isValid()) {
2678 StringRef S =
A.getValueAsString();
2679 if (S !=
"" && S !=
"true" && S !=
"false")
2681 "invalid value for 'branch-target-enforcement' attribute: " + S, V);
2684 if (
auto A =
Attrs.getFnAttr(
"branch-protection-pauth-lr");
A.isValid()) {
2685 StringRef S =
A.getValueAsString();
2686 if (S !=
"" && S !=
"true" && S !=
"false")
2688 "invalid value for 'branch-protection-pauth-lr' attribute: " + S, V);
2691 if (
auto A =
Attrs.getFnAttr(
"guarded-control-stack");
A.isValid()) {
2692 StringRef S =
A.getValueAsString();
2693 if (S !=
"" && S !=
"true" && S !=
"false")
2694 CheckFailed(
"invalid value for 'guarded-control-stack' attribute: " + S,
2698 if (
auto A =
Attrs.getFnAttr(
"vector-function-abi-variant");
A.isValid()) {
2699 StringRef S =
A.getValueAsString();
2702 CheckFailed(
"invalid name for a VFABI variant: " + S, V);
2705 if (
auto A =
Attrs.getFnAttr(
"modular-format");
A.isValid()) {
2706 StringRef S =
A.getValueAsString();
2710 "modular-format attribute requires at least 5 arguments", V);
2711 unsigned UpperBound = FT->getNumParams() + (FT->isVarArg() ? 1 : 0);
2713 Check(!Args[1].getAsInteger(10, FormatIdx),
2714 "modular-format attribute format string index is not an integer", V);
2715 Check(FormatIdx > 0,
2716 "modular-format attribute format string index must be greater than 0",
2718 Check(FormatIdx <= UpperBound,
2719 "modular-format attribute format string index is out of bounds", V);
2720 unsigned FirstArgIdx;
2721 Check(!Args[2].getAsInteger(10, FirstArgIdx),
2722 "modular-format attribute first arg index is not an integer", V);
2723 Check(FirstArgIdx <= UpperBound,
2724 "modular-format attribute first arg index is out of bounds", V);
2726 "modular-format attribute modular implementation function name "
2730 "modular-format attribute implementation name cannot be empty", V);
2733 if (
auto A =
Attrs.getFnAttr(
"target-features");
A.isValid()) {
2734 StringRef S =
A.getValueAsString();
2736 for (
auto FeatureFlag :
split(S,
',')) {
2737 if (FeatureFlag.empty())
2739 "target-features attribute should not contain an empty string");
2741 Check(FeatureFlag[0] ==
'+' || FeatureFlag[0] ==
'-',
2742 "target feature '" + FeatureFlag +
2743 "' must start with a '+' or '-'",
2749void Verifier::verifyUnknownProfileMetadata(MDNode *MD) {
2751 "'unknown' !prof should have a single additional operand", MD);
2754 "'unknown' !prof should have an additional operand of type "
2757 "the 'unknown' !prof operand should not be an empty string");
2760void Verifier::verifyFunctionMetadata(
2761 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2762 for (
const auto &Pair : MDs) {
2763 if (Pair.first == LLVMContext::MD_prof) {
2764 MDNode *MD = Pair.second;
2766 "!prof annotations should have no less than 2 operands", MD);
2771 verifyUnknownProfileMetadata(MD);
2776 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null",
2779 "expected string with name of the !prof annotation", MD);
2784 "first operand should be 'function_entry_count'"
2785 " or 'synthetic_function_entry_count'",
2789 Check(MD->
getOperand(1) !=
nullptr,
"second operand should not be null",
2792 "expected integer argument to function_entry_count", MD);
2793 }
else if (Pair.first == LLVMContext::MD_kcfi_type) {
2794 MDNode *MD = Pair.second;
2796 "!kcfi_type must have exactly one operand", MD);
2797 Check(MD->
getOperand(0) !=
nullptr,
"!kcfi_type operand must not be null",
2800 "expected a constant operand for !kcfi_type", MD);
2803 "expected a constant integer operand for !kcfi_type", MD);
2805 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2806 }
else if (Pair.first ==
Context.getMDKindID(
"reqd_work_group_size")) {
2807 MDNode *MD = Pair.second;
2809 "reqd_work_group_size must have exactly three operands", MD);
2814 for (
unsigned I = 0;
I != 3; ++
I) {
2816 Check(
C,
"reqd_work_group_size operands must be integer constants", MD);
2820 const APInt &
Value =
C->getValue();
2822 "reqd_work_group_size operands must fit in 64 bits", MD);
2823 if (
Value.getActiveBits() > 64)
2827 Check(Dim == 0 || Product <= std::numeric_limits<uint64_t>::max() / Dim,
2828 "reqd_work_group_size product must fit in 64 bits", MD);
2829 if (Dim != 0 && Product > std::numeric_limits<uint64_t>::max() / Dim)
2837void Verifier::visitConstantExprsRecursively(
const Constant *EntryC) {
2841 if (!ConstantExprVisited.
insert(EntryC).second)
2845 Stack.push_back(EntryC);
2847 while (!
Stack.empty()) {
2852 visitConstantExpr(CE);
2855 visitConstantPtrAuth(CPA);
2860 Check(GV->
getParent() == &M,
"Referencing global in another module!",
2866 for (
const Use &U :
C->operands()) {
2870 if (!ConstantExprVisited.
insert(OpC).second)
2872 Stack.push_back(OpC);
2877void Verifier::visitConstantExpr(
const ConstantExpr *CE) {
2878 if (
CE->getOpcode() == Instruction::BitCast)
2881 "Invalid bitcast", CE);
2882 else if (
CE->getOpcode() == Instruction::PtrToAddr)
2883 checkPtrToAddr(
CE->getOperand(0)->getType(),
CE->getType(), *CE);
2886void Verifier::visitConstantPtrAuth(
const ConstantPtrAuth *CPA) {
2888 "signed ptrauth constant base pointer must have pointer type");
2891 "signed ptrauth constant must have same type as its base pointer");
2894 "signed ptrauth constant key must be i32 constant integer");
2897 "signed ptrauth constant address discriminator must be a pointer");
2900 "signed ptrauth constant discriminator must be i64 constant integer");
2903 "signed ptrauth constant deactivation symbol must be a pointer");
2907 "signed ptrauth constant deactivation symbol must be a global value "
2911bool Verifier::verifyAttributeCount(AttributeList Attrs,
unsigned Params) {
2914 return Attrs.getNumAttrSets() <= Params + 2;
2917void Verifier::verifyInlineAsmCall(
const CallBase &
Call) {
2920 unsigned LabelNo = 0;
2921 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
2931 if (CI.isIndirect) {
2934 "Operand for indirect constraint must have pointer type", &
Call);
2937 "Operand for indirect constraint must have elementtype attribute",
2941 "Elementtype attribute can only be applied for indirect "
2950 Check(LabelNo == CallBr->getNumIndirectDests(),
2951 "Number of label constraints does not match number of callbr dests",
2954 Check(LabelNo == 0,
"Label constraints can only be used with callbr",
2960void Verifier::verifyStatepoint(
const CallBase &
Call) {
2965 "gc.statepoint must read and write all memory to preserve "
2966 "reordering restrictions required by safepoint semantics",
2969 const int64_t NumPatchBytes =
2972 Check(NumPatchBytes >= 0,
2973 "gc.statepoint number of patchable bytes must be "
2978 Check(TargetElemType,
2979 "gc.statepoint callee argument must have elementtype attribute",
Call);
2981 Check(TargetFuncType,
2982 "gc.statepoint callee elementtype must be function type",
Call);
2985 Check(NumCallArgs >= 0,
2986 "gc.statepoint number of arguments to underlying call "
2989 const int NumParams = (int)TargetFuncType->getNumParams();
2990 if (TargetFuncType->isVarArg()) {
2991 Check(NumCallArgs >= NumParams,
2992 "gc.statepoint mismatch in number of vararg call args",
Call);
2995 Check(TargetFuncType->getReturnType()->isVoidTy(),
2996 "gc.statepoint doesn't support wrapping non-void "
2997 "vararg functions yet",
3000 Check(NumCallArgs == NumParams,
3001 "gc.statepoint mismatch in number of call args",
Call);
3006 "unknown flag used in gc.statepoint flags argument",
Call);
3011 for (
int i = 0; i < NumParams; i++) {
3012 Type *ParamType = TargetFuncType->getParamType(i);
3014 Check(ArgType == ParamType,
3015 "gc.statepoint call argument does not match wrapped "
3019 if (TargetFuncType->isVarArg()) {
3020 AttributeSet ArgAttrs =
Attrs.getParamAttrs(5 + i);
3022 "Attribute 'sret' cannot be used for vararg call arguments!",
Call);
3026 const int EndCallArgsInx = 4 + NumCallArgs;
3030 "gc.statepoint number of transition arguments "
3031 "must be constant integer",
3033 const int NumTransitionArgs =
3035 Check(NumTransitionArgs == 0,
3036 "gc.statepoint w/inline transition bundle is deprecated",
Call);
3037 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
3041 "gc.statepoint number of deoptimization arguments "
3042 "must be constant integer",
3045 Check(NumDeoptArgs == 0,
3046 "gc.statepoint w/inline deopt operands is deprecated",
Call);
3048 const int ExpectedNumArgs = 7 + NumCallArgs;
3050 "gc.statepoint too many arguments",
Call);
3057 Check(UserCall,
"illegal use of statepoint token",
Call, U);
3061 "gc.result or gc.relocate are the only value uses "
3062 "of a gc.statepoint",
3065 Check(UserCall->getArgOperand(0) == &
Call,
3066 "gc.result connected to wrong gc.statepoint",
Call, UserCall);
3068 Check(UserCall->getArgOperand(0) == &
Call,
3069 "gc.relocate connected to wrong gc.statepoint",
Call, UserCall);
3083void Verifier::verifyFrameRecoverIndices() {
3084 for (
auto &Counts : FrameEscapeInfo) {
3086 unsigned EscapedObjectCount = Counts.second.first;
3087 unsigned MaxRecoveredIndex = Counts.second.second;
3088 Check(MaxRecoveredIndex <= EscapedObjectCount,
3089 "all indices passed to llvm.localrecover must be less than the "
3090 "number of arguments passed to llvm.localescape in the parent "
3099 UnwindDest =
II->getUnwindDest();
3101 UnwindDest = CSI->getUnwindDest();
3107void Verifier::verifySiblingFuncletUnwinds() {
3108 llvm::TimeTraceScope timeScope(
"Verifier verify sibling funclet unwinds");
3109 SmallPtrSet<Instruction *, 8> Visited;
3110 SmallPtrSet<Instruction *, 8>
Active;
3111 for (
const auto &Pair : SiblingFuncletInfo) {
3113 if (Visited.
count(PredPad))
3119 if (
Active.count(SuccPad)) {
3122 SmallVector<Instruction *, 8> CycleNodes;
3125 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
3126 if (CycleTerminator != CyclePad)
3129 }
while (CyclePad != SuccPad);
3130 Check(
false,
"EH pads can't handle each other's exceptions",
3134 if (!Visited.
insert(SuccPad).second)
3138 auto TermI = SiblingFuncletInfo.find(PredPad);
3139 if (TermI == SiblingFuncletInfo.end())
3152void Verifier::visitFunction(
const Function &
F) {
3153 visitGlobalValue(
F);
3156 FunctionType *FT =
F.getFunctionType();
3157 unsigned NumArgs =
F.arg_size();
3160 "Function context does not match Module context!", &
F);
3162 Check(!
F.hasCommonLinkage(),
"Functions may not have common linkage", &
F);
3163 Check(FT->getNumParams() == NumArgs,
3164 "# formal arguments must match # of arguments for function type!", &
F,
3166 Check(
F.getReturnType()->isFirstClassType() ||
3167 F.getReturnType()->isVoidTy() ||
F.getReturnType()->isStructTy(),
3168 "Functions cannot return aggregate values!", &
F);
3170 Check(!
F.hasStructRetAttr() ||
F.getReturnType()->isVoidTy(),
3171 "Invalid struct return type!", &
F);
3173 if (MaybeAlign
A =
F.getAlign()) {
3174 Check(
A->value() <= Value::MaximumAlignment,
3175 "huge alignment values are unsupported", &
F);
3178 AttributeList
Attrs =
F.getAttributes();
3180 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
3181 "Attribute after last parameter!", &
F);
3183 bool IsIntrinsic =
F.isIntrinsic();
3186 verifyFunctionAttrs(FT, Attrs, &
F, IsIntrinsic,
false);
3192 "Attribute 'builtin' can only be applied to a callsite.", &
F);
3194 Check(!
Attrs.hasAttrSomewhere(Attribute::ElementType),
3195 "Attribute 'elementtype' can only be applied to a callsite.", &
F);
3197 if (
Attrs.hasFnAttr(Attribute::Naked))
3198 for (
const Argument &Arg :
F.args())
3199 Check(Arg.use_empty(),
"cannot use argument of naked function", &Arg);
3204 switch (
F.getCallingConv()) {
3206 case CallingConv::C:
3208 case CallingConv::X86_INTR: {
3209 Check(
F.arg_empty() ||
Attrs.hasParamAttr(0, Attribute::ByVal),
3210 "Calling convention parameter requires byval", &
F);
3213 case CallingConv::AMDGPU_KERNEL:
3214 case CallingConv::SPIR_KERNEL:
3215 case CallingConv::AMDGPU_CS_Chain:
3216 case CallingConv::AMDGPU_CS_ChainPreserve:
3217 Check(
F.getReturnType()->isVoidTy(),
3218 "Calling convention requires void return type", &
F);
3220 case CallingConv::AMDGPU_VS:
3221 case CallingConv::AMDGPU_HS:
3222 case CallingConv::AMDGPU_GS:
3223 case CallingConv::AMDGPU_PS:
3224 case CallingConv::AMDGPU_CS:
3225 Check(!
F.hasStructRetAttr(),
"Calling convention does not allow sret", &
F);
3226 if (
F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3227 const unsigned StackAS =
DL.getAllocaAddrSpace();
3229 for (
const Argument &Arg :
F.args()) {
3230 Check(!
Attrs.hasParamAttr(i, Attribute::ByVal),
3231 "Calling convention disallows byval", &
F);
3232 Check(!
Attrs.hasParamAttr(i, Attribute::Preallocated),
3233 "Calling convention disallows preallocated", &
F);
3234 Check(!
Attrs.hasParamAttr(i, Attribute::InAlloca),
3235 "Calling convention disallows inalloca", &
F);
3237 if (
Attrs.hasParamAttr(i, Attribute::ByRef)) {
3240 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
3241 "Calling convention disallows stack byref", &
F);
3249 case CallingConv::Fast:
3250 case CallingConv::Cold:
3251 case CallingConv::Intel_OCL_BI:
3252 case CallingConv::PTX_Kernel:
3253 case CallingConv::PTX_Device:
3255 "Calling convention does not support varargs or "
3256 "perfect forwarding!",
3259 case CallingConv::AMDGPU_Gfx_WholeWave:
3260 Check(!
F.arg_empty() &&
F.arg_begin()->getType()->isIntegerTy(1),
3261 "Calling convention requires first argument to be i1", &
F);
3262 Check(!
F.arg_begin()->hasInRegAttr(),
3263 "Calling convention requires first argument to not be inreg", &
F);
3265 "Calling convention does not support varargs or "
3266 "perfect forwarding!",
3273 for (
const Argument &Arg :
F.args()) {
3274 Check(Arg.getType() == FT->getParamType(i),
3275 "Argument value does not match function argument type!", &Arg,
3276 FT->getParamType(i));
3277 Check(Arg.getType()->isFirstClassType(),
3278 "Function arguments must have first-class types!", &Arg);
3280 Check(!Arg.getType()->isMetadataTy(),
3281 "Function takes metadata but isn't an intrinsic", &Arg, &
F);
3282 Check(!Arg.getType()->isTokenLikeTy(),
3283 "Function takes token but isn't an intrinsic", &Arg, &
F);
3284 Check(!Arg.getType()->isX86_AMXTy(),
3285 "Function takes x86_amx but isn't an intrinsic", &Arg, &
F);
3289 if (
Attrs.hasParamAttr(i, Attribute::SwiftError)) {
3290 verifySwiftErrorValue(&Arg);
3296 Check(!
F.getReturnType()->isTokenLikeTy(),
3297 "Function returns a token but isn't an intrinsic", &
F);
3298 Check(!
F.getReturnType()->isX86_AMXTy(),
3299 "Function returns a x86_amx but isn't an intrinsic", &
F);
3304 F.getAllMetadata(MDs);
3305 assert(
F.hasMetadata() != MDs.
empty() &&
"Bit out-of-sync");
3306 verifyFunctionMetadata(MDs);
3312 if (
F.hasPersonalityFn()) {
3315 Check(Per->getParent() ==
F.getParent(),
3316 "Referencing personality function in another module!", &
F,
3317 F.getParent(), Per, Per->getParent());
3321 BlockEHFuncletColors.
clear();
3323 if (
F.isMaterializable()) {
3325 Check(MDs.
empty(),
"unmaterialized function cannot have metadata", &
F,
3327 }
else if (
F.isDeclaration()) {
3328 for (
const auto &
I : MDs) {
3330 CheckDI(
I.first != LLVMContext::MD_dbg ||
3332 "function declaration may only have a unique !dbg attachment",
3334 Check(
I.first != LLVMContext::MD_prof,
3335 "function declaration may not have a !prof attachment", &
F);
3338 visitMDNode(*
I.second, AreDebugLocsAllowed::Yes);
3340 Check(!
F.hasPersonalityFn(),
3341 "Function declaration shouldn't have a personality routine", &
F);
3345 Check(!IsIntrinsic,
"llvm intrinsics cannot be defined!", &
F);
3350 "Entry block to function must not have predecessors!", Entry);
3353 if (
Entry->hasAddressTaken()) {
3355 "blockaddress may not be used with the entry block!", Entry);
3358 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
3359 NumKCFIAttachments = 0;
3361 for (
const auto &
I : MDs) {
3363 auto AllowLocs = AreDebugLocsAllowed::No;
3367 case LLVMContext::MD_dbg: {
3368 ++NumDebugAttachments;
3369 CheckDI(NumDebugAttachments == 1,
3370 "function must have a single !dbg attachment", &
F,
I.second);
3372 "function !dbg attachment must be a subprogram", &
F,
I.second);
3374 "function definition may only have a distinct !dbg attachment",
3378 const Function *&AttachedTo = DISubprogramAttachments[
SP];
3379 CheckDI(!AttachedTo || AttachedTo == &
F,
3380 "DISubprogram attached to more than one function", SP, &
F);
3382 AllowLocs = AreDebugLocsAllowed::Yes;
3385 case LLVMContext::MD_prof:
3386 ++NumProfAttachments;
3387 Check(NumProfAttachments == 1,
3388 "function must have a single !prof attachment", &
F,
I.second);
3390 case LLVMContext::MD_kcfi_type:
3391 ++NumKCFIAttachments;
3392 Check(NumKCFIAttachments == 1,
3393 "function must have a single !kcfi_type attachment", &
F,
3399 visitMDNode(*
I.second, AllowLocs);
3407 bool isMaterialized =
F.getParent()->isMaterialized();
3408 if (
F.isIntrinsic() && isMaterialized) {
3410 if (
F.hasAddressTaken(&U,
false,
true,
false,
3412 Check(
false,
"Invalid user of intrinsic instruction!", U);
3419 if (IID && (isMaterialized || !
F.materialized_use_empty())) {
3423 raw_string_ostream ErrOS(ErrMsg);
3426 Printable PrintDecl([&
F](raw_ostream &OS) {
F.print(OS); });
3427 Check(IsValid, ErrMsg, PrintDecl);
3434 IID, OverloadTys,
const_cast<Module *
>(
F.getParent()), FT);
3435 Check(ExpectedName ==
F.getName(),
3436 "Intrinsic name not mangled correctly for type arguments! "
3442 auto *
N =
F.getSubprogram();
3443 HasDebugInfo = (
N !=
nullptr);
3451 SmallPtrSet<const MDNode *, 32> Seen;
3463 "DILocation's scope must be a DILocalScope",
N, &
F, &
I,
DL, Parent);
3465 DILocalScope *
Scope =
DL->getInlinedAtScope();
3466 Check(Scope,
"Failed to find DILocalScope",
DL);
3468 if (!Seen.
insert(Scope).second)
3472 if (hasDIScopeCycle(Scope))
3475 DISubprogram *
SP =
Scope->getSubprogram();
3479 if ((Scope != SP) && !Seen.
insert(SP).second)
3483 "!dbg attachment points at wrong subprogram for function",
N, &
F,
3487 for (
auto &
I : BB) {
3488 VisitDebugLoc(
I,
I.getDebugLoc().getAsMDNode());
3490 if (
auto MD =
I.getMetadata(LLVMContext::MD_loop))
3493 if (BrokenDebugInfo)
3500void Verifier::visitBasicBlock(BasicBlock &BB) {
3501 InstsInThisBlock.
clear();
3502 ConvergenceVerifyHelper.
visit(BB);
3513 for (
const PHINode &PN : BB.
phis()) {
3514 Check(PN.getNumIncomingValues() == Preds.size(),
3515 "PHINode should have one entry for each predecessor of its "
3516 "parent basic block!",
3521 Values.reserve(PN.getNumIncomingValues());
3522 for (
unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3524 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3527 for (
unsigned i = 0, e =
Values.size(); i != e; ++i) {
3534 "PHI node has multiple entries for the same basic block with "
3535 "different incoming values!",
3541 "PHI node entries do not match predecessors!", &PN,
3542 Values[i].first, Preds[i]);
3550 Check(
I.getParent() == &BB,
"Instruction has bogus parent pointer!");
3554 CheckDI(!BB.getTrailingDbgRecords(),
"Basic Block has trailing DbgRecords!",
3558void Verifier::visitTerminator(Instruction &
I) {
3560 Check(&
I ==
I.getParent()->getTerminator(),
3561 "Terminator found in the middle of a basic block!",
I.getParent());
3562 visitInstruction(
I);
3565void Verifier::visitCondBrInst(CondBrInst &BI) {
3567 "Branch condition is not 'i1' type!", &BI, BI.
getCondition());
3568 visitTerminator(BI);
3571void Verifier::visitReturnInst(ReturnInst &RI) {
3574 if (
F->getReturnType()->isVoidTy())
3576 "Found return instr that returns non-void in Function of void "
3578 &RI,
F->getReturnType());
3581 "Function return type does not match operand "
3582 "type of return inst!",
3583 &RI,
F->getReturnType());
3587 visitTerminator(RI);
3590void Verifier::visitSwitchInst(SwitchInst &SI) {
3591 Check(
SI.getType()->isVoidTy(),
"Switch must have void result type!", &SI);
3594 Type *SwitchTy =
SI.getCondition()->getType();
3595 SmallPtrSet<ConstantInt*, 32>
Constants;
3596 for (
auto &Case :
SI.cases()) {
3598 "Case value is not a constant integer.", &SI);
3599 Check(Case.getCaseValue()->getType() == SwitchTy,
3600 "Switch constants must all be same type as switch value!", &SI);
3602 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3605 visitTerminator(SI);
3608void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
3610 "Indirectbr operand must have pointer type!", &BI);
3613 "Indirectbr destinations must all have pointer type!", &BI);
3615 visitTerminator(BI);
3624void Verifier::visitCallBrInst(CallBrInst &CBI) {
3627 "callbr: indirect function / invalid signature");
3629 "callbr for intrinsics currently doesn't support operand bundles");
3633 "callbr currently only supports asm-goto and selected intrinsics");
3638 Check(!
IA->canThrow(),
"Unwinding from Callbr is not allowed");
3640 verifyInlineAsmCall(CBI);
3642 visitTerminator(CBI);
3645void Verifier::visitSelectInst(SelectInst &SI) {
3648 "Invalid operands for select instruction!", &SI);
3650 Check(
SI.getTrueValue()->getType() ==
SI.getType(),
3651 "Select values must have same type as select instruction!", &SI);
3652 visitInstruction(SI);
3658void Verifier::visitUserOp1(Instruction &
I) {
3659 Check(
false,
"User-defined operators should not live outside of a pass!", &
I);
3662void Verifier::visitTruncInst(TruncInst &
I) {
3664 Type *SrcTy =
I.getOperand(0)->getType();
3665 Type *DestTy =
I.getType();
3674 "trunc source and destination must both be a vector or neither", &
I);
3675 Check(SrcBitSize > DestBitSize,
"DestTy too big for Trunc", &
I);
3677 visitInstruction(
I);
3680void Verifier::visitZExtInst(ZExtInst &
I) {
3682 Type *SrcTy =
I.getOperand(0)->getType();
3683 Type *DestTy =
I.getType();
3689 "zext source and destination must both be a vector or neither", &
I);
3693 Check(SrcBitSize < DestBitSize,
"Type too small for ZExt", &
I);
3695 visitInstruction(
I);
3698void Verifier::visitSExtInst(SExtInst &
I) {
3700 Type *SrcTy =
I.getOperand(0)->getType();
3701 Type *DestTy =
I.getType();
3710 "sext source and destination must both be a vector or neither", &
I);
3711 Check(SrcBitSize < DestBitSize,
"Type too small for SExt", &
I);
3713 visitInstruction(
I);
3716void Verifier::visitFPTruncInst(FPTruncInst &
I) {
3718 Type *SrcTy =
I.getOperand(0)->getType();
3719 Type *DestTy =
I.getType();
3727 "fptrunc source and destination must both be a vector or neither", &
I);
3728 Check(SrcBitSize > DestBitSize,
"DestTy too big for FPTrunc", &
I);
3730 visitInstruction(
I);
3733void Verifier::visitFPExtInst(FPExtInst &
I) {
3735 Type *SrcTy =
I.getOperand(0)->getType();
3736 Type *DestTy =
I.getType();
3745 "fpext source and destination must both be a vector or neither", &
I);
3746 Check(SrcBitSize < DestBitSize,
"DestTy too small for FPExt", &
I);
3748 visitInstruction(
I);
3751void Verifier::visitUIToFPInst(UIToFPInst &
I) {
3753 Type *SrcTy =
I.getOperand(0)->getType();
3754 Type *DestTy =
I.getType();
3759 Check(SrcVec == DstVec,
3760 "UIToFP source and dest must both be vector or scalar", &
I);
3762 "UIToFP source must be integer or integer vector", &
I);
3766 if (SrcVec && DstVec)
3769 "UIToFP source and dest vector length mismatch", &
I);
3771 visitInstruction(
I);
3774void Verifier::visitSIToFPInst(SIToFPInst &
I) {
3776 Type *SrcTy =
I.getOperand(0)->getType();
3777 Type *DestTy =
I.getType();
3782 Check(SrcVec == DstVec,
3783 "SIToFP source and dest must both be vector or scalar", &
I);
3785 "SIToFP source must be integer or integer vector", &
I);
3789 if (SrcVec && DstVec)
3792 "SIToFP source and dest vector length mismatch", &
I);
3794 visitInstruction(
I);
3797void Verifier::visitFPToUIInst(FPToUIInst &
I) {
3799 Type *SrcTy =
I.getOperand(0)->getType();
3800 Type *DestTy =
I.getType();
3805 Check(SrcVec == DstVec,
3806 "FPToUI source and dest must both be vector or scalar", &
I);
3809 "FPToUI result must be integer or integer vector", &
I);
3811 if (SrcVec && DstVec)
3814 "FPToUI source and dest vector length mismatch", &
I);
3816 visitInstruction(
I);
3819void Verifier::visitFPToSIInst(FPToSIInst &
I) {
3821 Type *SrcTy =
I.getOperand(0)->getType();
3822 Type *DestTy =
I.getType();
3827 Check(SrcVec == DstVec,
3828 "FPToSI source and dest must both be vector or scalar", &
I);
3831 "FPToSI result must be integer or integer vector", &
I);
3833 if (SrcVec && DstVec)
3836 "FPToSI source and dest vector length mismatch", &
I);
3838 visitInstruction(
I);
3841void Verifier::checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V) {
3850 Check(VSrc->getElementCount() == VDest->getElementCount(),
3851 "PtrToAddr vector length mismatch", V);
3854 Type *AddrTy =
DL.getAddressType(SrcTy);
3855 Check(AddrTy == DestTy,
"PtrToAddr result must be address width", V);
3858void Verifier::visitPtrToAddrInst(PtrToAddrInst &
I) {
3859 checkPtrToAddr(
I.getOperand(0)->getType(),
I.getType(),
I);
3860 visitInstruction(
I);
3863void Verifier::visitPtrToIntInst(PtrToIntInst &
I) {
3865 Type *SrcTy =
I.getOperand(0)->getType();
3866 Type *DestTy =
I.getType();
3877 Check(VSrc->getElementCount() == VDest->getElementCount(),
3878 "PtrToInt Vector length mismatch", &
I);
3881 visitInstruction(
I);
3884void Verifier::visitIntToPtrInst(IntToPtrInst &
I) {
3886 Type *SrcTy =
I.getOperand(0)->getType();
3887 Type *DestTy =
I.getType();
3897 Check(VSrc->getElementCount() == VDest->getElementCount(),
3898 "IntToPtr Vector length mismatch", &
I);
3900 visitInstruction(
I);
3903void Verifier::visitBitCastInst(BitCastInst &
I) {
3906 "Invalid bitcast", &
I);
3907 visitInstruction(
I);
3910void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &
I) {
3911 Type *SrcTy =
I.getOperand(0)->getType();
3912 Type *DestTy =
I.getType();
3919 "AddrSpaceCast must be between different address spaces", &
I);
3921 Check(SrcVTy->getElementCount() ==
3923 "AddrSpaceCast vector pointer number of elements mismatch", &
I);
3924 visitInstruction(
I);
3929void Verifier::visitPHINode(PHINode &PN) {
3936 "PHI nodes not grouped at top of basic block!", &PN, PN.
getParent());
3945 "PHI node operands are not the same type as the result!", &PN);
3950 visitInstruction(PN);
3953void Verifier::visitCallBase(CallBase &
Call) {
3955 "Called function must be a pointer!",
Call);
3959 if (FTy->isVarArg())
3961 "Called function requires more parameters than were provided!",
Call);
3964 "Incorrect number of arguments passed to called function!",
Call);
3967 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3969 "Call parameter type does not match function signature!",
3975 "Attribute after last parameter!",
Call);
3982 "Intrinsic called with incompatible signature",
Call);
3986 "calling convention does not permit calls",
Call);
3992 auto VerifyTypeAlign = [&](
Type *Ty,
const Twine &Message) {
3995 Align ABIAlign =
DL.getABITypeAlign(Ty);
3996 Check(ABIAlign.
value() <= Value::MaximumAlignment,
3997 "Incorrect alignment of " + Message +
" to called function!",
Call);
4001 VerifyTypeAlign(FTy->getReturnType(),
"return type");
4002 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
4003 Type *Ty = FTy->getParamType(i);
4004 VerifyTypeAlign(Ty,
"argument passed");
4008 if (
Attrs.hasFnAttr(Attribute::Speculatable)) {
4012 "speculatable attribute may not apply to call sites",
Call);
4015 if (
Attrs.hasFnAttr(Attribute::Preallocated)) {
4017 "preallocated as a call site attribute can only be on "
4018 "llvm.call.preallocated.arg");
4021 Check(!
Attrs.hasFnAttr(Attribute::DenormalFPEnv),
4022 "denormal_fpenv attribute may not apply to call sites",
Call);
4033 Check(AI->isUsedWithInAlloca(),
4034 "inalloca argument for call has mismatched alloca", AI,
Call);
4040 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
4044 Check(AI->isSwiftError(),
4045 "swifterror argument for call has mismatched alloca", AI,
Call);
4049 Check(ArgI,
"swifterror argument should come from an alloca or parameter",
4050 SwiftErrorArg,
Call);
4051 Check(ArgI->hasSwiftErrorAttr(),
4052 "swifterror argument for call has mismatched parameter", ArgI,
4056 if (
Attrs.hasParamAttr(i, Attribute::ImmArg)) {
4059 Check(Callee &&
Callee->hasParamAttribute(i, Attribute::ImmArg),
4068 "immarg operand has non-immediate parameter", ArgVal,
Call);
4074 const ConstantRange &CR =
4077 formatv(
"immarg value {} for arg {} out of range {}",
4078 CI->getValue(), i, CR),
4085 formatv(
"immarg value {} for arg {} out of range set",
4095 Check(hasOB != isMustTail,
4096 "preallocated operand either requires a preallocated bundle or "
4097 "the call to be musttail (but not both)",
4102 if (FTy->isVarArg()) {
4104 bool SawNest =
false;
4105 bool SawReturned =
false;
4107 for (
unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
4108 if (
Attrs.hasParamAttr(Idx, Attribute::Nest))
4110 if (
Attrs.hasParamAttr(Idx, Attribute::Returned))
4115 for (
unsigned Idx = FTy->getNumParams(); Idx <
Call.
arg_size(); ++Idx) {
4117 AttributeSet ArgAttrs =
Attrs.getParamAttrs(Idx);
4118 verifyParameterAttrs(ArgAttrs, Ty, &
Call);
4121 Check(!SawNest,
"More than one parameter has attribute nest!",
Call);
4126 Check(!SawReturned,
"More than one parameter has attribute returned!",
4129 "Incompatible argument and return types for 'returned' "
4139 "Attribute 'sret' cannot be used for vararg call arguments!",
4144 "inalloca isn't on the last argument!",
Call);
4150 for (
Type *ParamTy : FTy->params()) {
4151 Check(!ParamTy->isMetadataTy(),
4152 "Function has metadata parameter but isn't an intrinsic",
Call);
4153 Check(!ParamTy->isTokenLikeTy(),
4154 "Function has token parameter but isn't an intrinsic",
Call);
4160 Check(!FTy->getReturnType()->isTokenLikeTy(),
4161 "Return type cannot be token for indirect call!");
4162 Check(!FTy->getReturnType()->isX86_AMXTy(),
4163 "Return type cannot be x86_amx for indirect call!");
4167 visitIntrinsicCall(ID,
Call);
4172 bool FoundDeoptBundle =
false, FoundFuncletBundle =
false,
4173 FoundGCTransitionBundle =
false, FoundCFGuardTargetBundle =
false,
4174 FoundPreallocatedBundle =
false, FoundGCLiveBundle =
false,
4175 FoundPtrauthBundle =
false, FoundKCFIBundle =
false,
4176 FoundAttachedCallBundle =
false;
4181 "Operand bundle operands cannot be labels",
Call);
4184 Check(!FoundDeoptBundle,
"Multiple deopt operand bundles",
Call);
4185 FoundDeoptBundle =
true;
4187 Check(!FoundGCTransitionBundle,
"Multiple gc-transition operand bundles",
4189 FoundGCTransitionBundle =
true;
4191 Check(!FoundFuncletBundle,
"Multiple funclet operand bundles",
Call);
4192 FoundFuncletBundle =
true;
4194 "Expected exactly one funclet bundle operand",
Call);
4196 "Funclet bundle operands should correspond to a FuncletPadInst",
4199 Check(!FoundCFGuardTargetBundle,
"Multiple CFGuardTarget operand bundles",
4201 FoundCFGuardTargetBundle =
true;
4203 "Expected exactly one cfguardtarget bundle operand",
Call);
4205 Check(!FoundPtrauthBundle,
"Multiple ptrauth operand bundles",
Call);
4206 FoundPtrauthBundle =
true;
4208 "Expected exactly two ptrauth bundle operands",
Call);
4210 BU.
Inputs[0]->getType()->isIntegerTy(32),
4211 "Ptrauth bundle key operand must be an i32 constant",
Call);
4213 "Ptrauth bundle discriminator operand must be an i64",
Call);
4215 Check(!FoundKCFIBundle,
"Multiple kcfi operand bundles",
Call);
4216 FoundKCFIBundle =
true;
4217 Check(BU.
Inputs.size() == 1,
"Expected exactly one kcfi bundle operand",
4220 BU.
Inputs[0]->getType()->isIntegerTy(32),
4221 "Kcfi bundle operand must be an i32 constant",
Call);
4223 Check(!FoundPreallocatedBundle,
"Multiple preallocated operand bundles",
4225 FoundPreallocatedBundle =
true;
4227 "Expected exactly one preallocated bundle operand",
Call);
4230 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
4231 "\"preallocated\" argument must be a token from "
4232 "llvm.call.preallocated.setup",
4235 Check(!FoundGCLiveBundle,
"Multiple gc-live operand bundles",
Call);
4236 FoundGCLiveBundle =
true;
4238 Check(!FoundAttachedCallBundle,
4239 "Multiple \"clang.arc.attachedcall\" operand bundles",
Call);
4240 FoundAttachedCallBundle =
true;
4241 verifyAttachedCallBundle(
Call, BU);
4247 "Direct call cannot have a ptrauth bundle",
Call);
4259 "inlinable function call in a function with "
4260 "debug info must have a !dbg location",
4264 verifyInlineAsmCall(
Call);
4268 visitInstruction(
Call);
4271void Verifier::verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs,
4274 Twine(
"inalloca attribute not allowed in ") +
Context);
4276 Twine(
"inreg attribute not allowed in ") +
Context);
4277 Check(!
Attrs.contains(Attribute::SwiftError),
4278 Twine(
"swifterror attribute not allowed in ") +
Context);
4279 Check(!
Attrs.contains(Attribute::Preallocated),
4280 Twine(
"preallocated attribute not allowed in ") +
Context);
4282 Twine(
"byref attribute not allowed in ") +
Context);
4287 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
4288 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
4289 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
4291 AttrBuilder Copy(
C);
4292 for (
auto AK : ABIAttrs) {
4293 Attribute Attr = Attrs.getParamAttrs(
I).getAttribute(AK);
4295 Copy.addAttribute(Attr);
4299 if (Attrs.hasParamAttr(
I, Attribute::Alignment) &&
4300 (Attrs.hasParamAttr(
I, Attribute::ByVal) ||
4301 Attrs.hasParamAttr(
I, Attribute::ByRef)))
4302 Copy.addAlignmentAttr(Attrs.getParamAlignment(
I));
4306void Verifier::verifyMustTailCall(CallInst &CI) {
4310 FunctionType *CallerTy =
F->getFunctionType();
4312 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
4313 "cannot guarantee tail call due to mismatched varargs", &CI);
4314 Check(CallerTy->getReturnType() == CalleeTy->getReturnType(),
4315 "cannot guarantee tail call due to mismatched return types", &CI);
4319 "cannot guarantee tail call due to mismatched calling conv", &CI);
4327 Check(Ret,
"musttail call must precede a ret", &CI);
4330 "musttail call result must be returned", Ret);
4332 AttributeList CallerAttrs =
F->getAttributes();
4337 CI.
getCallingConv() == CallingConv::Tail ?
"tailcc" :
"swifttailcc";
4341 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4343 SmallString<32>
Context{CCName, StringRef(
" musttail caller")};
4344 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4346 for (
unsigned I = 0,
E = CalleeTy->getNumParams();
I !=
E; ++
I) {
4348 SmallString<32>
Context{CCName, StringRef(
" musttail callee")};
4349 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4352 Check(!CallerTy->isVarArg(), Twine(
"cannot guarantee ") + CCName +
4353 " tail call for varargs function");
4359 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
4360 "cannot guarantee tail call due to mismatched parameter counts", &CI);
4361 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4362 Check(CallerTy->getParamType(
I) == CalleeTy->getParamType(
I),
4363 "cannot guarantee tail call due to mismatched parameter types",
4370 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4373 Check(CallerABIAttrs == CalleeABIAttrs,
4374 "cannot guarantee tail call due to mismatched ABI impacting "
4375 "function attributes",
4380void Verifier::visitCallInst(CallInst &CI) {
4384 verifyMustTailCall(CI);
4387void Verifier::visitInvokeInst(InvokeInst &
II) {
4393 II.getUnwindDest()->isEHPad(),
4394 "The unwind destination does not have an exception handling instruction!",
4397 visitTerminator(
II);
4402void Verifier::visitUnaryOperator(UnaryOperator &U) {
4403 Check(
U.getType() ==
U.getOperand(0)->getType(),
4404 "Unary operators must have same type for"
4405 "operands and result!",
4408 switch (
U.getOpcode()) {
4411 case Instruction::FNeg:
4412 Check(
U.getType()->isFPOrFPVectorTy(),
4413 "FNeg operator only works with float types!", &U);
4419 visitInstruction(U);
4425void Verifier::visitBinaryOperator(BinaryOperator &
B) {
4426 Check(
B.getOperand(0)->getType() ==
B.getOperand(1)->getType(),
4427 "Both operands to a binary operator are not of the same type!", &
B);
4429 switch (
B.getOpcode()) {
4432 case Instruction::Add:
4433 case Instruction::Sub:
4434 case Instruction::Mul:
4435 case Instruction::SDiv:
4436 case Instruction::UDiv:
4437 case Instruction::SRem:
4438 case Instruction::URem:
4439 Check(
B.getType()->isIntOrIntVectorTy(),
4440 "Integer arithmetic operators only work with integral types!", &
B);
4441 Check(
B.getType() ==
B.getOperand(0)->getType(),
4442 "Integer arithmetic operators must have same type "
4443 "for operands and result!",
4448 case Instruction::FAdd:
4449 case Instruction::FSub:
4450 case Instruction::FMul:
4451 case Instruction::FDiv:
4452 case Instruction::FRem:
4453 Check(
B.getType()->isFPOrFPVectorTy(),
4454 "Floating-point arithmetic operators only work with "
4455 "floating-point types!",
4457 Check(
B.getType() ==
B.getOperand(0)->getType(),
4458 "Floating-point arithmetic operators must have same type "
4459 "for operands and result!",
4463 case Instruction::And:
4464 case Instruction::Or:
4465 case Instruction::Xor:
4466 Check(
B.getType()->isIntOrIntVectorTy(),
4467 "Logical operators only work with integral types!", &
B);
4468 Check(
B.getType() ==
B.getOperand(0)->getType(),
4469 "Logical operators must have same type for operands and result!", &
B);
4471 case Instruction::Shl:
4472 case Instruction::LShr:
4473 case Instruction::AShr:
4474 Check(
B.getType()->isIntOrIntVectorTy(),
4475 "Shifts only work with integral types!", &
B);
4476 Check(
B.getType() ==
B.getOperand(0)->getType(),
4477 "Shift return type must be same as operands!", &
B);
4483 visitInstruction(
B);
4486void Verifier::visitICmpInst(ICmpInst &IC) {
4490 Check(Op0Ty == Op1Ty,
4491 "Both operands to ICmp instruction are not of the same type!", &IC);
4494 "Invalid operand types for ICmp instruction", &IC);
4498 visitInstruction(IC);
4501void Verifier::visitFCmpInst(FCmpInst &FC) {
4503 Type *Op0Ty =
FC.getOperand(0)->getType();
4504 Type *Op1Ty =
FC.getOperand(1)->getType();
4505 Check(Op0Ty == Op1Ty,
4506 "Both operands to FCmp instruction are not of the same type!", &FC);
4511 Check(
FC.isFPPredicate(),
"Invalid predicate in FCmp instruction!", &FC);
4513 visitInstruction(FC);
4516void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
4518 "Invalid extractelement operands!", &EI);
4519 visitInstruction(EI);
4522void Verifier::visitInsertElementInst(InsertElementInst &IE) {
4525 "Invalid insertelement operands!", &IE);
4526 visitInstruction(IE);
4529void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
4532 "Invalid shufflevector operands!", &SV);
4533 visitInstruction(SV);
4536void Verifier::visitGetElementPtrInst(GetElementPtrInst &
GEP) {
4538 GEP.getModule()->getModuleFlag(
"require-logical-pointer")))
4539 Check(!MD->getZExtValue(),
4540 "Non-logical getelementptr disallowed for this module.");
4542 Type *TargetTy =
GEP.getPointerOperandType()->getScalarType();
4545 "GEP base pointer is not a vector or a vector of pointers", &
GEP);
4546 Check(
GEP.getSourceElementType()->isSized(),
"GEP into unsized type!", &
GEP);
4549 Check(!STy->isScalableTy(),
4550 "getelementptr cannot target structure that contains scalable vector"
4555 SmallVector<Value *, 16> Idxs(
GEP.indices());
4557 all_of(Idxs, [](
Value *V) {
return V->getType()->isIntOrIntVectorTy(); }),
4558 "GEP indexes must be integers", &
GEP);
4561 Check(ElTy,
"Invalid indices for GEP pointer type!", &
GEP);
4565 Check(PtrTy &&
GEP.getResultElementType() == ElTy,
4566 "GEP is not of right type for indices!", &
GEP, ElTy);
4570 ElementCount GEPWidth = GEPVTy->getElementCount();
4571 if (
GEP.getPointerOperandType()->isVectorTy())
4575 "Vector GEP result width doesn't match operand's", &
GEP);
4576 for (
Value *Idx : Idxs) {
4577 Type *IndexTy = Idx->getType();
4579 ElementCount IndexWidth = IndexVTy->getElementCount();
4580 Check(IndexWidth == GEPWidth,
"Invalid GEP index vector width", &
GEP);
4583 "All GEP indices should be of integer type");
4590 GTI != GTE; ++GTI) {
4591 if (GTI.isVector()) {
4592 Type *ElemTy = GTI.getIndexedType();
4593 Check(
DL.typeSizeEqualsStoreSize(ElemTy),
4594 "GEP into vector with non-byte-addressable element type", &
GEP);
4598 Check(
GEP.getAddressSpace() == PtrTy->getAddressSpace(),
4599 "GEP address space doesn't match type", &
GEP);
4601 visitInstruction(
GEP);
4605 return A.getUpper() ==
B.getLower() ||
A.getLower() ==
B.getUpper();
4610void Verifier::verifyRangeLikeMetadata(
const Value &
I,
const MDNode *
Range,
4611 Type *Ty, RangeLikeMetadataKind Kind) {
4612 unsigned NumOperands =
Range->getNumOperands();
4613 Check(NumOperands % 2 == 0,
"Unfinished range!",
Range);
4614 unsigned NumRanges = NumOperands / 2;
4615 Check(NumRanges >= 1,
"It should have at least one range!",
Range);
4617 ConstantRange LastRange(1,
true);
4618 for (
unsigned i = 0; i < NumRanges; ++i) {
4621 Check(
Low,
"The lower limit must be an integer!",
Low);
4626 Check(
High->getType() ==
Low->getType(),
"Range pair types must match!",
4629 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4631 "noalias.addrspace type must be i32!", &
I);
4634 "Range types must match instruction type!", &
I);
4637 APInt HighV =
High->getValue();
4638 APInt LowV =
Low->getValue();
4643 "The upper and lower limits cannot be the same value", &
I);
4645 ConstantRange CurRange(LowV, HighV);
4646 Check(!CurRange.isEmptySet() &&
4647 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
4648 !CurRange.isFullSet()),
4649 "Range must not be empty!",
Range);
4651 Check(CurRange.intersectWith(LastRange).isEmptySet(),
4652 "Intervals are overlapping",
Range);
4653 Check(LowV.
sgt(LastRange.getLower()),
"Intervals are not in order",
4658 LastRange = ConstantRange(LowV, HighV);
4660 if (NumRanges > 2) {
4665 ConstantRange FirstRange(FirstLow, FirstHigh);
4666 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
4667 "Intervals are overlapping",
Range);
4673void Verifier::visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty) {
4675 "precondition violation");
4676 verifyRangeLikeMetadata(
I,
Range, Ty, RangeLikeMetadataKind::Range);
4679void Verifier::visitNoFPClassMetadata(Instruction &
I, MDNode *NoFPClass,
4681 Check(AttributeFuncs::isNoFPClassCompatibleType(Ty),
4682 "nofpclass only applies to floating-point typed loads",
I);
4685 "nofpclass must have exactly one entry", NoFPClass);
4686 ConstantInt *MaskVal =
4689 "nofpclass entry must be a constant i32", NoFPClass);
4691 Check(Val != 0,
"'nofpclass' must have at least one test bit set", NoFPClass,
4695 "Invalid value for 'nofpclass' test mask", NoFPClass,
I);
4698void Verifier::visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
4701 "precondition violation");
4702 verifyRangeLikeMetadata(
I,
Range, Ty,
4703 RangeLikeMetadataKind::NoaliasAddrspace);
4706void Verifier::checkAtomicMemAccessSize(
Type *Ty,
const Instruction *
I) {
4707 unsigned Size =
DL.getTypeSizeInBits(Ty).getFixedValue();
4708 Check(
Size >= 8,
"atomic memory access' size must be byte-sized", Ty,
I);
4710 "atomic memory access' operand must have a power-of-two size", Ty,
I);
4713void Verifier::visitLoadInst(LoadInst &LI) {
4715 Check(PTy,
"Load operand must be a pointer.", &LI);
4718 Check(
A->value() <= Value::MaximumAlignment,
4719 "huge alignment values are unsupported", &LI);
4721 Check(ElTy->
isSized(),
"loading unsized types is not allowed", &LI);
4724 LI.
getOrdering() != AtomicOrdering::AcquireRelease,
4725 "Load cannot have Release ordering", &LI);
4729 "atomic elementwise load cannot be sequentially consistent.", &LI);
4732 "atomic elementwise load operand must have fixed vector type!", &LI,
4735 checkAtomicMemAccessSize(VecTy->getElementType(), &LI);
4741 "atomic load operand must have integer, byte, pointer, floating "
4742 "point, or vector type!",
4745 checkAtomicMemAccessSize(ElTy, &LI);
4749 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4752 visitInstruction(LI);
4755void Verifier::visitStoreInst(StoreInst &SI) {
4757 Check(PTy,
"Store operand must be a pointer.", &SI);
4758 Type *ElTy =
SI.getOperand(0)->getType();
4759 if (MaybeAlign
A =
SI.getAlign()) {
4760 Check(
A->value() <= Value::MaximumAlignment,
4761 "huge alignment values are unsupported", &SI);
4763 Check(ElTy->
isSized(),
"storing unsized types is not allowed", &SI);
4764 if (
SI.isAtomic()) {
4765 Check(
SI.getOrdering() != AtomicOrdering::Acquire &&
4766 SI.getOrdering() != AtomicOrdering::AcquireRelease,
4767 "Store cannot have Acquire ordering", &SI);
4769 if (
SI.isElementwise()) {
4770 Check(
SI.getOrdering() != AtomicOrdering::SequentiallyConsistent,
4771 "atomic elementwise store cannot be sequentially consistent.", &SI);
4775 "atomic elementwise store operand must have fixed vector type!",
4778 checkAtomicMemAccessSize(VecTy->getElementType(), &SI);
4784 "atomic store operand must have integer, byte, pointer, floating "
4785 "point, or vector type!",
4787 checkAtomicMemAccessSize(ElTy, &SI);
4789 Check(!
SI.isElementwise(),
"non-atomic store cannot be elementwise", &SI);
4791 "Non-atomic store cannot have SynchronizationScope specified", &SI);
4793 visitInstruction(SI);
4797void Verifier::verifySwiftErrorCall(CallBase &
Call,
4798 const Value *SwiftErrorVal) {
4800 if (
I.value() == SwiftErrorVal) {
4802 "swifterror value when used in a callsite should be marked "
4803 "with swifterror attribute",
4804 SwiftErrorVal,
Call);
4809void Verifier::verifySwiftErrorValue(
const Value *SwiftErrorVal) {
4812 for (
const User *U : SwiftErrorVal->
users()) {
4815 "swifterror value can only be loaded and stored from, or "
4816 "as a swifterror argument!",
4820 Check(StoreI->getOperand(1) == SwiftErrorVal,
4821 "swifterror value should be the second operand when used "
4825 verifySwiftErrorCall(*
const_cast<CallBase *
>(
Call), SwiftErrorVal);
4829void Verifier::visitAllocaInst(AllocaInst &AI) {
4832 Check(!MD->getZExtValue(),
4833 "Non-logical alloca disallowed for this module.");
4836 SmallPtrSet<Type*, 4> Visited;
4837 Check(Ty->
isSized(&Visited),
"Cannot allocate unsized type", &AI);
4841 "Alloca has illegal target extension type", &AI);
4843 "Alloca array size must have integer type", &AI);
4845 Check(
A->value() <= Value::MaximumAlignment,
4846 "huge alignment values are unsupported", &AI);
4852 "swifterror alloca must not be array allocation", &AI);
4853 verifySwiftErrorValue(&AI);
4856 visitInstruction(AI);
4862void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4865 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4866 checkAtomicMemAccessSize(ElTy, &CXI);
4867 visitInstruction(CXI);
4870void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
4872 "atomicrmw instructions cannot be unordered.", &RMWI);
4878 "atomicrmw elementwise cannot be sequentially consistent.", &RMWI);
4880 Check(VecTy,
"atomicrmw elementwise operand must have fixed vector type!",
4883 checkAtomicMemAccessSize(VecTy->getElementType(), &RMWI);
4890 " operand must be an integer type, a floating-point type, a "
4891 "pointer type, or a fixed vector of any of these types!",
4896 " operand must have floating-point or fixed vector of "
4903 " operand must have integer or fixed vector of integer type!",
4906 checkAtomicMemAccessSize(ElTy, &RMWI);
4908 "Invalid binary operation!", &RMWI);
4909 visitInstruction(RMWI);
4912void Verifier::visitFenceInst(FenceInst &FI) {
4914 Check(Ordering == AtomicOrdering::Acquire ||
4915 Ordering == AtomicOrdering::Release ||
4916 Ordering == AtomicOrdering::AcquireRelease ||
4917 Ordering == AtomicOrdering::SequentiallyConsistent,
4918 "fence instructions may only have acquire, release, acq_rel, or "
4919 "seq_cst ordering.",
4921 visitInstruction(FI);
4924void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
4927 "Invalid ExtractValueInst operands!", &EVI);
4929 visitInstruction(EVI);
4932void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
4936 "Invalid InsertValueInst operands!", &IVI);
4938 visitInstruction(IVI);
4943 return FPI->getParentPad();
4948void Verifier::visitEHPadPredecessors(Instruction &
I) {
4954 Check(BB != &
F->getEntryBlock(),
"EH pad cannot be in entry block.", &
I);
4962 Check(
II &&
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4963 "Block containing LandingPadInst must be jumped to "
4964 "only by the unwind edge of an invoke.",
4972 "Block containg CatchPadInst must be jumped to "
4973 "only by its catchswitch.",
4975 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4976 "Catchswitch cannot unwind to one of its catchpads",
4977 CPI->getCatchSwitch(), CPI);
4989 Check(
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4990 "EH pad must be jumped to via an unwind edge", ToPad,
II);
4993 if (CalledFn && CalledFn->isIntrinsic() &&
II->doesNotThrow() &&
4997 FromPad = Bundle->Inputs[0];
5001 FromPad = CRI->getOperand(0);
5002 Check(FromPad != ToPadParent,
"A cleanupret must exit its cleanup", CRI);
5006 Check(
false,
"EH pad must be jumped to via an unwind edge", ToPad, TI);
5010 SmallPtrSet<Value *, 8> Seen;
5012 Check(FromPad != ToPad,
5013 "EH pad cannot handle exceptions raised within it", FromPad, TI);
5014 if (FromPad == ToPadParent) {
5019 "A single unwind edge may only enter one EH pad", TI);
5020 Check(Seen.
insert(FromPad).second,
"EH pad jumps through a cycle of pads",
5026 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
5031void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
5035 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
5037 visitEHPadPredecessors(LPI);
5039 if (!LandingPadResultTy)
5040 LandingPadResultTy = LPI.
getType();
5043 "The landingpad instruction should have a consistent result type "
5044 "inside a function.",
5048 Check(
F->hasPersonalityFn(),
5049 "LandingPadInst needs to be in a function with a personality.", &LPI);
5054 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
5060 "Catch operand does not have pointer type!", &LPI);
5062 Check(LPI.
isFilter(i),
"Clause is neither catch nor filter!", &LPI);
5064 "Filter operand is not an array of constants!", &LPI);
5068 visitInstruction(LPI);
5071void Verifier::visitResumeInst(ResumeInst &RI) {
5073 "ResumeInst needs to be in a function with a personality.", &RI);
5075 if (!LandingPadResultTy)
5079 "The resume instruction should have a consistent result type "
5080 "inside a function.",
5083 visitTerminator(RI);
5086void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
5090 Check(
F->hasPersonalityFn(),
5091 "CatchPadInst needs to be in a function with a personality.", &CPI);
5094 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
5100 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
5105 return isa<Constant>(V) || isa<AllocaInst>(V);
5107 "Argument operand must be alloca or constant.", &CPI);
5109 visitEHPadPredecessors(CPI);
5110 visitFuncletPadInst(CPI);
5113void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
5115 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
5118 visitTerminator(CatchReturn);
5121void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
5125 Check(
F->hasPersonalityFn(),
5126 "CleanupPadInst needs to be in a function with a personality.", &CPI);
5131 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
5135 "CleanupPadInst has an invalid parent.", &CPI);
5137 visitEHPadPredecessors(CPI);
5138 visitFuncletPadInst(CPI);
5141void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
5142 User *FirstUser =
nullptr;
5143 Value *FirstUnwindPad =
nullptr;
5145 SmallPtrSet<FuncletPadInst *, 8> Seen;
5147 while (!Worklist.empty()) {
5148 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
5150 "FuncletPadInst must not be nested within itself", CurrentPad);
5151 Value *UnresolvedAncestorPad =
nullptr;
5152 for (User *U : CurrentPad->
users()) {
5155 UnwindDest = CRI->getUnwindDest();
5161 if (CSI->unwindsToCaller())
5163 UnwindDest = CSI->getUnwindDest();
5165 UnwindDest =
II->getUnwindDest();
5175 Worklist.push_back(CPI);
5190 if (UnwindParent == CurrentPad)
5196 Value *ExitedPad = CurrentPad;
5199 if (ExitedPad == &FPI) {
5204 UnresolvedAncestorPad = &FPI;
5208 if (ExitedParent == UnwindParent) {
5212 UnresolvedAncestorPad = ExitedParent;
5215 ExitedPad = ExitedParent;
5221 UnresolvedAncestorPad = &FPI;
5228 Check(UnwindPad == FirstUnwindPad,
5229 "Unwind edges out of a funclet "
5230 "pad must have the same unwind "
5232 &FPI, U, FirstUser);
5235 FirstUnwindPad = UnwindPad;
5244 if (CurrentPad != &FPI)
5247 if (UnresolvedAncestorPad) {
5248 if (CurrentPad == UnresolvedAncestorPad) {
5252 assert(CurrentPad == &FPI);
5260 Value *ResolvedPad = CurrentPad;
5261 while (!Worklist.empty()) {
5262 Value *UnclePad = Worklist.back();
5266 while (ResolvedPad != AncestorPad) {
5268 if (ResolvedParent == UnresolvedAncestorPad) {
5271 ResolvedPad = ResolvedParent;
5275 if (ResolvedPad != AncestorPad)
5278 Worklist.pop_back();
5283 if (FirstUnwindPad) {
5285 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
5286 Value *SwitchUnwindPad;
5287 if (SwitchUnwindDest)
5291 Check(SwitchUnwindPad == FirstUnwindPad,
5292 "Unwind edges out of a catch must have the same unwind dest as "
5293 "the parent catchswitch",
5294 &FPI, FirstUser, CatchSwitch);
5298 visitInstruction(FPI);
5301void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
5305 Check(
F->hasPersonalityFn(),
5306 "CatchSwitchInst needs to be in a function with a personality.",
5312 "CatchSwitchInst not the first non-PHI instruction in the block.",
5317 "CatchSwitchInst has an invalid parent.", ParentPad);
5322 "CatchSwitchInst must unwind to an EH block which is not a "
5328 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
5332 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
5334 for (BasicBlock *Handler : CatchSwitch.
handlers()) {
5336 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
5339 visitEHPadPredecessors(CatchSwitch);
5340 visitTerminator(CatchSwitch);
5343void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
5345 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
5351 "CleanupReturnInst must unwind to an EH block which is not a "
5356 visitTerminator(CRI);
5359void Verifier::verifyDominatesUse(Instruction &
I,
unsigned i) {
5365 if (
II->getNormalDest() ==
II->getUnwindDest())
5379 const Use &
U =
I.getOperandUse(i);
5380 Check(DT.dominates(
Op, U),
"Instruction does not dominate all uses!",
Op, &
I);
5383void Verifier::visitDereferenceableMetadata(Instruction&
I, MDNode* MD) {
5384 Check(
I.getType()->isPointerTy(),
5385 "dereferenceable, dereferenceable_or_null "
5386 "apply only to pointer types",
5389 "dereferenceable, dereferenceable_or_null apply only to load"
5390 " and inttoptr instructions, use attributes for calls or invokes",
5393 "dereferenceable, dereferenceable_or_null "
5394 "take one operand!",
5399 "dereferenceable_or_null metadata value must be an i64!",
5403void Verifier::visitNoFreeObjMetadata(Instruction &
I, MDNode *MD) {
5404 Check(
I.getType()->isPointerTy(),
"nofreeobj applies only to pointer types",
5407 "nofreeobj applies only to inttoptr instruction", &
I);
5411void Verifier::visitProfMetadata(Instruction &
I, MDNode *MD) {
5412 auto GetBranchingTerminatorNumOperands = [&]() {
5413 unsigned ExpectedNumOperands = 0;
5417 ExpectedNumOperands =
SI->getNumSuccessors();
5419 ExpectedNumOperands = 1;
5421 ExpectedNumOperands = IBI->getNumDestinations();
5423 ExpectedNumOperands = 2;
5426 return ExpectedNumOperands;
5429 "!prof annotations should have at least 1 operand", MD);
5431 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null", MD);
5433 "expected string with name of the !prof annotation", MD);
5439 "'unknown' !prof should only appear on instructions on which "
5440 "'branch_weights' would",
5442 verifyUnknownProfileMetadata(MD);
5447 "!prof annotations should have no less than 2 operands", MD);
5453 Check(NumBranchWeights == 1 || NumBranchWeights == 2,
5454 "Wrong number of InvokeInst branch_weights operands", MD);
5456 const unsigned ExpectedNumOperands = GetBranchingTerminatorNumOperands();
5457 if (ExpectedNumOperands == 0)
5458 CheckFailed(
"!prof branch_weights are not allowed for this instruction",
5461 Check(NumBranchWeights == ExpectedNumOperands,
"Wrong number of operands",
5467 Check(MDO,
"second operand should not be null", MD);
5469 "!prof brunch_weights operand is not a const int");
5474 Check(KindInt,
"VP !prof missing kind argument", MD);
5477 Check(Kind >= InstrProfValueKind::IPVK_First &&
5478 Kind <= InstrProfValueKind::IPVK_Last,
5479 "Invalid VP !prof kind", MD);
5481 "VP !prof should have an even number "
5482 "of arguments after 'VP'",
5484 if (Kind == InstrProfValueKind::IPVK_IndirectCallTarget ||
5485 Kind == InstrProfValueKind::IPVK_MemOPSize)
5487 "VP !prof indirect call or memop size expected to be applied to "
5488 "CallBase instructions only",
5491 DenseSet<uint64_t> ProfileValues;
5493 ConstantInt *ProfileValue =
5495 Check(ProfileValue,
"VP !prof value operand is not a const int", MD);
5497 auto [ValueIt,
Inserted] = ProfileValues.
insert(ProfileValueInt);
5498 Check(Inserted,
"VP !prof should not have duplicate profile values", MD);
5501 CheckFailed(
"expected either branch_weights or VP profile name", MD);
5505void Verifier::visitDIAssignIDMetadata(Instruction &
I, MDNode *MD) {
5506 assert(
I.hasMetadata(LLVMContext::MD_DIAssignID));
5511 bool ExpectedInstTy =
5513 CheckDI(ExpectedInstTy,
"!DIAssignID attached to unexpected instruction kind",
5518 for (
auto *User : AsValue->users()) {
5520 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
5524 CheckDI(DAI->getFunction() ==
I.getFunction(),
5525 "dbg.assign not in same function as inst", DAI, &
I);
5528 for (DbgVariableRecord *DVR :
5531 "!DIAssignID should only be used by Assign DVRs.", MD, DVR);
5532 CheckDI(DVR->getFunction() ==
I.getFunction(),
5533 "DVRAssign not in same function as inst", DVR, &
I);
5537void Verifier::visitMMRAMetadata(Instruction &
I, MDNode *MD) {
5539 "!mmra metadata attached to unexpected instruction kind",
I, MD);
5550 for (
const MDOperand &MDOp : MD->
operands())
5552 "!mmra metadata tuple operand is not an MMRA tag",
I, MDOp.get());
5555void Verifier::visitCallStackMetadata(MDNode *MD) {
5559 "call stack metadata should have at least 1 operand", MD);
5563 "call stack metadata operand should be constant integer",
Op);
5566void Verifier::visitMemProfMetadata(Instruction &
I, MDNode *MD) {
5569 Check(
I.hasMetadata(LLVMContext::MD_callsite),
5570 "!memprof metadata requires !callsite metadata", &
I, MD);
5572 "!memprof annotations should have at least 1 metadata operand "
5577 for (
auto &MIBOp : MD->
operands()) {
5582 Check(MIB->getNumOperands() >= 2,
5583 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
5586 Check(MIB->getOperand(0) !=
nullptr,
5587 "!memprof MemInfoBlock first operand should not be null", MIB);
5589 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
5591 visitCallStackMetadata(StackMD);
5595 "!memprof MemInfoBlock second operand should be an MDString", MIB);
5598 for (
unsigned I = 2;
I < MIB->getNumOperands(); ++
I) {
5600 Check(OpNode,
"Not all !memprof MemInfoBlock operands 2 to N are MDNode",
5602 Check(OpNode->getNumOperands() == 2,
5603 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with 2 "
5608 [](
const MDOperand &
Op) {
5609 return mdconst::hasa<ConstantInt>(Op);
5611 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with "
5612 "ConstantInt operands",
5618void Verifier::visitCallsiteMetadata(Instruction &
I, MDNode *MD) {
5622 visitCallStackMetadata(MD);
5625void Verifier::visitCalleeTypeMetadata(Instruction &
I, MDNode *MD) {
5630 "The callee_type metadata must be a list of callgraph metadata nodes",
5633 Check(CallgraphMD->getNumOperands() == 1,
5634 "Well-formed callgraph metadata must contain exactly one "
5638 "The operand of callgraph metadata for functions must be an MDString",
5643void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
5646 "annotation must have at least one operand");
5648 bool TupleOfStrings =
5654 "operands must be a string or a tuple of strings");
5658void Verifier::visitAliasScopeMetadata(
const MDNode *MD) {
5663 "first scope operand must be self-referential or string", MD);
5666 "third scope operand must be string (if used)", MD);
5669 Check(
Domain !=
nullptr,
"second scope operand must be MDNode", MD);
5671 unsigned NumDomainOps =
Domain->getNumOperands();
5672 Check(NumDomainOps >= 1 && NumDomainOps <= 2,
5673 "domain must have one or two operands",
Domain);
5676 "first domain operand must be self-referential or string",
Domain);
5677 if (NumDomainOps == 2)
5679 "second domain operand must be string (if used)",
Domain);
5682void Verifier::visitAliasScopeListMetadata(
const MDNode *MD) {
5685 Check(OpMD !=
nullptr,
"scope list must consist of MDNodes", MD);
5686 visitAliasScopeMetadata(OpMD);
5690void Verifier::visitAccessGroupMetadata(
const MDNode *MD) {
5691 auto IsValidAccessScope = [](
const MDNode *MD) {
5706 Check(OpMD !=
nullptr,
"Access scope list must consist of MDNodes", MD);
5707 Check(IsValidAccessScope(OpMD),
5708 "Access scope list contains invalid access scope", MD);
5712void Verifier::visitCapturesMetadata(Instruction &
I,
const MDNode *Captures) {
5713 static const char *ValidArgs[] = {
"address_is_null",
"address",
5714 "read_provenance",
"provenance"};
5717 Check(SI,
"!captures metadata can only be applied to store instructions", &
I);
5718 Check(
SI->getValueOperand()->getType()->isPointerTy(),
5719 "!captures metadata can only be applied to store with value operand of "
5727 Check(Str,
"!captures metadata must be a list of strings", &
I);
5729 "invalid entry in !captures metadata", &
I, Str);
5733void Verifier::visitAllocTokenMetadata(Instruction &
I, MDNode *MD) {
5738 "expected integer constant", MD);
5741void Verifier::visitInlineHistoryMetadata(Instruction &
I, MDNode *MD) {
5750 ->stripPointerCastsAndAliases()),
5751 "!inline_history operands must be functions or null", MD);
5755void Verifier::visitMemCacheHintMetadata(Instruction &
I, MDNode *MD) {
5756 Check(
I.mayReadOrWriteMemory(),
5757 "!mem.cache_hint is only valid on memory operations", &
I);
5760 "!mem.cache_hint must have even number of operands "
5761 "(operand_no, hint_node pairs)",
5767 "!mem.cache_hint is not supported on non-intrinsic calls", &
I);
5769 unsigned NumOperands = CB ? CB->arg_size() :
I.getNumOperands();
5771 SmallDenseSet<unsigned, 4> SeenOperandNos;
5772 std::optional<uint64_t> LastOperandNo;
5778 "!mem.cache_hint must alternate between i32 operand numbers and "
5779 "metadata hint nodes",
5782 Check(OpNoCI->getValue().isNonNegative(),
5783 "!mem.cache_hint operand number must be non-negative", MD);
5785 uint64_t OperandNo = OpNoCI->getZExtValue();
5786 Check(OperandNo < NumOperands,
5787 "!mem.cache_hint operand number is out of range", &
I);
5790 CB ? CB->getArgOperand(OperandNo) :
I.getOperand(OperandNo);
5792 "!mem.cache_hint operand number must refer to a pointer operand", &
I);
5795 Check(Inserted,
"!mem.cache_hint contains duplicate operand number", MD);
5797 Check(!Inserted || !LastOperandNo || OperandNo > *LastOperandNo,
5798 "!mem.cache_hint operand numbers must be in increasing order", MD);
5799 LastOperandNo = OperandNo;
5803 "!mem.cache_hint must alternate between i32 operand numbers and "
5804 "metadata hint nodes",
5808 "!mem.cache_hint hint node must have even number of operands "
5809 "(key-value pairs)",
5812 StringSet<> SeenKeys;
5813 for (
unsigned K = 0;
K + 1 <
Node->getNumOperands();
K += 2) {
5815 Check(
Key,
"!mem.cache_hint key must be a string", Node);
5817 StringRef KeyStr =
Key->getString();
5819 "!mem.cache_hint hint node contains duplicate key", Node);
5824 "!mem.cache_hint value must be a string or integer", Node);
5831void Verifier::visitInstruction(Instruction &
I) {
5833 Check(BB,
"Instruction not embedded in basic block!", &
I);
5836 for (User *U :
I.users()) {
5837 Check(U != (User *)&
I || !DT.isReachableFromEntry(BB),
5838 "Only PHI nodes may reference their own value!", &
I);
5843 Check(!
I.getType()->isVoidTy() || !
I.hasName(),
5844 "Instruction has a name, but provides a void value!", &
I);
5848 Check(
I.getType()->isVoidTy() ||
I.getType()->isFirstClassType(),
5849 "Instruction returns a non-scalar type!", &
I);
5854 "Invalid use of metadata!", &
I);
5859 for (Use &U :
I.uses()) {
5862 "Instruction referencing"
5863 " instruction not embedded in a basic block!",
5866 CheckFailed(
"Use of instruction is not an instruction!", U);
5875 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i) {
5876 Check(
I.getOperand(i) !=
nullptr,
"Instruction has null operand!", &
I);
5880 if (!
I.getOperand(i)->getType()->isFirstClassType()) {
5881 Check(
false,
"Instruction operands must be first-class values!", &
I);
5887 auto IsAttachedCallOperand = [](
Function *
F,
const CallBase *CBI,
5889 return CBI && CBI->isOperandBundleOfType(
5897 Check((!
F->isIntrinsic() ||
5898 (CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i)) ||
5899 IsAttachedCallOperand(
F, CBI, i)),
5900 "Cannot take the address of an intrinsic!", &
I);
5902 F->getIntrinsicID() == Intrinsic::donothing ||
5903 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
5904 F->getIntrinsicID() == Intrinsic::seh_try_end ||
5905 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
5906 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
5907 F->getIntrinsicID() == Intrinsic::coro_resume ||
5908 F->getIntrinsicID() == Intrinsic::coro_destroy ||
5909 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
5910 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
5911 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
5912 F->getIntrinsicID() ==
5913 Intrinsic::experimental_patchpoint_void ||
5914 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
5915 F->getIntrinsicID() == Intrinsic::fake_use ||
5916 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
5917 F->getIntrinsicID() == Intrinsic::wasm_throw ||
5918 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
5919 IsAttachedCallOperand(
F, CBI, i),
5920 "Cannot invoke an intrinsic other than donothing, patchpoint, "
5921 "statepoint, coro_resume, coro_destroy, clang.arc.attachedcall or "
5924 Check(
F->getParent() == &M,
"Referencing function in another module!", &
I,
5925 &M,
F,
F->getParent());
5928 "Referring to a basic block in another function!", &
I);
5931 "Referring to an argument in another function!", &
I);
5933 Check(GV->
getParent() == &M,
"Referencing global in another module!", &
I,
5937 "Referring to an instruction in another function!", &
I);
5938 verifyDominatesUse(
I, i);
5940 Check(CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i),
5941 "Cannot take the address of an inline asm!", &
I);
5943 visitConstantExprsRecursively(
C);
5947 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_fpmath)) {
5949 "fpmath requires a floating point result!", &
I);
5951 if (ConstantFP *CFP0 =
5953 const APFloat &Accuracy = CFP0->getValueAPF();
5955 "fpmath accuracy must have float type", &
I);
5957 "fpmath accuracy not a positive number!", &
I);
5959 Check(
false,
"invalid fpmath accuracy!", &
I);
5963 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_range)) {
5965 "Ranges are only for loads, calls and invokes!", &
I);
5966 visitRangeMetadata(
I,
Range,
I.getType());
5969 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofpclass)) {
5971 visitNoFPClassMetadata(
I, MD,
I.getType());
5974 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_noalias_addrspace)) {
5977 "noalias.addrspace are only for memory operations!", &
I);
5978 visitNoaliasAddrspaceMetadata(
I,
Range,
I.getType());
5981 if (
I.hasMetadata(LLVMContext::MD_invariant_group)) {
5983 "invariant.group metadata is only for loads and stores", &
I);
5986 if (
I.hasMetadata(LLVMContext::MD_invariant_load)) {
5989 "invariant.load metadata is only for loads and readonly "
5994 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nonnull)) {
5995 Check(
I.getType()->isPointerTy(),
"nonnull applies only to pointer types",
5998 "nonnull applies only to load instructions, use attributes"
5999 " for calls or invokes",
6004 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noundef)) {
6009 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable))
6010 visitDereferenceableMetadata(
I, MD);
6012 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
6013 visitDereferenceableMetadata(
I, MD);
6015 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofreeobj))
6016 visitNoFreeObjMetadata(
I, MD);
6018 if (MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa))
6021 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noalias))
6022 visitAliasScopeListMetadata(MD);
6023 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alias_scope))
6024 visitAliasScopeListMetadata(MD);
6026 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_access_group))
6027 visitAccessGroupMetadata(MD);
6029 if (MDNode *AlignMD =
I.getMetadata(LLVMContext::MD_align)) {
6030 Check(
I.getType()->isPointerTy(),
"align applies only to pointer types",
6033 "align applies only to load instructions, "
6034 "use attributes for calls or invokes",
6036 Check(AlignMD->getNumOperands() == 1,
"align takes one operand!", &
I);
6039 "align metadata value must be an i64!", &
I);
6043 Check(Align <= Value::MaximumAlignment,
6044 "alignment is larger that implementation defined limit", &
I);
6047 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_prof))
6048 visitProfMetadata(
I, MD);
6050 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_memprof))
6051 visitMemProfMetadata(
I, MD);
6053 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callsite))
6054 visitCallsiteMetadata(
I, MD);
6056 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callee_type))
6057 visitCalleeTypeMetadata(
I, MD);
6059 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_DIAssignID))
6060 visitDIAssignIDMetadata(
I, MD);
6062 if (MDNode *MMRA =
I.getMetadata(LLVMContext::MD_mmra))
6063 visitMMRAMetadata(
I, MMRA);
6065 if (MDNode *Annotation =
I.getMetadata(LLVMContext::MD_annotation))
6066 visitAnnotationMetadata(Annotation);
6068 if (MDNode *Captures =
I.getMetadata(LLVMContext::MD_captures))
6069 visitCapturesMetadata(
I, Captures);
6071 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alloc_token))
6072 visitAllocTokenMetadata(
I, MD);
6074 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_inline_history))
6075 visitInlineHistoryMetadata(
I, MD);
6077 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_mem_cache_hint))
6078 visitMemCacheHintMetadata(
I, MD);
6080 if (MDNode *MD =
I.getMetadata(
"amdgpu.expected.active.lanes")) {
6082 "!amdgpu.expected.active.lanes must have exactly one operand", &
I,
6087 "!amdgpu.expected.active.lanes operand must be an i32 constant", &
I,
6091 if (MDNode *
N =
I.getDebugLoc().getAsMDNode()) {
6093 visitMDNode(*
N, AreDebugLocsAllowed::Yes);
6096 if (
DL->getAtomGroup()) {
6098 CheckDI(SP &&
SP->getKeyInstructionsEnabled(),
6099 "DbgLoc uses atomGroup but DISubprogram doesn't have Key "
6100 "Instructions enabled",
6107 I.getAllMetadata(MDs);
6108 for (
auto Attachment : MDs) {
6109 unsigned Kind = Attachment.first;
6111 (
Kind == LLVMContext::MD_dbg ||
Kind == LLVMContext::MD_loop)
6112 ? AreDebugLocsAllowed::Yes
6113 : AreDebugLocsAllowed::
No;
6114 visitMDNode(*Attachment.second, AllowLocs);
6131 "const x86_amx is not allowed in argument!");
6137 case Intrinsic::assume: {
6141 "assume with operand bundles must have i1 true condition",
Call);
6147 auto GetTypeAt = [&](
unsigned Index) {
6148 return OBU.Inputs[
Index]->getType();
6153 CheckFailed(
"tags must be valid attribute names",
Call);
6155 case BundleAttr::Align:
6156 Check(OBU.Inputs.size() >= 2 && OBU.Inputs.size() <= 3,
6157 "alignment assumptions should have 2 or 3 arguments",
Call);
6160 Check(GetTypeAt(1)->isIntegerTy() &&
6161 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6162 "second argument should be an integer with a maximum width of 64 "
6165 Check(OBU.Inputs.size() < 3 ||
6166 (GetTypeAt(2)->isIntegerTy() &&
6167 GetTypeAt(2)->getIntegerBitWidth() <= 64),
6168 "third argument should be an integer with a maximum width of 64 "
6172 case BundleAttr::Cold:
6173 Check(OBU.Inputs.size() == 0,
6174 "cold assumptions should have no arguments",
Call);
6176 case BundleAttr::Dereferenceable:
6177 case BundleAttr::DereferenceableOrNull:
6178 Check(OBU.Inputs.size() == 2,
6179 "dereferenceable assumptions should have 2 arguments",
Call);
6182 Check(GetTypeAt(1)->isIntegerTy() &&
6183 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6184 "second argument should be an integer with a maximum width of 64 "
6188 case BundleAttr::Ignore:
6190 case BundleAttr::NonNull:
6191 Check(OBU.Inputs.size() == 1,
6192 "nonnull assumptions should have 1 argument",
Call);
6196 case BundleAttr::NoUndef:
6197 Check(OBU.Inputs.size() == 1,
6198 "noundef assumptions should have 1 argument",
Call);
6200 case BundleAttr::SeparateStorage:
6201 Check(OBU.Inputs.size() == 2,
6202 "separate_storage assumptions should have 2 arguments",
Call);
6204 "arguments to separate_storage assumptions should be pointers",
6211 case Intrinsic::ucmp:
6212 case Intrinsic::scmp: {
6217 "result type must be at least 2 bits wide",
Call);
6219 bool IsDestTypeVector = DestTy->
isVectorTy();
6221 "ucmp/scmp argument and result types must both be either vector or "
6224 if (IsDestTypeVector) {
6227 Check(SrcVecLen == DestVecLen,
6228 "return type and arguments must have the same number of "
6234 case Intrinsic::coro_begin:
6235 case Intrinsic::coro_begin_custom_abi:
6237 "id argument of llvm.coro.begin must refer to coro.id");
6239 case Intrinsic::coro_id: {
6241 "align argument only accepts constants");
6244 "promise argument must refer to an alloca");
6249 "coro argument must refer to a function");
6253 if (BeforeCoroSplit)
6256 Check(!BeforeCoroEarly,
"cannot run CoroSplit before CoroEarly");
6259 "info argument of llvm.coro.id must refer to an initialized "
6263 "info argument of llvm.coro.id must refer to either a struct or "
6267 case Intrinsic::is_fpclass: {
6270 "unsupported bits for llvm.is.fpclass test mask");
6273 case Intrinsic::fptrunc_round: {
6278 MD = MAV->getMetadata();
6280 Check(MD !=
nullptr,
"missing rounding mode argument",
Call);
6283 (
"invalid value for llvm.fptrunc.round metadata operand"
6284 " (the operand should be a string)"),
6287 std::optional<RoundingMode> RoundMode =
6289 Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
6290 "unsupported rounding mode argument",
Call);
6293 case Intrinsic::convert_to_arbitrary_fp: {
6301 "if floating-point operand is a vector, integer operand must also "
6304 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6305 "floating-point and integer vector operands must have the same "
6312 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6314 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6315 StringRef Interp = InterpStr->getString();
6317 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6322 "unsupported interpretation metadata string",
Call);
6325 if (
unsigned FormatBits =
6328 "integer type bit width must equal the arbitrary FP format width",
6333 Check(RoundingMAV,
"missing rounding mode metadata operand",
Call);
6335 Check(RoundingStr,
"rounding mode metadata operand must be a string",
Call);
6337 std::optional<RoundingMode>
RM =
6339 Check(RM && *RM != RoundingMode::Dynamic,
6340 "unsupported rounding mode argument",
Call);
6343 case Intrinsic::convert_from_arbitrary_fp: {
6351 "if floating-point operand is a vector, integer operand must also "
6354 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6355 "floating-point and integer vector operands must have the same "
6362 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6364 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6365 StringRef Interp = InterpStr->getString();
6367 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6372 "unsupported interpretation metadata string",
Call);
6375 if (
unsigned FormatBits =
6378 "integer type bit width must equal the arbitrary FP format width",
6382#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6383#include "llvm/IR/VPIntrinsics.def"
6384#undef BEGIN_REGISTER_VP_INTRINSIC
6387#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
6388 case Intrinsic::INTRINSIC:
6389#include "llvm/IR/ConstrainedOps.def"
6393 case Intrinsic::dbg_declare:
6394 case Intrinsic::dbg_value:
6395 case Intrinsic::dbg_assign:
6396 case Intrinsic::dbg_label:
6403 case Intrinsic::memcpy:
6404 case Intrinsic::memcpy_inline:
6405 case Intrinsic::memmove:
6406 case Intrinsic::memset:
6407 case Intrinsic::memset_inline:
6409 case Intrinsic::experimental_memset_pattern: {
6411 Check(Memset->getValue()->getType()->isSized(),
6412 "unsized types cannot be used as memset patterns",
Call);
6415 case Intrinsic::memcpy_element_unordered_atomic:
6416 case Intrinsic::memmove_element_unordered_atomic:
6417 case Intrinsic::memset_element_unordered_atomic: {
6420 ConstantInt *ElementSizeCI =
6422 const APInt &ElementSizeVal = ElementSizeCI->
getValue();
6424 "element size of the element-wise atomic memory intrinsic "
6425 "must be a power of 2",
6428 auto IsValidAlignment = [&](MaybeAlign
Alignment) {
6431 Check(IsValidAlignment(AMI->getDestAlign()),
6432 "incorrect alignment of the destination argument",
Call);
6434 Check(IsValidAlignment(AMT->getSourceAlign()),
6435 "incorrect alignment of the source argument",
Call);
6439 case Intrinsic::call_preallocated_setup: {
6441 bool FoundCall =
false;
6444 Check(UseCall !=
nullptr,
6445 "Uses of llvm.call.preallocated.setup must be calls");
6447 if (IID == Intrinsic::call_preallocated_arg) {
6449 Check(AllocArgIndex !=
nullptr,
6450 "llvm.call.preallocated.alloc arg index must be a constant");
6451 auto AllocArgIndexInt = AllocArgIndex->getValue();
6452 Check(AllocArgIndexInt.sge(0) &&
6453 AllocArgIndexInt.slt(NumArgs->getValue()),
6454 "llvm.call.preallocated.alloc arg index must be between 0 and "
6456 "llvm.call.preallocated.setup's argument count");
6457 }
else if (IID == Intrinsic::call_preallocated_teardown) {
6460 Check(!FoundCall,
"Can have at most one call corresponding to a "
6461 "llvm.call.preallocated.setup");
6463 size_t NumPreallocatedArgs = 0;
6464 for (
unsigned i = 0; i < UseCall->arg_size(); i++) {
6465 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
6466 ++NumPreallocatedArgs;
6469 Check(NumPreallocatedArgs != 0,
6470 "cannot use preallocated intrinsics on a call without "
6471 "preallocated arguments");
6472 Check(NumArgs->equalsInt(NumPreallocatedArgs),
6473 "llvm.call.preallocated.setup arg size must be equal to number "
6474 "of preallocated arguments "
6484 auto PreallocatedBundle =
6486 Check(PreallocatedBundle,
6487 "Use of llvm.call.preallocated.setup outside intrinsics "
6488 "must be in \"preallocated\" operand bundle");
6489 Check(PreallocatedBundle->Inputs.front().get() == &
Call,
6490 "preallocated bundle must have token from corresponding "
6491 "llvm.call.preallocated.setup");
6496 case Intrinsic::call_preallocated_arg: {
6499 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6500 "llvm.call.preallocated.arg token argument must be a "
6501 "llvm.call.preallocated.setup");
6503 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
6504 "call site attribute");
6507 case Intrinsic::call_preallocated_teardown: {
6510 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6511 "llvm.call.preallocated.teardown token argument must be a "
6512 "llvm.call.preallocated.setup");
6515 case Intrinsic::gcroot:
6516 case Intrinsic::gcwrite:
6517 case Intrinsic::gcread:
6518 if (ID == Intrinsic::gcroot) {
6521 Check(AI,
"llvm.gcroot parameter #1 must be an alloca.",
Call);
6523 "llvm.gcroot parameter #2 must be a constant.",
Call);
6526 "llvm.gcroot parameter #1 must either be a pointer alloca, "
6527 "or argument #2 must be a non-null constant.",
6533 "Enclosing function does not use GC.",
Call);
6535 case Intrinsic::init_trampoline:
6537 "llvm.init_trampoline parameter #2 must resolve to a function.",
6540 case Intrinsic::reloc_none: {
6543 "llvm.reloc.none argument must be a metadata string", &
Call);
6546 case Intrinsic::stackprotector:
6548 "llvm.stackprotector parameter #2 must resolve to an alloca.",
Call);
6550 case Intrinsic::localescape: {
6554 Check(!SawFrameEscape,
"multiple calls to llvm.localescape in one function",
6561 "llvm.localescape only accepts static allocas",
Call);
6564 SawFrameEscape =
true;
6567 case Intrinsic::localrecover: {
6570 Check(Fn && !Fn->isDeclaration(),
6571 "llvm.localrecover first "
6572 "argument must be function defined in this module",
6575 auto &
Entry = FrameEscapeInfo[Fn];
6576 Entry.second = unsigned(
6577 std::max(
uint64_t(
Entry.second), IdxArg->getLimitedValue(~0U) + 1));
6581 case Intrinsic::experimental_gc_statepoint:
6583 Check(!CI->isInlineAsm(),
6584 "gc.statepoint support for inline assembly unimplemented", CI);
6586 "Enclosing function does not use GC.",
Call);
6588 verifyStatepoint(
Call);
6590 case Intrinsic::experimental_gc_result: {
6592 "Enclosing function does not use GC.",
Call);
6600 Check(StatepointCall && StatepointCall->getIntrinsicID() ==
6601 Intrinsic::experimental_gc_statepoint,
6602 "gc.result operand #1 must be from a statepoint",
Call,
6606 auto *TargetFuncType =
6609 "gc.result result type does not match wrapped callee",
Call);
6612 case Intrinsic::experimental_gc_relocate: {
6616 "gc.relocate must return a pointer or a vector of pointers",
Call);
6624 LandingPad->getParent()->getUniquePredecessor();
6628 Check(InvokeBB,
"safepoints should have unique landingpads",
6629 LandingPad->getParent());
6633 "gc relocate should be linked to a statepoint", InvokeBB);
6640 "gc relocate is incorrectly tied to the statepoint",
Call, Token);
6649 "gc.relocate operand #2 must be integer offset",
Call);
6653 "gc.relocate operand #3 must be integer offset",
Call);
6663 Check(BaseIndex < Opt->Inputs.size(),
6664 "gc.relocate: statepoint base index out of bounds",
Call);
6665 Check(DerivedIndex < Opt->Inputs.size(),
6666 "gc.relocate: statepoint derived index out of bounds",
Call);
6679 "gc.relocate: relocated value must be a pointer",
Call);
6680 Check(DerivedType->isPtrOrPtrVectorTy(),
6681 "gc.relocate: relocated value must be a pointer",
Call);
6683 Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
6684 "gc.relocate: vector relocates to vector and pointer to pointer",
6687 ResultType->getPointerAddressSpace() ==
6688 DerivedType->getPointerAddressSpace(),
6689 "gc.relocate: relocating a pointer shouldn't change its address space",
6693 Check(GC,
"gc.relocate: calling function must have GCStrategy",
6696 auto isGCPtr = [&
GC](
Type *PTy) {
6697 return GC->isGCManagedPointer(PTy->getScalarType()).value_or(
true);
6699 Check(isGCPtr(ResultType),
"gc.relocate: must return gc pointer",
Call);
6701 "gc.relocate: relocated value must be a gc pointer",
Call);
6702 Check(isGCPtr(DerivedType),
6703 "gc.relocate: relocated value must be a gc pointer",
Call);
6707 case Intrinsic::experimental_patchpoint: {
6710 "patchpoint: invalid return type used with anyregcc",
Call);
6714 case Intrinsic::eh_exceptioncode:
6715 case Intrinsic::eh_exceptionpointer: {
6717 "eh.exceptionpointer argument must be a catchpad",
Call);
6720 case Intrinsic::get_active_lane_mask: {
6723 "get_active_lane_mask: element type is not i1",
Call);
6726 case Intrinsic::experimental_get_vector_length: {
6728 Check(!VF->isNegative() && !VF->isZero(),
6729 "get_vector_length: VF must be positive",
Call);
6732 case Intrinsic::experimental_guard: {
6735 "experimental_guard must have exactly one "
6736 "\"deopt\" operand bundle");
6740 case Intrinsic::experimental_deoptimize: {
6744 "experimental_deoptimize must have exactly one "
6745 "\"deopt\" operand bundle");
6747 "experimental_deoptimize return type must match caller return type");
6752 "calls to experimental_deoptimize must be followed by a return");
6756 "calls to experimental_deoptimize must be followed by a return "
6757 "of the value computed by experimental_deoptimize");
6762 case Intrinsic::vastart: {
6764 "va_start called in a non-varargs function");
6767 case Intrinsic::get_dynamic_area_offset: {
6769 Check(IntTy &&
DL.getPointerSizeInBits(
DL.getAllocaAddrSpace()) ==
6770 IntTy->getBitWidth(),
6771 "get_dynamic_area_offset result type must be scalar integer matching "
6772 "alloca address space width",
6776 case Intrinsic::smul_fix:
6777 case Intrinsic::smul_fix_sat:
6778 case Intrinsic::umul_fix:
6779 case Intrinsic::umul_fix_sat:
6780 case Intrinsic::sdiv_fix:
6781 case Intrinsic::sdiv_fix_sat:
6782 case Intrinsic::udiv_fix:
6783 case Intrinsic::udiv_fix_sat: {
6787 if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
6788 ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
6790 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
6794 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
6795 "to the width of the operands");
6799 case Intrinsic::lrint:
6800 case Intrinsic::llrint:
6801 case Intrinsic::lround:
6802 case Intrinsic::llround: {
6806 IF->
getName() +
": argument and result disagree on vector use",
6810 Check(VTy->getElementCount() == RTy->getElementCount(),
6811 IF->
getName() +
": argument must be same length as result", &
Call);
6815 case Intrinsic::bswap: {
6818 Check(
Size % 16 == 0,
"bswap must be an even number of bytes", &
Call);
6821 case Intrinsic::invariant_start: {
6823 Check(InvariantSize &&
6824 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
6825 "invariant_start parameter must be -1, 0 or a positive number",
6829 case Intrinsic::matrix_multiply:
6830 case Intrinsic::matrix_transpose:
6831 case Intrinsic::matrix_column_major_load:
6832 case Intrinsic::matrix_column_major_store: {
6834 Value *Stride =
nullptr;
6835 ConstantInt *NumRows;
6836 ConstantInt *NumColumns;
6838 Type *Op0ElemTy =
nullptr;
6839 Type *Op1ElemTy =
nullptr;
6841 case Intrinsic::matrix_multiply: {
6846 ->getNumElements() ==
6848 "First argument of a matrix operation does not match specified "
6851 ->getNumElements() ==
6853 "Second argument of a matrix operation does not match specified "
6863 case Intrinsic::matrix_transpose:
6870 case Intrinsic::matrix_column_major_load: {
6877 case Intrinsic::matrix_column_major_store: {
6890 Check(ResultTy->getElementType()->isIntegerTy() ||
6891 ResultTy->getElementType()->isFloatingPointTy(),
6892 "Result type must be an integer or floating-point type!", IF);
6895 Check(ResultTy->getElementType() == Op0ElemTy,
6896 "Vector element type mismatch of the result and first operand "
6901 Check(ResultTy->getElementType() == Op1ElemTy,
6902 "Vector element type mismatch of the result and second operand "
6908 "Result of a matrix operation does not fit in the returned vector!");
6912 "Stride bitwidth cannot exceed 64!", IF);
6916 case Intrinsic::stepvector: {
6918 Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
6919 VecTy->getScalarSizeInBits() >= 8,
6920 "stepvector only supported for vectors of integers "
6921 "with a bitwidth of at least 8.",
6925 case Intrinsic::experimental_vector_match: {
6934 Check(Op1Ty && Op2Ty && MaskTy,
"Operands must be vectors.", &
Call);
6936 "Second operand must be a fixed length vector.", &
Call);
6938 "First operand must be a vector of integers.", &
Call);
6939 Check(Op1Ty->getElementType() == Op2Ty->getElementType(),
6940 "First two operands must have the same element type.", &
Call);
6941 Check(Op1Ty->getElementCount() == MaskTy->getElementCount(),
6942 "First operand and mask must have the same number of elements.",
6944 Check(MaskTy->getElementType()->isIntegerTy(1),
6945 "Mask must be a vector of i1's.", &
Call);
6950 case Intrinsic::vector_insert: {
6959 ElementCount VecEC = VecTy->getElementCount();
6960 ElementCount SubVecEC = SubVecTy->getElementCount();
6961 Check(VecTy->getElementType() == SubVecTy->getElementType(),
6962 "vector_insert parameters must have the same element "
6966 "vector_insert index must be a constant multiple of "
6967 "the subvector's known minimum vector length.");
6972 Check(VecEC.
isScalable(),
"cannot vector_insert a scalable vector into "
6982 "subvector operand of vector_insert would overrun the "
6983 "vector being inserted into.");
6987 case Intrinsic::vector_extract: {
6995 ElementCount VecEC = VecTy->getElementCount();
6996 ElementCount ResultEC = ResultTy->getElementCount();
6998 Check(ResultTy->getElementType() == VecTy->getElementType(),
6999 "vector_extract result must have the same element "
7000 "type as the input vector.",
7003 "vector_extract index must be a constant multiple of "
7004 "the result type's known minimum vector length.");
7009 Check(VecEC.
isScalable(),
"cannot vector_extract a scalable vector from "
7019 "vector_extract would overrun.");
7023 case Intrinsic::vector_partial_reduce_fadd:
7024 case Intrinsic::vector_partial_reduce_add: {
7028 unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
7029 unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
7031 Check((VecWidth % AccWidth) == 0,
7032 "Invalid vector widths for partial "
7033 "reduction. The width of the input vector "
7034 "must be a positive integer multiple of "
7035 "the width of the accumulator vector.");
7038 case Intrinsic::experimental_noalias_scope_decl: {
7042 case Intrinsic::preserve_array_access_index:
7043 case Intrinsic::preserve_struct_access_index:
7044 case Intrinsic::aarch64_ldaxr:
7045 case Intrinsic::aarch64_ldxr:
7046 case Intrinsic::arm_ldaex:
7047 case Intrinsic::arm_ldrex: {
7049 Check(ElemTy,
"Intrinsic requires elementtype attribute on first argument.",
7053 case Intrinsic::aarch64_stlxr:
7054 case Intrinsic::aarch64_stxr:
7055 case Intrinsic::arm_stlex:
7056 case Intrinsic::arm_strex: {
7059 "Intrinsic requires elementtype attribute on second argument.",
7063 case Intrinsic::aarch64_prefetch: {
7065 "write argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
7067 "target argument to llvm.aarch64.prefetch must be 0-3",
Call);
7069 "stream argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
7071 "isdata argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
7074 case Intrinsic::aarch64_range_prefetch: {
7076 "write argument to llvm.aarch64.range.prefetch must be 0 or 1",
Call);
7078 "stream argument to llvm.aarch64.range.prefetch must be 0 or 1",
7082 case Intrinsic::riscv_vsetvli:
7083 case Intrinsic::riscv_vsetvlimax: {
7088 "llvm.riscv.vsetvli/vsetvlimax result must be i32 or i64", &
Call);
7091 bool HasAVL =
ID == Intrinsic::riscv_vsetvli;
7092 unsigned Offset = HasAVL ? 1 : 0;
7097 Check(VSEW <= 3,
"llvm.riscv.vsetvli/vsetvlimax VSEW must be 0-3", &
Call);
7099 "llvm.riscv.vsetvli/vsetvlimax VLMUL is reserved", &
Call);
7102 case Intrinsic::callbr_landingpad: {
7104 Check(CBR,
"intrinstic requires callbr operand", &
Call);
7111 CheckFailed(
"Intrinsic in block must have 1 unique predecessor", &
Call);
7115 CheckFailed(
"Intrinsic must have corresponding callbr in predecessor",
7120 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
7121 "block in indirect destination list",
7124 Check(&
First == &
Call,
"No other instructions may proceed intrinsic",
7128 case Intrinsic::structured_gep: {
7134 "Intrinsic first parameter is missing an ElementType attribute",
7142 "Index operand type must be an integer", &
Call);
7145 T = AT->getElementType();
7147 Check(CI,
"Indexing into a struct requires a constant int", &
Call);
7149 "Indexing in a struct should be inbounds", &
Call);
7152 T = VT->getElementType();
7154 CheckFailed(
"Reached a non-composite type with more indices to process",
7160 case Intrinsic::structured_alloca:
7162 "@llvm.structured.alloca calls require elementtype attribute.",
7165 case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
7166 case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
7169 Check(RegCount % 8 == 0,
7170 "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
7173 case Intrinsic::experimental_convergence_entry:
7174 case Intrinsic::experimental_convergence_anchor:
7176 case Intrinsic::experimental_convergence_loop:
7178 case Intrinsic::ptrmask: {
7182 "llvm.ptrmask intrinsic first argument must be pointer or vector "
7187 "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
7192 "llvm.ptrmask intrinsic arguments must have the same number of "
7196 "llvm.ptrmask intrinsic second argument bitwidth must match "
7197 "pointer index type size of first argument",
7201 case Intrinsic::thread_pointer: {
7203 DL.getDefaultGlobalsAddressSpace(),
7204 "llvm.thread.pointer intrinsic return type must be for the globals "
7209 case Intrinsic::threadlocal_address: {
7212 "llvm.threadlocal.address first argument must be a GlobalValue");
7214 "llvm.threadlocal.address operand isThreadLocal() must be true");
7217 case Intrinsic::lifetime_start:
7218 case Intrinsic::lifetime_end: {
7222 (
II &&
II->getIntrinsicID() == Intrinsic::structured_alloca),
7223 "llvm.lifetime.start/end can only be used on alloca or poison",
7227 case Intrinsic::sponentry: {
7228 const unsigned StackAS =
DL.getAllocaAddrSpace();
7231 "llvm.sponentry must return a pointer to the stack", &
Call);
7234 case Intrinsic::write_volatile_register: {
7238 "llvm.write_volatile_register metadata must be a single MDString",
7242 case Intrinsic::ptrauth_auth_with_pc_and_resign: {
7247 "ptrauth.auth.with.pc.and.resign key must be IA (0) or IB (1)",
7256 if (
F->hasPersonalityFn() &&
7260 if (BlockEHFuncletColors.
empty())
7264 bool InEHFunclet =
false;
7268 for (BasicBlock *ColorFirstBB : CV)
7269 if (
auto It = ColorFirstBB->getFirstNonPHIIt();
7270 It != ColorFirstBB->end())
7275 bool HasToken =
false;
7282 Check(HasToken,
"Missing funclet token on intrinsic call", &
Call);
7294DISubprogram *Verifier::getSubprogram(
Metadata *LocalScope) {
7295 if (hasDIScopeCycle(LocalScope))
7312void Verifier::visit(DbgLabelRecord &DLR) {
7314 "invalid #dbg_label intrinsic variable", &DLR, DLR.
getRawLabel());
7327 CheckDI(Loc,
"#dbg_label record requires a !dbg attachment", &DLR, BB,
F);
7331 if (!LabelSP || !LocSP)
7335 "mismatched subprogram between #dbg_label label and !dbg attachment",
7336 &DLR, BB,
F, Label,
Label->getScope()->getSubprogram(), Loc,
7337 Loc->getScope()->getSubprogram());
7340void Verifier::visit(DbgVariableRecord &DVR) {
7344 CheckDI(DVR.
getType() == DbgVariableRecord::LocationType::Value ||
7345 DVR.
getType() == DbgVariableRecord::LocationType::Declare ||
7346 DVR.
getType() == DbgVariableRecord::LocationType::DeclareValue ||
7347 DVR.
getType() == DbgVariableRecord::LocationType::Assign,
7348 "invalid #dbg record type", &DVR, DVR.
getType(), BB,
F);
7356 "invalid #dbg record address/value", &DVR, MD, BB,
F);
7358 visitValueAsMetadata(*VAM,
F);
7361 Type *Ty = VAM->getValue()->getType();
7363 "location of #dbg_declare must be a pointer or int", &DVR, MD, BB,
7367 visitDIArgList(*AL,
F);
7381 "invalid #dbg_assign DIAssignID", &DVR, DVR.
getRawAssignID(), BB,
7384 AreDebugLocsAllowed::No);
7393 "invalid #dbg_assign address", &DVR, DVR.
getRawAddress(), BB,
F);
7395 visitValueAsMetadata(*VAM,
F);
7398 "invalid #dbg_assign address expression", &DVR,
7405 "inst not in same function as #dbg_assign",
I, &DVR, BB,
F);
7415 &DVR, DLNode, BB,
F);
7421 if (!VarSP || !LocSP)
7425 "mismatched subprogram between #dbg record variable and DILocation",
7427 Loc->getScope()->getSubprogram(), BB,
F);
7432void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
7434 case Intrinsic::experimental_vp_splice: {
7437 int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
7439 AttributeList
Attrs = VPI.
getParent()->getParent()->getAttributes();
7440 if (
Attrs.hasFnAttr(Attribute::VScaleRange))
7441 KnownMinNumElements *=
Attrs.getFnAttrs().getVScaleRangeMin();
7443 Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
7444 (Idx >= 0 && Idx < KnownMinNumElements),
7445 "The splice index exceeds the range [-VL, VL-1] where VL is the "
7446 "known minimum number of elements in the vector. For scalable "
7447 "vectors the minimum number of elements is determined from "
7455void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
7457 bool HasRoundingMD =
7461 NumOperands += (1 + HasRoundingMD);
7467 "invalid arguments for constrained FP intrinsic", &FPI);
7470 case Intrinsic::experimental_constrained_fcmp:
7471 case Intrinsic::experimental_constrained_fcmps: {
7474 "invalid predicate for constrained FP comparison intrinsic", &FPI);
7478 case Intrinsic::experimental_constrained_fptosi:
7479 case Intrinsic::experimental_constrained_fptoui: {
7483 "Intrinsic first argument must be floating point", &FPI);
7490 "Intrinsic first argument and result disagree on vector use", &FPI);
7492 "Intrinsic result must be an integer", &FPI);
7495 "Intrinsic first argument and result vector lengths must be equal",
7501 case Intrinsic::experimental_constrained_sitofp:
7502 case Intrinsic::experimental_constrained_uitofp: {
7506 "Intrinsic first argument must be integer", &FPI);
7513 "Intrinsic first argument and result disagree on vector use", &FPI);
7515 "Intrinsic result must be a floating point", &FPI);
7518 "Intrinsic first argument and result vector lengths must be equal",
7524 case Intrinsic::experimental_constrained_fptrunc:
7525 case Intrinsic::experimental_constrained_fpext: {
7531 "Intrinsic first argument must be FP or FP vector", &FPI);
7533 "Intrinsic result must be FP or FP vector", &FPI);
7535 "Intrinsic first argument and result disagree on vector use", &FPI);
7539 "Intrinsic first argument and result vector lengths must be equal",
7542 if (FPI.
getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
7544 "Intrinsic first argument's type must be larger than result type",
7548 "Intrinsic first argument's type must be smaller than result type",
7564 "invalid exception behavior argument", &FPI);
7565 if (HasRoundingMD) {
7571void Verifier::verifyFragmentExpression(
const DbgVariableRecord &DVR) {
7576 if (!V || !
E || !
E->isValid())
7580 auto Fragment =
E->getFragmentInfo();
7590 if (
V->isArtificial())
7593 verifyFragmentExpression(*V, *Fragment, &DVR);
7596template <
typename ValueOrMetadata>
7597void Verifier::verifyFragmentExpression(
const DIVariable &V,
7599 ValueOrMetadata *
Desc) {
7602 auto VarSize =
V.getSizeInBits();
7608 CheckDI(FragSize + FragOffset <= *VarSize,
7609 "fragment is larger than or outside of variable",
Desc, &V);
7610 CheckDI(FragSize != *VarSize,
"fragment covers entire variable",
Desc, &V);
7613void Verifier::verifyFnArgs(
const DbgVariableRecord &DVR) {
7625 CheckDI(Var,
"#dbg record without variable");
7627 unsigned ArgNo = Var->
getArg();
7633 if (DebugFnArgs.
size() < ArgNo)
7634 DebugFnArgs.
resize(ArgNo,
nullptr);
7636 auto *Prev = DebugFnArgs[ArgNo - 1];
7637 DebugFnArgs[ArgNo - 1] = Var;
7638 CheckDI(!Prev || (Prev == Var),
"conflicting debug info for argument", &DVR,
7642void Verifier::verifyNotEntryValue(
const DbgVariableRecord &DVR) {
7646 if (!
E || !
E->isValid())
7656 ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
7661 "Entry values are only allowed in MIR unless they target a "
7662 "swiftasync Argument",
7666void Verifier::verifyCompileUnits() {
7670 if (
M.getContext().isODRUniquingDebugTypes())
7672 auto *CUs =
M.getNamedMetadata(
"llvm.dbg.cu");
7673 SmallPtrSet<const Metadata *, 2> Listed;
7676 for (
const auto *CU : CUVisited)
7677 CheckDI(Listed.
count(CU),
"DICompileUnit not listed in llvm.dbg.cu", CU);
7681void Verifier::verifyDeoptimizeCallingConvs() {
7682 if (DeoptimizeDeclarations.
empty())
7686 for (
const auto *
F :
ArrayRef(DeoptimizeDeclarations).slice(1)) {
7687 Check(
First->getCallingConv() ==
F->getCallingConv(),
7688 "All llvm.experimental.deoptimize declarations must have the same "
7689 "calling convention",
7694void Verifier::verifyAttachedCallBundle(
const CallBase &
Call,
7695 const OperandBundleUse &BU) {
7698 Check((FTy->getReturnType()->isPointerTy() ||
7700 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
7701 "function returning a pointer or a non-returning function that has a "
7706 "operand bundle \"clang.arc.attachedcall\" requires one function as "
7714 Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
7715 IID == Intrinsic::objc_claimAutoreleasedReturnValue ||
7716 IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
7717 "invalid function argument",
Call);
7719 StringRef FnName = Fn->getName();
7720 Check((FnName ==
"objc_retainAutoreleasedReturnValue" ||
7721 FnName ==
"objc_claimAutoreleasedReturnValue" ||
7722 FnName ==
"objc_unsafeClaimAutoreleasedReturnValue"),
7723 "invalid function argument",
Call);
7727void Verifier::verifyNoAliasScopeDecl() {
7728 if (NoAliasScopeDecls.
empty())
7732 for (
auto *
II : NoAliasScopeDecls) {
7733 assert(
II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
7734 "Not a llvm.experimental.noalias.scope.decl ?");
7737 Check(ScopeListMV !=
nullptr,
7738 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
7743 Check(ScopeListMD !=
nullptr,
"!id.scope.list must point to an MDNode",
II);
7744 Check(ScopeListMD->getNumOperands() == 1,
7745 "!id.scope.list must point to a list with a single scope",
II);
7746 visitAliasScopeListMetadata(ScopeListMD);
7756 auto GetScope = [](IntrinsicInst *
II) {
7759 return &
cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
7764 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
7765 return GetScope(Lhs) < GetScope(Rhs);
7772 auto ItCurrent = NoAliasScopeDecls.begin();
7773 while (ItCurrent != NoAliasScopeDecls.end()) {
7774 auto CurScope = GetScope(*ItCurrent);
7775 auto ItNext = ItCurrent;
7778 }
while (ItNext != NoAliasScopeDecls.end() &&
7779 GetScope(*ItNext) == CurScope);
7784 if (ItNext - ItCurrent < 32)
7788 Check(!DT.dominates(
I, J),
7789 "llvm.experimental.noalias.scope.decl dominates another one "
7790 "with the same scope",
7804 Verifier V(OS,
true, *f.getParent());
7808 return !V.verify(
F);
7812 bool *BrokenDebugInfo) {
7814 Verifier V(OS, !BrokenDebugInfo, M);
7816 bool Broken =
false;
7818 Broken |= !V.verify(
F);
7820 Broken |= !V.verify();
7821 if (BrokenDebugInfo)
7822 *BrokenDebugInfo = V.hasBrokenDebugInfo();
7833 std::unique_ptr<Verifier> V;
7834 bool FatalErrors =
true;
7837 explicit VerifierLegacyPass(
bool FatalErrors)
7838 : FunctionPass(
ID), FatalErrors(FatalErrors) {}
7840 bool doInitialization(
Module &M)
override {
7841 V = std::make_unique<Verifier>(
7847 if (!
V->verify(
F) && FatalErrors) {
7848 errs() <<
"in function " <<
F.getName() <<
'\n';
7854 bool doFinalization(
Module &M)
override {
7855 bool HasErrors =
false;
7857 if (
F.isDeclaration())
7858 HasErrors |= !
V->verify(
F);
7860 HasErrors |= !
V->verify();
7861 if (FatalErrors && (HasErrors ||
V->hasBrokenDebugInfo()))
7866 void getAnalysisUsage(AnalysisUsage &AU)
const override {
7874template <
typename... Tys>
void TBAAVerifier::CheckFailed(Tys &&... Args) {
7876 return Diagnostic->CheckFailed(
Args...);
7879#define CheckTBAA(C, ...) \
7882 CheckFailed(__VA_ARGS__); \
7890TBAAVerifier::TBAABaseNodeSummary
7894 CheckFailed(
"Base nodes must have at least two operands",
I, BaseNode);
7898 auto Itr = TBAABaseNodes.find(BaseNode);
7899 if (Itr != TBAABaseNodes.end())
7902 auto Result = verifyTBAABaseNodeImpl(
I, BaseNode, IsNewFormat);
7903 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
7905 assert(InsertResult.second &&
"We just checked!");
7909TBAAVerifier::TBAABaseNodeSummary
7910TBAAVerifier::verifyTBAABaseNodeImpl(
const Instruction *
I,
7911 const MDNode *BaseNode,
bool IsNewFormat) {
7912 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {
true, ~0
u};
7916 return isValidScalarTBAANode(BaseNode)
7917 ? TBAAVerifier::TBAABaseNodeSummary({
false, 0})
7923 CheckFailed(
"Access tag nodes must have the number of operands that is a "
7924 "multiple of 3!", BaseNode);
7929 CheckFailed(
"Struct tag nodes must have an odd number of operands!",
7939 if (!TypeSizeNode) {
7940 CheckFailed(
"Type size nodes must be constants!",
I, BaseNode);
7947 CheckFailed(
"Struct tag nodes have a string as their first operand",
7954 std::optional<APInt> PrevOffset;
7959 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
7960 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
7961 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
7962 Idx += NumOpsPerField) {
7963 const MDOperand &FieldTy = BaseNode->
getOperand(Idx);
7964 const MDOperand &FieldOffset = BaseNode->
getOperand(Idx + 1);
7966 CheckFailed(
"Incorrect field entry in struct type node!",
I, BaseNode);
7971 auto *OffsetEntryCI =
7973 if (!OffsetEntryCI) {
7974 CheckFailed(
"Offset entries must be constants!",
I, BaseNode);
7980 BitWidth = OffsetEntryCI->getBitWidth();
7982 if (OffsetEntryCI->getBitWidth() !=
BitWidth) {
7984 "Bitwidth between the offsets and struct type entries must match",
I,
7996 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
7999 CheckFailed(
"Offsets must be increasing!",
I, BaseNode);
8003 PrevOffset = OffsetEntryCI->getValue();
8008 if (!MemberSizeNode) {
8009 CheckFailed(
"Member size entries must be constants!",
I, BaseNode);
8016 return Failed ? InvalidNode
8017 : TBAAVerifier::TBAABaseNodeSummary(
false,
BitWidth);
8039 return Parent && Visited.
insert(Parent).second &&
8043bool TBAAVerifier::isValidScalarTBAANode(
const MDNode *MD) {
8044 auto ResultIt = TBAAScalarNodes.find(MD);
8045 if (ResultIt != TBAAScalarNodes.end())
8046 return ResultIt->second;
8048 SmallPtrSet<const MDNode *, 4> Visited;
8050 auto InsertResult = TBAAScalarNodes.insert({MD,
Result});
8052 assert(InsertResult.second &&
"Just checked!");
8061MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(
const Instruction *
I,
8062 const MDNode *BaseNode,
8073 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8074 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8075 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
8076 Idx += NumOpsPerField) {
8077 auto *OffsetEntryCI =
8079 if (OffsetEntryCI->getValue().ugt(
Offset)) {
8080 if (Idx == FirstFieldOpNo) {
8081 CheckFailed(
"Could not find TBAA parent in struct type node",
I,
8086 unsigned PrevIdx = Idx - NumOpsPerField;
8087 auto *PrevOffsetEntryCI =
8089 Offset -= PrevOffsetEntryCI->getValue();
8097 Offset -= LastOffsetEntryCI->getValue();
8102 if (!
Type ||
Type->getNumOperands() < 3)
8118 "This instruction shall not have a TBAA access tag!",
I);
8120 bool IsStructPathTBAA =
8124 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
8134 "Access tag metadata must have either 4 or 5 operands",
I, MD);
8137 "Struct tag metadata must have either 3 or 4 operands",
I, MD);
8144 CheckTBAA(AccessSizeNode,
"Access size field must be a constant",
I, MD);
8148 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
8153 "Immutability tag on struct tag metadata must be a constant",
I,
8156 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
8157 "Immutability part of the struct tag metadata must be either 0 or 1",
I,
8162 "Malformed struct tag metadata: base and access-type "
8163 "should be non-null and point to Metadata nodes",
8164 I, MD, BaseNode, AccessType);
8167 CheckTBAA(isValidScalarTBAANode(AccessType),
8168 "Access type node must be a valid scalar type",
I, MD,
8173 CheckTBAA(OffsetCI,
"Offset must be constant integer",
I, MD);
8176 bool SeenAccessTypeInPath =
false;
8182 getFieldNodeFromTBAABaseNode(
I, BaseNode,
Offset, IsNewFormat)) {
8183 if (!StructPath.
insert(BaseNode).second) {
8184 CheckFailed(
"Cycle detected in struct path",
I, MD);
8189 unsigned BaseNodeBitWidth;
8190 std::tie(
Invalid, BaseNodeBitWidth) =
8191 verifyTBAABaseNode(
I, BaseNode, IsNewFormat);
8198 SeenAccessTypeInPath |= BaseNode == AccessType;
8200 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
8205 (BaseNodeBitWidth == 0 &&
Offset == 0) ||
8206 (IsNewFormat && BaseNodeBitWidth == ~0u),
8207 "Access bit-width not the same as description bit-width",
I, MD,
8208 BaseNodeBitWidth,
Offset.getBitWidth());
8210 if (IsNewFormat && SeenAccessTypeInPath)
8214 CheckTBAA(SeenAccessTypeInPath,
"Did not see access type in access path!",
I,
8219char VerifierLegacyPass::ID = 0;
8220INITIALIZE_PASS(VerifierLegacyPass,
"verify",
"Module Verifier",
false,
false)
8223 return new VerifierLegacyPass(FatalErrors);
8241 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
8249 if (res.IRBroken && FatalErrors)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericConvergenceVerifier template.
static DISubprogram * getSubprogram(bool IsDistinct, Ts &&...Args)
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
static bool runOnFunction(Function &F, bool PostInlining)
This file contains the declarations of entities that describe floating point environment and related ...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
static constexpr Value * getValue(Ty &ValueOrUse)
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
verify safepoint Safepoint IR Verifier
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static bool IsScalarTBAANodeImpl(const MDNode *MD, SmallPtrSetImpl< const MDNode * > &Visited)
static bool isType(const Metadata *MD)
static Instruction * getSuccPad(Instruction *Terminator)
static bool isMDTuple(const Metadata *MD)
static bool isNewFormatTBAATypeNode(llvm::MDNode *Type)
#define CheckDI(C,...)
We know that a debug info condition should be true, if not print an error message.
static void forEachUser(const Value *User, SmallPtrSet< const Value *, 32 > &Visited, llvm::function_ref< bool(const Value *)> Callback)
static const Metadata * getRawDIScopeParent(const Metadata *S)
Parent scope operand of S, or null if S has no parent (a DIFile, DICompileUnit, or non-scope).
static bool isDINode(const Metadata *MD)
static bool isSupportedCallBrIntrinsic(Intrinsic::ID ID)
static bool isScope(const Metadata *MD)
static cl::opt< bool > VerifyNoAliasScopeDomination("verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false), cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical " "scopes are not dominating"))
static bool IsRootTBAANode(const MDNode *MD)
static Value * getParentPad(Value *EHPad)
static bool hasConflictingReferenceFlags(unsigned Flags)
Detect mutually exclusive flags.
static AttrBuilder getParameterABIAttributes(LLVMContext &C, unsigned I, AttributeList Attrs)
static const char PassName[]
static LLVM_ABI bool isValidArbitraryFPFormat(StringRef Format)
Returns true if the given string is a valid arbitrary floating-point format interpretation for llvm....
static LLVM_ABI unsigned getArbitraryFPFormatSizeInBits(StringRef Format)
Returns the size in bits of a valid arbitrary floating-point format string, or 0 if the string is not...
bool isFiniteNonZero() const
const fltSemantics & getSemantics() const
Class for arbitrary precision integers.
bool sgt(const APInt &RHS) const
Signed greater than comparison.
bool isMinValue() const
Determine if this is the smallest unsigned value.
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
bool isMaxValue() const
Determine if this is the largest unsigned value.
This class represents a conversion between pointers from one address space to another.
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
const Value * getArraySize() const
Get the number of elements allocated.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void setPreservesAll()
Set by analyses that do not transform their input at all.
bool isElementwise() const
Return true if this RMW has elementwise vector semantics.
static bool isFPOperation(BinOp Op)
BinOp getOperation() const
static LLVM_ABI StringRef getOperationName(BinOp Op)
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
LLVM_ABI const ConstantRange & getValueAsConstantRange() const
Return the attribute's value as a ConstantRange.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
bool isValid() const
Return true if the attribute is any kind of attribute.
LLVM_ABI Type * getValueAsType() const
Return the attribute's value as a Type.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
const Instruction & front() const
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
This class represents a no-op cast from one type to another.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isInlineAsm() const
Check if this call is an inline asm statement.
auto operand_bundles() const
bool hasInAllocaArgument() const
Determine if there are is an inalloca argument.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool doesNotAccessMemory(unsigned OpNo) const
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Get the attribute of a given kind from a given arg.
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Type * getParamElementType(unsigned ArgNo) const
Extract the elementtype type for a parameter.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
bool doesNotReturn() const
Determine if the call cannot return.
LLVM_ABI bool onlyAccessesArgMemory() const
Determine if the call can access memmory only using pointers based on its arguments.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
bool isMustTailCall() const
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
unsigned getNumHandlers() const
return the number of 'handlers' in this catchswitch instruction, except the default handler
Value * getParentPad() const
BasicBlock * getUnwindDest() const
handler_range handlers()
iteration adapter for range-for loops.
BasicBlock * getUnwindDest() const
bool isFPPredicate() const
static bool isIntPredicate(Predicate P)
Value * getCondition() const
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
const APInt & getValue() const
Return the constant as an APInt value reference.
Constant * getAddrDiscriminator() const
The address discriminator if any, or the null constant.
Constant * getPointer() const
The pointer that is signed in this ptrauth signed pointer.
ConstantInt * getKey() const
The Key ID, an i32 constant.
Constant * getDeactivationSymbol() const
ConstantInt * getDiscriminator() const
The integer discriminator, an i64 constant, or 0.
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
This class represents a range of values.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI std::optional< RoundingMode > getRoundingMode() const
LLVM_ABI unsigned getNonMetadataArgCount() const
DbgVariableFragmentInfo FragmentInfo
@ FixedPointBinary
Scale factor 2^Factor.
@ FixedPointDecimal
Scale factor 10^Factor.
@ FixedPointRational
Arbitrary rational scale factor.
DIGlobalVariable * getVariable() const
DIExpression * getExpression() const
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
DILocalScope * getScope() const
Get the local scope for this variable.
Metadata * getRawScope() const
Base class for scope-like contexts.
Subprogram description. Uses SubclassData1.
static LLVM_ABI const DIScope * getRawRetainedNodeScope(const MDNode *N)
Base class for template parameters.
Base class for variables.
Metadata * getRawType() const
Metadata * getRawScope() const
uint64_t getNumOperands() const
Records a position in IR for a source label (DILabel).
MDNode * getRawLabel() const
DILabel * getLabel() const
Base class for non-instruction debug metadata records that have positions within IR.
DebugLoc getDebugLoc() const
LLVM_ABI BasicBlock * getParent()
LLVM_ABI Function * getFunction()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LocationType getType() const
MDNode * getRawExpression() const
MDNode * getRawAddressExpression() const
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
DIExpression * getExpression() const
Metadata * getRawAssignID() const
MDNode * getRawVariable() const
DILocalVariable * getVariable() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
bool isDbgDeclare() const
Metadata * getRawAddress() const
DIExpression * getAddressExpression() const
LLVM_ABI MDNode * getAsMDNode() const
Return this as a bar MDNode.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
This instruction compares its operands according to the predicate given to the constructor.
This class represents an extension of floating point types.
static bool isSupportedFloatingPointType(Type *Ty)
Returns true if Ty is a supported floating-point type for phi, select, or call FPMathOperators.
This class represents a cast from floating point to signed integer.
This class represents a cast from floating point to unsigned integer.
This class represents a truncation of floating point types.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
op_range arg_operands()
arg_operands - iteration adapter for range-for loops.
Value * getParentPad() const
Convenience accessors.
FunctionPass class - This class is used to implement most global optimizations.
Type * getReturnType() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool hasPersonalityFn() const
Check whether this function has a personality function.
const Function & getFunction() const
const std::string & getGC() const
Type * getReturnType() const
Returns the type of the ret val.
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
LLVM_ABI Value * getBasePtr() const
LLVM_ABI Value * getDerivedPtr() const
void visit(const BlockT &BB)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
const Constant * getAliasee() const
LLVM_ABI const Function * getResolverFunction() const
static bool isValidLinkage(LinkageTypes L)
const Constant * getResolver() const
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
bool hasExternalLinkage() const
bool isImplicitDSOLocal() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
bool hasValidDeclarationLinkage() const
LinkageTypes getLinkage() const
bool hasDefaultVisibility() const
bool hasPrivateLinkage() const
bool hasHiddenVisibility() const
bool hasExternalWeakLinkage() const
bool hasDLLImportStorageClass() const
bool hasDLLExportStorageClass() const
bool isDeclarationForLinker() const
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
bool hasCommonLinkage() const
bool hasGlobalUnnamedAddr() const
bool hasAppendingLinkage() const
bool hasAvailableExternallyLinkage() const
Type * getValueType() const
LLVM_ABI bool isInterposable(bool CheckNoIPA=true) const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
BasicBlock * getDestination(unsigned i)
Return the specified destination.
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
unsigned getNumSuccessors() const
This instruction inserts a single (scalar) element into a VectorType value.
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
Value * getAggregateOperand()
ArrayRef< unsigned > getIndices() const
Base class for instruction visitors.
void visit(Iterator Start, Iterator End)
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
This class represents a cast from an integer to a pointer.
static LLVM_ABI bool mayLowerToFunctionCall(Intrinsic::ID IID)
Check if the intrinsic might lower into a regular function call in the course of IR transformations.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
@ OB_clang_arc_attachedcall
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
bool isElementwise() const
Return true if this is an elementwise atomic load.
Align getAlign() const
Return the alignment of the access that is being performed.
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
unsigned getNumOperands() const
Return number of MDNode operands.
bool isResolved() const
Check if node is fully resolved.
LLVMContext & getContext() const
bool equalsStr(StringRef Str) const
LLVM_ABI StringRef getString() const
This class implements a map that also provides access to all stored values in a deterministic order.
A Module instance is used to store all the information related to an LLVM module.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
LLVM_ABI StringRef getName() const
LLVM_ABI unsigned getNumOperands() const
iterator_range< op_iterator > operands()
op_range incoming_values()
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
This class represents a cast from a pointer to an address (non-capturing ptrtoint).
This class represents a cast from a pointer to an integer.
Value * getValue() const
Convenience accessor.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents a sign extension of integer types.
This class represents a cast from signed integer to floating point.
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
This instruction constructs a fixed permutation of two input vectors.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
static constexpr size_t npos
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
Check if the string is empty.
std::pair< typename Base::iterator, bool > insert(StringRef key)
Verify that the TBAA Metadatas are valid.
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI unsigned getIntegerBitWidth() const
bool isByteTy() const
True if this is an instance of ByteType.
bool isVectorTy() const
True if this is an instance of VectorType.
LLVM_ABI bool containsNonGlobalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a global...
LLVM_ABI bool containsNonLocalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a local.
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
LLVM_ABI bool isTokenLikeTy() const
Returns true if this is 'token' or a token-like target type.s.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
LLVM_ABI bool canLosslesslyBitCastTo(Type *Ty) const
Return true if this type could be converted with a lossless BitCast to type 'Ty'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
This class represents a cast unsigned integer to floating point.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
iterator_range< user_iterator > materialized_users()
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
iterator_range< user_iterator > users()
bool materialized_use_empty() const
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.