1 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines the function verifier interface, that can be used for some
10 // basic correctness checking of input to the system.
12 // Note that this does not provide full `Java style' security and verifications,
13 // instead it just tries to ensure that code is well-formed.
15 // * Both of a binary operator's parameters are of the same type
16 // * Verify that the indices of mem access instructions match other operands
17 // * Verify that arithmetic and other things are only performed on first-class
18 // types. Verify that shifts & logicals only happen on integrals f.e.
19 // * All of the constants in a switch statement are of the correct type
20 // * The code is in valid SSA form
21 // * It should be illegal to put a label into any other type (like a structure)
22 // or to return one. [except constant arrays!]
23 // * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
24 // * PHI nodes must have an entry for each predecessor, with no extras.
25 // * PHI nodes must be the first thing in a basic block, all grouped together
26 // * All basic blocks should only end with terminator insts, not contain them
27 // * The entry node to a function must not have predecessors
28 // * All Instructions must be embedded into a basic block
29 // * Functions cannot take a void-typed parameter
30 // * Verify that a function's argument list agrees with it's declared type.
31 // * It is illegal to specify a name for a void value.
32 // * It is illegal to have a internal global value with no initializer
33 // * It is illegal to have a ret instruction that returns a value that does not
34 // agree with the function return value type.
35 // * Function call argument types match the function prototype
36 // * A landing pad is defined by a landingpad instruction, and can be jumped to
37 // only by the unwind edge of an invoke instruction.
38 // * A landingpad instruction must be the first non-PHI instruction in the
40 // * Landingpad instructions must be in a function with a personality function.
41 // * Convergence control intrinsics are introduced in ConvergentOperations.rst.
42 // The applied restrictions are too numerous to list here.
43 // * The convergence entry intrinsic and the loop heart must be the first
44 // non-PHI instruction in their respective block. This does not conflict with
45 // the landing pads, since these two kinds cannot occur in the same block.
46 // * All other things that are tested by asserts spread about the code...
48 //===----------------------------------------------------------------------===//
50 #include "llvm/IR/Verifier.h"
51 #include "llvm/ADT/APFloat.h"
52 #include "llvm/ADT/APInt.h"
53 #include "llvm/ADT/ArrayRef.h"
54 #include "llvm/ADT/DenseMap.h"
55 #include "llvm/ADT/MapVector.h"
56 #include "llvm/ADT/PostOrderIterator.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include "llvm/ADT/SmallPtrSet.h"
59 #include "llvm/ADT/SmallSet.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/ADT/StringExtras.h"
62 #include "llvm/ADT/StringMap.h"
63 #include "llvm/ADT/StringRef.h"
64 #include "llvm/ADT/Twine.h"
65 #include "llvm/BinaryFormat/Dwarf.h"
66 #include "llvm/IR/Argument.h"
67 #include "llvm/IR/AttributeMask.h"
68 #include "llvm/IR/Attributes.h"
69 #include "llvm/IR/BasicBlock.h"
70 #include "llvm/IR/CFG.h"
71 #include "llvm/IR/CallingConv.h"
72 #include "llvm/IR/Comdat.h"
73 #include "llvm/IR/Constant.h"
74 #include "llvm/IR/ConstantRange.h"
75 #include "llvm/IR/Constants.h"
76 #include "llvm/IR/ConvergenceVerifier.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DebugInfo.h"
79 #include "llvm/IR/DebugInfoMetadata.h"
80 #include "llvm/IR/DebugLoc.h"
81 #include "llvm/IR/DerivedTypes.h"
82 #include "llvm/IR/Dominators.h"
83 #include "llvm/IR/EHPersonalities.h"
84 #include "llvm/IR/Function.h"
85 #include "llvm/IR/GCStrategy.h"
86 #include "llvm/IR/GlobalAlias.h"
87 #include "llvm/IR/GlobalValue.h"
88 #include "llvm/IR/GlobalVariable.h"
89 #include "llvm/IR/InlineAsm.h"
90 #include "llvm/IR/InstVisitor.h"
91 #include "llvm/IR/InstrTypes.h"
92 #include "llvm/IR/Instruction.h"
93 #include "llvm/IR/Instructions.h"
94 #include "llvm/IR/IntrinsicInst.h"
95 #include "llvm/IR/Intrinsics.h"
96 #include "llvm/IR/IntrinsicsAArch64.h"
97 #include "llvm/IR/IntrinsicsAMDGPU.h"
98 #include "llvm/IR/IntrinsicsARM.h"
99 #include "llvm/IR/IntrinsicsWebAssembly.h"
100 #include "llvm/IR/LLVMContext.h"
101 #include "llvm/IR/Metadata.h"
102 #include "llvm/IR/Module.h"
103 #include "llvm/IR/ModuleSlotTracker.h"
104 #include "llvm/IR/PassManager.h"
105 #include "llvm/IR/Statepoint.h"
106 #include "llvm/IR/Type.h"
107 #include "llvm/IR/Use.h"
108 #include "llvm/IR/User.h"
109 #include "llvm/IR/Value.h"
110 #include "llvm/InitializePasses.h"
111 #include "llvm/Pass.h"
112 #include "llvm/Support/AtomicOrdering.h"
113 #include "llvm/Support/Casting.h"
114 #include "llvm/Support/CommandLine.h"
115 #include "llvm/Support/ErrorHandling.h"
116 #include "llvm/Support/MathExtras.h"
117 #include "llvm/Support/raw_ostream.h"
126 using namespace llvm
;
128 static cl::opt
<bool> VerifyNoAliasScopeDomination(
129 "verify-noalias-scope-decl-dom", cl::Hidden
, cl::init(false),
130 cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical "
131 "scopes are not dominating"));
135 struct VerifierSupport
{
138 ModuleSlotTracker MST
;
140 const DataLayout
&DL
;
141 LLVMContext
&Context
;
143 /// Track the brokenness of the module while recursively visiting.
145 /// Broken debug info can be "recovered" from by stripping the debug info.
146 bool BrokenDebugInfo
= false;
147 /// Whether to treat broken debug info as an error.
148 bool TreatBrokenDebugInfoAsError
= true;
150 explicit VerifierSupport(raw_ostream
*OS
, const Module
&M
)
151 : OS(OS
), M(M
), MST(&M
), TT(M
.getTargetTriple()), DL(M
.getDataLayout()),
152 Context(M
.getContext()) {}
155 void Write(const Module
*M
) {
156 *OS
<< "; ModuleID = '" << M
->getModuleIdentifier() << "'\n";
159 void Write(const Value
*V
) {
164 void Write(const Value
&V
) {
165 if (isa
<Instruction
>(V
)) {
169 V
.printAsOperand(*OS
, true, MST
);
174 void Write(const Metadata
*MD
) {
177 MD
->print(*OS
, MST
, &M
);
181 template <class T
> void Write(const MDTupleTypedArrayWrapper
<T
> &MD
) {
185 void Write(const NamedMDNode
*NMD
) {
188 NMD
->print(*OS
, MST
);
192 void Write(Type
*T
) {
198 void Write(const Comdat
*C
) {
204 void Write(const APInt
*AI
) {
210 void Write(const unsigned i
) { *OS
<< i
<< '\n'; }
212 // NOLINTNEXTLINE(readability-identifier-naming)
213 void Write(const Attribute
*A
) {
216 *OS
<< A
->getAsString() << '\n';
219 // NOLINTNEXTLINE(readability-identifier-naming)
220 void Write(const AttributeSet
*AS
) {
223 *OS
<< AS
->getAsString() << '\n';
226 // NOLINTNEXTLINE(readability-identifier-naming)
227 void Write(const AttributeList
*AL
) {
233 void Write(Printable P
) { *OS
<< P
<< '\n'; }
235 template <typename T
> void Write(ArrayRef
<T
> Vs
) {
236 for (const T
&V
: Vs
)
240 template <typename T1
, typename
... Ts
>
241 void WriteTs(const T1
&V1
, const Ts
&... Vs
) {
246 template <typename
... Ts
> void WriteTs() {}
249 /// A check failed, so printout out the condition and the message.
251 /// This provides a nice place to put a breakpoint if you want to see why
252 /// something is not correct.
253 void CheckFailed(const Twine
&Message
) {
255 *OS
<< Message
<< '\n';
259 /// A check failed (with values to print).
261 /// This calls the Message-only version so that the above is easier to set a
263 template <typename T1
, typename
... Ts
>
264 void CheckFailed(const Twine
&Message
, const T1
&V1
, const Ts
&... Vs
) {
265 CheckFailed(Message
);
270 /// A debug info check failed.
271 void DebugInfoCheckFailed(const Twine
&Message
) {
273 *OS
<< Message
<< '\n';
274 Broken
|= TreatBrokenDebugInfoAsError
;
275 BrokenDebugInfo
= true;
278 /// A debug info check failed (with values to print).
279 template <typename T1
, typename
... Ts
>
280 void DebugInfoCheckFailed(const Twine
&Message
, const T1
&V1
,
282 DebugInfoCheckFailed(Message
);
292 class Verifier
: public InstVisitor
<Verifier
>, VerifierSupport
{
293 friend class InstVisitor
<Verifier
>;
295 // ISD::ArgFlagsTy::MemAlign only have 4 bits for alignment, so
296 // the alignment size should not exceed 2^15. Since encode(Align)
297 // would plus the shift value by 1, the alignment size should
298 // not exceed 2^14, otherwise it can NOT be properly lowered
300 static constexpr unsigned ParamMaxAlignment
= 1 << 14;
303 /// When verifying a basic block, keep track of all of the
304 /// instructions we have seen so far.
306 /// This allows us to do efficient dominance checks for the case when an
307 /// instruction has an operand that is an instruction in the same block.
308 SmallPtrSet
<Instruction
*, 16> InstsInThisBlock
;
310 /// Keep track of the metadata nodes that have been checked already.
311 SmallPtrSet
<const Metadata
*, 32> MDNodes
;
313 /// Keep track which DISubprogram is attached to which function.
314 DenseMap
<const DISubprogram
*, const Function
*> DISubprogramAttachments
;
316 /// Track all DICompileUnits visited.
317 SmallPtrSet
<const Metadata
*, 2> CUVisited
;
319 /// The result type for a landingpad.
320 Type
*LandingPadResultTy
;
322 /// Whether we've seen a call to @llvm.localescape in this function
326 /// Whether the current function has a DISubprogram attached to it.
327 bool HasDebugInfo
= false;
329 /// The current source language.
330 dwarf::SourceLanguage CurrentSourceLang
= dwarf::DW_LANG_lo_user
;
332 /// Whether source was present on the first DIFile encountered in each CU.
333 DenseMap
<const DICompileUnit
*, bool> HasSourceDebugInfo
;
335 /// Stores the count of how many objects were passed to llvm.localescape for a
336 /// given function and the largest index passed to llvm.localrecover.
337 DenseMap
<Function
*, std::pair
<unsigned, unsigned>> FrameEscapeInfo
;
339 // Maps catchswitches and cleanuppads that unwind to siblings to the
340 // terminators that indicate the unwind, used to detect cycles therein.
341 MapVector
<Instruction
*, Instruction
*> SiblingFuncletInfo
;
343 /// Cache which blocks are in which funclet, if an EH funclet personality is
344 /// in use. Otherwise empty.
345 DenseMap
<BasicBlock
*, ColorVector
> BlockEHFuncletColors
;
347 /// Cache of constants visited in search of ConstantExprs.
348 SmallPtrSet
<const Constant
*, 32> ConstantExprVisited
;
350 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
351 SmallVector
<const Function
*, 4> DeoptimizeDeclarations
;
353 /// Cache of attribute lists verified.
354 SmallPtrSet
<const void *, 32> AttributeListsVisited
;
356 // Verify that this GlobalValue is only used in this module.
357 // This map is used to avoid visiting uses twice. We can arrive at a user
358 // twice, if they have multiple operands. In particular for very large
359 // constant expressions, we can arrive at a particular user many times.
360 SmallPtrSet
<const Value
*, 32> GlobalValueVisited
;
362 // Keeps track of duplicate function argument debug info.
363 SmallVector
<const DILocalVariable
*, 16> DebugFnArgs
;
365 TBAAVerifier TBAAVerifyHelper
;
366 ConvergenceVerifier ConvergenceVerifyHelper
;
368 SmallVector
<IntrinsicInst
*, 4> NoAliasScopeDecls
;
370 void checkAtomicMemAccessSize(Type
*Ty
, const Instruction
*I
);
373 explicit Verifier(raw_ostream
*OS
, bool ShouldTreatBrokenDebugInfoAsError
,
375 : VerifierSupport(OS
, M
), LandingPadResultTy(nullptr),
376 SawFrameEscape(false), TBAAVerifyHelper(this) {
377 TreatBrokenDebugInfoAsError
= ShouldTreatBrokenDebugInfoAsError
;
380 bool hasBrokenDebugInfo() const { return BrokenDebugInfo
; }
382 bool verify(const Function
&F
) {
383 assert(F
.getParent() == &M
&&
384 "An instance of this class only works with a specific module!");
386 // First ensure the function is well-enough formed to compute dominance
387 // information, and directly compute a dominance tree. We don't rely on the
388 // pass manager to provide this as it isolates us from a potentially
389 // out-of-date dominator tree and makes it significantly more complex to run
390 // this code outside of a pass manager.
391 // FIXME: It's really gross that we have to cast away constness here.
393 DT
.recalculate(const_cast<Function
&>(F
));
395 for (const BasicBlock
&BB
: F
) {
396 if (!BB
.empty() && BB
.back().isTerminator())
400 *OS
<< "Basic Block in function '" << F
.getName()
401 << "' does not have terminator!\n";
402 BB
.printAsOperand(*OS
, true, MST
);
408 auto FailureCB
= [this](const Twine
&Message
) {
409 this->CheckFailed(Message
);
411 ConvergenceVerifyHelper
.initialize(OS
, FailureCB
, F
);
414 // FIXME: We strip const here because the inst visitor strips const.
415 visit(const_cast<Function
&>(F
));
416 verifySiblingFuncletUnwinds();
418 if (ConvergenceVerifyHelper
.sawTokens())
419 ConvergenceVerifyHelper
.verify(DT
);
421 InstsInThisBlock
.clear();
423 LandingPadResultTy
= nullptr;
424 SawFrameEscape
= false;
425 SiblingFuncletInfo
.clear();
426 verifyNoAliasScopeDecl();
427 NoAliasScopeDecls
.clear();
432 /// Verify the module that this instance of \c Verifier was initialized with.
436 // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
437 for (const Function
&F
: M
)
438 if (F
.getIntrinsicID() == Intrinsic::experimental_deoptimize
)
439 DeoptimizeDeclarations
.push_back(&F
);
441 // Now that we've visited every function, verify that we never asked to
442 // recover a frame index that wasn't escaped.
443 verifyFrameRecoverIndices();
444 for (const GlobalVariable
&GV
: M
.globals())
445 visitGlobalVariable(GV
);
447 for (const GlobalAlias
&GA
: M
.aliases())
448 visitGlobalAlias(GA
);
450 for (const GlobalIFunc
&GI
: M
.ifuncs())
451 visitGlobalIFunc(GI
);
453 for (const NamedMDNode
&NMD
: M
.named_metadata())
454 visitNamedMDNode(NMD
);
456 for (const StringMapEntry
<Comdat
> &SMEC
: M
.getComdatSymbolTable())
457 visitComdat(SMEC
.getValue());
461 visitModuleCommandLines();
463 verifyCompileUnits();
465 verifyDeoptimizeCallingConvs();
466 DISubprogramAttachments
.clear();
471 /// Whether a metadata node is allowed to be, or contain, a DILocation.
472 enum class AreDebugLocsAllowed
{ No
, Yes
};
474 // Verification methods...
475 void visitGlobalValue(const GlobalValue
&GV
);
476 void visitGlobalVariable(const GlobalVariable
&GV
);
477 void visitGlobalAlias(const GlobalAlias
&GA
);
478 void visitGlobalIFunc(const GlobalIFunc
&GI
);
479 void visitAliaseeSubExpr(const GlobalAlias
&A
, const Constant
&C
);
480 void visitAliaseeSubExpr(SmallPtrSetImpl
<const GlobalAlias
*> &Visited
,
481 const GlobalAlias
&A
, const Constant
&C
);
482 void visitNamedMDNode(const NamedMDNode
&NMD
);
483 void visitMDNode(const MDNode
&MD
, AreDebugLocsAllowed AllowLocs
);
484 void visitMetadataAsValue(const MetadataAsValue
&MD
, Function
*F
);
485 void visitValueAsMetadata(const ValueAsMetadata
&MD
, Function
*F
);
486 void visitComdat(const Comdat
&C
);
487 void visitModuleIdents();
488 void visitModuleCommandLines();
489 void visitModuleFlags();
490 void visitModuleFlag(const MDNode
*Op
,
491 DenseMap
<const MDString
*, const MDNode
*> &SeenIDs
,
492 SmallVectorImpl
<const MDNode
*> &Requirements
);
493 void visitModuleFlagCGProfileEntry(const MDOperand
&MDO
);
494 void visitFunction(const Function
&F
);
495 void visitBasicBlock(BasicBlock
&BB
);
496 void verifyRangeMetadata(const Value
&V
, const MDNode
*Range
, Type
*Ty
,
497 bool IsAbsoluteSymbol
);
498 void visitRangeMetadata(Instruction
&I
, MDNode
*Range
, Type
*Ty
);
499 void visitDereferenceableMetadata(Instruction
&I
, MDNode
*MD
);
500 void visitProfMetadata(Instruction
&I
, MDNode
*MD
);
501 void visitCallStackMetadata(MDNode
*MD
);
502 void visitMemProfMetadata(Instruction
&I
, MDNode
*MD
);
503 void visitCallsiteMetadata(Instruction
&I
, MDNode
*MD
);
504 void visitDIAssignIDMetadata(Instruction
&I
, MDNode
*MD
);
505 void visitAnnotationMetadata(MDNode
*Annotation
);
506 void visitAliasScopeMetadata(const MDNode
*MD
);
507 void visitAliasScopeListMetadata(const MDNode
*MD
);
508 void visitAccessGroupMetadata(const MDNode
*MD
);
510 template <class Ty
> bool isValidMetadataArray(const MDTuple
&N
);
511 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
512 #include "llvm/IR/Metadata.def"
513 void visitDIScope(const DIScope
&N
);
514 void visitDIVariable(const DIVariable
&N
);
515 void visitDILexicalBlockBase(const DILexicalBlockBase
&N
);
516 void visitDITemplateParameter(const DITemplateParameter
&N
);
518 void visitTemplateParams(const MDNode
&N
, const Metadata
&RawParams
);
520 // InstVisitor overrides...
521 using InstVisitor
<Verifier
>::visit
;
522 void visit(Instruction
&I
);
524 void visitTruncInst(TruncInst
&I
);
525 void visitZExtInst(ZExtInst
&I
);
526 void visitSExtInst(SExtInst
&I
);
527 void visitFPTruncInst(FPTruncInst
&I
);
528 void visitFPExtInst(FPExtInst
&I
);
529 void visitFPToUIInst(FPToUIInst
&I
);
530 void visitFPToSIInst(FPToSIInst
&I
);
531 void visitUIToFPInst(UIToFPInst
&I
);
532 void visitSIToFPInst(SIToFPInst
&I
);
533 void visitIntToPtrInst(IntToPtrInst
&I
);
534 void visitPtrToIntInst(PtrToIntInst
&I
);
535 void visitBitCastInst(BitCastInst
&I
);
536 void visitAddrSpaceCastInst(AddrSpaceCastInst
&I
);
537 void visitPHINode(PHINode
&PN
);
538 void visitCallBase(CallBase
&Call
);
539 void visitUnaryOperator(UnaryOperator
&U
);
540 void visitBinaryOperator(BinaryOperator
&B
);
541 void visitICmpInst(ICmpInst
&IC
);
542 void visitFCmpInst(FCmpInst
&FC
);
543 void visitExtractElementInst(ExtractElementInst
&EI
);
544 void visitInsertElementInst(InsertElementInst
&EI
);
545 void visitShuffleVectorInst(ShuffleVectorInst
&EI
);
546 void visitVAArgInst(VAArgInst
&VAA
) { visitInstruction(VAA
); }
547 void visitCallInst(CallInst
&CI
);
548 void visitInvokeInst(InvokeInst
&II
);
549 void visitGetElementPtrInst(GetElementPtrInst
&GEP
);
550 void visitLoadInst(LoadInst
&LI
);
551 void visitStoreInst(StoreInst
&SI
);
552 void verifyDominatesUse(Instruction
&I
, unsigned i
);
553 void visitInstruction(Instruction
&I
);
554 void visitTerminator(Instruction
&I
);
555 void visitBranchInst(BranchInst
&BI
);
556 void visitReturnInst(ReturnInst
&RI
);
557 void visitSwitchInst(SwitchInst
&SI
);
558 void visitIndirectBrInst(IndirectBrInst
&BI
);
559 void visitCallBrInst(CallBrInst
&CBI
);
560 void visitSelectInst(SelectInst
&SI
);
561 void visitUserOp1(Instruction
&I
);
562 void visitUserOp2(Instruction
&I
) { visitUserOp1(I
); }
563 void visitIntrinsicCall(Intrinsic::ID ID
, CallBase
&Call
);
564 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic
&FPI
);
565 void visitVPIntrinsic(VPIntrinsic
&VPI
);
566 void visitDbgIntrinsic(StringRef Kind
, DbgVariableIntrinsic
&DII
);
567 void visitDbgLabelIntrinsic(StringRef Kind
, DbgLabelInst
&DLI
);
568 void visitAtomicCmpXchgInst(AtomicCmpXchgInst
&CXI
);
569 void visitAtomicRMWInst(AtomicRMWInst
&RMWI
);
570 void visitFenceInst(FenceInst
&FI
);
571 void visitAllocaInst(AllocaInst
&AI
);
572 void visitExtractValueInst(ExtractValueInst
&EVI
);
573 void visitInsertValueInst(InsertValueInst
&IVI
);
574 void visitEHPadPredecessors(Instruction
&I
);
575 void visitLandingPadInst(LandingPadInst
&LPI
);
576 void visitResumeInst(ResumeInst
&RI
);
577 void visitCatchPadInst(CatchPadInst
&CPI
);
578 void visitCatchReturnInst(CatchReturnInst
&CatchReturn
);
579 void visitCleanupPadInst(CleanupPadInst
&CPI
);
580 void visitFuncletPadInst(FuncletPadInst
&FPI
);
581 void visitCatchSwitchInst(CatchSwitchInst
&CatchSwitch
);
582 void visitCleanupReturnInst(CleanupReturnInst
&CRI
);
584 void verifySwiftErrorCall(CallBase
&Call
, const Value
*SwiftErrorVal
);
585 void verifySwiftErrorValue(const Value
*SwiftErrorVal
);
586 void verifyTailCCMustTailAttrs(const AttrBuilder
&Attrs
, StringRef Context
);
587 void verifyMustTailCall(CallInst
&CI
);
588 bool verifyAttributeCount(AttributeList Attrs
, unsigned Params
);
589 void verifyAttributeTypes(AttributeSet Attrs
, const Value
*V
);
590 void verifyParameterAttrs(AttributeSet Attrs
, Type
*Ty
, const Value
*V
);
591 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs
, StringRef Attr
,
593 void verifyFunctionAttrs(FunctionType
*FT
, AttributeList Attrs
,
594 const Value
*V
, bool IsIntrinsic
, bool IsInlineAsm
);
595 void verifyFunctionMetadata(ArrayRef
<std::pair
<unsigned, MDNode
*>> MDs
);
597 void visitConstantExprsRecursively(const Constant
*EntryC
);
598 void visitConstantExpr(const ConstantExpr
*CE
);
599 void verifyInlineAsmCall(const CallBase
&Call
);
600 void verifyStatepoint(const CallBase
&Call
);
601 void verifyFrameRecoverIndices();
602 void verifySiblingFuncletUnwinds();
604 void verifyFragmentExpression(const DbgVariableIntrinsic
&I
);
605 template <typename ValueOrMetadata
>
606 void verifyFragmentExpression(const DIVariable
&V
,
607 DIExpression::FragmentInfo Fragment
,
608 ValueOrMetadata
*Desc
);
609 void verifyFnArgs(const DbgVariableIntrinsic
&I
);
610 void verifyNotEntryValue(const DbgVariableIntrinsic
&I
);
612 /// Module-level debug info verification...
613 void verifyCompileUnits();
615 /// Module-level verification that all @llvm.experimental.deoptimize
616 /// declarations share the same calling convention.
617 void verifyDeoptimizeCallingConvs();
619 void verifyAttachedCallBundle(const CallBase
&Call
,
620 const OperandBundleUse
&BU
);
622 /// Verify all-or-nothing property of DIFile source attribute within a CU.
623 void verifySourceDebugInfo(const DICompileUnit
&U
, const DIFile
&F
);
625 /// Verify the llvm.experimental.noalias.scope.decl declarations
626 void verifyNoAliasScopeDecl();
629 } // end anonymous namespace
631 /// We know that cond should be true, if not print an error message.
632 #define Check(C, ...) \
635 CheckFailed(__VA_ARGS__); \
640 /// We know that a debug info condition should be true, if not print
641 /// an error message.
642 #define CheckDI(C, ...) \
645 DebugInfoCheckFailed(__VA_ARGS__); \
650 void Verifier::visit(Instruction
&I
) {
651 for (unsigned i
= 0, e
= I
.getNumOperands(); i
!= e
; ++i
)
652 Check(I
.getOperand(i
) != nullptr, "Operand is null", &I
);
653 InstVisitor
<Verifier
>::visit(I
);
656 // Helper to iterate over indirect users. By returning false, the callback can ask to stop traversing further.
657 static void forEachUser(const Value
*User
,
658 SmallPtrSet
<const Value
*, 32> &Visited
,
659 llvm::function_ref
<bool(const Value
*)> Callback
) {
660 if (!Visited
.insert(User
).second
)
663 SmallVector
<const Value
*> WorkList
;
664 append_range(WorkList
, User
->materialized_users());
665 while (!WorkList
.empty()) {
666 const Value
*Cur
= WorkList
.pop_back_val();
667 if (!Visited
.insert(Cur
).second
)
670 append_range(WorkList
, Cur
->materialized_users());
674 void Verifier::visitGlobalValue(const GlobalValue
&GV
) {
675 Check(!GV
.isDeclaration() || GV
.hasValidDeclarationLinkage(),
676 "Global is external, but doesn't have external or weak linkage!", &GV
);
678 if (const GlobalObject
*GO
= dyn_cast
<GlobalObject
>(&GV
)) {
680 if (MaybeAlign A
= GO
->getAlign()) {
681 Check(A
->value() <= Value::MaximumAlignment
,
682 "huge alignment values are unsupported", GO
);
685 if (const MDNode
*Associated
=
686 GO
->getMetadata(LLVMContext::MD_associated
)) {
687 Check(Associated
->getNumOperands() == 1,
688 "associated metadata must have one operand", &GV
, Associated
);
689 const Metadata
*Op
= Associated
->getOperand(0).get();
690 Check(Op
, "associated metadata must have a global value", GO
, Associated
);
692 const auto *VM
= dyn_cast_or_null
<ValueAsMetadata
>(Op
);
693 Check(VM
, "associated metadata must be ValueAsMetadata", GO
, Associated
);
695 Check(isa
<PointerType
>(VM
->getValue()->getType()),
696 "associated value must be pointer typed", GV
, Associated
);
698 const Value
*Stripped
= VM
->getValue()->stripPointerCastsAndAliases();
699 Check(isa
<GlobalObject
>(Stripped
) || isa
<Constant
>(Stripped
),
700 "associated metadata must point to a GlobalObject", GO
, Stripped
);
701 Check(Stripped
!= GO
,
702 "global values should not associate to themselves", GO
,
707 // FIXME: Why is getMetadata on GlobalValue protected?
708 if (const MDNode
*AbsoluteSymbol
=
709 GO
->getMetadata(LLVMContext::MD_absolute_symbol
)) {
710 verifyRangeMetadata(*GO
, AbsoluteSymbol
, DL
.getIntPtrType(GO
->getType()),
715 Check(!GV
.hasAppendingLinkage() || isa
<GlobalVariable
>(GV
),
716 "Only global variables can have appending linkage!", &GV
);
718 if (GV
.hasAppendingLinkage()) {
719 const GlobalVariable
*GVar
= dyn_cast
<GlobalVariable
>(&GV
);
720 Check(GVar
&& GVar
->getValueType()->isArrayTy(),
721 "Only global arrays can have appending linkage!", GVar
);
724 if (GV
.isDeclarationForLinker())
725 Check(!GV
.hasComdat(), "Declaration may not be in a Comdat!", &GV
);
727 if (GV
.hasDLLExportStorageClass()) {
728 Check(!GV
.hasHiddenVisibility(),
729 "dllexport GlobalValue must have default or protected visibility",
732 if (GV
.hasDLLImportStorageClass()) {
733 Check(GV
.hasDefaultVisibility(),
734 "dllimport GlobalValue must have default visibility", &GV
);
735 Check(!GV
.isDSOLocal(), "GlobalValue with DLLImport Storage is dso_local!",
738 Check((GV
.isDeclaration() &&
739 (GV
.hasExternalLinkage() || GV
.hasExternalWeakLinkage())) ||
740 GV
.hasAvailableExternallyLinkage(),
741 "Global is marked as dllimport, but not external", &GV
);
744 if (GV
.isImplicitDSOLocal())
745 Check(GV
.isDSOLocal(),
746 "GlobalValue with local linkage or non-default "
747 "visibility must be dso_local!",
750 forEachUser(&GV
, GlobalValueVisited
, [&](const Value
*V
) -> bool {
751 if (const Instruction
*I
= dyn_cast
<Instruction
>(V
)) {
752 if (!I
->getParent() || !I
->getParent()->getParent())
753 CheckFailed("Global is referenced by parentless instruction!", &GV
, &M
,
755 else if (I
->getParent()->getParent()->getParent() != &M
)
756 CheckFailed("Global is referenced in a different module!", &GV
, &M
, I
,
757 I
->getParent()->getParent(),
758 I
->getParent()->getParent()->getParent());
760 } else if (const Function
*F
= dyn_cast
<Function
>(V
)) {
761 if (F
->getParent() != &M
)
762 CheckFailed("Global is used by function in a different module", &GV
, &M
,
770 void Verifier::visitGlobalVariable(const GlobalVariable
&GV
) {
771 if (GV
.hasInitializer()) {
772 Check(GV
.getInitializer()->getType() == GV
.getValueType(),
773 "Global variable initializer type does not match global "
776 // If the global has common linkage, it must have a zero initializer and
777 // cannot be constant.
778 if (GV
.hasCommonLinkage()) {
779 Check(GV
.getInitializer()->isNullValue(),
780 "'common' global must have a zero initializer!", &GV
);
781 Check(!GV
.isConstant(), "'common' global may not be marked constant!",
783 Check(!GV
.hasComdat(), "'common' global may not be in a Comdat!", &GV
);
787 if (GV
.hasName() && (GV
.getName() == "llvm.global_ctors" ||
788 GV
.getName() == "llvm.global_dtors")) {
789 Check(!GV
.hasInitializer() || GV
.hasAppendingLinkage(),
790 "invalid linkage for intrinsic global variable", &GV
);
791 Check(GV
.materialized_use_empty(),
792 "invalid uses of intrinsic global variable", &GV
);
794 // Don't worry about emitting an error for it not being an array,
795 // visitGlobalValue will complain on appending non-array.
796 if (ArrayType
*ATy
= dyn_cast
<ArrayType
>(GV
.getValueType())) {
797 StructType
*STy
= dyn_cast
<StructType
>(ATy
->getElementType());
798 PointerType
*FuncPtrTy
=
799 PointerType::get(Context
, DL
.getProgramAddressSpace());
800 Check(STy
&& (STy
->getNumElements() == 2 || STy
->getNumElements() == 3) &&
801 STy
->getTypeAtIndex(0u)->isIntegerTy(32) &&
802 STy
->getTypeAtIndex(1) == FuncPtrTy
,
803 "wrong type for intrinsic global variable", &GV
);
804 Check(STy
->getNumElements() == 3,
805 "the third field of the element type is mandatory, "
806 "specify ptr null to migrate from the obsoleted 2-field form");
807 Type
*ETy
= STy
->getTypeAtIndex(2);
808 Check(ETy
->isPointerTy(), "wrong type for intrinsic global variable",
813 if (GV
.hasName() && (GV
.getName() == "llvm.used" ||
814 GV
.getName() == "llvm.compiler.used")) {
815 Check(!GV
.hasInitializer() || GV
.hasAppendingLinkage(),
816 "invalid linkage for intrinsic global variable", &GV
);
817 Check(GV
.materialized_use_empty(),
818 "invalid uses of intrinsic global variable", &GV
);
820 Type
*GVType
= GV
.getValueType();
821 if (ArrayType
*ATy
= dyn_cast
<ArrayType
>(GVType
)) {
822 PointerType
*PTy
= dyn_cast
<PointerType
>(ATy
->getElementType());
823 Check(PTy
, "wrong type for intrinsic global variable", &GV
);
824 if (GV
.hasInitializer()) {
825 const Constant
*Init
= GV
.getInitializer();
826 const ConstantArray
*InitArray
= dyn_cast
<ConstantArray
>(Init
);
827 Check(InitArray
, "wrong initalizer for intrinsic global variable",
829 for (Value
*Op
: InitArray
->operands()) {
830 Value
*V
= Op
->stripPointerCasts();
831 Check(isa
<GlobalVariable
>(V
) || isa
<Function
>(V
) ||
833 Twine("invalid ") + GV
.getName() + " member", V
);
835 Twine("members of ") + GV
.getName() + " must be named", V
);
841 // Visit any debug info attachments.
842 SmallVector
<MDNode
*, 1> MDs
;
843 GV
.getMetadata(LLVMContext::MD_dbg
, MDs
);
844 for (auto *MD
: MDs
) {
845 if (auto *GVE
= dyn_cast
<DIGlobalVariableExpression
>(MD
))
846 visitDIGlobalVariableExpression(*GVE
);
848 CheckDI(false, "!dbg attachment of global variable must be a "
849 "DIGlobalVariableExpression");
852 // Scalable vectors cannot be global variables, since we don't know
854 Check(!GV
.getValueType()->isScalableTy(),
855 "Globals cannot contain scalable types", &GV
);
857 // Check if it's a target extension type that disallows being used as a
859 if (auto *TTy
= dyn_cast
<TargetExtType
>(GV
.getValueType()))
860 Check(TTy
->hasProperty(TargetExtType::CanBeGlobal
),
861 "Global @" + GV
.getName() + " has illegal target extension type",
864 if (!GV
.hasInitializer()) {
865 visitGlobalValue(GV
);
869 // Walk any aggregate initializers looking for bitcasts between address spaces
870 visitConstantExprsRecursively(GV
.getInitializer());
872 visitGlobalValue(GV
);
875 void Verifier::visitAliaseeSubExpr(const GlobalAlias
&GA
, const Constant
&C
) {
876 SmallPtrSet
<const GlobalAlias
*, 4> Visited
;
878 visitAliaseeSubExpr(Visited
, GA
, C
);
881 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl
<const GlobalAlias
*> &Visited
,
882 const GlobalAlias
&GA
, const Constant
&C
) {
883 if (GA
.hasAvailableExternallyLinkage()) {
884 Check(isa
<GlobalValue
>(C
) &&
885 cast
<GlobalValue
>(C
).hasAvailableExternallyLinkage(),
886 "available_externally alias must point to available_externally "
890 if (const auto *GV
= dyn_cast
<GlobalValue
>(&C
)) {
891 if (!GA
.hasAvailableExternallyLinkage()) {
892 Check(!GV
->isDeclarationForLinker(), "Alias must point to a definition",
896 if (const auto *GA2
= dyn_cast
<GlobalAlias
>(GV
)) {
897 Check(Visited
.insert(GA2
).second
, "Aliases cannot form a cycle", &GA
);
899 Check(!GA2
->isInterposable(),
900 "Alias cannot point to an interposable alias", &GA
);
902 // Only continue verifying subexpressions of GlobalAliases.
903 // Do not recurse into global initializers.
908 if (const auto *CE
= dyn_cast
<ConstantExpr
>(&C
))
909 visitConstantExprsRecursively(CE
);
911 for (const Use
&U
: C
.operands()) {
913 if (const auto *GA2
= dyn_cast
<GlobalAlias
>(V
))
914 visitAliaseeSubExpr(Visited
, GA
, *GA2
->getAliasee());
915 else if (const auto *C2
= dyn_cast
<Constant
>(V
))
916 visitAliaseeSubExpr(Visited
, GA
, *C2
);
920 void Verifier::visitGlobalAlias(const GlobalAlias
&GA
) {
921 Check(GlobalAlias::isValidLinkage(GA
.getLinkage()),
922 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
923 "weak_odr, external, or available_externally linkage!",
925 const Constant
*Aliasee
= GA
.getAliasee();
926 Check(Aliasee
, "Aliasee cannot be NULL!", &GA
);
927 Check(GA
.getType() == Aliasee
->getType(),
928 "Alias and aliasee types should match!", &GA
);
930 Check(isa
<GlobalValue
>(Aliasee
) || isa
<ConstantExpr
>(Aliasee
),
931 "Aliasee should be either GlobalValue or ConstantExpr", &GA
);
933 visitAliaseeSubExpr(GA
, *Aliasee
);
935 visitGlobalValue(GA
);
938 void Verifier::visitGlobalIFunc(const GlobalIFunc
&GI
) {
939 Check(GlobalIFunc::isValidLinkage(GI
.getLinkage()),
940 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
941 "weak_odr, or external linkage!",
943 // Pierce through ConstantExprs and GlobalAliases and check that the resolver
944 // is a Function definition.
945 const Function
*Resolver
= GI
.getResolverFunction();
946 Check(Resolver
, "IFunc must have a Function resolver", &GI
);
947 Check(!Resolver
->isDeclarationForLinker(),
948 "IFunc resolver must be a definition", &GI
);
950 // Check that the immediate resolver operand (prior to any bitcasts) has the
952 const Type
*ResolverTy
= GI
.getResolver()->getType();
954 Check(isa
<PointerType
>(Resolver
->getFunctionType()->getReturnType()),
955 "IFunc resolver must return a pointer", &GI
);
957 const Type
*ResolverFuncTy
=
958 GlobalIFunc::getResolverFunctionType(GI
.getValueType());
959 Check(ResolverTy
== ResolverFuncTy
->getPointerTo(GI
.getAddressSpace()),
960 "IFunc resolver has incorrect type", &GI
);
963 void Verifier::visitNamedMDNode(const NamedMDNode
&NMD
) {
964 // There used to be various other llvm.dbg.* nodes, but we don't support
965 // upgrading them and we want to reserve the namespace for future uses.
966 if (NMD
.getName().startswith("llvm.dbg."))
967 CheckDI(NMD
.getName() == "llvm.dbg.cu",
968 "unrecognized named metadata node in the llvm.dbg namespace", &NMD
);
969 for (const MDNode
*MD
: NMD
.operands()) {
970 if (NMD
.getName() == "llvm.dbg.cu")
971 CheckDI(MD
&& isa
<DICompileUnit
>(MD
), "invalid compile unit", &NMD
, MD
);
976 visitMDNode(*MD
, AreDebugLocsAllowed::Yes
);
980 void Verifier::visitMDNode(const MDNode
&MD
, AreDebugLocsAllowed AllowLocs
) {
981 // Only visit each node once. Metadata can be mutually recursive, so this
982 // avoids infinite recursion here, as well as being an optimization.
983 if (!MDNodes
.insert(&MD
).second
)
986 Check(&MD
.getContext() == &Context
,
987 "MDNode context does not match Module context!", &MD
);
989 switch (MD
.getMetadataID()) {
991 llvm_unreachable("Invalid MDNode subclass");
992 case Metadata::MDTupleKind
:
994 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
995 case Metadata::CLASS##Kind: \
996 visit##CLASS(cast<CLASS>(MD)); \
998 #include "llvm/IR/Metadata.def"
1001 for (const Metadata
*Op
: MD
.operands()) {
1004 Check(!isa
<LocalAsMetadata
>(Op
), "Invalid operand for global metadata!",
1006 CheckDI(!isa
<DILocation
>(Op
) || AllowLocs
== AreDebugLocsAllowed::Yes
,
1007 "DILocation not allowed within this metadata node", &MD
, Op
);
1008 if (auto *N
= dyn_cast
<MDNode
>(Op
)) {
1009 visitMDNode(*N
, AllowLocs
);
1012 if (auto *V
= dyn_cast
<ValueAsMetadata
>(Op
)) {
1013 visitValueAsMetadata(*V
, nullptr);
1018 // Check these last, so we diagnose problems in operands first.
1019 Check(!MD
.isTemporary(), "Expected no forward declarations!", &MD
);
1020 Check(MD
.isResolved(), "All nodes should be resolved!", &MD
);
1023 void Verifier::visitValueAsMetadata(const ValueAsMetadata
&MD
, Function
*F
) {
1024 Check(MD
.getValue(), "Expected valid value", &MD
);
1025 Check(!MD
.getValue()->getType()->isMetadataTy(),
1026 "Unexpected metadata round-trip through values", &MD
, MD
.getValue());
1028 auto *L
= dyn_cast
<LocalAsMetadata
>(&MD
);
1032 Check(F
, "function-local metadata used outside a function", L
);
1034 // If this was an instruction, bb, or argument, verify that it is in the
1035 // function that we expect.
1036 Function
*ActualF
= nullptr;
1037 if (Instruction
*I
= dyn_cast
<Instruction
>(L
->getValue())) {
1038 Check(I
->getParent(), "function-local metadata not in basic block", L
, I
);
1039 ActualF
= I
->getParent()->getParent();
1040 } else if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(L
->getValue()))
1041 ActualF
= BB
->getParent();
1042 else if (Argument
*A
= dyn_cast
<Argument
>(L
->getValue()))
1043 ActualF
= A
->getParent();
1044 assert(ActualF
&& "Unimplemented function local metadata case!");
1046 Check(ActualF
== F
, "function-local metadata used in wrong function", L
);
1049 void Verifier::visitMetadataAsValue(const MetadataAsValue
&MDV
, Function
*F
) {
1050 Metadata
*MD
= MDV
.getMetadata();
1051 if (auto *N
= dyn_cast
<MDNode
>(MD
)) {
1052 visitMDNode(*N
, AreDebugLocsAllowed::No
);
1056 // Only visit each node once. Metadata can be mutually recursive, so this
1057 // avoids infinite recursion here, as well as being an optimization.
1058 if (!MDNodes
.insert(MD
).second
)
1061 if (auto *V
= dyn_cast
<ValueAsMetadata
>(MD
))
1062 visitValueAsMetadata(*V
, F
);
1065 static bool isType(const Metadata
*MD
) { return !MD
|| isa
<DIType
>(MD
); }
1066 static bool isScope(const Metadata
*MD
) { return !MD
|| isa
<DIScope
>(MD
); }
1067 static bool isDINode(const Metadata
*MD
) { return !MD
|| isa
<DINode
>(MD
); }
1069 void Verifier::visitDILocation(const DILocation
&N
) {
1070 CheckDI(N
.getRawScope() && isa
<DILocalScope
>(N
.getRawScope()),
1071 "location requires a valid scope", &N
, N
.getRawScope());
1072 if (auto *IA
= N
.getRawInlinedAt())
1073 CheckDI(isa
<DILocation
>(IA
), "inlined-at should be a location", &N
, IA
);
1074 if (auto *SP
= dyn_cast
<DISubprogram
>(N
.getRawScope()))
1075 CheckDI(SP
->isDefinition(), "scope points into the type hierarchy", &N
);
1078 void Verifier::visitGenericDINode(const GenericDINode
&N
) {
1079 CheckDI(N
.getTag(), "invalid tag", &N
);
1082 void Verifier::visitDIScope(const DIScope
&N
) {
1083 if (auto *F
= N
.getRawFile())
1084 CheckDI(isa
<DIFile
>(F
), "invalid file", &N
, F
);
1087 void Verifier::visitDISubrange(const DISubrange
&N
) {
1088 CheckDI(N
.getTag() == dwarf::DW_TAG_subrange_type
, "invalid tag", &N
);
1089 bool HasAssumedSizedArraySupport
= dwarf::isFortran(CurrentSourceLang
);
1090 CheckDI(HasAssumedSizedArraySupport
|| N
.getRawCountNode() ||
1091 N
.getRawUpperBound(),
1092 "Subrange must contain count or upperBound", &N
);
1093 CheckDI(!N
.getRawCountNode() || !N
.getRawUpperBound(),
1094 "Subrange can have any one of count or upperBound", &N
);
1095 auto *CBound
= N
.getRawCountNode();
1096 CheckDI(!CBound
|| isa
<ConstantAsMetadata
>(CBound
) ||
1097 isa
<DIVariable
>(CBound
) || isa
<DIExpression
>(CBound
),
1098 "Count must be signed constant or DIVariable or DIExpression", &N
);
1099 auto Count
= N
.getCount();
1100 CheckDI(!Count
|| !isa
<ConstantInt
*>(Count
) ||
1101 cast
<ConstantInt
*>(Count
)->getSExtValue() >= -1,
1102 "invalid subrange count", &N
);
1103 auto *LBound
= N
.getRawLowerBound();
1104 CheckDI(!LBound
|| isa
<ConstantAsMetadata
>(LBound
) ||
1105 isa
<DIVariable
>(LBound
) || isa
<DIExpression
>(LBound
),
1106 "LowerBound must be signed constant or DIVariable or DIExpression",
1108 auto *UBound
= N
.getRawUpperBound();
1109 CheckDI(!UBound
|| isa
<ConstantAsMetadata
>(UBound
) ||
1110 isa
<DIVariable
>(UBound
) || isa
<DIExpression
>(UBound
),
1111 "UpperBound must be signed constant or DIVariable or DIExpression",
1113 auto *Stride
= N
.getRawStride();
1114 CheckDI(!Stride
|| isa
<ConstantAsMetadata
>(Stride
) ||
1115 isa
<DIVariable
>(Stride
) || isa
<DIExpression
>(Stride
),
1116 "Stride must be signed constant or DIVariable or DIExpression", &N
);
1119 void Verifier::visitDIGenericSubrange(const DIGenericSubrange
&N
) {
1120 CheckDI(N
.getTag() == dwarf::DW_TAG_generic_subrange
, "invalid tag", &N
);
1121 CheckDI(N
.getRawCountNode() || N
.getRawUpperBound(),
1122 "GenericSubrange must contain count or upperBound", &N
);
1123 CheckDI(!N
.getRawCountNode() || !N
.getRawUpperBound(),
1124 "GenericSubrange can have any one of count or upperBound", &N
);
1125 auto *CBound
= N
.getRawCountNode();
1126 CheckDI(!CBound
|| isa
<DIVariable
>(CBound
) || isa
<DIExpression
>(CBound
),
1127 "Count must be signed constant or DIVariable or DIExpression", &N
);
1128 auto *LBound
= N
.getRawLowerBound();
1129 CheckDI(LBound
, "GenericSubrange must contain lowerBound", &N
);
1130 CheckDI(isa
<DIVariable
>(LBound
) || isa
<DIExpression
>(LBound
),
1131 "LowerBound must be signed constant or DIVariable or DIExpression",
1133 auto *UBound
= N
.getRawUpperBound();
1134 CheckDI(!UBound
|| isa
<DIVariable
>(UBound
) || isa
<DIExpression
>(UBound
),
1135 "UpperBound must be signed constant or DIVariable or DIExpression",
1137 auto *Stride
= N
.getRawStride();
1138 CheckDI(Stride
, "GenericSubrange must contain stride", &N
);
1139 CheckDI(isa
<DIVariable
>(Stride
) || isa
<DIExpression
>(Stride
),
1140 "Stride must be signed constant or DIVariable or DIExpression", &N
);
1143 void Verifier::visitDIEnumerator(const DIEnumerator
&N
) {
1144 CheckDI(N
.getTag() == dwarf::DW_TAG_enumerator
, "invalid tag", &N
);
1147 void Verifier::visitDIBasicType(const DIBasicType
&N
) {
1148 CheckDI(N
.getTag() == dwarf::DW_TAG_base_type
||
1149 N
.getTag() == dwarf::DW_TAG_unspecified_type
||
1150 N
.getTag() == dwarf::DW_TAG_string_type
,
1154 void Verifier::visitDIStringType(const DIStringType
&N
) {
1155 CheckDI(N
.getTag() == dwarf::DW_TAG_string_type
, "invalid tag", &N
);
1156 CheckDI(!(N
.isBigEndian() && N
.isLittleEndian()), "has conflicting flags",
1160 void Verifier::visitDIDerivedType(const DIDerivedType
&N
) {
1161 // Common scope checks.
1164 CheckDI(N
.getTag() == dwarf::DW_TAG_typedef
||
1165 N
.getTag() == dwarf::DW_TAG_pointer_type
||
1166 N
.getTag() == dwarf::DW_TAG_ptr_to_member_type
||
1167 N
.getTag() == dwarf::DW_TAG_reference_type
||
1168 N
.getTag() == dwarf::DW_TAG_rvalue_reference_type
||
1169 N
.getTag() == dwarf::DW_TAG_const_type
||
1170 N
.getTag() == dwarf::DW_TAG_immutable_type
||
1171 N
.getTag() == dwarf::DW_TAG_volatile_type
||
1172 N
.getTag() == dwarf::DW_TAG_restrict_type
||
1173 N
.getTag() == dwarf::DW_TAG_atomic_type
||
1174 N
.getTag() == dwarf::DW_TAG_member
||
1175 N
.getTag() == dwarf::DW_TAG_inheritance
||
1176 N
.getTag() == dwarf::DW_TAG_friend
||
1177 N
.getTag() == dwarf::DW_TAG_set_type
,
1179 if (N
.getTag() == dwarf::DW_TAG_ptr_to_member_type
) {
1180 CheckDI(isType(N
.getRawExtraData()), "invalid pointer to member type", &N
,
1181 N
.getRawExtraData());
1184 if (N
.getTag() == dwarf::DW_TAG_set_type
) {
1185 if (auto *T
= N
.getRawBaseType()) {
1186 auto *Enum
= dyn_cast_or_null
<DICompositeType
>(T
);
1187 auto *Basic
= dyn_cast_or_null
<DIBasicType
>(T
);
1189 (Enum
&& Enum
->getTag() == dwarf::DW_TAG_enumeration_type
) ||
1190 (Basic
&& (Basic
->getEncoding() == dwarf::DW_ATE_unsigned
||
1191 Basic
->getEncoding() == dwarf::DW_ATE_signed
||
1192 Basic
->getEncoding() == dwarf::DW_ATE_unsigned_char
||
1193 Basic
->getEncoding() == dwarf::DW_ATE_signed_char
||
1194 Basic
->getEncoding() == dwarf::DW_ATE_boolean
)),
1195 "invalid set base type", &N
, T
);
1199 CheckDI(isScope(N
.getRawScope()), "invalid scope", &N
, N
.getRawScope());
1200 CheckDI(isType(N
.getRawBaseType()), "invalid base type", &N
,
1201 N
.getRawBaseType());
1203 if (N
.getDWARFAddressSpace()) {
1204 CheckDI(N
.getTag() == dwarf::DW_TAG_pointer_type
||
1205 N
.getTag() == dwarf::DW_TAG_reference_type
||
1206 N
.getTag() == dwarf::DW_TAG_rvalue_reference_type
,
1207 "DWARF address space only applies to pointer or reference types",
1212 /// Detect mutually exclusive flags.
1213 static bool hasConflictingReferenceFlags(unsigned Flags
) {
1214 return ((Flags
& DINode::FlagLValueReference
) &&
1215 (Flags
& DINode::FlagRValueReference
)) ||
1216 ((Flags
& DINode::FlagTypePassByValue
) &&
1217 (Flags
& DINode::FlagTypePassByReference
));
1220 void Verifier::visitTemplateParams(const MDNode
&N
, const Metadata
&RawParams
) {
1221 auto *Params
= dyn_cast
<MDTuple
>(&RawParams
);
1222 CheckDI(Params
, "invalid template params", &N
, &RawParams
);
1223 for (Metadata
*Op
: Params
->operands()) {
1224 CheckDI(Op
&& isa
<DITemplateParameter
>(Op
), "invalid template parameter",
1229 void Verifier::visitDICompositeType(const DICompositeType
&N
) {
1230 // Common scope checks.
1233 CheckDI(N
.getTag() == dwarf::DW_TAG_array_type
||
1234 N
.getTag() == dwarf::DW_TAG_structure_type
||
1235 N
.getTag() == dwarf::DW_TAG_union_type
||
1236 N
.getTag() == dwarf::DW_TAG_enumeration_type
||
1237 N
.getTag() == dwarf::DW_TAG_class_type
||
1238 N
.getTag() == dwarf::DW_TAG_variant_part
||
1239 N
.getTag() == dwarf::DW_TAG_namelist
,
1242 CheckDI(isScope(N
.getRawScope()), "invalid scope", &N
, N
.getRawScope());
1243 CheckDI(isType(N
.getRawBaseType()), "invalid base type", &N
,
1244 N
.getRawBaseType());
1246 CheckDI(!N
.getRawElements() || isa
<MDTuple
>(N
.getRawElements()),
1247 "invalid composite elements", &N
, N
.getRawElements());
1248 CheckDI(isType(N
.getRawVTableHolder()), "invalid vtable holder", &N
,
1249 N
.getRawVTableHolder());
1250 CheckDI(!hasConflictingReferenceFlags(N
.getFlags()),
1251 "invalid reference flags", &N
);
1252 unsigned DIBlockByRefStruct
= 1 << 4;
1253 CheckDI((N
.getFlags() & DIBlockByRefStruct
) == 0,
1254 "DIBlockByRefStruct on DICompositeType is no longer supported", &N
);
1257 const DINodeArray Elements
= N
.getElements();
1258 CheckDI(Elements
.size() == 1 &&
1259 Elements
[0]->getTag() == dwarf::DW_TAG_subrange_type
,
1260 "invalid vector, expected one element of type subrange", &N
);
1263 if (auto *Params
= N
.getRawTemplateParams())
1264 visitTemplateParams(N
, *Params
);
1266 if (auto *D
= N
.getRawDiscriminator()) {
1267 CheckDI(isa
<DIDerivedType
>(D
) && N
.getTag() == dwarf::DW_TAG_variant_part
,
1268 "discriminator can only appear on variant part");
1271 if (N
.getRawDataLocation()) {
1272 CheckDI(N
.getTag() == dwarf::DW_TAG_array_type
,
1273 "dataLocation can only appear in array type");
1276 if (N
.getRawAssociated()) {
1277 CheckDI(N
.getTag() == dwarf::DW_TAG_array_type
,
1278 "associated can only appear in array type");
1281 if (N
.getRawAllocated()) {
1282 CheckDI(N
.getTag() == dwarf::DW_TAG_array_type
,
1283 "allocated can only appear in array type");
1286 if (N
.getRawRank()) {
1287 CheckDI(N
.getTag() == dwarf::DW_TAG_array_type
,
1288 "rank can only appear in array type");
1292 void Verifier::visitDISubroutineType(const DISubroutineType
&N
) {
1293 CheckDI(N
.getTag() == dwarf::DW_TAG_subroutine_type
, "invalid tag", &N
);
1294 if (auto *Types
= N
.getRawTypeArray()) {
1295 CheckDI(isa
<MDTuple
>(Types
), "invalid composite elements", &N
, Types
);
1296 for (Metadata
*Ty
: N
.getTypeArray()->operands()) {
1297 CheckDI(isType(Ty
), "invalid subroutine type ref", &N
, Types
, Ty
);
1300 CheckDI(!hasConflictingReferenceFlags(N
.getFlags()),
1301 "invalid reference flags", &N
);
1304 void Verifier::visitDIFile(const DIFile
&N
) {
1305 CheckDI(N
.getTag() == dwarf::DW_TAG_file_type
, "invalid tag", &N
);
1306 std::optional
<DIFile::ChecksumInfo
<StringRef
>> Checksum
= N
.getChecksum();
1308 CheckDI(Checksum
->Kind
<= DIFile::ChecksumKind::CSK_Last
,
1309 "invalid checksum kind", &N
);
1311 switch (Checksum
->Kind
) {
1312 case DIFile::CSK_MD5
:
1315 case DIFile::CSK_SHA1
:
1318 case DIFile::CSK_SHA256
:
1322 CheckDI(Checksum
->Value
.size() == Size
, "invalid checksum length", &N
);
1323 CheckDI(Checksum
->Value
.find_if_not(llvm::isHexDigit
) == StringRef::npos
,
1324 "invalid checksum", &N
);
1328 void Verifier::visitDICompileUnit(const DICompileUnit
&N
) {
1329 CheckDI(N
.isDistinct(), "compile units must be distinct", &N
);
1330 CheckDI(N
.getTag() == dwarf::DW_TAG_compile_unit
, "invalid tag", &N
);
1332 // Don't bother verifying the compilation directory or producer string
1333 // as those could be empty.
1334 CheckDI(N
.getRawFile() && isa
<DIFile
>(N
.getRawFile()), "invalid file", &N
,
1336 CheckDI(!N
.getFile()->getFilename().empty(), "invalid filename", &N
,
1339 CurrentSourceLang
= (dwarf::SourceLanguage
)N
.getSourceLanguage();
1341 verifySourceDebugInfo(N
, *N
.getFile());
1343 CheckDI((N
.getEmissionKind() <= DICompileUnit::LastEmissionKind
),
1344 "invalid emission kind", &N
);
1346 if (auto *Array
= N
.getRawEnumTypes()) {
1347 CheckDI(isa
<MDTuple
>(Array
), "invalid enum list", &N
, Array
);
1348 for (Metadata
*Op
: N
.getEnumTypes()->operands()) {
1349 auto *Enum
= dyn_cast_or_null
<DICompositeType
>(Op
);
1350 CheckDI(Enum
&& Enum
->getTag() == dwarf::DW_TAG_enumeration_type
,
1351 "invalid enum type", &N
, N
.getEnumTypes(), Op
);
1354 if (auto *Array
= N
.getRawRetainedTypes()) {
1355 CheckDI(isa
<MDTuple
>(Array
), "invalid retained type list", &N
, Array
);
1356 for (Metadata
*Op
: N
.getRetainedTypes()->operands()) {
1358 Op
&& (isa
<DIType
>(Op
) || (isa
<DISubprogram
>(Op
) &&
1359 !cast
<DISubprogram
>(Op
)->isDefinition())),
1360 "invalid retained type", &N
, Op
);
1363 if (auto *Array
= N
.getRawGlobalVariables()) {
1364 CheckDI(isa
<MDTuple
>(Array
), "invalid global variable list", &N
, Array
);
1365 for (Metadata
*Op
: N
.getGlobalVariables()->operands()) {
1366 CheckDI(Op
&& (isa
<DIGlobalVariableExpression
>(Op
)),
1367 "invalid global variable ref", &N
, Op
);
1370 if (auto *Array
= N
.getRawImportedEntities()) {
1371 CheckDI(isa
<MDTuple
>(Array
), "invalid imported entity list", &N
, Array
);
1372 for (Metadata
*Op
: N
.getImportedEntities()->operands()) {
1373 CheckDI(Op
&& isa
<DIImportedEntity
>(Op
), "invalid imported entity ref",
1377 if (auto *Array
= N
.getRawMacros()) {
1378 CheckDI(isa
<MDTuple
>(Array
), "invalid macro list", &N
, Array
);
1379 for (Metadata
*Op
: N
.getMacros()->operands()) {
1380 CheckDI(Op
&& isa
<DIMacroNode
>(Op
), "invalid macro ref", &N
, Op
);
1383 CUVisited
.insert(&N
);
1386 void Verifier::visitDISubprogram(const DISubprogram
&N
) {
1387 CheckDI(N
.getTag() == dwarf::DW_TAG_subprogram
, "invalid tag", &N
);
1388 CheckDI(isScope(N
.getRawScope()), "invalid scope", &N
, N
.getRawScope());
1389 if (auto *F
= N
.getRawFile())
1390 CheckDI(isa
<DIFile
>(F
), "invalid file", &N
, F
);
1392 CheckDI(N
.getLine() == 0, "line specified with no file", &N
, N
.getLine());
1393 if (auto *T
= N
.getRawType())
1394 CheckDI(isa
<DISubroutineType
>(T
), "invalid subroutine type", &N
, T
);
1395 CheckDI(isType(N
.getRawContainingType()), "invalid containing type", &N
,
1396 N
.getRawContainingType());
1397 if (auto *Params
= N
.getRawTemplateParams())
1398 visitTemplateParams(N
, *Params
);
1399 if (auto *S
= N
.getRawDeclaration())
1400 CheckDI(isa
<DISubprogram
>(S
) && !cast
<DISubprogram
>(S
)->isDefinition(),
1401 "invalid subprogram declaration", &N
, S
);
1402 if (auto *RawNode
= N
.getRawRetainedNodes()) {
1403 auto *Node
= dyn_cast
<MDTuple
>(RawNode
);
1404 CheckDI(Node
, "invalid retained nodes list", &N
, RawNode
);
1405 for (Metadata
*Op
: Node
->operands()) {
1406 CheckDI(Op
&& (isa
<DILocalVariable
>(Op
) || isa
<DILabel
>(Op
) ||
1407 isa
<DIImportedEntity
>(Op
)),
1408 "invalid retained nodes, expected DILocalVariable, DILabel or "
1413 CheckDI(!hasConflictingReferenceFlags(N
.getFlags()),
1414 "invalid reference flags", &N
);
1416 auto *Unit
= N
.getRawUnit();
1417 if (N
.isDefinition()) {
1418 // Subprogram definitions (not part of the type hierarchy).
1419 CheckDI(N
.isDistinct(), "subprogram definitions must be distinct", &N
);
1420 CheckDI(Unit
, "subprogram definitions must have a compile unit", &N
);
1421 CheckDI(isa
<DICompileUnit
>(Unit
), "invalid unit type", &N
, Unit
);
1422 // There's no good way to cross the CU boundary to insert a nested
1423 // DISubprogram definition in one CU into a type defined in another CU.
1424 auto *CT
= dyn_cast_or_null
<DICompositeType
>(N
.getRawScope());
1425 if (CT
&& CT
->getRawIdentifier() &&
1426 M
.getContext().isODRUniquingDebugTypes())
1427 CheckDI(N
.getDeclaration(),
1428 "definition subprograms cannot be nested within DICompositeType "
1429 "when enabling ODR",
1432 verifySourceDebugInfo(*N
.getUnit(), *N
.getFile());
1434 // Subprogram declarations (part of the type hierarchy).
1435 CheckDI(!Unit
, "subprogram declarations must not have a compile unit", &N
);
1436 CheckDI(!N
.getRawDeclaration(),
1437 "subprogram declaration must not have a declaration field");
1440 if (auto *RawThrownTypes
= N
.getRawThrownTypes()) {
1441 auto *ThrownTypes
= dyn_cast
<MDTuple
>(RawThrownTypes
);
1442 CheckDI(ThrownTypes
, "invalid thrown types list", &N
, RawThrownTypes
);
1443 for (Metadata
*Op
: ThrownTypes
->operands())
1444 CheckDI(Op
&& isa
<DIType
>(Op
), "invalid thrown type", &N
, ThrownTypes
,
1448 if (N
.areAllCallsDescribed())
1449 CheckDI(N
.isDefinition(),
1450 "DIFlagAllCallsDescribed must be attached to a definition");
1453 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase
&N
) {
1454 CheckDI(N
.getTag() == dwarf::DW_TAG_lexical_block
, "invalid tag", &N
);
1455 CheckDI(N
.getRawScope() && isa
<DILocalScope
>(N
.getRawScope()),
1456 "invalid local scope", &N
, N
.getRawScope());
1457 if (auto *SP
= dyn_cast
<DISubprogram
>(N
.getRawScope()))
1458 CheckDI(SP
->isDefinition(), "scope points into the type hierarchy", &N
);
1461 void Verifier::visitDILexicalBlock(const DILexicalBlock
&N
) {
1462 visitDILexicalBlockBase(N
);
1464 CheckDI(N
.getLine() || !N
.getColumn(),
1465 "cannot have column info without line info", &N
);
1468 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile
&N
) {
1469 visitDILexicalBlockBase(N
);
1472 void Verifier::visitDICommonBlock(const DICommonBlock
&N
) {
1473 CheckDI(N
.getTag() == dwarf::DW_TAG_common_block
, "invalid tag", &N
);
1474 if (auto *S
= N
.getRawScope())
1475 CheckDI(isa
<DIScope
>(S
), "invalid scope ref", &N
, S
);
1476 if (auto *S
= N
.getRawDecl())
1477 CheckDI(isa
<DIGlobalVariable
>(S
), "invalid declaration", &N
, S
);
1480 void Verifier::visitDINamespace(const DINamespace
&N
) {
1481 CheckDI(N
.getTag() == dwarf::DW_TAG_namespace
, "invalid tag", &N
);
1482 if (auto *S
= N
.getRawScope())
1483 CheckDI(isa
<DIScope
>(S
), "invalid scope ref", &N
, S
);
1486 void Verifier::visitDIMacro(const DIMacro
&N
) {
1487 CheckDI(N
.getMacinfoType() == dwarf::DW_MACINFO_define
||
1488 N
.getMacinfoType() == dwarf::DW_MACINFO_undef
,
1489 "invalid macinfo type", &N
);
1490 CheckDI(!N
.getName().empty(), "anonymous macro", &N
);
1491 if (!N
.getValue().empty()) {
1492 assert(N
.getValue().data()[0] != ' ' && "Macro value has a space prefix");
1496 void Verifier::visitDIMacroFile(const DIMacroFile
&N
) {
1497 CheckDI(N
.getMacinfoType() == dwarf::DW_MACINFO_start_file
,
1498 "invalid macinfo type", &N
);
1499 if (auto *F
= N
.getRawFile())
1500 CheckDI(isa
<DIFile
>(F
), "invalid file", &N
, F
);
1502 if (auto *Array
= N
.getRawElements()) {
1503 CheckDI(isa
<MDTuple
>(Array
), "invalid macro list", &N
, Array
);
1504 for (Metadata
*Op
: N
.getElements()->operands()) {
1505 CheckDI(Op
&& isa
<DIMacroNode
>(Op
), "invalid macro ref", &N
, Op
);
1510 void Verifier::visitDIArgList(const DIArgList
&N
) {
1511 CheckDI(!N
.getNumOperands(),
1512 "DIArgList should have no operands other than a list of "
1517 void Verifier::visitDIModule(const DIModule
&N
) {
1518 CheckDI(N
.getTag() == dwarf::DW_TAG_module
, "invalid tag", &N
);
1519 CheckDI(!N
.getName().empty(), "anonymous module", &N
);
1522 void Verifier::visitDITemplateParameter(const DITemplateParameter
&N
) {
1523 CheckDI(isType(N
.getRawType()), "invalid type ref", &N
, N
.getRawType());
1526 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter
&N
) {
1527 visitDITemplateParameter(N
);
1529 CheckDI(N
.getTag() == dwarf::DW_TAG_template_type_parameter
, "invalid tag",
1533 void Verifier::visitDITemplateValueParameter(
1534 const DITemplateValueParameter
&N
) {
1535 visitDITemplateParameter(N
);
1537 CheckDI(N
.getTag() == dwarf::DW_TAG_template_value_parameter
||
1538 N
.getTag() == dwarf::DW_TAG_GNU_template_template_param
||
1539 N
.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack
,
1543 void Verifier::visitDIVariable(const DIVariable
&N
) {
1544 if (auto *S
= N
.getRawScope())
1545 CheckDI(isa
<DIScope
>(S
), "invalid scope", &N
, S
);
1546 if (auto *F
= N
.getRawFile())
1547 CheckDI(isa
<DIFile
>(F
), "invalid file", &N
, F
);
1550 void Verifier::visitDIGlobalVariable(const DIGlobalVariable
&N
) {
1551 // Checks common to all variables.
1554 CheckDI(N
.getTag() == dwarf::DW_TAG_variable
, "invalid tag", &N
);
1555 CheckDI(isType(N
.getRawType()), "invalid type ref", &N
, N
.getRawType());
1556 // Check only if the global variable is not an extern
1557 if (N
.isDefinition())
1558 CheckDI(N
.getType(), "missing global variable type", &N
);
1559 if (auto *Member
= N
.getRawStaticDataMemberDeclaration()) {
1560 CheckDI(isa
<DIDerivedType
>(Member
),
1561 "invalid static data member declaration", &N
, Member
);
1565 void Verifier::visitDILocalVariable(const DILocalVariable
&N
) {
1566 // Checks common to all variables.
1569 CheckDI(isType(N
.getRawType()), "invalid type ref", &N
, N
.getRawType());
1570 CheckDI(N
.getTag() == dwarf::DW_TAG_variable
, "invalid tag", &N
);
1571 CheckDI(N
.getRawScope() && isa
<DILocalScope
>(N
.getRawScope()),
1572 "local variable requires a valid scope", &N
, N
.getRawScope());
1573 if (auto Ty
= N
.getType())
1574 CheckDI(!isa
<DISubroutineType
>(Ty
), "invalid type", &N
, N
.getType());
1577 void Verifier::visitDIAssignID(const DIAssignID
&N
) {
1578 CheckDI(!N
.getNumOperands(), "DIAssignID has no arguments", &N
);
1579 CheckDI(N
.isDistinct(), "DIAssignID must be distinct", &N
);
1582 void Verifier::visitDILabel(const DILabel
&N
) {
1583 if (auto *S
= N
.getRawScope())
1584 CheckDI(isa
<DIScope
>(S
), "invalid scope", &N
, S
);
1585 if (auto *F
= N
.getRawFile())
1586 CheckDI(isa
<DIFile
>(F
), "invalid file", &N
, F
);
1588 CheckDI(N
.getTag() == dwarf::DW_TAG_label
, "invalid tag", &N
);
1589 CheckDI(N
.getRawScope() && isa
<DILocalScope
>(N
.getRawScope()),
1590 "label requires a valid scope", &N
, N
.getRawScope());
1593 void Verifier::visitDIExpression(const DIExpression
&N
) {
1594 CheckDI(N
.isValid(), "invalid expression", &N
);
1597 void Verifier::visitDIGlobalVariableExpression(
1598 const DIGlobalVariableExpression
&GVE
) {
1599 CheckDI(GVE
.getVariable(), "missing variable");
1600 if (auto *Var
= GVE
.getVariable())
1601 visitDIGlobalVariable(*Var
);
1602 if (auto *Expr
= GVE
.getExpression()) {
1603 visitDIExpression(*Expr
);
1604 if (auto Fragment
= Expr
->getFragmentInfo())
1605 verifyFragmentExpression(*GVE
.getVariable(), *Fragment
, &GVE
);
1609 void Verifier::visitDIObjCProperty(const DIObjCProperty
&N
) {
1610 CheckDI(N
.getTag() == dwarf::DW_TAG_APPLE_property
, "invalid tag", &N
);
1611 if (auto *T
= N
.getRawType())
1612 CheckDI(isType(T
), "invalid type ref", &N
, T
);
1613 if (auto *F
= N
.getRawFile())
1614 CheckDI(isa
<DIFile
>(F
), "invalid file", &N
, F
);
1617 void Verifier::visitDIImportedEntity(const DIImportedEntity
&N
) {
1618 CheckDI(N
.getTag() == dwarf::DW_TAG_imported_module
||
1619 N
.getTag() == dwarf::DW_TAG_imported_declaration
,
1621 if (auto *S
= N
.getRawScope())
1622 CheckDI(isa
<DIScope
>(S
), "invalid scope for imported entity", &N
, S
);
1623 CheckDI(isDINode(N
.getRawEntity()), "invalid imported entity", &N
,
1627 void Verifier::visitComdat(const Comdat
&C
) {
1628 // In COFF the Module is invalid if the GlobalValue has private linkage.
1629 // Entities with private linkage don't have entries in the symbol table.
1630 if (TT
.isOSBinFormatCOFF())
1631 if (const GlobalValue
*GV
= M
.getNamedValue(C
.getName()))
1632 Check(!GV
->hasPrivateLinkage(), "comdat global value has private linkage",
1636 void Verifier::visitModuleIdents() {
1637 const NamedMDNode
*Idents
= M
.getNamedMetadata("llvm.ident");
1641 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1642 // Scan each llvm.ident entry and make sure that this requirement is met.
1643 for (const MDNode
*N
: Idents
->operands()) {
1644 Check(N
->getNumOperands() == 1,
1645 "incorrect number of operands in llvm.ident metadata", N
);
1646 Check(dyn_cast_or_null
<MDString
>(N
->getOperand(0)),
1647 ("invalid value for llvm.ident metadata entry operand"
1648 "(the operand should be a string)"),
1653 void Verifier::visitModuleCommandLines() {
1654 const NamedMDNode
*CommandLines
= M
.getNamedMetadata("llvm.commandline");
1658 // llvm.commandline takes a list of metadata entry. Each entry has only one
1659 // string. Scan each llvm.commandline entry and make sure that this
1660 // requirement is met.
1661 for (const MDNode
*N
: CommandLines
->operands()) {
1662 Check(N
->getNumOperands() == 1,
1663 "incorrect number of operands in llvm.commandline metadata", N
);
1664 Check(dyn_cast_or_null
<MDString
>(N
->getOperand(0)),
1665 ("invalid value for llvm.commandline metadata entry operand"
1666 "(the operand should be a string)"),
1671 void Verifier::visitModuleFlags() {
1672 const NamedMDNode
*Flags
= M
.getModuleFlagsMetadata();
1675 // Scan each flag, and track the flags and requirements.
1676 DenseMap
<const MDString
*, const MDNode
*> SeenIDs
;
1677 SmallVector
<const MDNode
*, 16> Requirements
;
1678 for (const MDNode
*MDN
: Flags
->operands())
1679 visitModuleFlag(MDN
, SeenIDs
, Requirements
);
1681 // Validate that the requirements in the module are valid.
1682 for (const MDNode
*Requirement
: Requirements
) {
1683 const MDString
*Flag
= cast
<MDString
>(Requirement
->getOperand(0));
1684 const Metadata
*ReqValue
= Requirement
->getOperand(1);
1686 const MDNode
*Op
= SeenIDs
.lookup(Flag
);
1688 CheckFailed("invalid requirement on flag, flag is not present in module",
1693 if (Op
->getOperand(2) != ReqValue
) {
1694 CheckFailed(("invalid requirement on flag, "
1695 "flag does not have the required value"),
1703 Verifier::visitModuleFlag(const MDNode
*Op
,
1704 DenseMap
<const MDString
*, const MDNode
*> &SeenIDs
,
1705 SmallVectorImpl
<const MDNode
*> &Requirements
) {
1706 // Each module flag should have three arguments, the merge behavior (a
1707 // constant int), the flag ID (an MDString), and the value.
1708 Check(Op
->getNumOperands() == 3,
1709 "incorrect number of operands in module flag", Op
);
1710 Module::ModFlagBehavior MFB
;
1711 if (!Module::isValidModFlagBehavior(Op
->getOperand(0), MFB
)) {
1712 Check(mdconst::dyn_extract_or_null
<ConstantInt
>(Op
->getOperand(0)),
1713 "invalid behavior operand in module flag (expected constant integer)",
1716 "invalid behavior operand in module flag (unexpected constant)",
1719 MDString
*ID
= dyn_cast_or_null
<MDString
>(Op
->getOperand(1));
1720 Check(ID
, "invalid ID operand in module flag (expected metadata string)",
1723 // Check the values for behaviors with additional requirements.
1726 case Module::Warning
:
1727 case Module::Override
:
1728 // These behavior types accept any value.
1732 auto *V
= mdconst::dyn_extract_or_null
<ConstantInt
>(Op
->getOperand(2));
1733 Check(V
&& V
->getValue().isNonNegative(),
1734 "invalid value for 'min' module flag (expected constant non-negative "
1741 Check(mdconst::dyn_extract_or_null
<ConstantInt
>(Op
->getOperand(2)),
1742 "invalid value for 'max' module flag (expected constant integer)",
1747 case Module::Require
: {
1748 // The value should itself be an MDNode with two operands, a flag ID (an
1749 // MDString), and a value.
1750 MDNode
*Value
= dyn_cast
<MDNode
>(Op
->getOperand(2));
1751 Check(Value
&& Value
->getNumOperands() == 2,
1752 "invalid value for 'require' module flag (expected metadata pair)",
1754 Check(isa
<MDString
>(Value
->getOperand(0)),
1755 ("invalid value for 'require' module flag "
1756 "(first value operand should be a string)"),
1757 Value
->getOperand(0));
1759 // Append it to the list of requirements, to check once all module flags are
1761 Requirements
.push_back(Value
);
1765 case Module::Append
:
1766 case Module::AppendUnique
: {
1767 // These behavior types require the operand be an MDNode.
1768 Check(isa
<MDNode
>(Op
->getOperand(2)),
1769 "invalid value for 'append'-type module flag "
1770 "(expected a metadata node)",
1776 // Unless this is a "requires" flag, check the ID is unique.
1777 if (MFB
!= Module::Require
) {
1778 bool Inserted
= SeenIDs
.insert(std::make_pair(ID
, Op
)).second
;
1780 "module flag identifiers must be unique (or of 'require' type)", ID
);
1783 if (ID
->getString() == "wchar_size") {
1785 = mdconst::dyn_extract_or_null
<ConstantInt
>(Op
->getOperand(2));
1786 Check(Value
, "wchar_size metadata requires constant integer argument");
1789 if (ID
->getString() == "Linker Options") {
1790 // If the llvm.linker.options named metadata exists, we assume that the
1791 // bitcode reader has upgraded the module flag. Otherwise the flag might
1792 // have been created by a client directly.
1793 Check(M
.getNamedMetadata("llvm.linker.options"),
1794 "'Linker Options' named metadata no longer supported");
1797 if (ID
->getString() == "SemanticInterposition") {
1798 ConstantInt
*Value
=
1799 mdconst::dyn_extract_or_null
<ConstantInt
>(Op
->getOperand(2));
1801 "SemanticInterposition metadata requires constant integer argument");
1804 if (ID
->getString() == "CG Profile") {
1805 for (const MDOperand
&MDO
: cast
<MDNode
>(Op
->getOperand(2))->operands())
1806 visitModuleFlagCGProfileEntry(MDO
);
1810 void Verifier::visitModuleFlagCGProfileEntry(const MDOperand
&MDO
) {
1811 auto CheckFunction
= [&](const MDOperand
&FuncMDO
) {
1814 auto F
= dyn_cast
<ValueAsMetadata
>(FuncMDO
);
1815 Check(F
&& isa
<Function
>(F
->getValue()->stripPointerCasts()),
1816 "expected a Function or null", FuncMDO
);
1818 auto Node
= dyn_cast_or_null
<MDNode
>(MDO
);
1819 Check(Node
&& Node
->getNumOperands() == 3, "expected a MDNode triple", MDO
);
1820 CheckFunction(Node
->getOperand(0));
1821 CheckFunction(Node
->getOperand(1));
1822 auto Count
= dyn_cast_or_null
<ConstantAsMetadata
>(Node
->getOperand(2));
1823 Check(Count
&& Count
->getType()->isIntegerTy(),
1824 "expected an integer constant", Node
->getOperand(2));
1827 void Verifier::verifyAttributeTypes(AttributeSet Attrs
, const Value
*V
) {
1828 for (Attribute A
: Attrs
) {
1830 if (A
.isStringAttribute()) {
1831 #define GET_ATTR_NAMES
1832 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1833 #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
1834 if (A.getKindAsString() == #DISPLAY_NAME) { \
1835 auto V = A.getValueAsString(); \
1836 if (!(V.empty() || V == "true" || V == "false")) \
1837 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
1841 #include "llvm/IR/Attributes.inc"
1845 if (A
.isIntAttribute() != Attribute::isIntAttrKind(A
.getKindAsEnum())) {
1846 CheckFailed("Attribute '" + A
.getAsString() + "' should have an Argument",
1853 // VerifyParameterAttrs - Check the given attributes for an argument or return
1854 // value of the specified type. The value V is printed in error messages.
1855 void Verifier::verifyParameterAttrs(AttributeSet Attrs
, Type
*Ty
,
1857 if (!Attrs
.hasAttributes())
1860 verifyAttributeTypes(Attrs
, V
);
1862 for (Attribute Attr
: Attrs
)
1863 Check(Attr
.isStringAttribute() ||
1864 Attribute::canUseAsParamAttr(Attr
.getKindAsEnum()),
1865 "Attribute '" + Attr
.getAsString() + "' does not apply to parameters",
1868 if (Attrs
.hasAttribute(Attribute::ImmArg
)) {
1869 Check(Attrs
.getNumAttributes() == 1,
1870 "Attribute 'immarg' is incompatible with other attributes", V
);
1873 // Check for mutually incompatible attributes. Only inreg is compatible with
1875 unsigned AttrCount
= 0;
1876 AttrCount
+= Attrs
.hasAttribute(Attribute::ByVal
);
1877 AttrCount
+= Attrs
.hasAttribute(Attribute::InAlloca
);
1878 AttrCount
+= Attrs
.hasAttribute(Attribute::Preallocated
);
1879 AttrCount
+= Attrs
.hasAttribute(Attribute::StructRet
) ||
1880 Attrs
.hasAttribute(Attribute::InReg
);
1881 AttrCount
+= Attrs
.hasAttribute(Attribute::Nest
);
1882 AttrCount
+= Attrs
.hasAttribute(Attribute::ByRef
);
1883 Check(AttrCount
<= 1,
1884 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
1885 "'byref', and 'sret' are incompatible!",
1888 Check(!(Attrs
.hasAttribute(Attribute::InAlloca
) &&
1889 Attrs
.hasAttribute(Attribute::ReadOnly
)),
1891 "'inalloca and readonly' are incompatible!",
1894 Check(!(Attrs
.hasAttribute(Attribute::StructRet
) &&
1895 Attrs
.hasAttribute(Attribute::Returned
)),
1897 "'sret and returned' are incompatible!",
1900 Check(!(Attrs
.hasAttribute(Attribute::ZExt
) &&
1901 Attrs
.hasAttribute(Attribute::SExt
)),
1903 "'zeroext and signext' are incompatible!",
1906 Check(!(Attrs
.hasAttribute(Attribute::ReadNone
) &&
1907 Attrs
.hasAttribute(Attribute::ReadOnly
)),
1909 "'readnone and readonly' are incompatible!",
1912 Check(!(Attrs
.hasAttribute(Attribute::ReadNone
) &&
1913 Attrs
.hasAttribute(Attribute::WriteOnly
)),
1915 "'readnone and writeonly' are incompatible!",
1918 Check(!(Attrs
.hasAttribute(Attribute::ReadOnly
) &&
1919 Attrs
.hasAttribute(Attribute::WriteOnly
)),
1921 "'readonly and writeonly' are incompatible!",
1924 Check(!(Attrs
.hasAttribute(Attribute::NoInline
) &&
1925 Attrs
.hasAttribute(Attribute::AlwaysInline
)),
1927 "'noinline and alwaysinline' are incompatible!",
1930 Check(!(Attrs
.hasAttribute(Attribute::Writable
) &&
1931 Attrs
.hasAttribute(Attribute::ReadNone
)),
1932 "Attributes writable and readnone are incompatible!", V
);
1934 Check(!(Attrs
.hasAttribute(Attribute::Writable
) &&
1935 Attrs
.hasAttribute(Attribute::ReadOnly
)),
1936 "Attributes writable and readonly are incompatible!", V
);
1938 AttributeMask IncompatibleAttrs
= AttributeFuncs::typeIncompatible(Ty
);
1939 for (Attribute Attr
: Attrs
) {
1940 if (!Attr
.isStringAttribute() &&
1941 IncompatibleAttrs
.contains(Attr
.getKindAsEnum())) {
1942 CheckFailed("Attribute '" + Attr
.getAsString() +
1943 "' applied to incompatible type!", V
);
1948 if (isa
<PointerType
>(Ty
)) {
1949 if (Attrs
.hasAttribute(Attribute::ByVal
)) {
1950 if (Attrs
.hasAttribute(Attribute::Alignment
)) {
1951 Align AttrAlign
= Attrs
.getAlignment().valueOrOne();
1952 Align
MaxAlign(ParamMaxAlignment
);
1953 Check(AttrAlign
<= MaxAlign
,
1954 "Attribute 'align' exceed the max size 2^14", V
);
1956 SmallPtrSet
<Type
*, 4> Visited
;
1957 Check(Attrs
.getByValType()->isSized(&Visited
),
1958 "Attribute 'byval' does not support unsized types!", V
);
1960 if (Attrs
.hasAttribute(Attribute::ByRef
)) {
1961 SmallPtrSet
<Type
*, 4> Visited
;
1962 Check(Attrs
.getByRefType()->isSized(&Visited
),
1963 "Attribute 'byref' does not support unsized types!", V
);
1965 if (Attrs
.hasAttribute(Attribute::InAlloca
)) {
1966 SmallPtrSet
<Type
*, 4> Visited
;
1967 Check(Attrs
.getInAllocaType()->isSized(&Visited
),
1968 "Attribute 'inalloca' does not support unsized types!", V
);
1970 if (Attrs
.hasAttribute(Attribute::Preallocated
)) {
1971 SmallPtrSet
<Type
*, 4> Visited
;
1972 Check(Attrs
.getPreallocatedType()->isSized(&Visited
),
1973 "Attribute 'preallocated' does not support unsized types!", V
);
1977 if (Attrs
.hasAttribute(Attribute::NoFPClass
)) {
1978 uint64_t Val
= Attrs
.getAttribute(Attribute::NoFPClass
).getValueAsInt();
1979 Check(Val
!= 0, "Attribute 'nofpclass' must have at least one test bit set",
1981 Check((Val
& ~static_cast<unsigned>(fcAllFlags
)) == 0,
1982 "Invalid value for 'nofpclass' test mask", V
);
1986 void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs
, StringRef Attr
,
1988 if (Attrs
.hasFnAttr(Attr
)) {
1989 StringRef S
= Attrs
.getFnAttr(Attr
).getValueAsString();
1991 if (S
.getAsInteger(10, N
))
1992 CheckFailed("\"" + Attr
+ "\" takes an unsigned integer: " + S
, V
);
1996 // Check parameter attributes against a function type.
1997 // The value V is printed in error messages.
1998 void Verifier::verifyFunctionAttrs(FunctionType
*FT
, AttributeList Attrs
,
1999 const Value
*V
, bool IsIntrinsic
,
2001 if (Attrs
.isEmpty())
2004 if (AttributeListsVisited
.insert(Attrs
.getRawPointer()).second
) {
2005 Check(Attrs
.hasParentContext(Context
),
2006 "Attribute list does not match Module context!", &Attrs
, V
);
2007 for (const auto &AttrSet
: Attrs
) {
2008 Check(!AttrSet
.hasAttributes() || AttrSet
.hasParentContext(Context
),
2009 "Attribute set does not match Module context!", &AttrSet
, V
);
2010 for (const auto &A
: AttrSet
) {
2011 Check(A
.hasParentContext(Context
),
2012 "Attribute does not match Module context!", &A
, V
);
2017 bool SawNest
= false;
2018 bool SawReturned
= false;
2019 bool SawSRet
= false;
2020 bool SawSwiftSelf
= false;
2021 bool SawSwiftAsync
= false;
2022 bool SawSwiftError
= false;
2024 // Verify return value attributes.
2025 AttributeSet RetAttrs
= Attrs
.getRetAttrs();
2026 for (Attribute RetAttr
: RetAttrs
)
2027 Check(RetAttr
.isStringAttribute() ||
2028 Attribute::canUseAsRetAttr(RetAttr
.getKindAsEnum()),
2029 "Attribute '" + RetAttr
.getAsString() +
2030 "' does not apply to function return values",
2033 unsigned MaxParameterWidth
= 0;
2034 auto GetMaxParameterWidth
= [&MaxParameterWidth
](Type
*Ty
) {
2035 if (Ty
->isVectorTy()) {
2036 if (auto *VT
= dyn_cast
<FixedVectorType
>(Ty
)) {
2037 unsigned Size
= VT
->getPrimitiveSizeInBits().getFixedValue();
2038 if (Size
> MaxParameterWidth
)
2039 MaxParameterWidth
= Size
;
2043 GetMaxParameterWidth(FT
->getReturnType());
2044 verifyParameterAttrs(RetAttrs
, FT
->getReturnType(), V
);
2046 // Verify parameter attributes.
2047 for (unsigned i
= 0, e
= FT
->getNumParams(); i
!= e
; ++i
) {
2048 Type
*Ty
= FT
->getParamType(i
);
2049 AttributeSet ArgAttrs
= Attrs
.getParamAttrs(i
);
2052 Check(!ArgAttrs
.hasAttribute(Attribute::ImmArg
),
2053 "immarg attribute only applies to intrinsics", V
);
2055 Check(!ArgAttrs
.hasAttribute(Attribute::ElementType
),
2056 "Attribute 'elementtype' can only be applied to intrinsics"
2061 verifyParameterAttrs(ArgAttrs
, Ty
, V
);
2062 GetMaxParameterWidth(Ty
);
2064 if (ArgAttrs
.hasAttribute(Attribute::Nest
)) {
2065 Check(!SawNest
, "More than one parameter has attribute nest!", V
);
2069 if (ArgAttrs
.hasAttribute(Attribute::Returned
)) {
2070 Check(!SawReturned
, "More than one parameter has attribute returned!", V
);
2071 Check(Ty
->canLosslesslyBitCastTo(FT
->getReturnType()),
2072 "Incompatible argument and return types for 'returned' attribute",
2077 if (ArgAttrs
.hasAttribute(Attribute::StructRet
)) {
2078 Check(!SawSRet
, "Cannot have multiple 'sret' parameters!", V
);
2079 Check(i
== 0 || i
== 1,
2080 "Attribute 'sret' is not on first or second parameter!", V
);
2084 if (ArgAttrs
.hasAttribute(Attribute::SwiftSelf
)) {
2085 Check(!SawSwiftSelf
, "Cannot have multiple 'swiftself' parameters!", V
);
2086 SawSwiftSelf
= true;
2089 if (ArgAttrs
.hasAttribute(Attribute::SwiftAsync
)) {
2090 Check(!SawSwiftAsync
, "Cannot have multiple 'swiftasync' parameters!", V
);
2091 SawSwiftAsync
= true;
2094 if (ArgAttrs
.hasAttribute(Attribute::SwiftError
)) {
2095 Check(!SawSwiftError
, "Cannot have multiple 'swifterror' parameters!", V
);
2096 SawSwiftError
= true;
2099 if (ArgAttrs
.hasAttribute(Attribute::InAlloca
)) {
2100 Check(i
== FT
->getNumParams() - 1,
2101 "inalloca isn't on the last parameter!", V
);
2105 if (!Attrs
.hasFnAttrs())
2108 verifyAttributeTypes(Attrs
.getFnAttrs(), V
);
2109 for (Attribute FnAttr
: Attrs
.getFnAttrs())
2110 Check(FnAttr
.isStringAttribute() ||
2111 Attribute::canUseAsFnAttr(FnAttr
.getKindAsEnum()),
2112 "Attribute '" + FnAttr
.getAsString() +
2113 "' does not apply to functions!",
2116 Check(!(Attrs
.hasFnAttr(Attribute::NoInline
) &&
2117 Attrs
.hasFnAttr(Attribute::AlwaysInline
)),
2118 "Attributes 'noinline and alwaysinline' are incompatible!", V
);
2120 if (Attrs
.hasFnAttr(Attribute::OptimizeNone
)) {
2121 Check(Attrs
.hasFnAttr(Attribute::NoInline
),
2122 "Attribute 'optnone' requires 'noinline'!", V
);
2124 Check(!Attrs
.hasFnAttr(Attribute::OptimizeForSize
),
2125 "Attributes 'optsize and optnone' are incompatible!", V
);
2127 Check(!Attrs
.hasFnAttr(Attribute::MinSize
),
2128 "Attributes 'minsize and optnone' are incompatible!", V
);
2130 Check(!Attrs
.hasFnAttr(Attribute::OptimizeForDebugging
),
2131 "Attributes 'optdebug and optnone' are incompatible!", V
);
2134 if (Attrs
.hasFnAttr(Attribute::OptimizeForDebugging
)) {
2135 Check(!Attrs
.hasFnAttr(Attribute::OptimizeForSize
),
2136 "Attributes 'optsize and optdebug' are incompatible!", V
);
2138 Check(!Attrs
.hasFnAttr(Attribute::MinSize
),
2139 "Attributes 'minsize and optdebug' are incompatible!", V
);
2142 Check(!Attrs
.hasAttrSomewhere(Attribute::Writable
) ||
2143 isModSet(Attrs
.getMemoryEffects().getModRef(IRMemLocation::ArgMem
)),
2144 "Attribute writable and memory without argmem: write are incompatible!",
2147 if (Attrs
.hasFnAttr("aarch64_pstate_sm_enabled")) {
2148 Check(!Attrs
.hasFnAttr("aarch64_pstate_sm_compatible"),
2149 "Attributes 'aarch64_pstate_sm_enabled and "
2150 "aarch64_pstate_sm_compatible' are incompatible!",
2154 if (Attrs
.hasFnAttr("aarch64_pstate_za_new")) {
2155 Check(!Attrs
.hasFnAttr("aarch64_pstate_za_preserved"),
2156 "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_preserved' "
2157 "are incompatible!",
2160 Check(!Attrs
.hasFnAttr("aarch64_pstate_za_shared"),
2161 "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_shared' "
2162 "are incompatible!",
2166 if (Attrs
.hasFnAttr(Attribute::JumpTable
)) {
2167 const GlobalValue
*GV
= cast
<GlobalValue
>(V
);
2168 Check(GV
->hasGlobalUnnamedAddr(),
2169 "Attribute 'jumptable' requires 'unnamed_addr'", V
);
2172 if (auto Args
= Attrs
.getFnAttrs().getAllocSizeArgs()) {
2173 auto CheckParam
= [&](StringRef Name
, unsigned ParamNo
) {
2174 if (ParamNo
>= FT
->getNumParams()) {
2175 CheckFailed("'allocsize' " + Name
+ " argument is out of bounds", V
);
2179 if (!FT
->getParamType(ParamNo
)->isIntegerTy()) {
2180 CheckFailed("'allocsize' " + Name
+
2181 " argument must refer to an integer parameter",
2189 if (!CheckParam("element size", Args
->first
))
2192 if (Args
->second
&& !CheckParam("number of elements", *Args
->second
))
2196 if (Attrs
.hasFnAttr(Attribute::AllocKind
)) {
2197 AllocFnKind K
= Attrs
.getAllocKind();
2199 K
& (AllocFnKind::Alloc
| AllocFnKind::Realloc
| AllocFnKind::Free
);
2201 {AllocFnKind::Alloc
, AllocFnKind::Realloc
, AllocFnKind::Free
},
2204 "'allockind()' requires exactly one of alloc, realloc, and free");
2205 if ((Type
== AllocFnKind::Free
) &&
2206 ((K
& (AllocFnKind::Uninitialized
| AllocFnKind::Zeroed
|
2207 AllocFnKind::Aligned
)) != AllocFnKind::Unknown
))
2208 CheckFailed("'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2209 "or aligned modifiers.");
2210 AllocFnKind ZeroedUninit
= AllocFnKind::Uninitialized
| AllocFnKind::Zeroed
;
2211 if ((K
& ZeroedUninit
) == ZeroedUninit
)
2212 CheckFailed("'allockind()' can't be both zeroed and uninitialized");
2215 if (Attrs
.hasFnAttr(Attribute::VScaleRange
)) {
2216 unsigned VScaleMin
= Attrs
.getFnAttrs().getVScaleRangeMin();
2218 CheckFailed("'vscale_range' minimum must be greater than 0", V
);
2219 else if (!isPowerOf2_32(VScaleMin
))
2220 CheckFailed("'vscale_range' minimum must be power-of-two value", V
);
2221 std::optional
<unsigned> VScaleMax
= Attrs
.getFnAttrs().getVScaleRangeMax();
2222 if (VScaleMax
&& VScaleMin
> VScaleMax
)
2223 CheckFailed("'vscale_range' minimum cannot be greater than maximum", V
);
2224 else if (VScaleMax
&& !isPowerOf2_32(*VScaleMax
))
2225 CheckFailed("'vscale_range' maximum must be power-of-two value", V
);
2228 if (Attrs
.hasFnAttr("frame-pointer")) {
2229 StringRef FP
= Attrs
.getFnAttr("frame-pointer").getValueAsString();
2230 if (FP
!= "all" && FP
!= "non-leaf" && FP
!= "none")
2231 CheckFailed("invalid value for 'frame-pointer' attribute: " + FP
, V
);
2234 // Check EVEX512 feature.
2235 if (MaxParameterWidth
>= 512 && Attrs
.hasFnAttr("target-features")) {
2236 Triple
T(M
.getTargetTriple());
2238 StringRef TF
= Attrs
.getFnAttr("target-features").getValueAsString();
2239 Check(!TF
.contains("+avx512f") || !TF
.contains("-evex512"),
2240 "512-bit vector arguments require 'evex512' for AVX512", V
);
2244 checkUnsignedBaseTenFuncAttr(Attrs
, "patchable-function-prefix", V
);
2245 checkUnsignedBaseTenFuncAttr(Attrs
, "patchable-function-entry", V
);
2246 checkUnsignedBaseTenFuncAttr(Attrs
, "warn-stack-size", V
);
2249 void Verifier::verifyFunctionMetadata(
2250 ArrayRef
<std::pair
<unsigned, MDNode
*>> MDs
) {
2251 for (const auto &Pair
: MDs
) {
2252 if (Pair
.first
== LLVMContext::MD_prof
) {
2253 MDNode
*MD
= Pair
.second
;
2254 Check(MD
->getNumOperands() >= 2,
2255 "!prof annotations should have no less than 2 operands", MD
);
2257 // Check first operand.
2258 Check(MD
->getOperand(0) != nullptr, "first operand should not be null",
2260 Check(isa
<MDString
>(MD
->getOperand(0)),
2261 "expected string with name of the !prof annotation", MD
);
2262 MDString
*MDS
= cast
<MDString
>(MD
->getOperand(0));
2263 StringRef ProfName
= MDS
->getString();
2264 Check(ProfName
.equals("function_entry_count") ||
2265 ProfName
.equals("synthetic_function_entry_count"),
2266 "first operand should be 'function_entry_count'"
2267 " or 'synthetic_function_entry_count'",
2270 // Check second operand.
2271 Check(MD
->getOperand(1) != nullptr, "second operand should not be null",
2273 Check(isa
<ConstantAsMetadata
>(MD
->getOperand(1)),
2274 "expected integer argument to function_entry_count", MD
);
2275 } else if (Pair
.first
== LLVMContext::MD_kcfi_type
) {
2276 MDNode
*MD
= Pair
.second
;
2277 Check(MD
->getNumOperands() == 1,
2278 "!kcfi_type must have exactly one operand", MD
);
2279 Check(MD
->getOperand(0) != nullptr, "!kcfi_type operand must not be null",
2281 Check(isa
<ConstantAsMetadata
>(MD
->getOperand(0)),
2282 "expected a constant operand for !kcfi_type", MD
);
2283 Constant
*C
= cast
<ConstantAsMetadata
>(MD
->getOperand(0))->getValue();
2284 Check(isa
<ConstantInt
>(C
),
2285 "expected a constant integer operand for !kcfi_type", MD
);
2286 IntegerType
*Type
= cast
<ConstantInt
>(C
)->getType();
2287 Check(Type
->getBitWidth() == 32,
2288 "expected a 32-bit integer constant operand for !kcfi_type", MD
);
2293 void Verifier::visitConstantExprsRecursively(const Constant
*EntryC
) {
2294 if (!ConstantExprVisited
.insert(EntryC
).second
)
2297 SmallVector
<const Constant
*, 16> Stack
;
2298 Stack
.push_back(EntryC
);
2300 while (!Stack
.empty()) {
2301 const Constant
*C
= Stack
.pop_back_val();
2303 // Check this constant expression.
2304 if (const auto *CE
= dyn_cast
<ConstantExpr
>(C
))
2305 visitConstantExpr(CE
);
2307 if (const auto *GV
= dyn_cast
<GlobalValue
>(C
)) {
2308 // Global Values get visited separately, but we do need to make sure
2309 // that the global value is in the correct module
2310 Check(GV
->getParent() == &M
, "Referencing global in another module!",
2311 EntryC
, &M
, GV
, GV
->getParent());
2315 // Visit all sub-expressions.
2316 for (const Use
&U
: C
->operands()) {
2317 const auto *OpC
= dyn_cast
<Constant
>(U
);
2320 if (!ConstantExprVisited
.insert(OpC
).second
)
2322 Stack
.push_back(OpC
);
2327 void Verifier::visitConstantExpr(const ConstantExpr
*CE
) {
2328 if (CE
->getOpcode() == Instruction::BitCast
)
2329 Check(CastInst::castIsValid(Instruction::BitCast
, CE
->getOperand(0),
2331 "Invalid bitcast", CE
);
2334 bool Verifier::verifyAttributeCount(AttributeList Attrs
, unsigned Params
) {
2335 // There shouldn't be more attribute sets than there are parameters plus the
2336 // function and return value.
2337 return Attrs
.getNumAttrSets() <= Params
+ 2;
2340 void Verifier::verifyInlineAsmCall(const CallBase
&Call
) {
2341 const InlineAsm
*IA
= cast
<InlineAsm
>(Call
.getCalledOperand());
2343 unsigned LabelNo
= 0;
2344 for (const InlineAsm::ConstraintInfo
&CI
: IA
->ParseConstraints()) {
2345 if (CI
.Type
== InlineAsm::isLabel
) {
2350 // Only deal with constraints that correspond to call arguments.
2354 if (CI
.isIndirect
) {
2355 const Value
*Arg
= Call
.getArgOperand(ArgNo
);
2356 Check(Arg
->getType()->isPointerTy(),
2357 "Operand for indirect constraint must have pointer type", &Call
);
2359 Check(Call
.getParamElementType(ArgNo
),
2360 "Operand for indirect constraint must have elementtype attribute",
2363 Check(!Call
.paramHasAttr(ArgNo
, Attribute::ElementType
),
2364 "Elementtype attribute can only be applied for indirect "
2372 if (auto *CallBr
= dyn_cast
<CallBrInst
>(&Call
)) {
2373 Check(LabelNo
== CallBr
->getNumIndirectDests(),
2374 "Number of label constraints does not match number of callbr dests",
2377 Check(LabelNo
== 0, "Label constraints can only be used with callbr",
2382 /// Verify that statepoint intrinsic is well formed.
2383 void Verifier::verifyStatepoint(const CallBase
&Call
) {
2384 assert(Call
.getCalledFunction() &&
2385 Call
.getCalledFunction()->getIntrinsicID() ==
2386 Intrinsic::experimental_gc_statepoint
);
2388 Check(!Call
.doesNotAccessMemory() && !Call
.onlyReadsMemory() &&
2389 !Call
.onlyAccessesArgMemory(),
2390 "gc.statepoint must read and write all memory to preserve "
2391 "reordering restrictions required by safepoint semantics",
2394 const int64_t NumPatchBytes
=
2395 cast
<ConstantInt
>(Call
.getArgOperand(1))->getSExtValue();
2396 assert(isInt
<32>(NumPatchBytes
) && "NumPatchBytesV is an i32!");
2397 Check(NumPatchBytes
>= 0,
2398 "gc.statepoint number of patchable bytes must be "
2402 Type
*TargetElemType
= Call
.getParamElementType(2);
2403 Check(TargetElemType
,
2404 "gc.statepoint callee argument must have elementtype attribute", Call
);
2405 FunctionType
*TargetFuncType
= dyn_cast
<FunctionType
>(TargetElemType
);
2406 Check(TargetFuncType
,
2407 "gc.statepoint callee elementtype must be function type", Call
);
2409 const int NumCallArgs
= cast
<ConstantInt
>(Call
.getArgOperand(3))->getZExtValue();
2410 Check(NumCallArgs
>= 0,
2411 "gc.statepoint number of arguments to underlying call "
2414 const int NumParams
= (int)TargetFuncType
->getNumParams();
2415 if (TargetFuncType
->isVarArg()) {
2416 Check(NumCallArgs
>= NumParams
,
2417 "gc.statepoint mismatch in number of vararg call args", Call
);
2419 // TODO: Remove this limitation
2420 Check(TargetFuncType
->getReturnType()->isVoidTy(),
2421 "gc.statepoint doesn't support wrapping non-void "
2422 "vararg functions yet",
2425 Check(NumCallArgs
== NumParams
,
2426 "gc.statepoint mismatch in number of call args", Call
);
2428 const uint64_t Flags
2429 = cast
<ConstantInt
>(Call
.getArgOperand(4))->getZExtValue();
2430 Check((Flags
& ~(uint64_t)StatepointFlags::MaskAll
) == 0,
2431 "unknown flag used in gc.statepoint flags argument", Call
);
2433 // Verify that the types of the call parameter arguments match
2434 // the type of the wrapped callee.
2435 AttributeList Attrs
= Call
.getAttributes();
2436 for (int i
= 0; i
< NumParams
; i
++) {
2437 Type
*ParamType
= TargetFuncType
->getParamType(i
);
2438 Type
*ArgType
= Call
.getArgOperand(5 + i
)->getType();
2439 Check(ArgType
== ParamType
,
2440 "gc.statepoint call argument does not match wrapped "
2444 if (TargetFuncType
->isVarArg()) {
2445 AttributeSet ArgAttrs
= Attrs
.getParamAttrs(5 + i
);
2446 Check(!ArgAttrs
.hasAttribute(Attribute::StructRet
),
2447 "Attribute 'sret' cannot be used for vararg call arguments!", Call
);
2451 const int EndCallArgsInx
= 4 + NumCallArgs
;
2453 const Value
*NumTransitionArgsV
= Call
.getArgOperand(EndCallArgsInx
+ 1);
2454 Check(isa
<ConstantInt
>(NumTransitionArgsV
),
2455 "gc.statepoint number of transition arguments "
2456 "must be constant integer",
2458 const int NumTransitionArgs
=
2459 cast
<ConstantInt
>(NumTransitionArgsV
)->getZExtValue();
2460 Check(NumTransitionArgs
== 0,
2461 "gc.statepoint w/inline transition bundle is deprecated", Call
);
2462 const int EndTransitionArgsInx
= EndCallArgsInx
+ 1 + NumTransitionArgs
;
2464 const Value
*NumDeoptArgsV
= Call
.getArgOperand(EndTransitionArgsInx
+ 1);
2465 Check(isa
<ConstantInt
>(NumDeoptArgsV
),
2466 "gc.statepoint number of deoptimization arguments "
2467 "must be constant integer",
2469 const int NumDeoptArgs
= cast
<ConstantInt
>(NumDeoptArgsV
)->getZExtValue();
2470 Check(NumDeoptArgs
== 0,
2471 "gc.statepoint w/inline deopt operands is deprecated", Call
);
2473 const int ExpectedNumArgs
= 7 + NumCallArgs
;
2474 Check(ExpectedNumArgs
== (int)Call
.arg_size(),
2475 "gc.statepoint too many arguments", Call
);
2477 // Check that the only uses of this gc.statepoint are gc.result or
2478 // gc.relocate calls which are tied to this statepoint and thus part
2479 // of the same statepoint sequence
2480 for (const User
*U
: Call
.users()) {
2481 const CallInst
*UserCall
= dyn_cast
<const CallInst
>(U
);
2482 Check(UserCall
, "illegal use of statepoint token", Call
, U
);
2485 Check(isa
<GCRelocateInst
>(UserCall
) || isa
<GCResultInst
>(UserCall
),
2486 "gc.result or gc.relocate are the only value uses "
2487 "of a gc.statepoint",
2489 if (isa
<GCResultInst
>(UserCall
)) {
2490 Check(UserCall
->getArgOperand(0) == &Call
,
2491 "gc.result connected to wrong gc.statepoint", Call
, UserCall
);
2492 } else if (isa
<GCRelocateInst
>(Call
)) {
2493 Check(UserCall
->getArgOperand(0) == &Call
,
2494 "gc.relocate connected to wrong gc.statepoint", Call
, UserCall
);
2498 // Note: It is legal for a single derived pointer to be listed multiple
2499 // times. It's non-optimal, but it is legal. It can also happen after
2500 // insertion if we strip a bitcast away.
2501 // Note: It is really tempting to check that each base is relocated and
2502 // that a derived pointer is never reused as a base pointer. This turns
2503 // out to be problematic since optimizations run after safepoint insertion
2504 // can recognize equality properties that the insertion logic doesn't know
2505 // about. See example statepoint.ll in the verifier subdirectory
2508 void Verifier::verifyFrameRecoverIndices() {
2509 for (auto &Counts
: FrameEscapeInfo
) {
2510 Function
*F
= Counts
.first
;
2511 unsigned EscapedObjectCount
= Counts
.second
.first
;
2512 unsigned MaxRecoveredIndex
= Counts
.second
.second
;
2513 Check(MaxRecoveredIndex
<= EscapedObjectCount
,
2514 "all indices passed to llvm.localrecover must be less than the "
2515 "number of arguments passed to llvm.localescape in the parent "
2521 static Instruction
*getSuccPad(Instruction
*Terminator
) {
2522 BasicBlock
*UnwindDest
;
2523 if (auto *II
= dyn_cast
<InvokeInst
>(Terminator
))
2524 UnwindDest
= II
->getUnwindDest();
2525 else if (auto *CSI
= dyn_cast
<CatchSwitchInst
>(Terminator
))
2526 UnwindDest
= CSI
->getUnwindDest();
2528 UnwindDest
= cast
<CleanupReturnInst
>(Terminator
)->getUnwindDest();
2529 return UnwindDest
->getFirstNonPHI();
2532 void Verifier::verifySiblingFuncletUnwinds() {
2533 SmallPtrSet
<Instruction
*, 8> Visited
;
2534 SmallPtrSet
<Instruction
*, 8> Active
;
2535 for (const auto &Pair
: SiblingFuncletInfo
) {
2536 Instruction
*PredPad
= Pair
.first
;
2537 if (Visited
.count(PredPad
))
2539 Active
.insert(PredPad
);
2540 Instruction
*Terminator
= Pair
.second
;
2542 Instruction
*SuccPad
= getSuccPad(Terminator
);
2543 if (Active
.count(SuccPad
)) {
2544 // Found a cycle; report error
2545 Instruction
*CyclePad
= SuccPad
;
2546 SmallVector
<Instruction
*, 8> CycleNodes
;
2548 CycleNodes
.push_back(CyclePad
);
2549 Instruction
*CycleTerminator
= SiblingFuncletInfo
[CyclePad
];
2550 if (CycleTerminator
!= CyclePad
)
2551 CycleNodes
.push_back(CycleTerminator
);
2552 CyclePad
= getSuccPad(CycleTerminator
);
2553 } while (CyclePad
!= SuccPad
);
2554 Check(false, "EH pads can't handle each other's exceptions",
2555 ArrayRef
<Instruction
*>(CycleNodes
));
2557 // Don't re-walk a node we've already checked
2558 if (!Visited
.insert(SuccPad
).second
)
2560 // Walk to this successor if it has a map entry.
2562 auto TermI
= SiblingFuncletInfo
.find(PredPad
);
2563 if (TermI
== SiblingFuncletInfo
.end())
2565 Terminator
= TermI
->second
;
2566 Active
.insert(PredPad
);
2568 // Each node only has one successor, so we've walked all the active
2569 // nodes' successors.
2574 // visitFunction - Verify that a function is ok.
2576 void Verifier::visitFunction(const Function
&F
) {
2577 visitGlobalValue(F
);
2579 // Check function arguments.
2580 FunctionType
*FT
= F
.getFunctionType();
2581 unsigned NumArgs
= F
.arg_size();
2583 Check(&Context
== &F
.getContext(),
2584 "Function context does not match Module context!", &F
);
2586 Check(!F
.hasCommonLinkage(), "Functions may not have common linkage", &F
);
2587 Check(FT
->getNumParams() == NumArgs
,
2588 "# formal arguments must match # of arguments for function type!", &F
,
2590 Check(F
.getReturnType()->isFirstClassType() ||
2591 F
.getReturnType()->isVoidTy() || F
.getReturnType()->isStructTy(),
2592 "Functions cannot return aggregate values!", &F
);
2594 Check(!F
.hasStructRetAttr() || F
.getReturnType()->isVoidTy(),
2595 "Invalid struct return type!", &F
);
2597 AttributeList Attrs
= F
.getAttributes();
2599 Check(verifyAttributeCount(Attrs
, FT
->getNumParams()),
2600 "Attribute after last parameter!", &F
);
2602 bool IsIntrinsic
= F
.isIntrinsic();
2604 // Check function attributes.
2605 verifyFunctionAttrs(FT
, Attrs
, &F
, IsIntrinsic
, /* IsInlineAsm */ false);
2607 // On function declarations/definitions, we do not support the builtin
2608 // attribute. We do not check this in VerifyFunctionAttrs since that is
2609 // checking for Attributes that can/can not ever be on functions.
2610 Check(!Attrs
.hasFnAttr(Attribute::Builtin
),
2611 "Attribute 'builtin' can only be applied to a callsite.", &F
);
2613 Check(!Attrs
.hasAttrSomewhere(Attribute::ElementType
),
2614 "Attribute 'elementtype' can only be applied to a callsite.", &F
);
2616 // Check that this function meets the restrictions on this calling convention.
2617 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
2618 // restrictions can be lifted.
2619 switch (F
.getCallingConv()) {
2621 case CallingConv::C
:
2623 case CallingConv::X86_INTR
: {
2624 Check(F
.arg_empty() || Attrs
.hasParamAttr(0, Attribute::ByVal
),
2625 "Calling convention parameter requires byval", &F
);
2628 case CallingConv::AMDGPU_KERNEL
:
2629 case CallingConv::SPIR_KERNEL
:
2630 case CallingConv::AMDGPU_CS_Chain
:
2631 case CallingConv::AMDGPU_CS_ChainPreserve
:
2632 Check(F
.getReturnType()->isVoidTy(),
2633 "Calling convention requires void return type", &F
);
2635 case CallingConv::AMDGPU_VS
:
2636 case CallingConv::AMDGPU_HS
:
2637 case CallingConv::AMDGPU_GS
:
2638 case CallingConv::AMDGPU_PS
:
2639 case CallingConv::AMDGPU_CS
:
2640 Check(!F
.hasStructRetAttr(), "Calling convention does not allow sret", &F
);
2641 if (F
.getCallingConv() != CallingConv::SPIR_KERNEL
) {
2642 const unsigned StackAS
= DL
.getAllocaAddrSpace();
2644 for (const Argument
&Arg
: F
.args()) {
2645 Check(!Attrs
.hasParamAttr(i
, Attribute::ByVal
),
2646 "Calling convention disallows byval", &F
);
2647 Check(!Attrs
.hasParamAttr(i
, Attribute::Preallocated
),
2648 "Calling convention disallows preallocated", &F
);
2649 Check(!Attrs
.hasParamAttr(i
, Attribute::InAlloca
),
2650 "Calling convention disallows inalloca", &F
);
2652 if (Attrs
.hasParamAttr(i
, Attribute::ByRef
)) {
2653 // FIXME: Should also disallow LDS and GDS, but we don't have the enum
2655 Check(Arg
.getType()->getPointerAddressSpace() != StackAS
,
2656 "Calling convention disallows stack byref", &F
);
2664 case CallingConv::Fast
:
2665 case CallingConv::Cold
:
2666 case CallingConv::Intel_OCL_BI
:
2667 case CallingConv::PTX_Kernel
:
2668 case CallingConv::PTX_Device
:
2669 Check(!F
.isVarArg(),
2670 "Calling convention does not support varargs or "
2671 "perfect forwarding!",
2676 // Check that the argument values match the function type for this function...
2678 for (const Argument
&Arg
: F
.args()) {
2679 Check(Arg
.getType() == FT
->getParamType(i
),
2680 "Argument value does not match function argument type!", &Arg
,
2681 FT
->getParamType(i
));
2682 Check(Arg
.getType()->isFirstClassType(),
2683 "Function arguments must have first-class types!", &Arg
);
2685 Check(!Arg
.getType()->isMetadataTy(),
2686 "Function takes metadata but isn't an intrinsic", &Arg
, &F
);
2687 Check(!Arg
.getType()->isTokenTy(),
2688 "Function takes token but isn't an intrinsic", &Arg
, &F
);
2689 Check(!Arg
.getType()->isX86_AMXTy(),
2690 "Function takes x86_amx but isn't an intrinsic", &Arg
, &F
);
2693 // Check that swifterror argument is only used by loads and stores.
2694 if (Attrs
.hasParamAttr(i
, Attribute::SwiftError
)) {
2695 verifySwiftErrorValue(&Arg
);
2701 Check(!F
.getReturnType()->isTokenTy(),
2702 "Function returns a token but isn't an intrinsic", &F
);
2703 Check(!F
.getReturnType()->isX86_AMXTy(),
2704 "Function returns a x86_amx but isn't an intrinsic", &F
);
2707 // Get the function metadata attachments.
2708 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
2709 F
.getAllMetadata(MDs
);
2710 assert(F
.hasMetadata() != MDs
.empty() && "Bit out-of-sync");
2711 verifyFunctionMetadata(MDs
);
2713 // Check validity of the personality function
2714 if (F
.hasPersonalityFn()) {
2715 auto *Per
= dyn_cast
<Function
>(F
.getPersonalityFn()->stripPointerCasts());
2717 Check(Per
->getParent() == F
.getParent(),
2718 "Referencing personality function in another module!", &F
,
2719 F
.getParent(), Per
, Per
->getParent());
2722 // EH funclet coloring can be expensive, recompute on-demand
2723 BlockEHFuncletColors
.clear();
2725 if (F
.isMaterializable()) {
2726 // Function has a body somewhere we can't see.
2727 Check(MDs
.empty(), "unmaterialized function cannot have metadata", &F
,
2728 MDs
.empty() ? nullptr : MDs
.front().second
);
2729 } else if (F
.isDeclaration()) {
2730 for (const auto &I
: MDs
) {
2731 // This is used for call site debug information.
2732 CheckDI(I
.first
!= LLVMContext::MD_dbg
||
2733 !cast
<DISubprogram
>(I
.second
)->isDistinct(),
2734 "function declaration may only have a unique !dbg attachment",
2736 Check(I
.first
!= LLVMContext::MD_prof
,
2737 "function declaration may not have a !prof attachment", &F
);
2739 // Verify the metadata itself.
2740 visitMDNode(*I
.second
, AreDebugLocsAllowed::Yes
);
2742 Check(!F
.hasPersonalityFn(),
2743 "Function declaration shouldn't have a personality routine", &F
);
2745 // Verify that this function (which has a body) is not named "llvm.*". It
2746 // is not legal to define intrinsics.
2747 Check(!IsIntrinsic
, "llvm intrinsics cannot be defined!", &F
);
2749 // Check the entry node
2750 const BasicBlock
*Entry
= &F
.getEntryBlock();
2751 Check(pred_empty(Entry
),
2752 "Entry block to function must not have predecessors!", Entry
);
2754 // The address of the entry block cannot be taken, unless it is dead.
2755 if (Entry
->hasAddressTaken()) {
2756 Check(!BlockAddress::lookup(Entry
)->isConstantUsed(),
2757 "blockaddress may not be used with the entry block!", Entry
);
2760 unsigned NumDebugAttachments
= 0, NumProfAttachments
= 0,
2761 NumKCFIAttachments
= 0;
2762 // Visit metadata attachments.
2763 for (const auto &I
: MDs
) {
2764 // Verify that the attachment is legal.
2765 auto AllowLocs
= AreDebugLocsAllowed::No
;
2769 case LLVMContext::MD_dbg
: {
2770 ++NumDebugAttachments
;
2771 CheckDI(NumDebugAttachments
== 1,
2772 "function must have a single !dbg attachment", &F
, I
.second
);
2773 CheckDI(isa
<DISubprogram
>(I
.second
),
2774 "function !dbg attachment must be a subprogram", &F
, I
.second
);
2775 CheckDI(cast
<DISubprogram
>(I
.second
)->isDistinct(),
2776 "function definition may only have a distinct !dbg attachment",
2779 auto *SP
= cast
<DISubprogram
>(I
.second
);
2780 const Function
*&AttachedTo
= DISubprogramAttachments
[SP
];
2781 CheckDI(!AttachedTo
|| AttachedTo
== &F
,
2782 "DISubprogram attached to more than one function", SP
, &F
);
2784 AllowLocs
= AreDebugLocsAllowed::Yes
;
2787 case LLVMContext::MD_prof
:
2788 ++NumProfAttachments
;
2789 Check(NumProfAttachments
== 1,
2790 "function must have a single !prof attachment", &F
, I
.second
);
2792 case LLVMContext::MD_kcfi_type
:
2793 ++NumKCFIAttachments
;
2794 Check(NumKCFIAttachments
== 1,
2795 "function must have a single !kcfi_type attachment", &F
,
2800 // Verify the metadata itself.
2801 visitMDNode(*I
.second
, AllowLocs
);
2805 // If this function is actually an intrinsic, verify that it is only used in
2806 // direct call/invokes, never having its "address taken".
2807 // Only do this if the module is materialized, otherwise we don't have all the
2809 if (F
.isIntrinsic() && F
.getParent()->isMaterialized()) {
2811 if (F
.hasAddressTaken(&U
, false, true, false,
2812 /*IgnoreARCAttachedCall=*/true))
2813 Check(false, "Invalid user of intrinsic instruction!", U
);
2816 // Check intrinsics' signatures.
2817 switch (F
.getIntrinsicID()) {
2818 case Intrinsic::experimental_gc_get_pointer_base
: {
2819 FunctionType
*FT
= F
.getFunctionType();
2820 Check(FT
->getNumParams() == 1, "wrong number of parameters", F
);
2821 Check(isa
<PointerType
>(F
.getReturnType()),
2822 "gc.get.pointer.base must return a pointer", F
);
2823 Check(FT
->getParamType(0) == F
.getReturnType(),
2824 "gc.get.pointer.base operand and result must be of the same type", F
);
2827 case Intrinsic::experimental_gc_get_pointer_offset
: {
2828 FunctionType
*FT
= F
.getFunctionType();
2829 Check(FT
->getNumParams() == 1, "wrong number of parameters", F
);
2830 Check(isa
<PointerType
>(FT
->getParamType(0)),
2831 "gc.get.pointer.offset operand must be a pointer", F
);
2832 Check(F
.getReturnType()->isIntegerTy(),
2833 "gc.get.pointer.offset must return integer", F
);
2838 auto *N
= F
.getSubprogram();
2839 HasDebugInfo
= (N
!= nullptr);
2843 // Check that all !dbg attachments lead to back to N.
2845 // FIXME: Check this incrementally while visiting !dbg attachments.
2846 // FIXME: Only check when N is the canonical subprogram for F.
2847 SmallPtrSet
<const MDNode
*, 32> Seen
;
2848 auto VisitDebugLoc
= [&](const Instruction
&I
, const MDNode
*Node
) {
2849 // Be careful about using DILocation here since we might be dealing with
2850 // broken code (this is the Verifier after all).
2851 const DILocation
*DL
= dyn_cast_or_null
<DILocation
>(Node
);
2854 if (!Seen
.insert(DL
).second
)
2857 Metadata
*Parent
= DL
->getRawScope();
2858 CheckDI(Parent
&& isa
<DILocalScope
>(Parent
),
2859 "DILocation's scope must be a DILocalScope", N
, &F
, &I
, DL
, Parent
);
2861 DILocalScope
*Scope
= DL
->getInlinedAtScope();
2862 Check(Scope
, "Failed to find DILocalScope", DL
);
2864 if (!Seen
.insert(Scope
).second
)
2867 DISubprogram
*SP
= Scope
->getSubprogram();
2869 // Scope and SP could be the same MDNode and we don't want to skip
2870 // validation in that case
2871 if (SP
&& ((Scope
!= SP
) && !Seen
.insert(SP
).second
))
2874 CheckDI(SP
->describes(&F
),
2875 "!dbg attachment points at wrong subprogram for function", N
, &F
,
2879 for (auto &I
: BB
) {
2880 VisitDebugLoc(I
, I
.getDebugLoc().getAsMDNode());
2881 // The llvm.loop annotations also contain two DILocations.
2882 if (auto MD
= I
.getMetadata(LLVMContext::MD_loop
))
2883 for (unsigned i
= 1; i
< MD
->getNumOperands(); ++i
)
2884 VisitDebugLoc(I
, dyn_cast_or_null
<MDNode
>(MD
->getOperand(i
)));
2885 if (BrokenDebugInfo
)
2890 // verifyBasicBlock - Verify that a basic block is well formed...
2892 void Verifier::visitBasicBlock(BasicBlock
&BB
) {
2893 InstsInThisBlock
.clear();
2894 ConvergenceVerifyHelper
.visit(BB
);
2896 // Ensure that basic blocks have terminators!
2897 Check(BB
.getTerminator(), "Basic Block does not have terminator!", &BB
);
2899 // Check constraints that this basic block imposes on all of the PHI nodes in
2901 if (isa
<PHINode
>(BB
.front())) {
2902 SmallVector
<BasicBlock
*, 8> Preds(predecessors(&BB
));
2903 SmallVector
<std::pair
<BasicBlock
*, Value
*>, 8> Values
;
2905 for (const PHINode
&PN
: BB
.phis()) {
2906 Check(PN
.getNumIncomingValues() == Preds
.size(),
2907 "PHINode should have one entry for each predecessor of its "
2908 "parent basic block!",
2911 // Get and sort all incoming values in the PHI node...
2913 Values
.reserve(PN
.getNumIncomingValues());
2914 for (unsigned i
= 0, e
= PN
.getNumIncomingValues(); i
!= e
; ++i
)
2916 std::make_pair(PN
.getIncomingBlock(i
), PN
.getIncomingValue(i
)));
2919 for (unsigned i
= 0, e
= Values
.size(); i
!= e
; ++i
) {
2920 // Check to make sure that if there is more than one entry for a
2921 // particular basic block in this PHI node, that the incoming values are
2924 Check(i
== 0 || Values
[i
].first
!= Values
[i
- 1].first
||
2925 Values
[i
].second
== Values
[i
- 1].second
,
2926 "PHI node has multiple entries for the same basic block with "
2927 "different incoming values!",
2928 &PN
, Values
[i
].first
, Values
[i
].second
, Values
[i
- 1].second
);
2930 // Check to make sure that the predecessors and PHI node entries are
2932 Check(Values
[i
].first
== Preds
[i
],
2933 "PHI node entries do not match predecessors!", &PN
,
2934 Values
[i
].first
, Preds
[i
]);
2939 // Check that all instructions have their parent pointers set up correctly.
2942 Check(I
.getParent() == &BB
, "Instruction has bogus parent pointer!");
2946 void Verifier::visitTerminator(Instruction
&I
) {
2947 // Ensure that terminators only exist at the end of the basic block.
2948 Check(&I
== I
.getParent()->getTerminator(),
2949 "Terminator found in the middle of a basic block!", I
.getParent());
2950 visitInstruction(I
);
2953 void Verifier::visitBranchInst(BranchInst
&BI
) {
2954 if (BI
.isConditional()) {
2955 Check(BI
.getCondition()->getType()->isIntegerTy(1),
2956 "Branch condition is not 'i1' type!", &BI
, BI
.getCondition());
2958 visitTerminator(BI
);
2961 void Verifier::visitReturnInst(ReturnInst
&RI
) {
2962 Function
*F
= RI
.getParent()->getParent();
2963 unsigned N
= RI
.getNumOperands();
2964 if (F
->getReturnType()->isVoidTy())
2966 "Found return instr that returns non-void in Function of void "
2968 &RI
, F
->getReturnType());
2970 Check(N
== 1 && F
->getReturnType() == RI
.getOperand(0)->getType(),
2971 "Function return type does not match operand "
2972 "type of return inst!",
2973 &RI
, F
->getReturnType());
2975 // Check to make sure that the return value has necessary properties for
2977 visitTerminator(RI
);
2980 void Verifier::visitSwitchInst(SwitchInst
&SI
) {
2981 Check(SI
.getType()->isVoidTy(), "Switch must have void result type!", &SI
);
2982 // Check to make sure that all of the constants in the switch instruction
2983 // have the same type as the switched-on value.
2984 Type
*SwitchTy
= SI
.getCondition()->getType();
2985 SmallPtrSet
<ConstantInt
*, 32> Constants
;
2986 for (auto &Case
: SI
.cases()) {
2987 Check(isa
<ConstantInt
>(SI
.getOperand(Case
.getCaseIndex() * 2 + 2)),
2988 "Case value is not a constant integer.", &SI
);
2989 Check(Case
.getCaseValue()->getType() == SwitchTy
,
2990 "Switch constants must all be same type as switch value!", &SI
);
2991 Check(Constants
.insert(Case
.getCaseValue()).second
,
2992 "Duplicate integer as switch case", &SI
, Case
.getCaseValue());
2995 visitTerminator(SI
);
2998 void Verifier::visitIndirectBrInst(IndirectBrInst
&BI
) {
2999 Check(BI
.getAddress()->getType()->isPointerTy(),
3000 "Indirectbr operand must have pointer type!", &BI
);
3001 for (unsigned i
= 0, e
= BI
.getNumDestinations(); i
!= e
; ++i
)
3002 Check(BI
.getDestination(i
)->getType()->isLabelTy(),
3003 "Indirectbr destinations must all have pointer type!", &BI
);
3005 visitTerminator(BI
);
3008 void Verifier::visitCallBrInst(CallBrInst
&CBI
) {
3009 Check(CBI
.isInlineAsm(), "Callbr is currently only used for asm-goto!", &CBI
);
3010 const InlineAsm
*IA
= cast
<InlineAsm
>(CBI
.getCalledOperand());
3011 Check(!IA
->canThrow(), "Unwinding from Callbr is not allowed");
3013 verifyInlineAsmCall(CBI
);
3014 visitTerminator(CBI
);
3017 void Verifier::visitSelectInst(SelectInst
&SI
) {
3018 Check(!SelectInst::areInvalidOperands(SI
.getOperand(0), SI
.getOperand(1),
3020 "Invalid operands for select instruction!", &SI
);
3022 Check(SI
.getTrueValue()->getType() == SI
.getType(),
3023 "Select values must have same type as select instruction!", &SI
);
3024 visitInstruction(SI
);
3027 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
3028 /// a pass, if any exist, it's an error.
3030 void Verifier::visitUserOp1(Instruction
&I
) {
3031 Check(false, "User-defined operators should not live outside of a pass!", &I
);
3034 void Verifier::visitTruncInst(TruncInst
&I
) {
3035 // Get the source and destination types
3036 Type
*SrcTy
= I
.getOperand(0)->getType();
3037 Type
*DestTy
= I
.getType();
3039 // Get the size of the types in bits, we'll need this later
3040 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
3041 unsigned DestBitSize
= DestTy
->getScalarSizeInBits();
3043 Check(SrcTy
->isIntOrIntVectorTy(), "Trunc only operates on integer", &I
);
3044 Check(DestTy
->isIntOrIntVectorTy(), "Trunc only produces integer", &I
);
3045 Check(SrcTy
->isVectorTy() == DestTy
->isVectorTy(),
3046 "trunc source and destination must both be a vector or neither", &I
);
3047 Check(SrcBitSize
> DestBitSize
, "DestTy too big for Trunc", &I
);
3049 visitInstruction(I
);
3052 void Verifier::visitZExtInst(ZExtInst
&I
) {
3053 // Get the source and destination types
3054 Type
*SrcTy
= I
.getOperand(0)->getType();
3055 Type
*DestTy
= I
.getType();
3057 // Get the size of the types in bits, we'll need this later
3058 Check(SrcTy
->isIntOrIntVectorTy(), "ZExt only operates on integer", &I
);
3059 Check(DestTy
->isIntOrIntVectorTy(), "ZExt only produces an integer", &I
);
3060 Check(SrcTy
->isVectorTy() == DestTy
->isVectorTy(),
3061 "zext source and destination must both be a vector or neither", &I
);
3062 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
3063 unsigned DestBitSize
= DestTy
->getScalarSizeInBits();
3065 Check(SrcBitSize
< DestBitSize
, "Type too small for ZExt", &I
);
3067 visitInstruction(I
);
3070 void Verifier::visitSExtInst(SExtInst
&I
) {
3071 // Get the source and destination types
3072 Type
*SrcTy
= I
.getOperand(0)->getType();
3073 Type
*DestTy
= I
.getType();
3075 // Get the size of the types in bits, we'll need this later
3076 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
3077 unsigned DestBitSize
= DestTy
->getScalarSizeInBits();
3079 Check(SrcTy
->isIntOrIntVectorTy(), "SExt only operates on integer", &I
);
3080 Check(DestTy
->isIntOrIntVectorTy(), "SExt only produces an integer", &I
);
3081 Check(SrcTy
->isVectorTy() == DestTy
->isVectorTy(),
3082 "sext source and destination must both be a vector or neither", &I
);
3083 Check(SrcBitSize
< DestBitSize
, "Type too small for SExt", &I
);
3085 visitInstruction(I
);
3088 void Verifier::visitFPTruncInst(FPTruncInst
&I
) {
3089 // Get the source and destination types
3090 Type
*SrcTy
= I
.getOperand(0)->getType();
3091 Type
*DestTy
= I
.getType();
3092 // Get the size of the types in bits, we'll need this later
3093 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
3094 unsigned DestBitSize
= DestTy
->getScalarSizeInBits();
3096 Check(SrcTy
->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I
);
3097 Check(DestTy
->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I
);
3098 Check(SrcTy
->isVectorTy() == DestTy
->isVectorTy(),
3099 "fptrunc source and destination must both be a vector or neither", &I
);
3100 Check(SrcBitSize
> DestBitSize
, "DestTy too big for FPTrunc", &I
);
3102 visitInstruction(I
);
3105 void Verifier::visitFPExtInst(FPExtInst
&I
) {
3106 // Get the source and destination types
3107 Type
*SrcTy
= I
.getOperand(0)->getType();
3108 Type
*DestTy
= I
.getType();
3110 // Get the size of the types in bits, we'll need this later
3111 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
3112 unsigned DestBitSize
= DestTy
->getScalarSizeInBits();
3114 Check(SrcTy
->isFPOrFPVectorTy(), "FPExt only operates on FP", &I
);
3115 Check(DestTy
->isFPOrFPVectorTy(), "FPExt only produces an FP", &I
);
3116 Check(SrcTy
->isVectorTy() == DestTy
->isVectorTy(),
3117 "fpext source and destination must both be a vector or neither", &I
);
3118 Check(SrcBitSize
< DestBitSize
, "DestTy too small for FPExt", &I
);
3120 visitInstruction(I
);
3123 void Verifier::visitUIToFPInst(UIToFPInst
&I
) {
3124 // Get the source and destination types
3125 Type
*SrcTy
= I
.getOperand(0)->getType();
3126 Type
*DestTy
= I
.getType();
3128 bool SrcVec
= SrcTy
->isVectorTy();
3129 bool DstVec
= DestTy
->isVectorTy();
3131 Check(SrcVec
== DstVec
,
3132 "UIToFP source and dest must both be vector or scalar", &I
);
3133 Check(SrcTy
->isIntOrIntVectorTy(),
3134 "UIToFP source must be integer or integer vector", &I
);
3135 Check(DestTy
->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
3138 if (SrcVec
&& DstVec
)
3139 Check(cast
<VectorType
>(SrcTy
)->getElementCount() ==
3140 cast
<VectorType
>(DestTy
)->getElementCount(),
3141 "UIToFP source and dest vector length mismatch", &I
);
3143 visitInstruction(I
);
3146 void Verifier::visitSIToFPInst(SIToFPInst
&I
) {
3147 // Get the source and destination types
3148 Type
*SrcTy
= I
.getOperand(0)->getType();
3149 Type
*DestTy
= I
.getType();
3151 bool SrcVec
= SrcTy
->isVectorTy();
3152 bool DstVec
= DestTy
->isVectorTy();
3154 Check(SrcVec
== DstVec
,
3155 "SIToFP source and dest must both be vector or scalar", &I
);
3156 Check(SrcTy
->isIntOrIntVectorTy(),
3157 "SIToFP source must be integer or integer vector", &I
);
3158 Check(DestTy
->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
3161 if (SrcVec
&& DstVec
)
3162 Check(cast
<VectorType
>(SrcTy
)->getElementCount() ==
3163 cast
<VectorType
>(DestTy
)->getElementCount(),
3164 "SIToFP source and dest vector length mismatch", &I
);
3166 visitInstruction(I
);
3169 void Verifier::visitFPToUIInst(FPToUIInst
&I
) {
3170 // Get the source and destination types
3171 Type
*SrcTy
= I
.getOperand(0)->getType();
3172 Type
*DestTy
= I
.getType();
3174 bool SrcVec
= SrcTy
->isVectorTy();
3175 bool DstVec
= DestTy
->isVectorTy();
3177 Check(SrcVec
== DstVec
,
3178 "FPToUI source and dest must both be vector or scalar", &I
);
3179 Check(SrcTy
->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", &I
);
3180 Check(DestTy
->isIntOrIntVectorTy(),
3181 "FPToUI result must be integer or integer vector", &I
);
3183 if (SrcVec
&& DstVec
)
3184 Check(cast
<VectorType
>(SrcTy
)->getElementCount() ==
3185 cast
<VectorType
>(DestTy
)->getElementCount(),
3186 "FPToUI source and dest vector length mismatch", &I
);
3188 visitInstruction(I
);
3191 void Verifier::visitFPToSIInst(FPToSIInst
&I
) {
3192 // Get the source and destination types
3193 Type
*SrcTy
= I
.getOperand(0)->getType();
3194 Type
*DestTy
= I
.getType();
3196 bool SrcVec
= SrcTy
->isVectorTy();
3197 bool DstVec
= DestTy
->isVectorTy();
3199 Check(SrcVec
== DstVec
,
3200 "FPToSI source and dest must both be vector or scalar", &I
);
3201 Check(SrcTy
->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", &I
);
3202 Check(DestTy
->isIntOrIntVectorTy(),
3203 "FPToSI result must be integer or integer vector", &I
);
3205 if (SrcVec
&& DstVec
)
3206 Check(cast
<VectorType
>(SrcTy
)->getElementCount() ==
3207 cast
<VectorType
>(DestTy
)->getElementCount(),
3208 "FPToSI source and dest vector length mismatch", &I
);
3210 visitInstruction(I
);
3213 void Verifier::visitPtrToIntInst(PtrToIntInst
&I
) {
3214 // Get the source and destination types
3215 Type
*SrcTy
= I
.getOperand(0)->getType();
3216 Type
*DestTy
= I
.getType();
3218 Check(SrcTy
->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I
);
3220 Check(DestTy
->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I
);
3221 Check(SrcTy
->isVectorTy() == DestTy
->isVectorTy(), "PtrToInt type mismatch",
3224 if (SrcTy
->isVectorTy()) {
3225 auto *VSrc
= cast
<VectorType
>(SrcTy
);
3226 auto *VDest
= cast
<VectorType
>(DestTy
);
3227 Check(VSrc
->getElementCount() == VDest
->getElementCount(),
3228 "PtrToInt Vector width mismatch", &I
);
3231 visitInstruction(I
);
3234 void Verifier::visitIntToPtrInst(IntToPtrInst
&I
) {
3235 // Get the source and destination types
3236 Type
*SrcTy
= I
.getOperand(0)->getType();
3237 Type
*DestTy
= I
.getType();
3239 Check(SrcTy
->isIntOrIntVectorTy(), "IntToPtr source must be an integral", &I
);
3240 Check(DestTy
->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I
);
3242 Check(SrcTy
->isVectorTy() == DestTy
->isVectorTy(), "IntToPtr type mismatch",
3244 if (SrcTy
->isVectorTy()) {
3245 auto *VSrc
= cast
<VectorType
>(SrcTy
);
3246 auto *VDest
= cast
<VectorType
>(DestTy
);
3247 Check(VSrc
->getElementCount() == VDest
->getElementCount(),
3248 "IntToPtr Vector width mismatch", &I
);
3250 visitInstruction(I
);
3253 void Verifier::visitBitCastInst(BitCastInst
&I
) {
3255 CastInst::castIsValid(Instruction::BitCast
, I
.getOperand(0), I
.getType()),
3256 "Invalid bitcast", &I
);
3257 visitInstruction(I
);
3260 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst
&I
) {
3261 Type
*SrcTy
= I
.getOperand(0)->getType();
3262 Type
*DestTy
= I
.getType();
3264 Check(SrcTy
->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
3266 Check(DestTy
->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
3268 Check(SrcTy
->getPointerAddressSpace() != DestTy
->getPointerAddressSpace(),
3269 "AddrSpaceCast must be between different address spaces", &I
);
3270 if (auto *SrcVTy
= dyn_cast
<VectorType
>(SrcTy
))
3271 Check(SrcVTy
->getElementCount() ==
3272 cast
<VectorType
>(DestTy
)->getElementCount(),
3273 "AddrSpaceCast vector pointer number of elements mismatch", &I
);
3274 visitInstruction(I
);
3277 /// visitPHINode - Ensure that a PHI node is well formed.
3279 void Verifier::visitPHINode(PHINode
&PN
) {
3280 // Ensure that the PHI nodes are all grouped together at the top of the block.
3281 // This can be tested by checking whether the instruction before this is
3282 // either nonexistent (because this is begin()) or is a PHI node. If not,
3283 // then there is some other instruction before a PHI.
3284 Check(&PN
== &PN
.getParent()->front() ||
3285 isa
<PHINode
>(--BasicBlock::iterator(&PN
)),
3286 "PHI nodes not grouped at top of basic block!", &PN
, PN
.getParent());
3288 // Check that a PHI doesn't yield a Token.
3289 Check(!PN
.getType()->isTokenTy(), "PHI nodes cannot have token type!");
3291 // Check that all of the values of the PHI node have the same type as the
3292 // result, and that the incoming blocks are really basic blocks.
3293 for (Value
*IncValue
: PN
.incoming_values()) {
3294 Check(PN
.getType() == IncValue
->getType(),
3295 "PHI node operands are not the same type as the result!", &PN
);
3298 // All other PHI node constraints are checked in the visitBasicBlock method.
3300 visitInstruction(PN
);
3303 void Verifier::visitCallBase(CallBase
&Call
) {
3304 Check(Call
.getCalledOperand()->getType()->isPointerTy(),
3305 "Called function must be a pointer!", Call
);
3306 FunctionType
*FTy
= Call
.getFunctionType();
3308 // Verify that the correct number of arguments are being passed
3309 if (FTy
->isVarArg())
3310 Check(Call
.arg_size() >= FTy
->getNumParams(),
3311 "Called function requires more parameters than were provided!", Call
);
3313 Check(Call
.arg_size() == FTy
->getNumParams(),
3314 "Incorrect number of arguments passed to called function!", Call
);
3316 // Verify that all arguments to the call match the function type.
3317 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
)
3318 Check(Call
.getArgOperand(i
)->getType() == FTy
->getParamType(i
),
3319 "Call parameter type does not match function signature!",
3320 Call
.getArgOperand(i
), FTy
->getParamType(i
), Call
);
3322 AttributeList Attrs
= Call
.getAttributes();
3324 Check(verifyAttributeCount(Attrs
, Call
.arg_size()),
3325 "Attribute after last parameter!", Call
);
3328 dyn_cast
<Function
>(Call
.getCalledOperand()->stripPointerCasts());
3329 bool IsIntrinsic
= Callee
&& Callee
->isIntrinsic();
3331 Check(Callee
->getValueType() == FTy
,
3332 "Intrinsic called with incompatible signature", Call
);
3334 // Disallow calls to functions with the amdgpu_cs_chain[_preserve] calling
3336 auto CC
= Call
.getCallingConv();
3337 Check(CC
!= CallingConv::AMDGPU_CS_Chain
&&
3338 CC
!= CallingConv::AMDGPU_CS_ChainPreserve
,
3339 "Direct calls to amdgpu_cs_chain/amdgpu_cs_chain_preserve functions "
3340 "not allowed. Please use the @llvm.amdgpu.cs.chain intrinsic instead.",
3343 auto VerifyTypeAlign
= [&](Type
*Ty
, const Twine
&Message
) {
3346 Align ABIAlign
= DL
.getABITypeAlign(Ty
);
3347 Align
MaxAlign(ParamMaxAlignment
);
3348 Check(ABIAlign
<= MaxAlign
,
3349 "Incorrect alignment of " + Message
+ " to called function!", Call
);
3353 VerifyTypeAlign(FTy
->getReturnType(), "return type");
3354 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
) {
3355 Type
*Ty
= FTy
->getParamType(i
);
3356 VerifyTypeAlign(Ty
, "argument passed");
3360 if (Attrs
.hasFnAttr(Attribute::Speculatable
)) {
3361 // Don't allow speculatable on call sites, unless the underlying function
3362 // declaration is also speculatable.
3363 Check(Callee
&& Callee
->isSpeculatable(),
3364 "speculatable attribute may not apply to call sites", Call
);
3367 if (Attrs
.hasFnAttr(Attribute::Preallocated
)) {
3368 Check(Call
.getCalledFunction()->getIntrinsicID() ==
3369 Intrinsic::call_preallocated_arg
,
3370 "preallocated as a call site attribute can only be on "
3371 "llvm.call.preallocated.arg");
3374 // Verify call attributes.
3375 verifyFunctionAttrs(FTy
, Attrs
, &Call
, IsIntrinsic
, Call
.isInlineAsm());
3377 // Conservatively check the inalloca argument.
3378 // We have a bug if we can find that there is an underlying alloca without
3380 if (Call
.hasInAllocaArgument()) {
3381 Value
*InAllocaArg
= Call
.getArgOperand(FTy
->getNumParams() - 1);
3382 if (auto AI
= dyn_cast
<AllocaInst
>(InAllocaArg
->stripInBoundsOffsets()))
3383 Check(AI
->isUsedWithInAlloca(),
3384 "inalloca argument for call has mismatched alloca", AI
, Call
);
3387 // For each argument of the callsite, if it has the swifterror argument,
3388 // make sure the underlying alloca/parameter it comes from has a swifterror as
3390 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
) {
3391 if (Call
.paramHasAttr(i
, Attribute::SwiftError
)) {
3392 Value
*SwiftErrorArg
= Call
.getArgOperand(i
);
3393 if (auto AI
= dyn_cast
<AllocaInst
>(SwiftErrorArg
->stripInBoundsOffsets())) {
3394 Check(AI
->isSwiftError(),
3395 "swifterror argument for call has mismatched alloca", AI
, Call
);
3398 auto ArgI
= dyn_cast
<Argument
>(SwiftErrorArg
);
3399 Check(ArgI
, "swifterror argument should come from an alloca or parameter",
3400 SwiftErrorArg
, Call
);
3401 Check(ArgI
->hasSwiftErrorAttr(),
3402 "swifterror argument for call has mismatched parameter", ArgI
,
3406 if (Attrs
.hasParamAttr(i
, Attribute::ImmArg
)) {
3407 // Don't allow immarg on call sites, unless the underlying declaration
3408 // also has the matching immarg.
3409 Check(Callee
&& Callee
->hasParamAttribute(i
, Attribute::ImmArg
),
3410 "immarg may not apply only to call sites", Call
.getArgOperand(i
),
3414 if (Call
.paramHasAttr(i
, Attribute::ImmArg
)) {
3415 Value
*ArgVal
= Call
.getArgOperand(i
);
3416 Check(isa
<ConstantInt
>(ArgVal
) || isa
<ConstantFP
>(ArgVal
),
3417 "immarg operand has non-immediate parameter", ArgVal
, Call
);
3420 if (Call
.paramHasAttr(i
, Attribute::Preallocated
)) {
3421 Value
*ArgVal
= Call
.getArgOperand(i
);
3423 Call
.countOperandBundlesOfType(LLVMContext::OB_preallocated
) != 0;
3424 bool isMustTail
= Call
.isMustTailCall();
3425 Check(hasOB
!= isMustTail
,
3426 "preallocated operand either requires a preallocated bundle or "
3427 "the call to be musttail (but not both)",
3432 if (FTy
->isVarArg()) {
3433 // FIXME? is 'nest' even legal here?
3434 bool SawNest
= false;
3435 bool SawReturned
= false;
3437 for (unsigned Idx
= 0; Idx
< FTy
->getNumParams(); ++Idx
) {
3438 if (Attrs
.hasParamAttr(Idx
, Attribute::Nest
))
3440 if (Attrs
.hasParamAttr(Idx
, Attribute::Returned
))
3444 // Check attributes on the varargs part.
3445 for (unsigned Idx
= FTy
->getNumParams(); Idx
< Call
.arg_size(); ++Idx
) {
3446 Type
*Ty
= Call
.getArgOperand(Idx
)->getType();
3447 AttributeSet ArgAttrs
= Attrs
.getParamAttrs(Idx
);
3448 verifyParameterAttrs(ArgAttrs
, Ty
, &Call
);
3450 if (ArgAttrs
.hasAttribute(Attribute::Nest
)) {
3451 Check(!SawNest
, "More than one parameter has attribute nest!", Call
);
3455 if (ArgAttrs
.hasAttribute(Attribute::Returned
)) {
3456 Check(!SawReturned
, "More than one parameter has attribute returned!",
3458 Check(Ty
->canLosslesslyBitCastTo(FTy
->getReturnType()),
3459 "Incompatible argument and return types for 'returned' "
3465 // Statepoint intrinsic is vararg but the wrapped function may be not.
3466 // Allow sret here and check the wrapped function in verifyStatepoint.
3467 if (!Call
.getCalledFunction() ||
3468 Call
.getCalledFunction()->getIntrinsicID() !=
3469 Intrinsic::experimental_gc_statepoint
)
3470 Check(!ArgAttrs
.hasAttribute(Attribute::StructRet
),
3471 "Attribute 'sret' cannot be used for vararg call arguments!",
3474 if (ArgAttrs
.hasAttribute(Attribute::InAlloca
))
3475 Check(Idx
== Call
.arg_size() - 1,
3476 "inalloca isn't on the last argument!", Call
);
3480 // Verify that there's no metadata unless it's a direct call to an intrinsic.
3482 for (Type
*ParamTy
: FTy
->params()) {
3483 Check(!ParamTy
->isMetadataTy(),
3484 "Function has metadata parameter but isn't an intrinsic", Call
);
3485 Check(!ParamTy
->isTokenTy(),
3486 "Function has token parameter but isn't an intrinsic", Call
);
3490 // Verify that indirect calls don't return tokens.
3491 if (!Call
.getCalledFunction()) {
3492 Check(!FTy
->getReturnType()->isTokenTy(),
3493 "Return type cannot be token for indirect call!");
3494 Check(!FTy
->getReturnType()->isX86_AMXTy(),
3495 "Return type cannot be x86_amx for indirect call!");
3498 if (Function
*F
= Call
.getCalledFunction())
3499 if (Intrinsic::ID ID
= (Intrinsic::ID
)F
->getIntrinsicID())
3500 visitIntrinsicCall(ID
, Call
);
3502 // Verify that a callsite has at most one "deopt", at most one "funclet", at
3503 // most one "gc-transition", at most one "cfguardtarget", at most one
3504 // "preallocated" operand bundle, and at most one "ptrauth" operand bundle.
3505 bool FoundDeoptBundle
= false, FoundFuncletBundle
= false,
3506 FoundGCTransitionBundle
= false, FoundCFGuardTargetBundle
= false,
3507 FoundPreallocatedBundle
= false, FoundGCLiveBundle
= false,
3508 FoundPtrauthBundle
= false, FoundKCFIBundle
= false,
3509 FoundAttachedCallBundle
= false;
3510 for (unsigned i
= 0, e
= Call
.getNumOperandBundles(); i
< e
; ++i
) {
3511 OperandBundleUse BU
= Call
.getOperandBundleAt(i
);
3512 uint32_t Tag
= BU
.getTagID();
3513 if (Tag
== LLVMContext::OB_deopt
) {
3514 Check(!FoundDeoptBundle
, "Multiple deopt operand bundles", Call
);
3515 FoundDeoptBundle
= true;
3516 } else if (Tag
== LLVMContext::OB_gc_transition
) {
3517 Check(!FoundGCTransitionBundle
, "Multiple gc-transition operand bundles",
3519 FoundGCTransitionBundle
= true;
3520 } else if (Tag
== LLVMContext::OB_funclet
) {
3521 Check(!FoundFuncletBundle
, "Multiple funclet operand bundles", Call
);
3522 FoundFuncletBundle
= true;
3523 Check(BU
.Inputs
.size() == 1,
3524 "Expected exactly one funclet bundle operand", Call
);
3525 Check(isa
<FuncletPadInst
>(BU
.Inputs
.front()),
3526 "Funclet bundle operands should correspond to a FuncletPadInst",
3528 } else if (Tag
== LLVMContext::OB_cfguardtarget
) {
3529 Check(!FoundCFGuardTargetBundle
, "Multiple CFGuardTarget operand bundles",
3531 FoundCFGuardTargetBundle
= true;
3532 Check(BU
.Inputs
.size() == 1,
3533 "Expected exactly one cfguardtarget bundle operand", Call
);
3534 } else if (Tag
== LLVMContext::OB_ptrauth
) {
3535 Check(!FoundPtrauthBundle
, "Multiple ptrauth operand bundles", Call
);
3536 FoundPtrauthBundle
= true;
3537 Check(BU
.Inputs
.size() == 2,
3538 "Expected exactly two ptrauth bundle operands", Call
);
3539 Check(isa
<ConstantInt
>(BU
.Inputs
[0]) &&
3540 BU
.Inputs
[0]->getType()->isIntegerTy(32),
3541 "Ptrauth bundle key operand must be an i32 constant", Call
);
3542 Check(BU
.Inputs
[1]->getType()->isIntegerTy(64),
3543 "Ptrauth bundle discriminator operand must be an i64", Call
);
3544 } else if (Tag
== LLVMContext::OB_kcfi
) {
3545 Check(!FoundKCFIBundle
, "Multiple kcfi operand bundles", Call
);
3546 FoundKCFIBundle
= true;
3547 Check(BU
.Inputs
.size() == 1, "Expected exactly one kcfi bundle operand",
3549 Check(isa
<ConstantInt
>(BU
.Inputs
[0]) &&
3550 BU
.Inputs
[0]->getType()->isIntegerTy(32),
3551 "Kcfi bundle operand must be an i32 constant", Call
);
3552 } else if (Tag
== LLVMContext::OB_preallocated
) {
3553 Check(!FoundPreallocatedBundle
, "Multiple preallocated operand bundles",
3555 FoundPreallocatedBundle
= true;
3556 Check(BU
.Inputs
.size() == 1,
3557 "Expected exactly one preallocated bundle operand", Call
);
3558 auto Input
= dyn_cast
<IntrinsicInst
>(BU
.Inputs
.front());
3560 Input
->getIntrinsicID() == Intrinsic::call_preallocated_setup
,
3561 "\"preallocated\" argument must be a token from "
3562 "llvm.call.preallocated.setup",
3564 } else if (Tag
== LLVMContext::OB_gc_live
) {
3565 Check(!FoundGCLiveBundle
, "Multiple gc-live operand bundles", Call
);
3566 FoundGCLiveBundle
= true;
3567 } else if (Tag
== LLVMContext::OB_clang_arc_attachedcall
) {
3568 Check(!FoundAttachedCallBundle
,
3569 "Multiple \"clang.arc.attachedcall\" operand bundles", Call
);
3570 FoundAttachedCallBundle
= true;
3571 verifyAttachedCallBundle(Call
, BU
);
3575 // Verify that callee and callsite agree on whether to use pointer auth.
3576 Check(!(Call
.getCalledFunction() && FoundPtrauthBundle
),
3577 "Direct call cannot have a ptrauth bundle", Call
);
3579 // Verify that each inlinable callsite of a debug-info-bearing function in a
3580 // debug-info-bearing function has a debug location attached to it. Failure to
3581 // do so causes assertion failures when the inliner sets up inline scope info
3582 // (Interposable functions are not inlinable, neither are functions without
3584 if (Call
.getFunction()->getSubprogram() && Call
.getCalledFunction() &&
3585 !Call
.getCalledFunction()->isInterposable() &&
3586 !Call
.getCalledFunction()->isDeclaration() &&
3587 Call
.getCalledFunction()->getSubprogram())
3588 CheckDI(Call
.getDebugLoc(),
3589 "inlinable function call in a function with "
3590 "debug info must have a !dbg location",
3593 if (Call
.isInlineAsm())
3594 verifyInlineAsmCall(Call
);
3596 ConvergenceVerifyHelper
.visit(Call
);
3598 visitInstruction(Call
);
3601 void Verifier::verifyTailCCMustTailAttrs(const AttrBuilder
&Attrs
,
3602 StringRef Context
) {
3603 Check(!Attrs
.contains(Attribute::InAlloca
),
3604 Twine("inalloca attribute not allowed in ") + Context
);
3605 Check(!Attrs
.contains(Attribute::InReg
),
3606 Twine("inreg attribute not allowed in ") + Context
);
3607 Check(!Attrs
.contains(Attribute::SwiftError
),
3608 Twine("swifterror attribute not allowed in ") + Context
);
3609 Check(!Attrs
.contains(Attribute::Preallocated
),
3610 Twine("preallocated attribute not allowed in ") + Context
);
3611 Check(!Attrs
.contains(Attribute::ByRef
),
3612 Twine("byref attribute not allowed in ") + Context
);
3615 /// Two types are "congruent" if they are identical, or if they are both pointer
3616 /// types with different pointee types and the same address space.
3617 static bool isTypeCongruent(Type
*L
, Type
*R
) {
3620 PointerType
*PL
= dyn_cast
<PointerType
>(L
);
3621 PointerType
*PR
= dyn_cast
<PointerType
>(R
);
3624 return PL
->getAddressSpace() == PR
->getAddressSpace();
3627 static AttrBuilder
getParameterABIAttributes(LLVMContext
& C
, unsigned I
, AttributeList Attrs
) {
3628 static const Attribute::AttrKind ABIAttrs
[] = {
3629 Attribute::StructRet
, Attribute::ByVal
, Attribute::InAlloca
,
3630 Attribute::InReg
, Attribute::StackAlignment
, Attribute::SwiftSelf
,
3631 Attribute::SwiftAsync
, Attribute::SwiftError
, Attribute::Preallocated
,
3633 AttrBuilder
Copy(C
);
3634 for (auto AK
: ABIAttrs
) {
3635 Attribute Attr
= Attrs
.getParamAttrs(I
).getAttribute(AK
);
3637 Copy
.addAttribute(Attr
);
3640 // `align` is ABI-affecting only in combination with `byval` or `byref`.
3641 if (Attrs
.hasParamAttr(I
, Attribute::Alignment
) &&
3642 (Attrs
.hasParamAttr(I
, Attribute::ByVal
) ||
3643 Attrs
.hasParamAttr(I
, Attribute::ByRef
)))
3644 Copy
.addAlignmentAttr(Attrs
.getParamAlignment(I
));
3648 void Verifier::verifyMustTailCall(CallInst
&CI
) {
3649 Check(!CI
.isInlineAsm(), "cannot use musttail call with inline asm", &CI
);
3651 Function
*F
= CI
.getParent()->getParent();
3652 FunctionType
*CallerTy
= F
->getFunctionType();
3653 FunctionType
*CalleeTy
= CI
.getFunctionType();
3654 Check(CallerTy
->isVarArg() == CalleeTy
->isVarArg(),
3655 "cannot guarantee tail call due to mismatched varargs", &CI
);
3656 Check(isTypeCongruent(CallerTy
->getReturnType(), CalleeTy
->getReturnType()),
3657 "cannot guarantee tail call due to mismatched return types", &CI
);
3659 // - The calling conventions of the caller and callee must match.
3660 Check(F
->getCallingConv() == CI
.getCallingConv(),
3661 "cannot guarantee tail call due to mismatched calling conv", &CI
);
3663 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
3664 // or a pointer bitcast followed by a ret instruction.
3665 // - The ret instruction must return the (possibly bitcasted) value
3666 // produced by the call or void.
3667 Value
*RetVal
= &CI
;
3668 Instruction
*Next
= CI
.getNextNode();
3670 // Handle the optional bitcast.
3671 if (BitCastInst
*BI
= dyn_cast_or_null
<BitCastInst
>(Next
)) {
3672 Check(BI
->getOperand(0) == RetVal
,
3673 "bitcast following musttail call must use the call", BI
);
3675 Next
= BI
->getNextNode();
3678 // Check the return.
3679 ReturnInst
*Ret
= dyn_cast_or_null
<ReturnInst
>(Next
);
3680 Check(Ret
, "musttail call must precede a ret with an optional bitcast", &CI
);
3681 Check(!Ret
->getReturnValue() || Ret
->getReturnValue() == RetVal
||
3682 isa
<UndefValue
>(Ret
->getReturnValue()),
3683 "musttail call result must be returned", Ret
);
3685 AttributeList CallerAttrs
= F
->getAttributes();
3686 AttributeList CalleeAttrs
= CI
.getAttributes();
3687 if (CI
.getCallingConv() == CallingConv::SwiftTail
||
3688 CI
.getCallingConv() == CallingConv::Tail
) {
3690 CI
.getCallingConv() == CallingConv::Tail
? "tailcc" : "swifttailcc";
3692 // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
3693 // are allowed in swifttailcc call
3694 for (unsigned I
= 0, E
= CallerTy
->getNumParams(); I
!= E
; ++I
) {
3695 AttrBuilder ABIAttrs
= getParameterABIAttributes(F
->getContext(), I
, CallerAttrs
);
3696 SmallString
<32> Context
{CCName
, StringRef(" musttail caller")};
3697 verifyTailCCMustTailAttrs(ABIAttrs
, Context
);
3699 for (unsigned I
= 0, E
= CalleeTy
->getNumParams(); I
!= E
; ++I
) {
3700 AttrBuilder ABIAttrs
= getParameterABIAttributes(F
->getContext(), I
, CalleeAttrs
);
3701 SmallString
<32> Context
{CCName
, StringRef(" musttail callee")};
3702 verifyTailCCMustTailAttrs(ABIAttrs
, Context
);
3704 // - Varargs functions are not allowed
3705 Check(!CallerTy
->isVarArg(), Twine("cannot guarantee ") + CCName
+
3706 " tail call for varargs function");
3710 // - The caller and callee prototypes must match. Pointer types of
3711 // parameters or return types may differ in pointee type, but not
3713 if (!CI
.getCalledFunction() || !CI
.getCalledFunction()->isIntrinsic()) {
3714 Check(CallerTy
->getNumParams() == CalleeTy
->getNumParams(),
3715 "cannot guarantee tail call due to mismatched parameter counts", &CI
);
3716 for (unsigned I
= 0, E
= CallerTy
->getNumParams(); I
!= E
; ++I
) {
3718 isTypeCongruent(CallerTy
->getParamType(I
), CalleeTy
->getParamType(I
)),
3719 "cannot guarantee tail call due to mismatched parameter types", &CI
);
3723 // - All ABI-impacting function attributes, such as sret, byval, inreg,
3724 // returned, preallocated, and inalloca, must match.
3725 for (unsigned I
= 0, E
= CallerTy
->getNumParams(); I
!= E
; ++I
) {
3726 AttrBuilder CallerABIAttrs
= getParameterABIAttributes(F
->getContext(), I
, CallerAttrs
);
3727 AttrBuilder CalleeABIAttrs
= getParameterABIAttributes(F
->getContext(), I
, CalleeAttrs
);
3728 Check(CallerABIAttrs
== CalleeABIAttrs
,
3729 "cannot guarantee tail call due to mismatched ABI impacting "
3730 "function attributes",
3731 &CI
, CI
.getOperand(I
));
3735 void Verifier::visitCallInst(CallInst
&CI
) {
3738 if (CI
.isMustTailCall())
3739 verifyMustTailCall(CI
);
3742 void Verifier::visitInvokeInst(InvokeInst
&II
) {
3745 // Verify that the first non-PHI instruction of the unwind destination is an
3746 // exception handling instruction.
3748 II
.getUnwindDest()->isEHPad(),
3749 "The unwind destination does not have an exception handling instruction!",
3752 visitTerminator(II
);
3755 /// visitUnaryOperator - Check the argument to the unary operator.
3757 void Verifier::visitUnaryOperator(UnaryOperator
&U
) {
3758 Check(U
.getType() == U
.getOperand(0)->getType(),
3759 "Unary operators must have same type for"
3760 "operands and result!",
3763 switch (U
.getOpcode()) {
3764 // Check that floating-point arithmetic operators are only used with
3765 // floating-point operands.
3766 case Instruction::FNeg
:
3767 Check(U
.getType()->isFPOrFPVectorTy(),
3768 "FNeg operator only works with float types!", &U
);
3771 llvm_unreachable("Unknown UnaryOperator opcode!");
3774 visitInstruction(U
);
3777 /// visitBinaryOperator - Check that both arguments to the binary operator are
3778 /// of the same type!
3780 void Verifier::visitBinaryOperator(BinaryOperator
&B
) {
3781 Check(B
.getOperand(0)->getType() == B
.getOperand(1)->getType(),
3782 "Both operands to a binary operator are not of the same type!", &B
);
3784 switch (B
.getOpcode()) {
3785 // Check that integer arithmetic operators are only used with
3786 // integral operands.
3787 case Instruction::Add
:
3788 case Instruction::Sub
:
3789 case Instruction::Mul
:
3790 case Instruction::SDiv
:
3791 case Instruction::UDiv
:
3792 case Instruction::SRem
:
3793 case Instruction::URem
:
3794 Check(B
.getType()->isIntOrIntVectorTy(),
3795 "Integer arithmetic operators only work with integral types!", &B
);
3796 Check(B
.getType() == B
.getOperand(0)->getType(),
3797 "Integer arithmetic operators must have same type "
3798 "for operands and result!",
3801 // Check that floating-point arithmetic operators are only used with
3802 // floating-point operands.
3803 case Instruction::FAdd
:
3804 case Instruction::FSub
:
3805 case Instruction::FMul
:
3806 case Instruction::FDiv
:
3807 case Instruction::FRem
:
3808 Check(B
.getType()->isFPOrFPVectorTy(),
3809 "Floating-point arithmetic operators only work with "
3810 "floating-point types!",
3812 Check(B
.getType() == B
.getOperand(0)->getType(),
3813 "Floating-point arithmetic operators must have same type "
3814 "for operands and result!",
3817 // Check that logical operators are only used with integral operands.
3818 case Instruction::And
:
3819 case Instruction::Or
:
3820 case Instruction::Xor
:
3821 Check(B
.getType()->isIntOrIntVectorTy(),
3822 "Logical operators only work with integral types!", &B
);
3823 Check(B
.getType() == B
.getOperand(0)->getType(),
3824 "Logical operators must have same type for operands and result!", &B
);
3826 case Instruction::Shl
:
3827 case Instruction::LShr
:
3828 case Instruction::AShr
:
3829 Check(B
.getType()->isIntOrIntVectorTy(),
3830 "Shifts only work with integral types!", &B
);
3831 Check(B
.getType() == B
.getOperand(0)->getType(),
3832 "Shift return type must be same as operands!", &B
);
3835 llvm_unreachable("Unknown BinaryOperator opcode!");
3838 visitInstruction(B
);
3841 void Verifier::visitICmpInst(ICmpInst
&IC
) {
3842 // Check that the operands are the same type
3843 Type
*Op0Ty
= IC
.getOperand(0)->getType();
3844 Type
*Op1Ty
= IC
.getOperand(1)->getType();
3845 Check(Op0Ty
== Op1Ty
,
3846 "Both operands to ICmp instruction are not of the same type!", &IC
);
3847 // Check that the operands are the right type
3848 Check(Op0Ty
->isIntOrIntVectorTy() || Op0Ty
->isPtrOrPtrVectorTy(),
3849 "Invalid operand types for ICmp instruction", &IC
);
3850 // Check that the predicate is valid.
3851 Check(IC
.isIntPredicate(), "Invalid predicate in ICmp instruction!", &IC
);
3853 visitInstruction(IC
);
3856 void Verifier::visitFCmpInst(FCmpInst
&FC
) {
3857 // Check that the operands are the same type
3858 Type
*Op0Ty
= FC
.getOperand(0)->getType();
3859 Type
*Op1Ty
= FC
.getOperand(1)->getType();
3860 Check(Op0Ty
== Op1Ty
,
3861 "Both operands to FCmp instruction are not of the same type!", &FC
);
3862 // Check that the operands are the right type
3863 Check(Op0Ty
->isFPOrFPVectorTy(), "Invalid operand types for FCmp instruction",
3865 // Check that the predicate is valid.
3866 Check(FC
.isFPPredicate(), "Invalid predicate in FCmp instruction!", &FC
);
3868 visitInstruction(FC
);
3871 void Verifier::visitExtractElementInst(ExtractElementInst
&EI
) {
3872 Check(ExtractElementInst::isValidOperands(EI
.getOperand(0), EI
.getOperand(1)),
3873 "Invalid extractelement operands!", &EI
);
3874 visitInstruction(EI
);
3877 void Verifier::visitInsertElementInst(InsertElementInst
&IE
) {
3878 Check(InsertElementInst::isValidOperands(IE
.getOperand(0), IE
.getOperand(1),
3880 "Invalid insertelement operands!", &IE
);
3881 visitInstruction(IE
);
3884 void Verifier::visitShuffleVectorInst(ShuffleVectorInst
&SV
) {
3885 Check(ShuffleVectorInst::isValidOperands(SV
.getOperand(0), SV
.getOperand(1),
3886 SV
.getShuffleMask()),
3887 "Invalid shufflevector operands!", &SV
);
3888 visitInstruction(SV
);
3891 void Verifier::visitGetElementPtrInst(GetElementPtrInst
&GEP
) {
3892 Type
*TargetTy
= GEP
.getPointerOperandType()->getScalarType();
3894 Check(isa
<PointerType
>(TargetTy
),
3895 "GEP base pointer is not a vector or a vector of pointers", &GEP
);
3896 Check(GEP
.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP
);
3898 if (auto *STy
= dyn_cast
<StructType
>(GEP
.getSourceElementType())) {
3899 SmallPtrSet
<Type
*, 4> Visited
;
3900 Check(!STy
->containsScalableVectorType(&Visited
),
3901 "getelementptr cannot target structure that contains scalable vector"
3906 SmallVector
<Value
*, 16> Idxs(GEP
.indices());
3908 all_of(Idxs
, [](Value
*V
) { return V
->getType()->isIntOrIntVectorTy(); }),
3909 "GEP indexes must be integers", &GEP
);
3911 GetElementPtrInst::getIndexedType(GEP
.getSourceElementType(), Idxs
);
3912 Check(ElTy
, "Invalid indices for GEP pointer type!", &GEP
);
3914 Check(GEP
.getType()->isPtrOrPtrVectorTy() &&
3915 GEP
.getResultElementType() == ElTy
,
3916 "GEP is not of right type for indices!", &GEP
, ElTy
);
3918 if (auto *GEPVTy
= dyn_cast
<VectorType
>(GEP
.getType())) {
3919 // Additional checks for vector GEPs.
3920 ElementCount GEPWidth
= GEPVTy
->getElementCount();
3921 if (GEP
.getPointerOperandType()->isVectorTy())
3924 cast
<VectorType
>(GEP
.getPointerOperandType())->getElementCount(),
3925 "Vector GEP result width doesn't match operand's", &GEP
);
3926 for (Value
*Idx
: Idxs
) {
3927 Type
*IndexTy
= Idx
->getType();
3928 if (auto *IndexVTy
= dyn_cast
<VectorType
>(IndexTy
)) {
3929 ElementCount IndexWidth
= IndexVTy
->getElementCount();
3930 Check(IndexWidth
== GEPWidth
, "Invalid GEP index vector width", &GEP
);
3932 Check(IndexTy
->isIntOrIntVectorTy(),
3933 "All GEP indices should be of integer type");
3937 if (auto *PTy
= dyn_cast
<PointerType
>(GEP
.getType())) {
3938 Check(GEP
.getAddressSpace() == PTy
->getAddressSpace(),
3939 "GEP address space doesn't match type", &GEP
);
3942 visitInstruction(GEP
);
3945 static bool isContiguous(const ConstantRange
&A
, const ConstantRange
&B
) {
3946 return A
.getUpper() == B
.getLower() || A
.getLower() == B
.getUpper();
3949 /// Verify !range and !absolute_symbol metadata. These have the same
3950 /// restrictions, except !absolute_symbol allows the full set.
3951 void Verifier::verifyRangeMetadata(const Value
&I
, const MDNode
*Range
,
3952 Type
*Ty
, bool IsAbsoluteSymbol
) {
3953 unsigned NumOperands
= Range
->getNumOperands();
3954 Check(NumOperands
% 2 == 0, "Unfinished range!", Range
);
3955 unsigned NumRanges
= NumOperands
/ 2;
3956 Check(NumRanges
>= 1, "It should have at least one range!", Range
);
3958 ConstantRange
LastRange(1, true); // Dummy initial value
3959 for (unsigned i
= 0; i
< NumRanges
; ++i
) {
3961 mdconst::dyn_extract
<ConstantInt
>(Range
->getOperand(2 * i
));
3962 Check(Low
, "The lower limit must be an integer!", Low
);
3964 mdconst::dyn_extract
<ConstantInt
>(Range
->getOperand(2 * i
+ 1));
3965 Check(High
, "The upper limit must be an integer!", High
);
3966 Check(High
->getType() == Low
->getType() &&
3967 High
->getType() == Ty
->getScalarType(),
3968 "Range types must match instruction type!", &I
);
3970 APInt HighV
= High
->getValue();
3971 APInt LowV
= Low
->getValue();
3973 // ConstantRange asserts if the ranges are the same except for the min/max
3974 // value. Leave the cases it tolerates for the empty range error below.
3975 Check(LowV
!= HighV
|| LowV
.isMaxValue() || LowV
.isMinValue(),
3976 "The upper and lower limits cannot be the same value", &I
);
3978 ConstantRange
CurRange(LowV
, HighV
);
3979 Check(!CurRange
.isEmptySet() && (IsAbsoluteSymbol
|| !CurRange
.isFullSet()),
3980 "Range must not be empty!", Range
);
3982 Check(CurRange
.intersectWith(LastRange
).isEmptySet(),
3983 "Intervals are overlapping", Range
);
3984 Check(LowV
.sgt(LastRange
.getLower()), "Intervals are not in order",
3986 Check(!isContiguous(CurRange
, LastRange
), "Intervals are contiguous",
3989 LastRange
= ConstantRange(LowV
, HighV
);
3991 if (NumRanges
> 2) {
3993 mdconst::dyn_extract
<ConstantInt
>(Range
->getOperand(0))->getValue();
3995 mdconst::dyn_extract
<ConstantInt
>(Range
->getOperand(1))->getValue();
3996 ConstantRange
FirstRange(FirstLow
, FirstHigh
);
3997 Check(FirstRange
.intersectWith(LastRange
).isEmptySet(),
3998 "Intervals are overlapping", Range
);
3999 Check(!isContiguous(FirstRange
, LastRange
), "Intervals are contiguous",
4004 void Verifier::visitRangeMetadata(Instruction
&I
, MDNode
*Range
, Type
*Ty
) {
4005 assert(Range
&& Range
== I
.getMetadata(LLVMContext::MD_range
) &&
4006 "precondition violation");
4007 verifyRangeMetadata(I
, Range
, Ty
, false);
4010 void Verifier::checkAtomicMemAccessSize(Type
*Ty
, const Instruction
*I
) {
4011 unsigned Size
= DL
.getTypeSizeInBits(Ty
);
4012 Check(Size
>= 8, "atomic memory access' size must be byte-sized", Ty
, I
);
4013 Check(!(Size
& (Size
- 1)),
4014 "atomic memory access' operand must have a power-of-two size", Ty
, I
);
4017 void Verifier::visitLoadInst(LoadInst
&LI
) {
4018 PointerType
*PTy
= dyn_cast
<PointerType
>(LI
.getOperand(0)->getType());
4019 Check(PTy
, "Load operand must be a pointer.", &LI
);
4020 Type
*ElTy
= LI
.getType();
4021 if (MaybeAlign A
= LI
.getAlign()) {
4022 Check(A
->value() <= Value::MaximumAlignment
,
4023 "huge alignment values are unsupported", &LI
);
4025 Check(ElTy
->isSized(), "loading unsized types is not allowed", &LI
);
4026 if (LI
.isAtomic()) {
4027 Check(LI
.getOrdering() != AtomicOrdering::Release
&&
4028 LI
.getOrdering() != AtomicOrdering::AcquireRelease
,
4029 "Load cannot have Release ordering", &LI
);
4030 Check(ElTy
->isIntOrPtrTy() || ElTy
->isFloatingPointTy(),
4031 "atomic load operand must have integer, pointer, or floating point "
4034 checkAtomicMemAccessSize(ElTy
, &LI
);
4036 Check(LI
.getSyncScopeID() == SyncScope::System
,
4037 "Non-atomic load cannot have SynchronizationScope specified", &LI
);
4040 visitInstruction(LI
);
4043 void Verifier::visitStoreInst(StoreInst
&SI
) {
4044 PointerType
*PTy
= dyn_cast
<PointerType
>(SI
.getOperand(1)->getType());
4045 Check(PTy
, "Store operand must be a pointer.", &SI
);
4046 Type
*ElTy
= SI
.getOperand(0)->getType();
4047 if (MaybeAlign A
= SI
.getAlign()) {
4048 Check(A
->value() <= Value::MaximumAlignment
,
4049 "huge alignment values are unsupported", &SI
);
4051 Check(ElTy
->isSized(), "storing unsized types is not allowed", &SI
);
4052 if (SI
.isAtomic()) {
4053 Check(SI
.getOrdering() != AtomicOrdering::Acquire
&&
4054 SI
.getOrdering() != AtomicOrdering::AcquireRelease
,
4055 "Store cannot have Acquire ordering", &SI
);
4056 Check(ElTy
->isIntOrPtrTy() || ElTy
->isFloatingPointTy(),
4057 "atomic store operand must have integer, pointer, or floating point "
4060 checkAtomicMemAccessSize(ElTy
, &SI
);
4062 Check(SI
.getSyncScopeID() == SyncScope::System
,
4063 "Non-atomic store cannot have SynchronizationScope specified", &SI
);
4065 visitInstruction(SI
);
4068 /// Check that SwiftErrorVal is used as a swifterror argument in CS.
4069 void Verifier::verifySwiftErrorCall(CallBase
&Call
,
4070 const Value
*SwiftErrorVal
) {
4071 for (const auto &I
: llvm::enumerate(Call
.args())) {
4072 if (I
.value() == SwiftErrorVal
) {
4073 Check(Call
.paramHasAttr(I
.index(), Attribute::SwiftError
),
4074 "swifterror value when used in a callsite should be marked "
4075 "with swifterror attribute",
4076 SwiftErrorVal
, Call
);
4081 void Verifier::verifySwiftErrorValue(const Value
*SwiftErrorVal
) {
4082 // Check that swifterror value is only used by loads, stores, or as
4083 // a swifterror argument.
4084 for (const User
*U
: SwiftErrorVal
->users()) {
4085 Check(isa
<LoadInst
>(U
) || isa
<StoreInst
>(U
) || isa
<CallInst
>(U
) ||
4087 "swifterror value can only be loaded and stored from, or "
4088 "as a swifterror argument!",
4090 // If it is used by a store, check it is the second operand.
4091 if (auto StoreI
= dyn_cast
<StoreInst
>(U
))
4092 Check(StoreI
->getOperand(1) == SwiftErrorVal
,
4093 "swifterror value should be the second operand when used "
4096 if (auto *Call
= dyn_cast
<CallBase
>(U
))
4097 verifySwiftErrorCall(*const_cast<CallBase
*>(Call
), SwiftErrorVal
);
4101 void Verifier::visitAllocaInst(AllocaInst
&AI
) {
4102 SmallPtrSet
<Type
*, 4> Visited
;
4103 Check(AI
.getAllocatedType()->isSized(&Visited
),
4104 "Cannot allocate unsized type", &AI
);
4105 Check(AI
.getArraySize()->getType()->isIntegerTy(),
4106 "Alloca array size must have integer type", &AI
);
4107 if (MaybeAlign A
= AI
.getAlign()) {
4108 Check(A
->value() <= Value::MaximumAlignment
,
4109 "huge alignment values are unsupported", &AI
);
4112 if (AI
.isSwiftError()) {
4113 Check(AI
.getAllocatedType()->isPointerTy(),
4114 "swifterror alloca must have pointer type", &AI
);
4115 Check(!AI
.isArrayAllocation(),
4116 "swifterror alloca must not be array allocation", &AI
);
4117 verifySwiftErrorValue(&AI
);
4120 visitInstruction(AI
);
4123 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst
&CXI
) {
4124 Type
*ElTy
= CXI
.getOperand(1)->getType();
4125 Check(ElTy
->isIntOrPtrTy(),
4126 "cmpxchg operand must have integer or pointer type", ElTy
, &CXI
);
4127 checkAtomicMemAccessSize(ElTy
, &CXI
);
4128 visitInstruction(CXI
);
4131 void Verifier::visitAtomicRMWInst(AtomicRMWInst
&RMWI
) {
4132 Check(RMWI
.getOrdering() != AtomicOrdering::Unordered
,
4133 "atomicrmw instructions cannot be unordered.", &RMWI
);
4134 auto Op
= RMWI
.getOperation();
4135 Type
*ElTy
= RMWI
.getOperand(1)->getType();
4136 if (Op
== AtomicRMWInst::Xchg
) {
4137 Check(ElTy
->isIntegerTy() || ElTy
->isFloatingPointTy() ||
4138 ElTy
->isPointerTy(),
4139 "atomicrmw " + AtomicRMWInst::getOperationName(Op
) +
4140 " operand must have integer or floating point type!",
4142 } else if (AtomicRMWInst::isFPOperation(Op
)) {
4143 Check(ElTy
->isFloatingPointTy(),
4144 "atomicrmw " + AtomicRMWInst::getOperationName(Op
) +
4145 " operand must have floating point type!",
4148 Check(ElTy
->isIntegerTy(),
4149 "atomicrmw " + AtomicRMWInst::getOperationName(Op
) +
4150 " operand must have integer type!",
4153 checkAtomicMemAccessSize(ElTy
, &RMWI
);
4154 Check(AtomicRMWInst::FIRST_BINOP
<= Op
&& Op
<= AtomicRMWInst::LAST_BINOP
,
4155 "Invalid binary operation!", &RMWI
);
4156 visitInstruction(RMWI
);
4159 void Verifier::visitFenceInst(FenceInst
&FI
) {
4160 const AtomicOrdering Ordering
= FI
.getOrdering();
4161 Check(Ordering
== AtomicOrdering::Acquire
||
4162 Ordering
== AtomicOrdering::Release
||
4163 Ordering
== AtomicOrdering::AcquireRelease
||
4164 Ordering
== AtomicOrdering::SequentiallyConsistent
,
4165 "fence instructions may only have acquire, release, acq_rel, or "
4166 "seq_cst ordering.",
4168 visitInstruction(FI
);
4171 void Verifier::visitExtractValueInst(ExtractValueInst
&EVI
) {
4172 Check(ExtractValueInst::getIndexedType(EVI
.getAggregateOperand()->getType(),
4173 EVI
.getIndices()) == EVI
.getType(),
4174 "Invalid ExtractValueInst operands!", &EVI
);
4176 visitInstruction(EVI
);
4179 void Verifier::visitInsertValueInst(InsertValueInst
&IVI
) {
4180 Check(ExtractValueInst::getIndexedType(IVI
.getAggregateOperand()->getType(),
4181 IVI
.getIndices()) ==
4182 IVI
.getOperand(1)->getType(),
4183 "Invalid InsertValueInst operands!", &IVI
);
4185 visitInstruction(IVI
);
4188 static Value
*getParentPad(Value
*EHPad
) {
4189 if (auto *FPI
= dyn_cast
<FuncletPadInst
>(EHPad
))
4190 return FPI
->getParentPad();
4192 return cast
<CatchSwitchInst
>(EHPad
)->getParentPad();
4195 void Verifier::visitEHPadPredecessors(Instruction
&I
) {
4196 assert(I
.isEHPad());
4198 BasicBlock
*BB
= I
.getParent();
4199 Function
*F
= BB
->getParent();
4201 Check(BB
!= &F
->getEntryBlock(), "EH pad cannot be in entry block.", &I
);
4203 if (auto *LPI
= dyn_cast
<LandingPadInst
>(&I
)) {
4204 // The landingpad instruction defines its parent as a landing pad block. The
4205 // landing pad block may be branched to only by the unwind edge of an
4207 for (BasicBlock
*PredBB
: predecessors(BB
)) {
4208 const auto *II
= dyn_cast
<InvokeInst
>(PredBB
->getTerminator());
4209 Check(II
&& II
->getUnwindDest() == BB
&& II
->getNormalDest() != BB
,
4210 "Block containing LandingPadInst must be jumped to "
4211 "only by the unwind edge of an invoke.",
4216 if (auto *CPI
= dyn_cast
<CatchPadInst
>(&I
)) {
4217 if (!pred_empty(BB
))
4218 Check(BB
->getUniquePredecessor() == CPI
->getCatchSwitch()->getParent(),
4219 "Block containg CatchPadInst must be jumped to "
4220 "only by its catchswitch.",
4222 Check(BB
!= CPI
->getCatchSwitch()->getUnwindDest(),
4223 "Catchswitch cannot unwind to one of its catchpads",
4224 CPI
->getCatchSwitch(), CPI
);
4228 // Verify that each pred has a legal terminator with a legal to/from EH
4229 // pad relationship.
4230 Instruction
*ToPad
= &I
;
4231 Value
*ToPadParent
= getParentPad(ToPad
);
4232 for (BasicBlock
*PredBB
: predecessors(BB
)) {
4233 Instruction
*TI
= PredBB
->getTerminator();
4235 if (auto *II
= dyn_cast
<InvokeInst
>(TI
)) {
4236 Check(II
->getUnwindDest() == BB
&& II
->getNormalDest() != BB
,
4237 "EH pad must be jumped to via an unwind edge", ToPad
, II
);
4238 if (auto Bundle
= II
->getOperandBundle(LLVMContext::OB_funclet
))
4239 FromPad
= Bundle
->Inputs
[0];
4241 FromPad
= ConstantTokenNone::get(II
->getContext());
4242 } else if (auto *CRI
= dyn_cast
<CleanupReturnInst
>(TI
)) {
4243 FromPad
= CRI
->getOperand(0);
4244 Check(FromPad
!= ToPadParent
, "A cleanupret must exit its cleanup", CRI
);
4245 } else if (auto *CSI
= dyn_cast
<CatchSwitchInst
>(TI
)) {
4248 Check(false, "EH pad must be jumped to via an unwind edge", ToPad
, TI
);
4251 // The edge may exit from zero or more nested pads.
4252 SmallSet
<Value
*, 8> Seen
;
4253 for (;; FromPad
= getParentPad(FromPad
)) {
4254 Check(FromPad
!= ToPad
,
4255 "EH pad cannot handle exceptions raised within it", FromPad
, TI
);
4256 if (FromPad
== ToPadParent
) {
4257 // This is a legal unwind edge.
4260 Check(!isa
<ConstantTokenNone
>(FromPad
),
4261 "A single unwind edge may only enter one EH pad", TI
);
4262 Check(Seen
.insert(FromPad
).second
, "EH pad jumps through a cycle of pads",
4265 // This will be diagnosed on the corresponding instruction already. We
4266 // need the extra check here to make sure getParentPad() works.
4267 Check(isa
<FuncletPadInst
>(FromPad
) || isa
<CatchSwitchInst
>(FromPad
),
4268 "Parent pad must be catchpad/cleanuppad/catchswitch", TI
);
4273 void Verifier::visitLandingPadInst(LandingPadInst
&LPI
) {
4274 // The landingpad instruction is ill-formed if it doesn't have any clauses and
4276 Check(LPI
.getNumClauses() > 0 || LPI
.isCleanup(),
4277 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI
);
4279 visitEHPadPredecessors(LPI
);
4281 if (!LandingPadResultTy
)
4282 LandingPadResultTy
= LPI
.getType();
4284 Check(LandingPadResultTy
== LPI
.getType(),
4285 "The landingpad instruction should have a consistent result type "
4286 "inside a function.",
4289 Function
*F
= LPI
.getParent()->getParent();
4290 Check(F
->hasPersonalityFn(),
4291 "LandingPadInst needs to be in a function with a personality.", &LPI
);
4293 // The landingpad instruction must be the first non-PHI instruction in the
4295 Check(LPI
.getParent()->getLandingPadInst() == &LPI
,
4296 "LandingPadInst not the first non-PHI instruction in the block.", &LPI
);
4298 for (unsigned i
= 0, e
= LPI
.getNumClauses(); i
< e
; ++i
) {
4299 Constant
*Clause
= LPI
.getClause(i
);
4300 if (LPI
.isCatch(i
)) {
4301 Check(isa
<PointerType
>(Clause
->getType()),
4302 "Catch operand does not have pointer type!", &LPI
);
4304 Check(LPI
.isFilter(i
), "Clause is neither catch nor filter!", &LPI
);
4305 Check(isa
<ConstantArray
>(Clause
) || isa
<ConstantAggregateZero
>(Clause
),
4306 "Filter operand is not an array of constants!", &LPI
);
4310 visitInstruction(LPI
);
4313 void Verifier::visitResumeInst(ResumeInst
&RI
) {
4314 Check(RI
.getFunction()->hasPersonalityFn(),
4315 "ResumeInst needs to be in a function with a personality.", &RI
);
4317 if (!LandingPadResultTy
)
4318 LandingPadResultTy
= RI
.getValue()->getType();
4320 Check(LandingPadResultTy
== RI
.getValue()->getType(),
4321 "The resume instruction should have a consistent result type "
4322 "inside a function.",
4325 visitTerminator(RI
);
4328 void Verifier::visitCatchPadInst(CatchPadInst
&CPI
) {
4329 BasicBlock
*BB
= CPI
.getParent();
4331 Function
*F
= BB
->getParent();
4332 Check(F
->hasPersonalityFn(),
4333 "CatchPadInst needs to be in a function with a personality.", &CPI
);
4335 Check(isa
<CatchSwitchInst
>(CPI
.getParentPad()),
4336 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4337 CPI
.getParentPad());
4339 // The catchpad instruction must be the first non-PHI instruction in the
4341 Check(BB
->getFirstNonPHI() == &CPI
,
4342 "CatchPadInst not the first non-PHI instruction in the block.", &CPI
);
4344 visitEHPadPredecessors(CPI
);
4345 visitFuncletPadInst(CPI
);
4348 void Verifier::visitCatchReturnInst(CatchReturnInst
&CatchReturn
) {
4349 Check(isa
<CatchPadInst
>(CatchReturn
.getOperand(0)),
4350 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn
,
4351 CatchReturn
.getOperand(0));
4353 visitTerminator(CatchReturn
);
4356 void Verifier::visitCleanupPadInst(CleanupPadInst
&CPI
) {
4357 BasicBlock
*BB
= CPI
.getParent();
4359 Function
*F
= BB
->getParent();
4360 Check(F
->hasPersonalityFn(),
4361 "CleanupPadInst needs to be in a function with a personality.", &CPI
);
4363 // The cleanuppad instruction must be the first non-PHI instruction in the
4365 Check(BB
->getFirstNonPHI() == &CPI
,
4366 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI
);
4368 auto *ParentPad
= CPI
.getParentPad();
4369 Check(isa
<ConstantTokenNone
>(ParentPad
) || isa
<FuncletPadInst
>(ParentPad
),
4370 "CleanupPadInst has an invalid parent.", &CPI
);
4372 visitEHPadPredecessors(CPI
);
4373 visitFuncletPadInst(CPI
);
4376 void Verifier::visitFuncletPadInst(FuncletPadInst
&FPI
) {
4377 User
*FirstUser
= nullptr;
4378 Value
*FirstUnwindPad
= nullptr;
4379 SmallVector
<FuncletPadInst
*, 8> Worklist({&FPI
});
4380 SmallSet
<FuncletPadInst
*, 8> Seen
;
4382 while (!Worklist
.empty()) {
4383 FuncletPadInst
*CurrentPad
= Worklist
.pop_back_val();
4384 Check(Seen
.insert(CurrentPad
).second
,
4385 "FuncletPadInst must not be nested within itself", CurrentPad
);
4386 Value
*UnresolvedAncestorPad
= nullptr;
4387 for (User
*U
: CurrentPad
->users()) {
4388 BasicBlock
*UnwindDest
;
4389 if (auto *CRI
= dyn_cast
<CleanupReturnInst
>(U
)) {
4390 UnwindDest
= CRI
->getUnwindDest();
4391 } else if (auto *CSI
= dyn_cast
<CatchSwitchInst
>(U
)) {
4392 // We allow catchswitch unwind to caller to nest
4393 // within an outer pad that unwinds somewhere else,
4394 // because catchswitch doesn't have a nounwind variant.
4395 // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
4396 if (CSI
->unwindsToCaller())
4398 UnwindDest
= CSI
->getUnwindDest();
4399 } else if (auto *II
= dyn_cast
<InvokeInst
>(U
)) {
4400 UnwindDest
= II
->getUnwindDest();
4401 } else if (isa
<CallInst
>(U
)) {
4402 // Calls which don't unwind may be found inside funclet
4403 // pads that unwind somewhere else. We don't *require*
4404 // such calls to be annotated nounwind.
4406 } else if (auto *CPI
= dyn_cast
<CleanupPadInst
>(U
)) {
4407 // The unwind dest for a cleanup can only be found by
4408 // recursive search. Add it to the worklist, and we'll
4409 // search for its first use that determines where it unwinds.
4410 Worklist
.push_back(CPI
);
4413 Check(isa
<CatchReturnInst
>(U
), "Bogus funclet pad use", U
);
4420 UnwindPad
= UnwindDest
->getFirstNonPHI();
4421 if (!cast
<Instruction
>(UnwindPad
)->isEHPad())
4423 Value
*UnwindParent
= getParentPad(UnwindPad
);
4424 // Ignore unwind edges that don't exit CurrentPad.
4425 if (UnwindParent
== CurrentPad
)
4427 // Determine whether the original funclet pad is exited,
4428 // and if we are scanning nested pads determine how many
4429 // of them are exited so we can stop searching their
4431 Value
*ExitedPad
= CurrentPad
;
4434 if (ExitedPad
== &FPI
) {
4436 // Now we can resolve any ancestors of CurrentPad up to
4437 // FPI, but not including FPI since we need to make sure
4438 // to check all direct users of FPI for consistency.
4439 UnresolvedAncestorPad
= &FPI
;
4442 Value
*ExitedParent
= getParentPad(ExitedPad
);
4443 if (ExitedParent
== UnwindParent
) {
4444 // ExitedPad is the ancestor-most pad which this unwind
4445 // edge exits, so we can resolve up to it, meaning that
4446 // ExitedParent is the first ancestor still unresolved.
4447 UnresolvedAncestorPad
= ExitedParent
;
4450 ExitedPad
= ExitedParent
;
4451 } while (!isa
<ConstantTokenNone
>(ExitedPad
));
4453 // Unwinding to caller exits all pads.
4454 UnwindPad
= ConstantTokenNone::get(FPI
.getContext());
4456 UnresolvedAncestorPad
= &FPI
;
4460 // This unwind edge exits FPI. Make sure it agrees with other
4463 Check(UnwindPad
== FirstUnwindPad
,
4464 "Unwind edges out of a funclet "
4465 "pad must have the same unwind "
4467 &FPI
, U
, FirstUser
);
4470 FirstUnwindPad
= UnwindPad
;
4471 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
4472 if (isa
<CleanupPadInst
>(&FPI
) && !isa
<ConstantTokenNone
>(UnwindPad
) &&
4473 getParentPad(UnwindPad
) == getParentPad(&FPI
))
4474 SiblingFuncletInfo
[&FPI
] = cast
<Instruction
>(U
);
4477 // Make sure we visit all uses of FPI, but for nested pads stop as
4478 // soon as we know where they unwind to.
4479 if (CurrentPad
!= &FPI
)
4482 if (UnresolvedAncestorPad
) {
4483 if (CurrentPad
== UnresolvedAncestorPad
) {
4484 // When CurrentPad is FPI itself, we don't mark it as resolved even if
4485 // we've found an unwind edge that exits it, because we need to verify
4486 // all direct uses of FPI.
4487 assert(CurrentPad
== &FPI
);
4490 // Pop off the worklist any nested pads that we've found an unwind
4491 // destination for. The pads on the worklist are the uncles,
4492 // great-uncles, etc. of CurrentPad. We've found an unwind destination
4493 // for all ancestors of CurrentPad up to but not including
4494 // UnresolvedAncestorPad.
4495 Value
*ResolvedPad
= CurrentPad
;
4496 while (!Worklist
.empty()) {
4497 Value
*UnclePad
= Worklist
.back();
4498 Value
*AncestorPad
= getParentPad(UnclePad
);
4499 // Walk ResolvedPad up the ancestor list until we either find the
4500 // uncle's parent or the last resolved ancestor.
4501 while (ResolvedPad
!= AncestorPad
) {
4502 Value
*ResolvedParent
= getParentPad(ResolvedPad
);
4503 if (ResolvedParent
== UnresolvedAncestorPad
) {
4506 ResolvedPad
= ResolvedParent
;
4508 // If the resolved ancestor search didn't find the uncle's parent,
4509 // then the uncle is not yet resolved.
4510 if (ResolvedPad
!= AncestorPad
)
4512 // This uncle is resolved, so pop it from the worklist.
4513 Worklist
.pop_back();
4518 if (FirstUnwindPad
) {
4519 if (auto *CatchSwitch
= dyn_cast
<CatchSwitchInst
>(FPI
.getParentPad())) {
4520 BasicBlock
*SwitchUnwindDest
= CatchSwitch
->getUnwindDest();
4521 Value
*SwitchUnwindPad
;
4522 if (SwitchUnwindDest
)
4523 SwitchUnwindPad
= SwitchUnwindDest
->getFirstNonPHI();
4525 SwitchUnwindPad
= ConstantTokenNone::get(FPI
.getContext());
4526 Check(SwitchUnwindPad
== FirstUnwindPad
,
4527 "Unwind edges out of a catch must have the same unwind dest as "
4528 "the parent catchswitch",
4529 &FPI
, FirstUser
, CatchSwitch
);
4533 visitInstruction(FPI
);
4536 void Verifier::visitCatchSwitchInst(CatchSwitchInst
&CatchSwitch
) {
4537 BasicBlock
*BB
= CatchSwitch
.getParent();
4539 Function
*F
= BB
->getParent();
4540 Check(F
->hasPersonalityFn(),
4541 "CatchSwitchInst needs to be in a function with a personality.",
4544 // The catchswitch instruction must be the first non-PHI instruction in the
4546 Check(BB
->getFirstNonPHI() == &CatchSwitch
,
4547 "CatchSwitchInst not the first non-PHI instruction in the block.",
4550 auto *ParentPad
= CatchSwitch
.getParentPad();
4551 Check(isa
<ConstantTokenNone
>(ParentPad
) || isa
<FuncletPadInst
>(ParentPad
),
4552 "CatchSwitchInst has an invalid parent.", ParentPad
);
4554 if (BasicBlock
*UnwindDest
= CatchSwitch
.getUnwindDest()) {
4555 Instruction
*I
= UnwindDest
->getFirstNonPHI();
4556 Check(I
->isEHPad() && !isa
<LandingPadInst
>(I
),
4557 "CatchSwitchInst must unwind to an EH block which is not a "
4561 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
4562 if (getParentPad(I
) == ParentPad
)
4563 SiblingFuncletInfo
[&CatchSwitch
] = &CatchSwitch
;
4566 Check(CatchSwitch
.getNumHandlers() != 0,
4567 "CatchSwitchInst cannot have empty handler list", &CatchSwitch
);
4569 for (BasicBlock
*Handler
: CatchSwitch
.handlers()) {
4570 Check(isa
<CatchPadInst
>(Handler
->getFirstNonPHI()),
4571 "CatchSwitchInst handlers must be catchpads", &CatchSwitch
, Handler
);
4574 visitEHPadPredecessors(CatchSwitch
);
4575 visitTerminator(CatchSwitch
);
4578 void Verifier::visitCleanupReturnInst(CleanupReturnInst
&CRI
) {
4579 Check(isa
<CleanupPadInst
>(CRI
.getOperand(0)),
4580 "CleanupReturnInst needs to be provided a CleanupPad", &CRI
,
4583 if (BasicBlock
*UnwindDest
= CRI
.getUnwindDest()) {
4584 Instruction
*I
= UnwindDest
->getFirstNonPHI();
4585 Check(I
->isEHPad() && !isa
<LandingPadInst
>(I
),
4586 "CleanupReturnInst must unwind to an EH block which is not a "
4591 visitTerminator(CRI
);
4594 void Verifier::verifyDominatesUse(Instruction
&I
, unsigned i
) {
4595 Instruction
*Op
= cast
<Instruction
>(I
.getOperand(i
));
4596 // If the we have an invalid invoke, don't try to compute the dominance.
4597 // We already reject it in the invoke specific checks and the dominance
4598 // computation doesn't handle multiple edges.
4599 if (InvokeInst
*II
= dyn_cast
<InvokeInst
>(Op
)) {
4600 if (II
->getNormalDest() == II
->getUnwindDest())
4604 // Quick check whether the def has already been encountered in the same block.
4605 // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
4606 // uses are defined to happen on the incoming edge, not at the instruction.
4608 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
4609 // wrapping an SSA value, assert that we've already encountered it. See
4610 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
4611 if (!isa
<PHINode
>(I
) && InstsInThisBlock
.count(Op
))
4614 const Use
&U
= I
.getOperandUse(i
);
4615 Check(DT
.dominates(Op
, U
), "Instruction does not dominate all uses!", Op
, &I
);
4618 void Verifier::visitDereferenceableMetadata(Instruction
& I
, MDNode
* MD
) {
4619 Check(I
.getType()->isPointerTy(),
4620 "dereferenceable, dereferenceable_or_null "
4621 "apply only to pointer types",
4623 Check((isa
<LoadInst
>(I
) || isa
<IntToPtrInst
>(I
)),
4624 "dereferenceable, dereferenceable_or_null apply only to load"
4625 " and inttoptr instructions, use attributes for calls or invokes",
4627 Check(MD
->getNumOperands() == 1,
4628 "dereferenceable, dereferenceable_or_null "
4629 "take one operand!",
4631 ConstantInt
*CI
= mdconst::dyn_extract
<ConstantInt
>(MD
->getOperand(0));
4632 Check(CI
&& CI
->getType()->isIntegerTy(64),
4634 "dereferenceable_or_null metadata value must be an i64!",
4638 void Verifier::visitProfMetadata(Instruction
&I
, MDNode
*MD
) {
4639 Check(MD
->getNumOperands() >= 2,
4640 "!prof annotations should have no less than 2 operands", MD
);
4642 // Check first operand.
4643 Check(MD
->getOperand(0) != nullptr, "first operand should not be null", MD
);
4644 Check(isa
<MDString
>(MD
->getOperand(0)),
4645 "expected string with name of the !prof annotation", MD
);
4646 MDString
*MDS
= cast
<MDString
>(MD
->getOperand(0));
4647 StringRef ProfName
= MDS
->getString();
4649 // Check consistency of !prof branch_weights metadata.
4650 if (ProfName
.equals("branch_weights")) {
4651 if (isa
<InvokeInst
>(&I
)) {
4652 Check(MD
->getNumOperands() == 2 || MD
->getNumOperands() == 3,
4653 "Wrong number of InvokeInst branch_weights operands", MD
);
4655 unsigned ExpectedNumOperands
= 0;
4656 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(&I
))
4657 ExpectedNumOperands
= BI
->getNumSuccessors();
4658 else if (SwitchInst
*SI
= dyn_cast
<SwitchInst
>(&I
))
4659 ExpectedNumOperands
= SI
->getNumSuccessors();
4660 else if (isa
<CallInst
>(&I
))
4661 ExpectedNumOperands
= 1;
4662 else if (IndirectBrInst
*IBI
= dyn_cast
<IndirectBrInst
>(&I
))
4663 ExpectedNumOperands
= IBI
->getNumDestinations();
4664 else if (isa
<SelectInst
>(&I
))
4665 ExpectedNumOperands
= 2;
4666 else if (CallBrInst
*CI
= dyn_cast
<CallBrInst
>(&I
))
4667 ExpectedNumOperands
= CI
->getNumSuccessors();
4669 CheckFailed("!prof branch_weights are not allowed for this instruction",
4672 Check(MD
->getNumOperands() == 1 + ExpectedNumOperands
,
4673 "Wrong number of operands", MD
);
4675 for (unsigned i
= 1; i
< MD
->getNumOperands(); ++i
) {
4676 auto &MDO
= MD
->getOperand(i
);
4677 Check(MDO
, "second operand should not be null", MD
);
4678 Check(mdconst::dyn_extract
<ConstantInt
>(MDO
),
4679 "!prof brunch_weights operand is not a const int");
4684 void Verifier::visitDIAssignIDMetadata(Instruction
&I
, MDNode
*MD
) {
4685 assert(I
.hasMetadata(LLVMContext::MD_DIAssignID
));
4686 bool ExpectedInstTy
=
4687 isa
<AllocaInst
>(I
) || isa
<StoreInst
>(I
) || isa
<MemIntrinsic
>(I
);
4688 CheckDI(ExpectedInstTy
, "!DIAssignID attached to unexpected instruction kind",
4690 // Iterate over the MetadataAsValue uses of the DIAssignID - these should
4691 // only be found as DbgAssignIntrinsic operands.
4692 if (auto *AsValue
= MetadataAsValue::getIfExists(Context
, MD
)) {
4693 for (auto *User
: AsValue
->users()) {
4694 CheckDI(isa
<DbgAssignIntrinsic
>(User
),
4695 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
4697 // All of the dbg.assign intrinsics should be in the same function as I.
4698 if (auto *DAI
= dyn_cast
<DbgAssignIntrinsic
>(User
))
4699 CheckDI(DAI
->getFunction() == I
.getFunction(),
4700 "dbg.assign not in same function as inst", DAI
, &I
);
4705 void Verifier::visitCallStackMetadata(MDNode
*MD
) {
4706 // Call stack metadata should consist of a list of at least 1 constant int
4707 // (representing a hash of the location).
4708 Check(MD
->getNumOperands() >= 1,
4709 "call stack metadata should have at least 1 operand", MD
);
4711 for (const auto &Op
: MD
->operands())
4712 Check(mdconst::dyn_extract_or_null
<ConstantInt
>(Op
),
4713 "call stack metadata operand should be constant integer", Op
);
4716 void Verifier::visitMemProfMetadata(Instruction
&I
, MDNode
*MD
) {
4717 Check(isa
<CallBase
>(I
), "!memprof metadata should only exist on calls", &I
);
4718 Check(MD
->getNumOperands() >= 1,
4719 "!memprof annotations should have at least 1 metadata operand "
4724 for (auto &MIBOp
: MD
->operands()) {
4725 MDNode
*MIB
= dyn_cast
<MDNode
>(MIBOp
);
4726 // The first operand of an MIB should be the call stack metadata.
4727 // There rest of the operands should be MDString tags, and there should be
4729 Check(MIB
->getNumOperands() >= 2,
4730 "Each !memprof MemInfoBlock should have at least 2 operands", MIB
);
4732 // Check call stack metadata (first operand).
4733 Check(MIB
->getOperand(0) != nullptr,
4734 "!memprof MemInfoBlock first operand should not be null", MIB
);
4735 Check(isa
<MDNode
>(MIB
->getOperand(0)),
4736 "!memprof MemInfoBlock first operand should be an MDNode", MIB
);
4737 MDNode
*StackMD
= dyn_cast
<MDNode
>(MIB
->getOperand(0));
4738 visitCallStackMetadata(StackMD
);
4740 // Check that remaining operands are MDString.
4741 Check(llvm::all_of(llvm::drop_begin(MIB
->operands()),
4742 [](const MDOperand
&Op
) { return isa
<MDString
>(Op
); }),
4743 "Not all !memprof MemInfoBlock operands 1 to N are MDString", MIB
);
4747 void Verifier::visitCallsiteMetadata(Instruction
&I
, MDNode
*MD
) {
4748 Check(isa
<CallBase
>(I
), "!callsite metadata should only exist on calls", &I
);
4749 // Verify the partial callstack annotated from memprof profiles. This callsite
4750 // is a part of a profiled allocation callstack.
4751 visitCallStackMetadata(MD
);
4754 void Verifier::visitAnnotationMetadata(MDNode
*Annotation
) {
4755 Check(isa
<MDTuple
>(Annotation
), "annotation must be a tuple");
4756 Check(Annotation
->getNumOperands() >= 1,
4757 "annotation must have at least one operand");
4758 for (const MDOperand
&Op
: Annotation
->operands()) {
4759 bool TupleOfStrings
=
4760 isa
<MDTuple
>(Op
.get()) &&
4761 all_of(cast
<MDTuple
>(Op
)->operands(), [](auto &Annotation
) {
4762 return isa
<MDString
>(Annotation
.get());
4764 Check(isa
<MDString
>(Op
.get()) || TupleOfStrings
,
4765 "operands must be a string or a tuple of strings");
4769 void Verifier::visitAliasScopeMetadata(const MDNode
*MD
) {
4770 unsigned NumOps
= MD
->getNumOperands();
4771 Check(NumOps
>= 2 && NumOps
<= 3, "scope must have two or three operands",
4773 Check(MD
->getOperand(0).get() == MD
|| isa
<MDString
>(MD
->getOperand(0)),
4774 "first scope operand must be self-referential or string", MD
);
4776 Check(isa
<MDString
>(MD
->getOperand(2)),
4777 "third scope operand must be string (if used)", MD
);
4779 MDNode
*Domain
= dyn_cast
<MDNode
>(MD
->getOperand(1));
4780 Check(Domain
!= nullptr, "second scope operand must be MDNode", MD
);
4782 unsigned NumDomainOps
= Domain
->getNumOperands();
4783 Check(NumDomainOps
>= 1 && NumDomainOps
<= 2,
4784 "domain must have one or two operands", Domain
);
4785 Check(Domain
->getOperand(0).get() == Domain
||
4786 isa
<MDString
>(Domain
->getOperand(0)),
4787 "first domain operand must be self-referential or string", Domain
);
4788 if (NumDomainOps
== 2)
4789 Check(isa
<MDString
>(Domain
->getOperand(1)),
4790 "second domain operand must be string (if used)", Domain
);
4793 void Verifier::visitAliasScopeListMetadata(const MDNode
*MD
) {
4794 for (const MDOperand
&Op
: MD
->operands()) {
4795 const MDNode
*OpMD
= dyn_cast
<MDNode
>(Op
);
4796 Check(OpMD
!= nullptr, "scope list must consist of MDNodes", MD
);
4797 visitAliasScopeMetadata(OpMD
);
4801 void Verifier::visitAccessGroupMetadata(const MDNode
*MD
) {
4802 auto IsValidAccessScope
= [](const MDNode
*MD
) {
4803 return MD
->getNumOperands() == 0 && MD
->isDistinct();
4806 // It must be either an access scope itself...
4807 if (IsValidAccessScope(MD
))
4810 // ...or a list of access scopes.
4811 for (const MDOperand
&Op
: MD
->operands()) {
4812 const MDNode
*OpMD
= dyn_cast
<MDNode
>(Op
);
4813 Check(OpMD
!= nullptr, "Access scope list must consist of MDNodes", MD
);
4814 Check(IsValidAccessScope(OpMD
),
4815 "Access scope list contains invalid access scope", MD
);
4819 /// verifyInstruction - Verify that an instruction is well formed.
4821 void Verifier::visitInstruction(Instruction
&I
) {
4822 BasicBlock
*BB
= I
.getParent();
4823 Check(BB
, "Instruction not embedded in basic block!", &I
);
4825 if (!isa
<PHINode
>(I
)) { // Check that non-phi nodes are not self referential
4826 for (User
*U
: I
.users()) {
4827 Check(U
!= (User
*)&I
|| !DT
.isReachableFromEntry(BB
),
4828 "Only PHI nodes may reference their own value!", &I
);
4832 // Check that void typed values don't have names
4833 Check(!I
.getType()->isVoidTy() || !I
.hasName(),
4834 "Instruction has a name, but provides a void value!", &I
);
4836 // Check that the return value of the instruction is either void or a legal
4838 Check(I
.getType()->isVoidTy() || I
.getType()->isFirstClassType(),
4839 "Instruction returns a non-scalar type!", &I
);
4841 // Check that the instruction doesn't produce metadata. Calls are already
4842 // checked against the callee type.
4843 Check(!I
.getType()->isMetadataTy() || isa
<CallInst
>(I
) || isa
<InvokeInst
>(I
),
4844 "Invalid use of metadata!", &I
);
4846 // Check that all uses of the instruction, if they are instructions
4847 // themselves, actually have parent basic blocks. If the use is not an
4848 // instruction, it is an error!
4849 for (Use
&U
: I
.uses()) {
4850 if (Instruction
*Used
= dyn_cast
<Instruction
>(U
.getUser()))
4851 Check(Used
->getParent() != nullptr,
4852 "Instruction referencing"
4853 " instruction not embedded in a basic block!",
4856 CheckFailed("Use of instruction is not an instruction!", U
);
4861 // Get a pointer to the call base of the instruction if it is some form of
4863 const CallBase
*CBI
= dyn_cast
<CallBase
>(&I
);
4865 for (unsigned i
= 0, e
= I
.getNumOperands(); i
!= e
; ++i
) {
4866 Check(I
.getOperand(i
) != nullptr, "Instruction has null operand!", &I
);
4868 // Check to make sure that only first-class-values are operands to
4870 if (!I
.getOperand(i
)->getType()->isFirstClassType()) {
4871 Check(false, "Instruction operands must be first-class values!", &I
);
4874 if (Function
*F
= dyn_cast
<Function
>(I
.getOperand(i
))) {
4875 // This code checks whether the function is used as the operand of a
4876 // clang_arc_attachedcall operand bundle.
4877 auto IsAttachedCallOperand
= [](Function
*F
, const CallBase
*CBI
,
4879 return CBI
&& CBI
->isOperandBundleOfType(
4880 LLVMContext::OB_clang_arc_attachedcall
, Idx
);
4883 // Check to make sure that the "address of" an intrinsic function is never
4884 // taken. Ignore cases where the address of the intrinsic function is used
4885 // as the argument of operand bundle "clang.arc.attachedcall" as those
4886 // cases are handled in verifyAttachedCallBundle.
4887 Check((!F
->isIntrinsic() ||
4888 (CBI
&& &CBI
->getCalledOperandUse() == &I
.getOperandUse(i
)) ||
4889 IsAttachedCallOperand(F
, CBI
, i
)),
4890 "Cannot take the address of an intrinsic!", &I
);
4891 Check(!F
->isIntrinsic() || isa
<CallInst
>(I
) ||
4892 F
->getIntrinsicID() == Intrinsic::donothing
||
4893 F
->getIntrinsicID() == Intrinsic::seh_try_begin
||
4894 F
->getIntrinsicID() == Intrinsic::seh_try_end
||
4895 F
->getIntrinsicID() == Intrinsic::seh_scope_begin
||
4896 F
->getIntrinsicID() == Intrinsic::seh_scope_end
||
4897 F
->getIntrinsicID() == Intrinsic::coro_resume
||
4898 F
->getIntrinsicID() == Intrinsic::coro_destroy
||
4899 F
->getIntrinsicID() ==
4900 Intrinsic::experimental_patchpoint_void
||
4901 F
->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64
||
4902 F
->getIntrinsicID() == Intrinsic::experimental_gc_statepoint
||
4903 F
->getIntrinsicID() == Intrinsic::wasm_rethrow
||
4904 IsAttachedCallOperand(F
, CBI
, i
),
4905 "Cannot invoke an intrinsic other than donothing, patchpoint, "
4906 "statepoint, coro_resume, coro_destroy or clang.arc.attachedcall",
4908 Check(F
->getParent() == &M
, "Referencing function in another module!", &I
,
4909 &M
, F
, F
->getParent());
4910 } else if (BasicBlock
*OpBB
= dyn_cast
<BasicBlock
>(I
.getOperand(i
))) {
4911 Check(OpBB
->getParent() == BB
->getParent(),
4912 "Referring to a basic block in another function!", &I
);
4913 } else if (Argument
*OpArg
= dyn_cast
<Argument
>(I
.getOperand(i
))) {
4914 Check(OpArg
->getParent() == BB
->getParent(),
4915 "Referring to an argument in another function!", &I
);
4916 } else if (GlobalValue
*GV
= dyn_cast
<GlobalValue
>(I
.getOperand(i
))) {
4917 Check(GV
->getParent() == &M
, "Referencing global in another module!", &I
,
4918 &M
, GV
, GV
->getParent());
4919 } else if (isa
<Instruction
>(I
.getOperand(i
))) {
4920 verifyDominatesUse(I
, i
);
4921 } else if (isa
<InlineAsm
>(I
.getOperand(i
))) {
4922 Check(CBI
&& &CBI
->getCalledOperandUse() == &I
.getOperandUse(i
),
4923 "Cannot take the address of an inline asm!", &I
);
4924 } else if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(I
.getOperand(i
))) {
4925 if (CE
->getType()->isPtrOrPtrVectorTy()) {
4926 // If we have a ConstantExpr pointer, we need to see if it came from an
4928 visitConstantExprsRecursively(CE
);
4933 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_fpmath
)) {
4934 Check(I
.getType()->isFPOrFPVectorTy(),
4935 "fpmath requires a floating point result!", &I
);
4936 Check(MD
->getNumOperands() == 1, "fpmath takes one operand!", &I
);
4937 if (ConstantFP
*CFP0
=
4938 mdconst::dyn_extract_or_null
<ConstantFP
>(MD
->getOperand(0))) {
4939 const APFloat
&Accuracy
= CFP0
->getValueAPF();
4940 Check(&Accuracy
.getSemantics() == &APFloat::IEEEsingle(),
4941 "fpmath accuracy must have float type", &I
);
4942 Check(Accuracy
.isFiniteNonZero() && !Accuracy
.isNegative(),
4943 "fpmath accuracy not a positive number!", &I
);
4945 Check(false, "invalid fpmath accuracy!", &I
);
4949 if (MDNode
*Range
= I
.getMetadata(LLVMContext::MD_range
)) {
4950 Check(isa
<LoadInst
>(I
) || isa
<CallInst
>(I
) || isa
<InvokeInst
>(I
),
4951 "Ranges are only for loads, calls and invokes!", &I
);
4952 visitRangeMetadata(I
, Range
, I
.getType());
4955 if (I
.hasMetadata(LLVMContext::MD_invariant_group
)) {
4956 Check(isa
<LoadInst
>(I
) || isa
<StoreInst
>(I
),
4957 "invariant.group metadata is only for loads and stores", &I
);
4960 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_nonnull
)) {
4961 Check(I
.getType()->isPointerTy(), "nonnull applies only to pointer types",
4963 Check(isa
<LoadInst
>(I
),
4964 "nonnull applies only to load instructions, use attributes"
4965 " for calls or invokes",
4967 Check(MD
->getNumOperands() == 0, "nonnull metadata must be empty", &I
);
4970 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_dereferenceable
))
4971 visitDereferenceableMetadata(I
, MD
);
4973 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_dereferenceable_or_null
))
4974 visitDereferenceableMetadata(I
, MD
);
4976 if (MDNode
*TBAA
= I
.getMetadata(LLVMContext::MD_tbaa
))
4977 TBAAVerifyHelper
.visitTBAAMetadata(I
, TBAA
);
4979 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_noalias
))
4980 visitAliasScopeListMetadata(MD
);
4981 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_alias_scope
))
4982 visitAliasScopeListMetadata(MD
);
4984 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_access_group
))
4985 visitAccessGroupMetadata(MD
);
4987 if (MDNode
*AlignMD
= I
.getMetadata(LLVMContext::MD_align
)) {
4988 Check(I
.getType()->isPointerTy(), "align applies only to pointer types",
4990 Check(isa
<LoadInst
>(I
),
4991 "align applies only to load instructions, "
4992 "use attributes for calls or invokes",
4994 Check(AlignMD
->getNumOperands() == 1, "align takes one operand!", &I
);
4995 ConstantInt
*CI
= mdconst::dyn_extract
<ConstantInt
>(AlignMD
->getOperand(0));
4996 Check(CI
&& CI
->getType()->isIntegerTy(64),
4997 "align metadata value must be an i64!", &I
);
4998 uint64_t Align
= CI
->getZExtValue();
4999 Check(isPowerOf2_64(Align
), "align metadata value must be a power of 2!",
5001 Check(Align
<= Value::MaximumAlignment
,
5002 "alignment is larger that implementation defined limit", &I
);
5005 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_prof
))
5006 visitProfMetadata(I
, MD
);
5008 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_memprof
))
5009 visitMemProfMetadata(I
, MD
);
5011 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_callsite
))
5012 visitCallsiteMetadata(I
, MD
);
5014 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_DIAssignID
))
5015 visitDIAssignIDMetadata(I
, MD
);
5017 if (MDNode
*Annotation
= I
.getMetadata(LLVMContext::MD_annotation
))
5018 visitAnnotationMetadata(Annotation
);
5020 if (MDNode
*N
= I
.getDebugLoc().getAsMDNode()) {
5021 CheckDI(isa
<DILocation
>(N
), "invalid !dbg metadata attachment", &I
, N
);
5022 visitMDNode(*N
, AreDebugLocsAllowed::Yes
);
5025 if (auto *DII
= dyn_cast
<DbgVariableIntrinsic
>(&I
)) {
5026 verifyFragmentExpression(*DII
);
5027 verifyNotEntryValue(*DII
);
5030 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
5031 I
.getAllMetadata(MDs
);
5032 for (auto Attachment
: MDs
) {
5033 unsigned Kind
= Attachment
.first
;
5035 (Kind
== LLVMContext::MD_dbg
|| Kind
== LLVMContext::MD_loop
)
5036 ? AreDebugLocsAllowed::Yes
5037 : AreDebugLocsAllowed::No
;
5038 visitMDNode(*Attachment
.second
, AllowLocs
);
5041 InstsInThisBlock
.insert(&I
);
5044 /// Allow intrinsics to be verified in different ways.
5045 void Verifier::visitIntrinsicCall(Intrinsic::ID ID
, CallBase
&Call
) {
5046 Function
*IF
= Call
.getCalledFunction();
5047 Check(IF
->isDeclaration(), "Intrinsic functions should never be defined!",
5050 // Verify that the intrinsic prototype lines up with what the .td files
5052 FunctionType
*IFTy
= IF
->getFunctionType();
5053 bool IsVarArg
= IFTy
->isVarArg();
5055 SmallVector
<Intrinsic::IITDescriptor
, 8> Table
;
5056 getIntrinsicInfoTableEntries(ID
, Table
);
5057 ArrayRef
<Intrinsic::IITDescriptor
> TableRef
= Table
;
5059 // Walk the descriptors to extract overloaded types.
5060 SmallVector
<Type
*, 4> ArgTys
;
5061 Intrinsic::MatchIntrinsicTypesResult Res
=
5062 Intrinsic::matchIntrinsicSignature(IFTy
, TableRef
, ArgTys
);
5063 Check(Res
!= Intrinsic::MatchIntrinsicTypes_NoMatchRet
,
5064 "Intrinsic has incorrect return type!", IF
);
5065 Check(Res
!= Intrinsic::MatchIntrinsicTypes_NoMatchArg
,
5066 "Intrinsic has incorrect argument type!", IF
);
5068 // Verify if the intrinsic call matches the vararg property.
5070 Check(!Intrinsic::matchIntrinsicVarArg(IsVarArg
, TableRef
),
5071 "Intrinsic was not defined with variable arguments!", IF
);
5073 Check(!Intrinsic::matchIntrinsicVarArg(IsVarArg
, TableRef
),
5074 "Callsite was not defined with variable arguments!", IF
);
5076 // All descriptors should be absorbed by now.
5077 Check(TableRef
.empty(), "Intrinsic has too few arguments!", IF
);
5079 // Now that we have the intrinsic ID and the actual argument types (and we
5080 // know they are legal for the intrinsic!) get the intrinsic name through the
5081 // usual means. This allows us to verify the mangling of argument types into
5083 const std::string ExpectedName
=
5084 Intrinsic::getName(ID
, ArgTys
, IF
->getParent(), IFTy
);
5085 Check(ExpectedName
== IF
->getName(),
5086 "Intrinsic name not mangled correctly for type arguments! "
5091 // If the intrinsic takes MDNode arguments, verify that they are either global
5092 // or are local to *this* function.
5093 for (Value
*V
: Call
.args()) {
5094 if (auto *MD
= dyn_cast
<MetadataAsValue
>(V
))
5095 visitMetadataAsValue(*MD
, Call
.getCaller());
5096 if (auto *Const
= dyn_cast
<Constant
>(V
))
5097 Check(!Const
->getType()->isX86_AMXTy(),
5098 "const x86_amx is not allowed in argument!");
5104 case Intrinsic::assume
: {
5105 for (auto &Elem
: Call
.bundle_op_infos()) {
5106 unsigned ArgCount
= Elem
.End
- Elem
.Begin
;
5107 // Separate storage assumptions are special insofar as they're the only
5108 // operand bundles allowed on assumes that aren't parameter attributes.
5109 if (Elem
.Tag
->getKey() == "separate_storage") {
5110 Check(ArgCount
== 2,
5111 "separate_storage assumptions should have 2 arguments", Call
);
5112 Check(Call
.getOperand(Elem
.Begin
)->getType()->isPointerTy() &&
5113 Call
.getOperand(Elem
.Begin
+ 1)->getType()->isPointerTy(),
5114 "arguments to separate_storage assumptions should be pointers",
5118 Check(Elem
.Tag
->getKey() == "ignore" ||
5119 Attribute::isExistingAttribute(Elem
.Tag
->getKey()),
5120 "tags must be valid attribute names", Call
);
5121 Attribute::AttrKind Kind
=
5122 Attribute::getAttrKindFromName(Elem
.Tag
->getKey());
5123 if (Kind
== Attribute::Alignment
) {
5124 Check(ArgCount
<= 3 && ArgCount
>= 2,
5125 "alignment assumptions should have 2 or 3 arguments", Call
);
5126 Check(Call
.getOperand(Elem
.Begin
)->getType()->isPointerTy(),
5127 "first argument should be a pointer", Call
);
5128 Check(Call
.getOperand(Elem
.Begin
+ 1)->getType()->isIntegerTy(),
5129 "second argument should be an integer", Call
);
5131 Check(Call
.getOperand(Elem
.Begin
+ 2)->getType()->isIntegerTy(),
5132 "third argument should be an integer if present", Call
);
5135 Check(ArgCount
<= 2, "too many arguments", Call
);
5136 if (Kind
== Attribute::None
)
5138 if (Attribute::isIntAttrKind(Kind
)) {
5139 Check(ArgCount
== 2, "this attribute should have 2 arguments", Call
);
5140 Check(isa
<ConstantInt
>(Call
.getOperand(Elem
.Begin
+ 1)),
5141 "the second argument should be a constant integral value", Call
);
5142 } else if (Attribute::canUseAsParamAttr(Kind
)) {
5143 Check((ArgCount
) == 1, "this attribute should have one argument", Call
);
5144 } else if (Attribute::canUseAsFnAttr(Kind
)) {
5145 Check((ArgCount
) == 0, "this attribute has no argument", Call
);
5150 case Intrinsic::coro_id
: {
5151 auto *InfoArg
= Call
.getArgOperand(3)->stripPointerCasts();
5152 if (isa
<ConstantPointerNull
>(InfoArg
))
5154 auto *GV
= dyn_cast
<GlobalVariable
>(InfoArg
);
5155 Check(GV
&& GV
->isConstant() && GV
->hasDefinitiveInitializer(),
5156 "info argument of llvm.coro.id must refer to an initialized "
5158 Constant
*Init
= GV
->getInitializer();
5159 Check(isa
<ConstantStruct
>(Init
) || isa
<ConstantArray
>(Init
),
5160 "info argument of llvm.coro.id must refer to either a struct or "
5164 case Intrinsic::is_fpclass
: {
5165 const ConstantInt
*TestMask
= cast
<ConstantInt
>(Call
.getOperand(1));
5166 Check((TestMask
->getZExtValue() & ~static_cast<unsigned>(fcAllFlags
)) == 0,
5167 "unsupported bits for llvm.is.fpclass test mask");
5170 case Intrinsic::fptrunc_round
: {
5171 // Check the rounding mode
5172 Metadata
*MD
= nullptr;
5173 auto *MAV
= dyn_cast
<MetadataAsValue
>(Call
.getOperand(1));
5175 MD
= MAV
->getMetadata();
5177 Check(MD
!= nullptr, "missing rounding mode argument", Call
);
5179 Check(isa
<MDString
>(MD
),
5180 ("invalid value for llvm.fptrunc.round metadata operand"
5181 " (the operand should be a string)"),
5184 std::optional
<RoundingMode
> RoundMode
=
5185 convertStrToRoundingMode(cast
<MDString
>(MD
)->getString());
5186 Check(RoundMode
&& *RoundMode
!= RoundingMode::Dynamic
,
5187 "unsupported rounding mode argument", Call
);
5190 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
5191 #include "llvm/IR/VPIntrinsics.def"
5192 visitVPIntrinsic(cast
<VPIntrinsic
>(Call
));
5194 #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
5195 case Intrinsic::INTRINSIC:
5196 #include "llvm/IR/ConstrainedOps.def"
5197 visitConstrainedFPIntrinsic(cast
<ConstrainedFPIntrinsic
>(Call
));
5199 case Intrinsic::dbg_declare
: // llvm.dbg.declare
5200 Check(isa
<MetadataAsValue
>(Call
.getArgOperand(0)),
5201 "invalid llvm.dbg.declare intrinsic call 1", Call
);
5202 visitDbgIntrinsic("declare", cast
<DbgVariableIntrinsic
>(Call
));
5204 case Intrinsic::dbg_value
: // llvm.dbg.value
5205 visitDbgIntrinsic("value", cast
<DbgVariableIntrinsic
>(Call
));
5207 case Intrinsic::dbg_assign
: // llvm.dbg.assign
5208 visitDbgIntrinsic("assign", cast
<DbgVariableIntrinsic
>(Call
));
5210 case Intrinsic::dbg_label
: // llvm.dbg.label
5211 visitDbgLabelIntrinsic("label", cast
<DbgLabelInst
>(Call
));
5213 case Intrinsic::memcpy
:
5214 case Intrinsic::memcpy_inline
:
5215 case Intrinsic::memmove
:
5216 case Intrinsic::memset
:
5217 case Intrinsic::memset_inline
: {
5220 case Intrinsic::memcpy_element_unordered_atomic
:
5221 case Intrinsic::memmove_element_unordered_atomic
:
5222 case Intrinsic::memset_element_unordered_atomic
: {
5223 const auto *AMI
= cast
<AtomicMemIntrinsic
>(&Call
);
5225 ConstantInt
*ElementSizeCI
=
5226 cast
<ConstantInt
>(AMI
->getRawElementSizeInBytes());
5227 const APInt
&ElementSizeVal
= ElementSizeCI
->getValue();
5228 Check(ElementSizeVal
.isPowerOf2(),
5229 "element size of the element-wise atomic memory intrinsic "
5230 "must be a power of 2",
5233 auto IsValidAlignment
= [&](MaybeAlign Alignment
) {
5234 return Alignment
&& ElementSizeVal
.ule(Alignment
->value());
5236 Check(IsValidAlignment(AMI
->getDestAlign()),
5237 "incorrect alignment of the destination argument", Call
);
5238 if (const auto *AMT
= dyn_cast
<AtomicMemTransferInst
>(AMI
)) {
5239 Check(IsValidAlignment(AMT
->getSourceAlign()),
5240 "incorrect alignment of the source argument", Call
);
5244 case Intrinsic::call_preallocated_setup
: {
5245 auto *NumArgs
= dyn_cast
<ConstantInt
>(Call
.getArgOperand(0));
5246 Check(NumArgs
!= nullptr,
5247 "llvm.call.preallocated.setup argument must be a constant");
5248 bool FoundCall
= false;
5249 for (User
*U
: Call
.users()) {
5250 auto *UseCall
= dyn_cast
<CallBase
>(U
);
5251 Check(UseCall
!= nullptr,
5252 "Uses of llvm.call.preallocated.setup must be calls");
5253 const Function
*Fn
= UseCall
->getCalledFunction();
5254 if (Fn
&& Fn
->getIntrinsicID() == Intrinsic::call_preallocated_arg
) {
5255 auto *AllocArgIndex
= dyn_cast
<ConstantInt
>(UseCall
->getArgOperand(1));
5256 Check(AllocArgIndex
!= nullptr,
5257 "llvm.call.preallocated.alloc arg index must be a constant");
5258 auto AllocArgIndexInt
= AllocArgIndex
->getValue();
5259 Check(AllocArgIndexInt
.sge(0) &&
5260 AllocArgIndexInt
.slt(NumArgs
->getValue()),
5261 "llvm.call.preallocated.alloc arg index must be between 0 and "
5263 "llvm.call.preallocated.setup's argument count");
5264 } else if (Fn
&& Fn
->getIntrinsicID() ==
5265 Intrinsic::call_preallocated_teardown
) {
5268 Check(!FoundCall
, "Can have at most one call corresponding to a "
5269 "llvm.call.preallocated.setup");
5271 size_t NumPreallocatedArgs
= 0;
5272 for (unsigned i
= 0; i
< UseCall
->arg_size(); i
++) {
5273 if (UseCall
->paramHasAttr(i
, Attribute::Preallocated
)) {
5274 ++NumPreallocatedArgs
;
5277 Check(NumPreallocatedArgs
!= 0,
5278 "cannot use preallocated intrinsics on a call without "
5279 "preallocated arguments");
5280 Check(NumArgs
->equalsInt(NumPreallocatedArgs
),
5281 "llvm.call.preallocated.setup arg size must be equal to number "
5282 "of preallocated arguments "
5285 // getOperandBundle() cannot be called if more than one of the operand
5286 // bundle exists. There is already a check elsewhere for this, so skip
5287 // here if we see more than one.
5288 if (UseCall
->countOperandBundlesOfType(LLVMContext::OB_preallocated
) >
5292 auto PreallocatedBundle
=
5293 UseCall
->getOperandBundle(LLVMContext::OB_preallocated
);
5294 Check(PreallocatedBundle
,
5295 "Use of llvm.call.preallocated.setup outside intrinsics "
5296 "must be in \"preallocated\" operand bundle");
5297 Check(PreallocatedBundle
->Inputs
.front().get() == &Call
,
5298 "preallocated bundle must have token from corresponding "
5299 "llvm.call.preallocated.setup");
5304 case Intrinsic::call_preallocated_arg
: {
5305 auto *Token
= dyn_cast
<CallBase
>(Call
.getArgOperand(0));
5306 Check(Token
&& Token
->getCalledFunction()->getIntrinsicID() ==
5307 Intrinsic::call_preallocated_setup
,
5308 "llvm.call.preallocated.arg token argument must be a "
5309 "llvm.call.preallocated.setup");
5310 Check(Call
.hasFnAttr(Attribute::Preallocated
),
5311 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
5312 "call site attribute");
5315 case Intrinsic::call_preallocated_teardown
: {
5316 auto *Token
= dyn_cast
<CallBase
>(Call
.getArgOperand(0));
5317 Check(Token
&& Token
->getCalledFunction()->getIntrinsicID() ==
5318 Intrinsic::call_preallocated_setup
,
5319 "llvm.call.preallocated.teardown token argument must be a "
5320 "llvm.call.preallocated.setup");
5323 case Intrinsic::gcroot
:
5324 case Intrinsic::gcwrite
:
5325 case Intrinsic::gcread
:
5326 if (ID
== Intrinsic::gcroot
) {
5328 dyn_cast
<AllocaInst
>(Call
.getArgOperand(0)->stripPointerCasts());
5329 Check(AI
, "llvm.gcroot parameter #1 must be an alloca.", Call
);
5330 Check(isa
<Constant
>(Call
.getArgOperand(1)),
5331 "llvm.gcroot parameter #2 must be a constant.", Call
);
5332 if (!AI
->getAllocatedType()->isPointerTy()) {
5333 Check(!isa
<ConstantPointerNull
>(Call
.getArgOperand(1)),
5334 "llvm.gcroot parameter #1 must either be a pointer alloca, "
5335 "or argument #2 must be a non-null constant.",
5340 Check(Call
.getParent()->getParent()->hasGC(),
5341 "Enclosing function does not use GC.", Call
);
5343 case Intrinsic::init_trampoline
:
5344 Check(isa
<Function
>(Call
.getArgOperand(1)->stripPointerCasts()),
5345 "llvm.init_trampoline parameter #2 must resolve to a function.",
5348 case Intrinsic::prefetch
:
5349 Check(cast
<ConstantInt
>(Call
.getArgOperand(1))->getZExtValue() < 2,
5350 "rw argument to llvm.prefetch must be 0-1", Call
);
5351 Check(cast
<ConstantInt
>(Call
.getArgOperand(2))->getZExtValue() < 4,
5352 "locality argument to llvm.prefetch must be 0-4", Call
);
5353 Check(cast
<ConstantInt
>(Call
.getArgOperand(3))->getZExtValue() < 2,
5354 "cache type argument to llvm.prefetch must be 0-1", Call
);
5356 case Intrinsic::stackprotector
:
5357 Check(isa
<AllocaInst
>(Call
.getArgOperand(1)->stripPointerCasts()),
5358 "llvm.stackprotector parameter #2 must resolve to an alloca.", Call
);
5360 case Intrinsic::localescape
: {
5361 BasicBlock
*BB
= Call
.getParent();
5362 Check(BB
->isEntryBlock(), "llvm.localescape used outside of entry block",
5364 Check(!SawFrameEscape
, "multiple calls to llvm.localescape in one function",
5366 for (Value
*Arg
: Call
.args()) {
5367 if (isa
<ConstantPointerNull
>(Arg
))
5368 continue; // Null values are allowed as placeholders.
5369 auto *AI
= dyn_cast
<AllocaInst
>(Arg
->stripPointerCasts());
5370 Check(AI
&& AI
->isStaticAlloca(),
5371 "llvm.localescape only accepts static allocas", Call
);
5373 FrameEscapeInfo
[BB
->getParent()].first
= Call
.arg_size();
5374 SawFrameEscape
= true;
5377 case Intrinsic::localrecover
: {
5378 Value
*FnArg
= Call
.getArgOperand(0)->stripPointerCasts();
5379 Function
*Fn
= dyn_cast
<Function
>(FnArg
);
5380 Check(Fn
&& !Fn
->isDeclaration(),
5381 "llvm.localrecover first "
5382 "argument must be function defined in this module",
5384 auto *IdxArg
= cast
<ConstantInt
>(Call
.getArgOperand(2));
5385 auto &Entry
= FrameEscapeInfo
[Fn
];
5386 Entry
.second
= unsigned(
5387 std::max(uint64_t(Entry
.second
), IdxArg
->getLimitedValue(~0U) + 1));
5391 case Intrinsic::experimental_gc_statepoint
:
5392 if (auto *CI
= dyn_cast
<CallInst
>(&Call
))
5393 Check(!CI
->isInlineAsm(),
5394 "gc.statepoint support for inline assembly unimplemented", CI
);
5395 Check(Call
.getParent()->getParent()->hasGC(),
5396 "Enclosing function does not use GC.", Call
);
5398 verifyStatepoint(Call
);
5400 case Intrinsic::experimental_gc_result
: {
5401 Check(Call
.getParent()->getParent()->hasGC(),
5402 "Enclosing function does not use GC.", Call
);
5404 auto *Statepoint
= Call
.getArgOperand(0);
5405 if (isa
<UndefValue
>(Statepoint
))
5408 // Are we tied to a statepoint properly?
5409 const auto *StatepointCall
= dyn_cast
<CallBase
>(Statepoint
);
5410 const Function
*StatepointFn
=
5411 StatepointCall
? StatepointCall
->getCalledFunction() : nullptr;
5412 Check(StatepointFn
&& StatepointFn
->isDeclaration() &&
5413 StatepointFn
->getIntrinsicID() ==
5414 Intrinsic::experimental_gc_statepoint
,
5415 "gc.result operand #1 must be from a statepoint", Call
,
5416 Call
.getArgOperand(0));
5418 // Check that result type matches wrapped callee.
5419 auto *TargetFuncType
=
5420 cast
<FunctionType
>(StatepointCall
->getParamElementType(2));
5421 Check(Call
.getType() == TargetFuncType
->getReturnType(),
5422 "gc.result result type does not match wrapped callee", Call
);
5425 case Intrinsic::experimental_gc_relocate
: {
5426 Check(Call
.arg_size() == 3, "wrong number of arguments", Call
);
5428 Check(isa
<PointerType
>(Call
.getType()->getScalarType()),
5429 "gc.relocate must return a pointer or a vector of pointers", Call
);
5431 // Check that this relocate is correctly tied to the statepoint
5433 // This is case for relocate on the unwinding path of an invoke statepoint
5434 if (LandingPadInst
*LandingPad
=
5435 dyn_cast
<LandingPadInst
>(Call
.getArgOperand(0))) {
5437 const BasicBlock
*InvokeBB
=
5438 LandingPad
->getParent()->getUniquePredecessor();
5440 // Landingpad relocates should have only one predecessor with invoke
5441 // statepoint terminator
5442 Check(InvokeBB
, "safepoints should have unique landingpads",
5443 LandingPad
->getParent());
5444 Check(InvokeBB
->getTerminator(), "safepoint block should be well formed",
5446 Check(isa
<GCStatepointInst
>(InvokeBB
->getTerminator()),
5447 "gc relocate should be linked to a statepoint", InvokeBB
);
5449 // In all other cases relocate should be tied to the statepoint directly.
5450 // This covers relocates on a normal return path of invoke statepoint and
5451 // relocates of a call statepoint.
5452 auto *Token
= Call
.getArgOperand(0);
5453 Check(isa
<GCStatepointInst
>(Token
) || isa
<UndefValue
>(Token
),
5454 "gc relocate is incorrectly tied to the statepoint", Call
, Token
);
5457 // Verify rest of the relocate arguments.
5458 const Value
&StatepointCall
= *cast
<GCRelocateInst
>(Call
).getStatepoint();
5460 // Both the base and derived must be piped through the safepoint.
5461 Value
*Base
= Call
.getArgOperand(1);
5462 Check(isa
<ConstantInt
>(Base
),
5463 "gc.relocate operand #2 must be integer offset", Call
);
5465 Value
*Derived
= Call
.getArgOperand(2);
5466 Check(isa
<ConstantInt
>(Derived
),
5467 "gc.relocate operand #3 must be integer offset", Call
);
5469 const uint64_t BaseIndex
= cast
<ConstantInt
>(Base
)->getZExtValue();
5470 const uint64_t DerivedIndex
= cast
<ConstantInt
>(Derived
)->getZExtValue();
5473 if (isa
<UndefValue
>(StatepointCall
))
5475 if (auto Opt
= cast
<GCStatepointInst
>(StatepointCall
)
5476 .getOperandBundle(LLVMContext::OB_gc_live
)) {
5477 Check(BaseIndex
< Opt
->Inputs
.size(),
5478 "gc.relocate: statepoint base index out of bounds", Call
);
5479 Check(DerivedIndex
< Opt
->Inputs
.size(),
5480 "gc.relocate: statepoint derived index out of bounds", Call
);
5483 // Relocated value must be either a pointer type or vector-of-pointer type,
5484 // but gc_relocate does not need to return the same pointer type as the
5485 // relocated pointer. It can be casted to the correct type later if it's
5486 // desired. However, they must have the same address space and 'vectorness'
5487 GCRelocateInst
&Relocate
= cast
<GCRelocateInst
>(Call
);
5488 auto *ResultType
= Call
.getType();
5489 auto *DerivedType
= Relocate
.getDerivedPtr()->getType();
5490 auto *BaseType
= Relocate
.getBasePtr()->getType();
5492 Check(BaseType
->isPtrOrPtrVectorTy(),
5493 "gc.relocate: relocated value must be a pointer", Call
);
5494 Check(DerivedType
->isPtrOrPtrVectorTy(),
5495 "gc.relocate: relocated value must be a pointer", Call
);
5497 Check(ResultType
->isVectorTy() == DerivedType
->isVectorTy(),
5498 "gc.relocate: vector relocates to vector and pointer to pointer",
5501 ResultType
->getPointerAddressSpace() ==
5502 DerivedType
->getPointerAddressSpace(),
5503 "gc.relocate: relocating a pointer shouldn't change its address space",
5506 auto GC
= llvm::getGCStrategy(Relocate
.getFunction()->getGC());
5507 Check(GC
, "gc.relocate: calling function must have GCStrategy",
5508 Call
.getFunction());
5510 auto isGCPtr
= [&GC
](Type
*PTy
) {
5511 return GC
->isGCManagedPointer(PTy
->getScalarType()).value_or(true);
5513 Check(isGCPtr(ResultType
), "gc.relocate: must return gc pointer", Call
);
5514 Check(isGCPtr(BaseType
),
5515 "gc.relocate: relocated value must be a gc pointer", Call
);
5516 Check(isGCPtr(DerivedType
),
5517 "gc.relocate: relocated value must be a gc pointer", Call
);
5521 case Intrinsic::eh_exceptioncode
:
5522 case Intrinsic::eh_exceptionpointer
: {
5523 Check(isa
<CatchPadInst
>(Call
.getArgOperand(0)),
5524 "eh.exceptionpointer argument must be a catchpad", Call
);
5527 case Intrinsic::get_active_lane_mask
: {
5528 Check(Call
.getType()->isVectorTy(),
5529 "get_active_lane_mask: must return a "
5532 auto *ElemTy
= Call
.getType()->getScalarType();
5533 Check(ElemTy
->isIntegerTy(1),
5534 "get_active_lane_mask: element type is not "
5539 case Intrinsic::experimental_get_vector_length
: {
5540 ConstantInt
*VF
= cast
<ConstantInt
>(Call
.getArgOperand(1));
5541 Check(!VF
->isNegative() && !VF
->isZero(),
5542 "get_vector_length: VF must be positive", Call
);
5545 case Intrinsic::masked_load
: {
5546 Check(Call
.getType()->isVectorTy(), "masked_load: must return a vector",
5549 ConstantInt
*Alignment
= cast
<ConstantInt
>(Call
.getArgOperand(1));
5550 Value
*Mask
= Call
.getArgOperand(2);
5551 Value
*PassThru
= Call
.getArgOperand(3);
5552 Check(Mask
->getType()->isVectorTy(), "masked_load: mask must be vector",
5554 Check(Alignment
->getValue().isPowerOf2(),
5555 "masked_load: alignment must be a power of 2", Call
);
5556 Check(PassThru
->getType() == Call
.getType(),
5557 "masked_load: pass through and return type must match", Call
);
5558 Check(cast
<VectorType
>(Mask
->getType())->getElementCount() ==
5559 cast
<VectorType
>(Call
.getType())->getElementCount(),
5560 "masked_load: vector mask must be same length as return", Call
);
5563 case Intrinsic::masked_store
: {
5564 Value
*Val
= Call
.getArgOperand(0);
5565 ConstantInt
*Alignment
= cast
<ConstantInt
>(Call
.getArgOperand(2));
5566 Value
*Mask
= Call
.getArgOperand(3);
5567 Check(Mask
->getType()->isVectorTy(), "masked_store: mask must be vector",
5569 Check(Alignment
->getValue().isPowerOf2(),
5570 "masked_store: alignment must be a power of 2", Call
);
5571 Check(cast
<VectorType
>(Mask
->getType())->getElementCount() ==
5572 cast
<VectorType
>(Val
->getType())->getElementCount(),
5573 "masked_store: vector mask must be same length as value", Call
);
5577 case Intrinsic::masked_gather
: {
5578 const APInt
&Alignment
=
5579 cast
<ConstantInt
>(Call
.getArgOperand(1))->getValue();
5580 Check(Alignment
.isZero() || Alignment
.isPowerOf2(),
5581 "masked_gather: alignment must be 0 or a power of 2", Call
);
5584 case Intrinsic::masked_scatter
: {
5585 const APInt
&Alignment
=
5586 cast
<ConstantInt
>(Call
.getArgOperand(2))->getValue();
5587 Check(Alignment
.isZero() || Alignment
.isPowerOf2(),
5588 "masked_scatter: alignment must be 0 or a power of 2", Call
);
5592 case Intrinsic::experimental_guard
: {
5593 Check(isa
<CallInst
>(Call
), "experimental_guard cannot be invoked", Call
);
5594 Check(Call
.countOperandBundlesOfType(LLVMContext::OB_deopt
) == 1,
5595 "experimental_guard must have exactly one "
5596 "\"deopt\" operand bundle");
5600 case Intrinsic::experimental_deoptimize
: {
5601 Check(isa
<CallInst
>(Call
), "experimental_deoptimize cannot be invoked",
5603 Check(Call
.countOperandBundlesOfType(LLVMContext::OB_deopt
) == 1,
5604 "experimental_deoptimize must have exactly one "
5605 "\"deopt\" operand bundle");
5606 Check(Call
.getType() == Call
.getFunction()->getReturnType(),
5607 "experimental_deoptimize return type must match caller return type");
5609 if (isa
<CallInst
>(Call
)) {
5610 auto *RI
= dyn_cast
<ReturnInst
>(Call
.getNextNode());
5612 "calls to experimental_deoptimize must be followed by a return");
5614 if (!Call
.getType()->isVoidTy() && RI
)
5615 Check(RI
->getReturnValue() == &Call
,
5616 "calls to experimental_deoptimize must be followed by a return "
5617 "of the value computed by experimental_deoptimize");
5622 case Intrinsic::vector_reduce_and
:
5623 case Intrinsic::vector_reduce_or
:
5624 case Intrinsic::vector_reduce_xor
:
5625 case Intrinsic::vector_reduce_add
:
5626 case Intrinsic::vector_reduce_mul
:
5627 case Intrinsic::vector_reduce_smax
:
5628 case Intrinsic::vector_reduce_smin
:
5629 case Intrinsic::vector_reduce_umax
:
5630 case Intrinsic::vector_reduce_umin
: {
5631 Type
*ArgTy
= Call
.getArgOperand(0)->getType();
5632 Check(ArgTy
->isIntOrIntVectorTy() && ArgTy
->isVectorTy(),
5633 "Intrinsic has incorrect argument type!");
5636 case Intrinsic::vector_reduce_fmax
:
5637 case Intrinsic::vector_reduce_fmin
: {
5638 Type
*ArgTy
= Call
.getArgOperand(0)->getType();
5639 Check(ArgTy
->isFPOrFPVectorTy() && ArgTy
->isVectorTy(),
5640 "Intrinsic has incorrect argument type!");
5643 case Intrinsic::vector_reduce_fadd
:
5644 case Intrinsic::vector_reduce_fmul
: {
5645 // Unlike the other reductions, the first argument is a start value. The
5646 // second argument is the vector to be reduced.
5647 Type
*ArgTy
= Call
.getArgOperand(1)->getType();
5648 Check(ArgTy
->isFPOrFPVectorTy() && ArgTy
->isVectorTy(),
5649 "Intrinsic has incorrect argument type!");
5652 case Intrinsic::smul_fix
:
5653 case Intrinsic::smul_fix_sat
:
5654 case Intrinsic::umul_fix
:
5655 case Intrinsic::umul_fix_sat
:
5656 case Intrinsic::sdiv_fix
:
5657 case Intrinsic::sdiv_fix_sat
:
5658 case Intrinsic::udiv_fix
:
5659 case Intrinsic::udiv_fix_sat
: {
5660 Value
*Op1
= Call
.getArgOperand(0);
5661 Value
*Op2
= Call
.getArgOperand(1);
5662 Check(Op1
->getType()->isIntOrIntVectorTy(),
5663 "first operand of [us][mul|div]_fix[_sat] must be an int type or "
5665 Check(Op2
->getType()->isIntOrIntVectorTy(),
5666 "second operand of [us][mul|div]_fix[_sat] must be an int type or "
5669 auto *Op3
= cast
<ConstantInt
>(Call
.getArgOperand(2));
5670 Check(Op3
->getType()->getBitWidth() <= 32,
5671 "third argument of [us][mul|div]_fix[_sat] must fit within 32 bits");
5673 if (ID
== Intrinsic::smul_fix
|| ID
== Intrinsic::smul_fix_sat
||
5674 ID
== Intrinsic::sdiv_fix
|| ID
== Intrinsic::sdiv_fix_sat
) {
5675 Check(Op3
->getZExtValue() < Op1
->getType()->getScalarSizeInBits(),
5676 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
5679 Check(Op3
->getZExtValue() <= Op1
->getType()->getScalarSizeInBits(),
5680 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
5681 "to the width of the operands");
5685 case Intrinsic::lrint
:
5686 case Intrinsic::llrint
: {
5687 Type
*ValTy
= Call
.getArgOperand(0)->getType();
5688 Type
*ResultTy
= Call
.getType();
5690 ValTy
->isFPOrFPVectorTy() && ResultTy
->isIntOrIntVectorTy(),
5691 "llvm.lrint, llvm.llrint: argument must be floating-point or vector "
5692 "of floating-points, and result must be integer or vector of integers",
5694 Check(ValTy
->isVectorTy() == ResultTy
->isVectorTy(),
5695 "llvm.lrint, llvm.llrint: argument and result disagree on vector use",
5697 if (ValTy
->isVectorTy()) {
5698 Check(cast
<VectorType
>(ValTy
)->getElementCount() ==
5699 cast
<VectorType
>(ResultTy
)->getElementCount(),
5700 "llvm.lrint, llvm.llrint: argument must be same length as result",
5705 case Intrinsic::lround
:
5706 case Intrinsic::llround
: {
5707 Type
*ValTy
= Call
.getArgOperand(0)->getType();
5708 Type
*ResultTy
= Call
.getType();
5709 Check(!ValTy
->isVectorTy() && !ResultTy
->isVectorTy(),
5710 "Intrinsic does not support vectors", &Call
);
5713 case Intrinsic::bswap
: {
5714 Type
*Ty
= Call
.getType();
5715 unsigned Size
= Ty
->getScalarSizeInBits();
5716 Check(Size
% 16 == 0, "bswap must be an even number of bytes", &Call
);
5719 case Intrinsic::invariant_start
: {
5720 ConstantInt
*InvariantSize
= dyn_cast
<ConstantInt
>(Call
.getArgOperand(0));
5721 Check(InvariantSize
&&
5722 (!InvariantSize
->isNegative() || InvariantSize
->isMinusOne()),
5723 "invariant_start parameter must be -1, 0 or a positive number",
5727 case Intrinsic::matrix_multiply
:
5728 case Intrinsic::matrix_transpose
:
5729 case Intrinsic::matrix_column_major_load
:
5730 case Intrinsic::matrix_column_major_store
: {
5731 Function
*IF
= Call
.getCalledFunction();
5732 ConstantInt
*Stride
= nullptr;
5733 ConstantInt
*NumRows
;
5734 ConstantInt
*NumColumns
;
5735 VectorType
*ResultTy
;
5736 Type
*Op0ElemTy
= nullptr;
5737 Type
*Op1ElemTy
= nullptr;
5739 case Intrinsic::matrix_multiply
: {
5740 NumRows
= cast
<ConstantInt
>(Call
.getArgOperand(2));
5741 ConstantInt
*N
= cast
<ConstantInt
>(Call
.getArgOperand(3));
5742 NumColumns
= cast
<ConstantInt
>(Call
.getArgOperand(4));
5743 Check(cast
<FixedVectorType
>(Call
.getArgOperand(0)->getType())
5744 ->getNumElements() ==
5745 NumRows
->getZExtValue() * N
->getZExtValue(),
5746 "First argument of a matrix operation does not match specified "
5748 Check(cast
<FixedVectorType
>(Call
.getArgOperand(1)->getType())
5749 ->getNumElements() ==
5750 N
->getZExtValue() * NumColumns
->getZExtValue(),
5751 "Second argument of a matrix operation does not match specified "
5754 ResultTy
= cast
<VectorType
>(Call
.getType());
5756 cast
<VectorType
>(Call
.getArgOperand(0)->getType())->getElementType();
5758 cast
<VectorType
>(Call
.getArgOperand(1)->getType())->getElementType();
5761 case Intrinsic::matrix_transpose
:
5762 NumRows
= cast
<ConstantInt
>(Call
.getArgOperand(1));
5763 NumColumns
= cast
<ConstantInt
>(Call
.getArgOperand(2));
5764 ResultTy
= cast
<VectorType
>(Call
.getType());
5766 cast
<VectorType
>(Call
.getArgOperand(0)->getType())->getElementType();
5768 case Intrinsic::matrix_column_major_load
: {
5769 Stride
= dyn_cast
<ConstantInt
>(Call
.getArgOperand(1));
5770 NumRows
= cast
<ConstantInt
>(Call
.getArgOperand(3));
5771 NumColumns
= cast
<ConstantInt
>(Call
.getArgOperand(4));
5772 ResultTy
= cast
<VectorType
>(Call
.getType());
5775 case Intrinsic::matrix_column_major_store
: {
5776 Stride
= dyn_cast
<ConstantInt
>(Call
.getArgOperand(2));
5777 NumRows
= cast
<ConstantInt
>(Call
.getArgOperand(4));
5778 NumColumns
= cast
<ConstantInt
>(Call
.getArgOperand(5));
5779 ResultTy
= cast
<VectorType
>(Call
.getArgOperand(0)->getType());
5781 cast
<VectorType
>(Call
.getArgOperand(0)->getType())->getElementType();
5785 llvm_unreachable("unexpected intrinsic");
5788 Check(ResultTy
->getElementType()->isIntegerTy() ||
5789 ResultTy
->getElementType()->isFloatingPointTy(),
5790 "Result type must be an integer or floating-point type!", IF
);
5793 Check(ResultTy
->getElementType() == Op0ElemTy
,
5794 "Vector element type mismatch of the result and first operand "
5799 Check(ResultTy
->getElementType() == Op1ElemTy
,
5800 "Vector element type mismatch of the result and second operand "
5804 Check(cast
<FixedVectorType
>(ResultTy
)->getNumElements() ==
5805 NumRows
->getZExtValue() * NumColumns
->getZExtValue(),
5806 "Result of a matrix operation does not fit in the returned vector!");
5809 Check(Stride
->getZExtValue() >= NumRows
->getZExtValue(),
5810 "Stride must be greater or equal than the number of rows!", IF
);
5814 case Intrinsic::experimental_vector_splice
: {
5815 VectorType
*VecTy
= cast
<VectorType
>(Call
.getType());
5816 int64_t Idx
= cast
<ConstantInt
>(Call
.getArgOperand(2))->getSExtValue();
5817 int64_t KnownMinNumElements
= VecTy
->getElementCount().getKnownMinValue();
5818 if (Call
.getParent() && Call
.getParent()->getParent()) {
5819 AttributeList Attrs
= Call
.getParent()->getParent()->getAttributes();
5820 if (Attrs
.hasFnAttr(Attribute::VScaleRange
))
5821 KnownMinNumElements
*= Attrs
.getFnAttrs().getVScaleRangeMin();
5823 Check((Idx
< 0 && std::abs(Idx
) <= KnownMinNumElements
) ||
5824 (Idx
>= 0 && Idx
< KnownMinNumElements
),
5825 "The splice index exceeds the range [-VL, VL-1] where VL is the "
5826 "known minimum number of elements in the vector. For scalable "
5827 "vectors the minimum number of elements is determined from "
5832 case Intrinsic::experimental_stepvector
: {
5833 VectorType
*VecTy
= dyn_cast
<VectorType
>(Call
.getType());
5834 Check(VecTy
&& VecTy
->getScalarType()->isIntegerTy() &&
5835 VecTy
->getScalarSizeInBits() >= 8,
5836 "experimental_stepvector only supported for vectors of integers "
5837 "with a bitwidth of at least 8.",
5841 case Intrinsic::vector_insert
: {
5842 Value
*Vec
= Call
.getArgOperand(0);
5843 Value
*SubVec
= Call
.getArgOperand(1);
5844 Value
*Idx
= Call
.getArgOperand(2);
5845 unsigned IdxN
= cast
<ConstantInt
>(Idx
)->getZExtValue();
5847 VectorType
*VecTy
= cast
<VectorType
>(Vec
->getType());
5848 VectorType
*SubVecTy
= cast
<VectorType
>(SubVec
->getType());
5850 ElementCount VecEC
= VecTy
->getElementCount();
5851 ElementCount SubVecEC
= SubVecTy
->getElementCount();
5852 Check(VecTy
->getElementType() == SubVecTy
->getElementType(),
5853 "vector_insert parameters must have the same element "
5856 Check(IdxN
% SubVecEC
.getKnownMinValue() == 0,
5857 "vector_insert index must be a constant multiple of "
5858 "the subvector's known minimum vector length.");
5860 // If this insertion is not the 'mixed' case where a fixed vector is
5861 // inserted into a scalable vector, ensure that the insertion of the
5862 // subvector does not overrun the parent vector.
5863 if (VecEC
.isScalable() == SubVecEC
.isScalable()) {
5864 Check(IdxN
< VecEC
.getKnownMinValue() &&
5865 IdxN
+ SubVecEC
.getKnownMinValue() <= VecEC
.getKnownMinValue(),
5866 "subvector operand of vector_insert would overrun the "
5867 "vector being inserted into.");
5871 case Intrinsic::vector_extract
: {
5872 Value
*Vec
= Call
.getArgOperand(0);
5873 Value
*Idx
= Call
.getArgOperand(1);
5874 unsigned IdxN
= cast
<ConstantInt
>(Idx
)->getZExtValue();
5876 VectorType
*ResultTy
= cast
<VectorType
>(Call
.getType());
5877 VectorType
*VecTy
= cast
<VectorType
>(Vec
->getType());
5879 ElementCount VecEC
= VecTy
->getElementCount();
5880 ElementCount ResultEC
= ResultTy
->getElementCount();
5882 Check(ResultTy
->getElementType() == VecTy
->getElementType(),
5883 "vector_extract result must have the same element "
5884 "type as the input vector.",
5886 Check(IdxN
% ResultEC
.getKnownMinValue() == 0,
5887 "vector_extract index must be a constant multiple of "
5888 "the result type's known minimum vector length.");
5890 // If this extraction is not the 'mixed' case where a fixed vector is
5891 // extracted from a scalable vector, ensure that the extraction does not
5892 // overrun the parent vector.
5893 if (VecEC
.isScalable() == ResultEC
.isScalable()) {
5894 Check(IdxN
< VecEC
.getKnownMinValue() &&
5895 IdxN
+ ResultEC
.getKnownMinValue() <= VecEC
.getKnownMinValue(),
5896 "vector_extract would overrun.");
5900 case Intrinsic::experimental_noalias_scope_decl
: {
5901 NoAliasScopeDecls
.push_back(cast
<IntrinsicInst
>(&Call
));
5904 case Intrinsic::preserve_array_access_index
:
5905 case Intrinsic::preserve_struct_access_index
:
5906 case Intrinsic::aarch64_ldaxr
:
5907 case Intrinsic::aarch64_ldxr
:
5908 case Intrinsic::arm_ldaex
:
5909 case Intrinsic::arm_ldrex
: {
5910 Type
*ElemTy
= Call
.getParamElementType(0);
5911 Check(ElemTy
, "Intrinsic requires elementtype attribute on first argument.",
5915 case Intrinsic::aarch64_stlxr
:
5916 case Intrinsic::aarch64_stxr
:
5917 case Intrinsic::arm_stlex
:
5918 case Intrinsic::arm_strex
: {
5919 Type
*ElemTy
= Call
.getAttributes().getParamElementType(1);
5921 "Intrinsic requires elementtype attribute on second argument.",
5925 case Intrinsic::aarch64_prefetch
: {
5926 Check(cast
<ConstantInt
>(Call
.getArgOperand(1))->getZExtValue() < 2,
5927 "write argument to llvm.aarch64.prefetch must be 0 or 1", Call
);
5928 Check(cast
<ConstantInt
>(Call
.getArgOperand(2))->getZExtValue() < 4,
5929 "target argument to llvm.aarch64.prefetch must be 0-3", Call
);
5930 Check(cast
<ConstantInt
>(Call
.getArgOperand(3))->getZExtValue() < 2,
5931 "stream argument to llvm.aarch64.prefetch must be 0 or 1", Call
);
5932 Check(cast
<ConstantInt
>(Call
.getArgOperand(4))->getZExtValue() < 2,
5933 "isdata argument to llvm.aarch64.prefetch must be 0 or 1", Call
);
5936 case Intrinsic::callbr_landingpad
: {
5937 const auto *CBR
= dyn_cast
<CallBrInst
>(Call
.getOperand(0));
5938 Check(CBR
, "intrinstic requires callbr operand", &Call
);
5942 const BasicBlock
*LandingPadBB
= Call
.getParent();
5943 const BasicBlock
*PredBB
= LandingPadBB
->getUniquePredecessor();
5945 CheckFailed("Intrinsic in block must have 1 unique predecessor", &Call
);
5948 if (!isa
<CallBrInst
>(PredBB
->getTerminator())) {
5949 CheckFailed("Intrinsic must have corresponding callbr in predecessor",
5953 Check(llvm::any_of(CBR
->getIndirectDests(),
5954 [LandingPadBB
](const BasicBlock
*IndDest
) {
5955 return IndDest
== LandingPadBB
;
5957 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
5958 "block in indirect destination list",
5960 const Instruction
&First
= *LandingPadBB
->begin();
5961 Check(&First
== &Call
, "No other instructions may proceed intrinsic",
5965 case Intrinsic::amdgcn_cs_chain
: {
5966 auto CallerCC
= Call
.getCaller()->getCallingConv();
5968 case CallingConv::AMDGPU_CS
:
5969 case CallingConv::AMDGPU_CS_Chain
:
5970 case CallingConv::AMDGPU_CS_ChainPreserve
:
5973 CheckFailed("Intrinsic can only be used from functions with the "
5974 "amdgpu_cs, amdgpu_cs_chain or amdgpu_cs_chain_preserve "
5975 "calling conventions",
5980 Check(Call
.paramHasAttr(2, Attribute::InReg
),
5981 "SGPR arguments must have the `inreg` attribute", &Call
);
5982 Check(!Call
.paramHasAttr(3, Attribute::InReg
),
5983 "VGPR arguments must not have the `inreg` attribute", &Call
);
5986 case Intrinsic::experimental_convergence_entry
:
5988 case Intrinsic::experimental_convergence_anchor
:
5990 case Intrinsic::experimental_convergence_loop
:
5992 case Intrinsic::ptrmask
: {
5993 Type
*Ty0
= Call
.getArgOperand(0)->getType();
5994 Type
*Ty1
= Call
.getArgOperand(1)->getType();
5995 Check(Ty0
->isPtrOrPtrVectorTy(),
5996 "llvm.ptrmask intrinsic first argument must be pointer or vector "
6000 Ty0
->isVectorTy() == Ty1
->isVectorTy(),
6001 "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
6003 if (Ty0
->isVectorTy())
6004 Check(cast
<VectorType
>(Ty0
)->getElementCount() ==
6005 cast
<VectorType
>(Ty1
)->getElementCount(),
6006 "llvm.ptrmask intrinsic arguments must have the same number of "
6009 Check(DL
.getIndexTypeSizeInBits(Ty0
) == Ty1
->getScalarSizeInBits(),
6010 "llvm.ptrmask intrinsic second argument bitwidth must match "
6011 "pointer index type size of first argument",
6017 // Verify that there aren't any unmediated control transfers between funclets.
6018 if (IntrinsicInst::mayLowerToFunctionCall(ID
)) {
6019 Function
*F
= Call
.getParent()->getParent();
6020 if (F
->hasPersonalityFn() &&
6021 isScopedEHPersonality(classifyEHPersonality(F
->getPersonalityFn()))) {
6022 // Run EH funclet coloring on-demand and cache results for other intrinsic
6023 // calls in this function
6024 if (BlockEHFuncletColors
.empty())
6025 BlockEHFuncletColors
= colorEHFunclets(*F
);
6027 // Check for catch-/cleanup-pad in first funclet block
6028 bool InEHFunclet
= false;
6029 BasicBlock
*CallBB
= Call
.getParent();
6030 const ColorVector
&CV
= BlockEHFuncletColors
.find(CallBB
)->second
;
6031 assert(CV
.size() > 0 && "Uncolored block");
6032 for (BasicBlock
*ColorFirstBB
: CV
)
6033 if (dyn_cast_or_null
<FuncletPadInst
>(ColorFirstBB
->getFirstNonPHI()))
6036 // Check for funclet operand bundle
6037 bool HasToken
= false;
6038 for (unsigned I
= 0, E
= Call
.getNumOperandBundles(); I
!= E
; ++I
)
6039 if (Call
.getOperandBundleAt(I
).getTagID() == LLVMContext::OB_funclet
)
6042 // This would cause silent code truncation in WinEHPrepare
6044 Check(HasToken
, "Missing funclet token on intrinsic call", &Call
);
6049 /// Carefully grab the subprogram from a local scope.
6051 /// This carefully grabs the subprogram from a local scope, avoiding the
6052 /// built-in assertions that would typically fire.
6053 static DISubprogram
*getSubprogram(Metadata
*LocalScope
) {
6057 if (auto *SP
= dyn_cast
<DISubprogram
>(LocalScope
))
6060 if (auto *LB
= dyn_cast
<DILexicalBlockBase
>(LocalScope
))
6061 return getSubprogram(LB
->getRawScope());
6063 // Just return null; broken scope chains are checked elsewhere.
6064 assert(!isa
<DILocalScope
>(LocalScope
) && "Unknown type of local scope");
6068 void Verifier::visitVPIntrinsic(VPIntrinsic
&VPI
) {
6069 if (auto *VPCast
= dyn_cast
<VPCastIntrinsic
>(&VPI
)) {
6070 auto *RetTy
= cast
<VectorType
>(VPCast
->getType());
6071 auto *ValTy
= cast
<VectorType
>(VPCast
->getOperand(0)->getType());
6072 Check(RetTy
->getElementCount() == ValTy
->getElementCount(),
6073 "VP cast intrinsic first argument and result vector lengths must be "
6077 switch (VPCast
->getIntrinsicID()) {
6079 llvm_unreachable("Unknown VP cast intrinsic");
6080 case Intrinsic::vp_trunc
:
6081 Check(RetTy
->isIntOrIntVectorTy() && ValTy
->isIntOrIntVectorTy(),
6082 "llvm.vp.trunc intrinsic first argument and result element type "
6085 Check(RetTy
->getScalarSizeInBits() < ValTy
->getScalarSizeInBits(),
6086 "llvm.vp.trunc intrinsic the bit size of first argument must be "
6087 "larger than the bit size of the return type",
6090 case Intrinsic::vp_zext
:
6091 case Intrinsic::vp_sext
:
6092 Check(RetTy
->isIntOrIntVectorTy() && ValTy
->isIntOrIntVectorTy(),
6093 "llvm.vp.zext or llvm.vp.sext intrinsic first argument and result "
6094 "element type must be integer",
6096 Check(RetTy
->getScalarSizeInBits() > ValTy
->getScalarSizeInBits(),
6097 "llvm.vp.zext or llvm.vp.sext intrinsic the bit size of first "
6098 "argument must be smaller than the bit size of the return type",
6101 case Intrinsic::vp_fptoui
:
6102 case Intrinsic::vp_fptosi
:
6104 RetTy
->isIntOrIntVectorTy() && ValTy
->isFPOrFPVectorTy(),
6105 "llvm.vp.fptoui or llvm.vp.fptosi intrinsic first argument element "
6106 "type must be floating-point and result element type must be integer",
6109 case Intrinsic::vp_uitofp
:
6110 case Intrinsic::vp_sitofp
:
6112 RetTy
->isFPOrFPVectorTy() && ValTy
->isIntOrIntVectorTy(),
6113 "llvm.vp.uitofp or llvm.vp.sitofp intrinsic first argument element "
6114 "type must be integer and result element type must be floating-point",
6117 case Intrinsic::vp_fptrunc
:
6118 Check(RetTy
->isFPOrFPVectorTy() && ValTy
->isFPOrFPVectorTy(),
6119 "llvm.vp.fptrunc intrinsic first argument and result element type "
6120 "must be floating-point",
6122 Check(RetTy
->getScalarSizeInBits() < ValTy
->getScalarSizeInBits(),
6123 "llvm.vp.fptrunc intrinsic the bit size of first argument must be "
6124 "larger than the bit size of the return type",
6127 case Intrinsic::vp_fpext
:
6128 Check(RetTy
->isFPOrFPVectorTy() && ValTy
->isFPOrFPVectorTy(),
6129 "llvm.vp.fpext intrinsic first argument and result element type "
6130 "must be floating-point",
6132 Check(RetTy
->getScalarSizeInBits() > ValTy
->getScalarSizeInBits(),
6133 "llvm.vp.fpext intrinsic the bit size of first argument must be "
6134 "smaller than the bit size of the return type",
6137 case Intrinsic::vp_ptrtoint
:
6138 Check(RetTy
->isIntOrIntVectorTy() && ValTy
->isPtrOrPtrVectorTy(),
6139 "llvm.vp.ptrtoint intrinsic first argument element type must be "
6140 "pointer and result element type must be integer",
6143 case Intrinsic::vp_inttoptr
:
6144 Check(RetTy
->isPtrOrPtrVectorTy() && ValTy
->isIntOrIntVectorTy(),
6145 "llvm.vp.inttoptr intrinsic first argument element type must be "
6146 "integer and result element type must be pointer",
6151 if (VPI
.getIntrinsicID() == Intrinsic::vp_fcmp
) {
6152 auto Pred
= cast
<VPCmpIntrinsic
>(&VPI
)->getPredicate();
6153 Check(CmpInst::isFPPredicate(Pred
),
6154 "invalid predicate for VP FP comparison intrinsic", &VPI
);
6156 if (VPI
.getIntrinsicID() == Intrinsic::vp_icmp
) {
6157 auto Pred
= cast
<VPCmpIntrinsic
>(&VPI
)->getPredicate();
6158 Check(CmpInst::isIntPredicate(Pred
),
6159 "invalid predicate for VP integer comparison intrinsic", &VPI
);
6161 if (VPI
.getIntrinsicID() == Intrinsic::vp_is_fpclass
) {
6162 auto TestMask
= cast
<ConstantInt
>(VPI
.getOperand(1));
6163 Check((TestMask
->getZExtValue() & ~static_cast<unsigned>(fcAllFlags
)) == 0,
6164 "unsupported bits for llvm.vp.is.fpclass test mask");
6168 void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic
&FPI
) {
6169 unsigned NumOperands
;
6171 switch (FPI
.getIntrinsicID()) {
6172 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
6173 case Intrinsic::INTRINSIC: \
6174 NumOperands = NARG; \
6175 HasRoundingMD = ROUND_MODE; \
6177 #include "llvm/IR/ConstrainedOps.def"
6179 llvm_unreachable("Invalid constrained FP intrinsic!");
6181 NumOperands
+= (1 + HasRoundingMD
);
6182 // Compare intrinsics carry an extra predicate metadata operand.
6183 if (isa
<ConstrainedFPCmpIntrinsic
>(FPI
))
6185 Check((FPI
.arg_size() == NumOperands
),
6186 "invalid arguments for constrained FP intrinsic", &FPI
);
6188 switch (FPI
.getIntrinsicID()) {
6189 case Intrinsic::experimental_constrained_lrint
:
6190 case Intrinsic::experimental_constrained_llrint
: {
6191 Type
*ValTy
= FPI
.getArgOperand(0)->getType();
6192 Type
*ResultTy
= FPI
.getType();
6193 Check(!ValTy
->isVectorTy() && !ResultTy
->isVectorTy(),
6194 "Intrinsic does not support vectors", &FPI
);
6198 case Intrinsic::experimental_constrained_lround
:
6199 case Intrinsic::experimental_constrained_llround
: {
6200 Type
*ValTy
= FPI
.getArgOperand(0)->getType();
6201 Type
*ResultTy
= FPI
.getType();
6202 Check(!ValTy
->isVectorTy() && !ResultTy
->isVectorTy(),
6203 "Intrinsic does not support vectors", &FPI
);
6207 case Intrinsic::experimental_constrained_fcmp
:
6208 case Intrinsic::experimental_constrained_fcmps
: {
6209 auto Pred
= cast
<ConstrainedFPCmpIntrinsic
>(&FPI
)->getPredicate();
6210 Check(CmpInst::isFPPredicate(Pred
),
6211 "invalid predicate for constrained FP comparison intrinsic", &FPI
);
6215 case Intrinsic::experimental_constrained_fptosi
:
6216 case Intrinsic::experimental_constrained_fptoui
: {
6217 Value
*Operand
= FPI
.getArgOperand(0);
6219 Check(Operand
->getType()->isFPOrFPVectorTy(),
6220 "Intrinsic first argument must be floating point", &FPI
);
6221 if (auto *OperandT
= dyn_cast
<VectorType
>(Operand
->getType())) {
6222 SrcEC
= cast
<VectorType
>(OperandT
)->getElementCount();
6226 Check(SrcEC
.isNonZero() == Operand
->getType()->isVectorTy(),
6227 "Intrinsic first argument and result disagree on vector use", &FPI
);
6228 Check(Operand
->getType()->isIntOrIntVectorTy(),
6229 "Intrinsic result must be an integer", &FPI
);
6230 if (auto *OperandT
= dyn_cast
<VectorType
>(Operand
->getType())) {
6231 Check(SrcEC
== cast
<VectorType
>(OperandT
)->getElementCount(),
6232 "Intrinsic first argument and result vector lengths must be equal",
6238 case Intrinsic::experimental_constrained_sitofp
:
6239 case Intrinsic::experimental_constrained_uitofp
: {
6240 Value
*Operand
= FPI
.getArgOperand(0);
6242 Check(Operand
->getType()->isIntOrIntVectorTy(),
6243 "Intrinsic first argument must be integer", &FPI
);
6244 if (auto *OperandT
= dyn_cast
<VectorType
>(Operand
->getType())) {
6245 SrcEC
= cast
<VectorType
>(OperandT
)->getElementCount();
6249 Check(SrcEC
.isNonZero() == Operand
->getType()->isVectorTy(),
6250 "Intrinsic first argument and result disagree on vector use", &FPI
);
6251 Check(Operand
->getType()->isFPOrFPVectorTy(),
6252 "Intrinsic result must be a floating point", &FPI
);
6253 if (auto *OperandT
= dyn_cast
<VectorType
>(Operand
->getType())) {
6254 Check(SrcEC
== cast
<VectorType
>(OperandT
)->getElementCount(),
6255 "Intrinsic first argument and result vector lengths must be equal",
6260 case Intrinsic::experimental_constrained_fptrunc
:
6261 case Intrinsic::experimental_constrained_fpext
: {
6262 Value
*Operand
= FPI
.getArgOperand(0);
6263 Type
*OperandTy
= Operand
->getType();
6264 Value
*Result
= &FPI
;
6265 Type
*ResultTy
= Result
->getType();
6266 Check(OperandTy
->isFPOrFPVectorTy(),
6267 "Intrinsic first argument must be FP or FP vector", &FPI
);
6268 Check(ResultTy
->isFPOrFPVectorTy(),
6269 "Intrinsic result must be FP or FP vector", &FPI
);
6270 Check(OperandTy
->isVectorTy() == ResultTy
->isVectorTy(),
6271 "Intrinsic first argument and result disagree on vector use", &FPI
);
6272 if (OperandTy
->isVectorTy()) {
6273 Check(cast
<VectorType
>(OperandTy
)->getElementCount() ==
6274 cast
<VectorType
>(ResultTy
)->getElementCount(),
6275 "Intrinsic first argument and result vector lengths must be equal",
6278 if (FPI
.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc
) {
6279 Check(OperandTy
->getScalarSizeInBits() > ResultTy
->getScalarSizeInBits(),
6280 "Intrinsic first argument's type must be larger than result type",
6283 Check(OperandTy
->getScalarSizeInBits() < ResultTy
->getScalarSizeInBits(),
6284 "Intrinsic first argument's type must be smaller than result type",
6294 // If a non-metadata argument is passed in a metadata slot then the
6295 // error will be caught earlier when the incorrect argument doesn't
6296 // match the specification in the intrinsic call table. Thus, no
6297 // argument type check is needed here.
6299 Check(FPI
.getExceptionBehavior().has_value(),
6300 "invalid exception behavior argument", &FPI
);
6301 if (HasRoundingMD
) {
6302 Check(FPI
.getRoundingMode().has_value(), "invalid rounding mode argument",
6307 void Verifier::visitDbgIntrinsic(StringRef Kind
, DbgVariableIntrinsic
&DII
) {
6308 auto *MD
= DII
.getRawLocation();
6309 CheckDI(isa
<ValueAsMetadata
>(MD
) || isa
<DIArgList
>(MD
) ||
6310 (isa
<MDNode
>(MD
) && !cast
<MDNode
>(MD
)->getNumOperands()),
6311 "invalid llvm.dbg." + Kind
+ " intrinsic address/value", &DII
, MD
);
6312 CheckDI(isa
<DILocalVariable
>(DII
.getRawVariable()),
6313 "invalid llvm.dbg." + Kind
+ " intrinsic variable", &DII
,
6314 DII
.getRawVariable());
6315 CheckDI(isa
<DIExpression
>(DII
.getRawExpression()),
6316 "invalid llvm.dbg." + Kind
+ " intrinsic expression", &DII
,
6317 DII
.getRawExpression());
6319 if (auto *DAI
= dyn_cast
<DbgAssignIntrinsic
>(&DII
)) {
6320 CheckDI(isa
<DIAssignID
>(DAI
->getRawAssignID()),
6321 "invalid llvm.dbg.assign intrinsic DIAssignID", &DII
,
6322 DAI
->getRawAssignID());
6323 const auto *RawAddr
= DAI
->getRawAddress();
6325 isa
<ValueAsMetadata
>(RawAddr
) ||
6326 (isa
<MDNode
>(RawAddr
) && !cast
<MDNode
>(RawAddr
)->getNumOperands()),
6327 "invalid llvm.dbg.assign intrinsic address", &DII
,
6328 DAI
->getRawAddress());
6329 CheckDI(isa
<DIExpression
>(DAI
->getRawAddressExpression()),
6330 "invalid llvm.dbg.assign intrinsic address expression", &DII
,
6331 DAI
->getRawAddressExpression());
6332 // All of the linked instructions should be in the same function as DII.
6333 for (Instruction
*I
: at::getAssignmentInsts(DAI
))
6334 CheckDI(DAI
->getFunction() == I
->getFunction(),
6335 "inst not in same function as dbg.assign", I
, DAI
);
6338 // Ignore broken !dbg attachments; they're checked elsewhere.
6339 if (MDNode
*N
= DII
.getDebugLoc().getAsMDNode())
6340 if (!isa
<DILocation
>(N
))
6343 BasicBlock
*BB
= DII
.getParent();
6344 Function
*F
= BB
? BB
->getParent() : nullptr;
6346 // The scopes for variables and !dbg attachments must agree.
6347 DILocalVariable
*Var
= DII
.getVariable();
6348 DILocation
*Loc
= DII
.getDebugLoc();
6349 CheckDI(Loc
, "llvm.dbg." + Kind
+ " intrinsic requires a !dbg attachment",
6352 DISubprogram
*VarSP
= getSubprogram(Var
->getRawScope());
6353 DISubprogram
*LocSP
= getSubprogram(Loc
->getRawScope());
6354 if (!VarSP
|| !LocSP
)
6355 return; // Broken scope chains are checked elsewhere.
6357 CheckDI(VarSP
== LocSP
,
6358 "mismatched subprogram between llvm.dbg." + Kind
+
6359 " variable and !dbg attachment",
6360 &DII
, BB
, F
, Var
, Var
->getScope()->getSubprogram(), Loc
,
6361 Loc
->getScope()->getSubprogram());
6363 // This check is redundant with one in visitLocalVariable().
6364 CheckDI(isType(Var
->getRawType()), "invalid type ref", Var
,
6369 void Verifier::visitDbgLabelIntrinsic(StringRef Kind
, DbgLabelInst
&DLI
) {
6370 CheckDI(isa
<DILabel
>(DLI
.getRawLabel()),
6371 "invalid llvm.dbg." + Kind
+ " intrinsic variable", &DLI
,
6374 // Ignore broken !dbg attachments; they're checked elsewhere.
6375 if (MDNode
*N
= DLI
.getDebugLoc().getAsMDNode())
6376 if (!isa
<DILocation
>(N
))
6379 BasicBlock
*BB
= DLI
.getParent();
6380 Function
*F
= BB
? BB
->getParent() : nullptr;
6382 // The scopes for variables and !dbg attachments must agree.
6383 DILabel
*Label
= DLI
.getLabel();
6384 DILocation
*Loc
= DLI
.getDebugLoc();
6385 Check(Loc
, "llvm.dbg." + Kind
+ " intrinsic requires a !dbg attachment", &DLI
,
6388 DISubprogram
*LabelSP
= getSubprogram(Label
->getRawScope());
6389 DISubprogram
*LocSP
= getSubprogram(Loc
->getRawScope());
6390 if (!LabelSP
|| !LocSP
)
6393 CheckDI(LabelSP
== LocSP
,
6394 "mismatched subprogram between llvm.dbg." + Kind
+
6395 " label and !dbg attachment",
6396 &DLI
, BB
, F
, Label
, Label
->getScope()->getSubprogram(), Loc
,
6397 Loc
->getScope()->getSubprogram());
6400 void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic
&I
) {
6401 DILocalVariable
*V
= dyn_cast_or_null
<DILocalVariable
>(I
.getRawVariable());
6402 DIExpression
*E
= dyn_cast_or_null
<DIExpression
>(I
.getRawExpression());
6404 // We don't know whether this intrinsic verified correctly.
6405 if (!V
|| !E
|| !E
->isValid())
6408 // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
6409 auto Fragment
= E
->getFragmentInfo();
6413 // The frontend helps out GDB by emitting the members of local anonymous
6414 // unions as artificial local variables with shared storage. When SROA splits
6415 // the storage for artificial local variables that are smaller than the entire
6416 // union, the overhang piece will be outside of the allotted space for the
6417 // variable and this check fails.
6418 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
6419 if (V
->isArtificial())
6422 verifyFragmentExpression(*V
, *Fragment
, &I
);
6425 template <typename ValueOrMetadata
>
6426 void Verifier::verifyFragmentExpression(const DIVariable
&V
,
6427 DIExpression::FragmentInfo Fragment
,
6428 ValueOrMetadata
*Desc
) {
6429 // If there's no size, the type is broken, but that should be checked
6431 auto VarSize
= V
.getSizeInBits();
6435 unsigned FragSize
= Fragment
.SizeInBits
;
6436 unsigned FragOffset
= Fragment
.OffsetInBits
;
6437 CheckDI(FragSize
+ FragOffset
<= *VarSize
,
6438 "fragment is larger than or outside of variable", Desc
, &V
);
6439 CheckDI(FragSize
!= *VarSize
, "fragment covers entire variable", Desc
, &V
);
6442 void Verifier::verifyFnArgs(const DbgVariableIntrinsic
&I
) {
6443 // This function does not take the scope of noninlined function arguments into
6444 // account. Don't run it if current function is nodebug, because it may
6445 // contain inlined debug intrinsics.
6449 // For performance reasons only check non-inlined ones.
6450 if (I
.getDebugLoc()->getInlinedAt())
6453 DILocalVariable
*Var
= I
.getVariable();
6454 CheckDI(Var
, "dbg intrinsic without variable");
6456 unsigned ArgNo
= Var
->getArg();
6460 // Verify there are no duplicate function argument debug info entries.
6461 // These will cause hard-to-debug assertions in the DWARF backend.
6462 if (DebugFnArgs
.size() < ArgNo
)
6463 DebugFnArgs
.resize(ArgNo
, nullptr);
6465 auto *Prev
= DebugFnArgs
[ArgNo
- 1];
6466 DebugFnArgs
[ArgNo
- 1] = Var
;
6467 CheckDI(!Prev
|| (Prev
== Var
), "conflicting debug info for argument", &I
,
6471 void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic
&I
) {
6472 DIExpression
*E
= dyn_cast_or_null
<DIExpression
>(I
.getRawExpression());
6474 // We don't know whether this intrinsic verified correctly.
6475 if (!E
|| !E
->isValid())
6478 if (isa
<ValueAsMetadata
>(I
.getRawLocation())) {
6479 Value
*VarValue
= I
.getVariableLocationOp(0);
6480 if (isa
<UndefValue
>(VarValue
) || isa
<PoisonValue
>(VarValue
))
6482 // We allow EntryValues for swift async arguments, as they have an
6483 // ABI-guarantee to be turned into a specific register.
6484 if (auto *ArgLoc
= dyn_cast_or_null
<Argument
>(VarValue
);
6485 ArgLoc
&& ArgLoc
->hasAttribute(Attribute::SwiftAsync
))
6489 CheckDI(!E
->isEntryValue(),
6490 "Entry values are only allowed in MIR unless they target a "
6491 "swiftasync Argument",
6495 void Verifier::verifyCompileUnits() {
6496 // When more than one Module is imported into the same context, such as during
6497 // an LTO build before linking the modules, ODR type uniquing may cause types
6498 // to point to a different CU. This check does not make sense in this case.
6499 if (M
.getContext().isODRUniquingDebugTypes())
6501 auto *CUs
= M
.getNamedMetadata("llvm.dbg.cu");
6502 SmallPtrSet
<const Metadata
*, 2> Listed
;
6504 Listed
.insert(CUs
->op_begin(), CUs
->op_end());
6505 for (const auto *CU
: CUVisited
)
6506 CheckDI(Listed
.count(CU
), "DICompileUnit not listed in llvm.dbg.cu", CU
);
6510 void Verifier::verifyDeoptimizeCallingConvs() {
6511 if (DeoptimizeDeclarations
.empty())
6514 const Function
*First
= DeoptimizeDeclarations
[0];
6515 for (const auto *F
: ArrayRef(DeoptimizeDeclarations
).slice(1)) {
6516 Check(First
->getCallingConv() == F
->getCallingConv(),
6517 "All llvm.experimental.deoptimize declarations must have the same "
6518 "calling convention",
6523 void Verifier::verifyAttachedCallBundle(const CallBase
&Call
,
6524 const OperandBundleUse
&BU
) {
6525 FunctionType
*FTy
= Call
.getFunctionType();
6527 Check((FTy
->getReturnType()->isPointerTy() ||
6528 (Call
.doesNotReturn() && FTy
->getReturnType()->isVoidTy())),
6529 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
6530 "function returning a pointer or a non-returning function that has a "
6534 Check(BU
.Inputs
.size() == 1 && isa
<Function
>(BU
.Inputs
.front()),
6535 "operand bundle \"clang.arc.attachedcall\" requires one function as "
6539 auto *Fn
= cast
<Function
>(BU
.Inputs
.front());
6540 Intrinsic::ID IID
= Fn
->getIntrinsicID();
6543 Check((IID
== Intrinsic::objc_retainAutoreleasedReturnValue
||
6544 IID
== Intrinsic::objc_unsafeClaimAutoreleasedReturnValue
),
6545 "invalid function argument", Call
);
6547 StringRef FnName
= Fn
->getName();
6548 Check((FnName
== "objc_retainAutoreleasedReturnValue" ||
6549 FnName
== "objc_unsafeClaimAutoreleasedReturnValue"),
6550 "invalid function argument", Call
);
6554 void Verifier::verifySourceDebugInfo(const DICompileUnit
&U
, const DIFile
&F
) {
6555 bool HasSource
= F
.getSource().has_value();
6556 if (!HasSourceDebugInfo
.count(&U
))
6557 HasSourceDebugInfo
[&U
] = HasSource
;
6558 CheckDI(HasSource
== HasSourceDebugInfo
[&U
],
6559 "inconsistent use of embedded source");
6562 void Verifier::verifyNoAliasScopeDecl() {
6563 if (NoAliasScopeDecls
.empty())
6566 // only a single scope must be declared at a time.
6567 for (auto *II
: NoAliasScopeDecls
) {
6568 assert(II
->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl
&&
6569 "Not a llvm.experimental.noalias.scope.decl ?");
6570 const auto *ScopeListMV
= dyn_cast
<MetadataAsValue
>(
6571 II
->getOperand(Intrinsic::NoAliasScopeDeclScopeArg
));
6572 Check(ScopeListMV
!= nullptr,
6573 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
6577 const auto *ScopeListMD
= dyn_cast
<MDNode
>(ScopeListMV
->getMetadata());
6578 Check(ScopeListMD
!= nullptr, "!id.scope.list must point to an MDNode", II
);
6579 Check(ScopeListMD
->getNumOperands() == 1,
6580 "!id.scope.list must point to a list with a single scope", II
);
6581 visitAliasScopeListMetadata(ScopeListMD
);
6584 // Only check the domination rule when requested. Once all passes have been
6585 // adapted this option can go away.
6586 if (!VerifyNoAliasScopeDomination
)
6589 // Now sort the intrinsics based on the scope MDNode so that declarations of
6590 // the same scopes are next to each other.
6591 auto GetScope
= [](IntrinsicInst
*II
) {
6592 const auto *ScopeListMV
= cast
<MetadataAsValue
>(
6593 II
->getOperand(Intrinsic::NoAliasScopeDeclScopeArg
));
6594 return &cast
<MDNode
>(ScopeListMV
->getMetadata())->getOperand(0);
6597 // We are sorting on MDNode pointers here. For valid input IR this is ok.
6598 // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
6599 auto Compare
= [GetScope
](IntrinsicInst
*Lhs
, IntrinsicInst
*Rhs
) {
6600 return GetScope(Lhs
) < GetScope(Rhs
);
6603 llvm::sort(NoAliasScopeDecls
, Compare
);
6605 // Go over the intrinsics and check that for the same scope, they are not
6606 // dominating each other.
6607 auto ItCurrent
= NoAliasScopeDecls
.begin();
6608 while (ItCurrent
!= NoAliasScopeDecls
.end()) {
6609 auto CurScope
= GetScope(*ItCurrent
);
6610 auto ItNext
= ItCurrent
;
6613 } while (ItNext
!= NoAliasScopeDecls
.end() &&
6614 GetScope(*ItNext
) == CurScope
);
6616 // [ItCurrent, ItNext) represents the declarations for the same scope.
6617 // Ensure they are not dominating each other.. but only if it is not too
6619 if (ItNext
- ItCurrent
< 32)
6620 for (auto *I
: llvm::make_range(ItCurrent
, ItNext
))
6621 for (auto *J
: llvm::make_range(ItCurrent
, ItNext
))
6623 Check(!DT
.dominates(I
, J
),
6624 "llvm.experimental.noalias.scope.decl dominates another one "
6625 "with the same scope",
6631 //===----------------------------------------------------------------------===//
6632 // Implement the public interfaces to this file...
6633 //===----------------------------------------------------------------------===//
6635 bool llvm::verifyFunction(const Function
&f
, raw_ostream
*OS
) {
6636 Function
&F
= const_cast<Function
&>(f
);
6638 // Don't use a raw_null_ostream. Printing IR is expensive.
6639 Verifier
V(OS
, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f
.getParent());
6641 // Note that this function's return value is inverted from what you would
6642 // expect of a function called "verify".
6643 return !V
.verify(F
);
6646 bool llvm::verifyModule(const Module
&M
, raw_ostream
*OS
,
6647 bool *BrokenDebugInfo
) {
6648 // Don't use a raw_null_ostream. Printing IR is expensive.
6649 Verifier
V(OS
, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo
, M
);
6651 bool Broken
= false;
6652 for (const Function
&F
: M
)
6653 Broken
|= !V
.verify(F
);
6655 Broken
|= !V
.verify();
6656 if (BrokenDebugInfo
)
6657 *BrokenDebugInfo
= V
.hasBrokenDebugInfo();
6658 // Note that this function's return value is inverted from what you would
6659 // expect of a function called "verify".
6665 struct VerifierLegacyPass
: public FunctionPass
{
6668 std::unique_ptr
<Verifier
> V
;
6669 bool FatalErrors
= true;
6671 VerifierLegacyPass() : FunctionPass(ID
) {
6672 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
6674 explicit VerifierLegacyPass(bool FatalErrors
)
6676 FatalErrors(FatalErrors
) {
6677 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
6680 bool doInitialization(Module
&M
) override
{
6681 V
= std::make_unique
<Verifier
>(
6682 &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M
);
6686 bool runOnFunction(Function
&F
) override
{
6687 if (!V
->verify(F
) && FatalErrors
) {
6688 errs() << "in function " << F
.getName() << '\n';
6689 report_fatal_error("Broken function found, compilation aborted!");
6694 bool doFinalization(Module
&M
) override
{
6695 bool HasErrors
= false;
6696 for (Function
&F
: M
)
6697 if (F
.isDeclaration())
6698 HasErrors
|= !V
->verify(F
);
6700 HasErrors
|= !V
->verify();
6701 if (FatalErrors
&& (HasErrors
|| V
->hasBrokenDebugInfo()))
6702 report_fatal_error("Broken module found, compilation aborted!");
6706 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
6707 AU
.setPreservesAll();
6711 } // end anonymous namespace
6713 /// Helper to issue failure from the TBAA verification
6714 template <typename
... Tys
> void TBAAVerifier::CheckFailed(Tys
&&... Args
) {
6716 return Diagnostic
->CheckFailed(Args
...);
6719 #define CheckTBAA(C, ...) \
6722 CheckFailed(__VA_ARGS__); \
6727 /// Verify that \p BaseNode can be used as the "base type" in the struct-path
6728 /// TBAA scheme. This means \p BaseNode is either a scalar node, or a
6729 /// struct-type node describing an aggregate data structure (like a struct).
6730 TBAAVerifier::TBAABaseNodeSummary
6731 TBAAVerifier::verifyTBAABaseNode(Instruction
&I
, const MDNode
*BaseNode
,
6733 if (BaseNode
->getNumOperands() < 2) {
6734 CheckFailed("Base nodes must have at least two operands", &I
, BaseNode
);
6738 auto Itr
= TBAABaseNodes
.find(BaseNode
);
6739 if (Itr
!= TBAABaseNodes
.end())
6742 auto Result
= verifyTBAABaseNodeImpl(I
, BaseNode
, IsNewFormat
);
6743 auto InsertResult
= TBAABaseNodes
.insert({BaseNode
, Result
});
6745 assert(InsertResult
.second
&& "We just checked!");
6749 TBAAVerifier::TBAABaseNodeSummary
6750 TBAAVerifier::verifyTBAABaseNodeImpl(Instruction
&I
, const MDNode
*BaseNode
,
6752 const TBAAVerifier::TBAABaseNodeSummary InvalidNode
= {true, ~0u};
6754 if (BaseNode
->getNumOperands() == 2) {
6755 // Scalar nodes can only be accessed at offset 0.
6756 return isValidScalarTBAANode(BaseNode
)
6757 ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
6762 if (BaseNode
->getNumOperands() % 3 != 0) {
6763 CheckFailed("Access tag nodes must have the number of operands that is a "
6764 "multiple of 3!", BaseNode
);
6768 if (BaseNode
->getNumOperands() % 2 != 1) {
6769 CheckFailed("Struct tag nodes must have an odd number of operands!",
6775 // Check the type size field.
6777 auto *TypeSizeNode
= mdconst::dyn_extract_or_null
<ConstantInt
>(
6778 BaseNode
->getOperand(1));
6779 if (!TypeSizeNode
) {
6780 CheckFailed("Type size nodes must be constants!", &I
, BaseNode
);
6785 // Check the type name field. In the new format it can be anything.
6786 if (!IsNewFormat
&& !isa
<MDString
>(BaseNode
->getOperand(0))) {
6787 CheckFailed("Struct tag nodes have a string as their first operand",
6792 bool Failed
= false;
6794 std::optional
<APInt
> PrevOffset
;
6795 unsigned BitWidth
= ~0u;
6797 // We've already checked that BaseNode is not a degenerate root node with one
6798 // operand in \c verifyTBAABaseNode, so this loop should run at least once.
6799 unsigned FirstFieldOpNo
= IsNewFormat
? 3 : 1;
6800 unsigned NumOpsPerField
= IsNewFormat
? 3 : 2;
6801 for (unsigned Idx
= FirstFieldOpNo
; Idx
< BaseNode
->getNumOperands();
6802 Idx
+= NumOpsPerField
) {
6803 const MDOperand
&FieldTy
= BaseNode
->getOperand(Idx
);
6804 const MDOperand
&FieldOffset
= BaseNode
->getOperand(Idx
+ 1);
6805 if (!isa
<MDNode
>(FieldTy
)) {
6806 CheckFailed("Incorrect field entry in struct type node!", &I
, BaseNode
);
6811 auto *OffsetEntryCI
=
6812 mdconst::dyn_extract_or_null
<ConstantInt
>(FieldOffset
);
6813 if (!OffsetEntryCI
) {
6814 CheckFailed("Offset entries must be constants!", &I
, BaseNode
);
6819 if (BitWidth
== ~0u)
6820 BitWidth
= OffsetEntryCI
->getBitWidth();
6822 if (OffsetEntryCI
->getBitWidth() != BitWidth
) {
6824 "Bitwidth between the offsets and struct type entries must match", &I
,
6830 // NB! As far as I can tell, we generate a non-strictly increasing offset
6831 // sequence only from structs that have zero size bit fields. When
6832 // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
6833 // pick the field lexically the latest in struct type metadata node. This
6834 // mirrors the actual behavior of the alias analysis implementation.
6836 !PrevOffset
|| PrevOffset
->ule(OffsetEntryCI
->getValue());
6839 CheckFailed("Offsets must be increasing!", &I
, BaseNode
);
6843 PrevOffset
= OffsetEntryCI
->getValue();
6846 auto *MemberSizeNode
= mdconst::dyn_extract_or_null
<ConstantInt
>(
6847 BaseNode
->getOperand(Idx
+ 2));
6848 if (!MemberSizeNode
) {
6849 CheckFailed("Member size entries must be constants!", &I
, BaseNode
);
6856 return Failed
? InvalidNode
6857 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth
);
6860 static bool IsRootTBAANode(const MDNode
*MD
) {
6861 return MD
->getNumOperands() < 2;
6864 static bool IsScalarTBAANodeImpl(const MDNode
*MD
,
6865 SmallPtrSetImpl
<const MDNode
*> &Visited
) {
6866 if (MD
->getNumOperands() != 2 && MD
->getNumOperands() != 3)
6869 if (!isa
<MDString
>(MD
->getOperand(0)))
6872 if (MD
->getNumOperands() == 3) {
6873 auto *Offset
= mdconst::dyn_extract
<ConstantInt
>(MD
->getOperand(2));
6874 if (!(Offset
&& Offset
->isZero() && isa
<MDString
>(MD
->getOperand(0))))
6878 auto *Parent
= dyn_cast_or_null
<MDNode
>(MD
->getOperand(1));
6879 return Parent
&& Visited
.insert(Parent
).second
&&
6880 (IsRootTBAANode(Parent
) || IsScalarTBAANodeImpl(Parent
, Visited
));
6883 bool TBAAVerifier::isValidScalarTBAANode(const MDNode
*MD
) {
6884 auto ResultIt
= TBAAScalarNodes
.find(MD
);
6885 if (ResultIt
!= TBAAScalarNodes
.end())
6886 return ResultIt
->second
;
6888 SmallPtrSet
<const MDNode
*, 4> Visited
;
6889 bool Result
= IsScalarTBAANodeImpl(MD
, Visited
);
6890 auto InsertResult
= TBAAScalarNodes
.insert({MD
, Result
});
6892 assert(InsertResult
.second
&& "Just checked!");
6897 /// Returns the field node at the offset \p Offset in \p BaseNode. Update \p
6898 /// Offset in place to be the offset within the field node returned.
6900 /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
6901 MDNode
*TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction
&I
,
6902 const MDNode
*BaseNode
,
6905 assert(BaseNode
->getNumOperands() >= 2 && "Invalid base node!");
6907 // Scalar nodes have only one possible "field" -- their parent in the access
6908 // hierarchy. Offset must be zero at this point, but our caller is supposed
6910 if (BaseNode
->getNumOperands() == 2)
6911 return cast
<MDNode
>(BaseNode
->getOperand(1));
6913 unsigned FirstFieldOpNo
= IsNewFormat
? 3 : 1;
6914 unsigned NumOpsPerField
= IsNewFormat
? 3 : 2;
6915 for (unsigned Idx
= FirstFieldOpNo
; Idx
< BaseNode
->getNumOperands();
6916 Idx
+= NumOpsPerField
) {
6917 auto *OffsetEntryCI
=
6918 mdconst::extract
<ConstantInt
>(BaseNode
->getOperand(Idx
+ 1));
6919 if (OffsetEntryCI
->getValue().ugt(Offset
)) {
6920 if (Idx
== FirstFieldOpNo
) {
6921 CheckFailed("Could not find TBAA parent in struct type node", &I
,
6926 unsigned PrevIdx
= Idx
- NumOpsPerField
;
6927 auto *PrevOffsetEntryCI
=
6928 mdconst::extract
<ConstantInt
>(BaseNode
->getOperand(PrevIdx
+ 1));
6929 Offset
-= PrevOffsetEntryCI
->getValue();
6930 return cast
<MDNode
>(BaseNode
->getOperand(PrevIdx
));
6934 unsigned LastIdx
= BaseNode
->getNumOperands() - NumOpsPerField
;
6935 auto *LastOffsetEntryCI
= mdconst::extract
<ConstantInt
>(
6936 BaseNode
->getOperand(LastIdx
+ 1));
6937 Offset
-= LastOffsetEntryCI
->getValue();
6938 return cast
<MDNode
>(BaseNode
->getOperand(LastIdx
));
6941 static bool isNewFormatTBAATypeNode(llvm::MDNode
*Type
) {
6942 if (!Type
|| Type
->getNumOperands() < 3)
6945 // In the new format type nodes shall have a reference to the parent type as
6946 // its first operand.
6947 return isa_and_nonnull
<MDNode
>(Type
->getOperand(0));
6950 bool TBAAVerifier::visitTBAAMetadata(Instruction
&I
, const MDNode
*MD
) {
6951 CheckTBAA(MD
->getNumOperands() > 0, "TBAA metadata cannot have 0 operands",
6954 CheckTBAA(isa
<LoadInst
>(I
) || isa
<StoreInst
>(I
) || isa
<CallInst
>(I
) ||
6955 isa
<VAArgInst
>(I
) || isa
<AtomicRMWInst
>(I
) ||
6956 isa
<AtomicCmpXchgInst
>(I
),
6957 "This instruction shall not have a TBAA access tag!", &I
);
6959 bool IsStructPathTBAA
=
6960 isa
<MDNode
>(MD
->getOperand(0)) && MD
->getNumOperands() >= 3;
6962 CheckTBAA(IsStructPathTBAA
,
6963 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
6966 MDNode
*BaseNode
= dyn_cast_or_null
<MDNode
>(MD
->getOperand(0));
6967 MDNode
*AccessType
= dyn_cast_or_null
<MDNode
>(MD
->getOperand(1));
6969 bool IsNewFormat
= isNewFormatTBAATypeNode(AccessType
);
6972 CheckTBAA(MD
->getNumOperands() == 4 || MD
->getNumOperands() == 5,
6973 "Access tag metadata must have either 4 or 5 operands", &I
, MD
);
6975 CheckTBAA(MD
->getNumOperands() < 5,
6976 "Struct tag metadata must have either 3 or 4 operands", &I
, MD
);
6979 // Check the access size field.
6981 auto *AccessSizeNode
= mdconst::dyn_extract_or_null
<ConstantInt
>(
6983 CheckTBAA(AccessSizeNode
, "Access size field must be a constant", &I
, MD
);
6986 // Check the immutability flag.
6987 unsigned ImmutabilityFlagOpNo
= IsNewFormat
? 4 : 3;
6988 if (MD
->getNumOperands() == ImmutabilityFlagOpNo
+ 1) {
6989 auto *IsImmutableCI
= mdconst::dyn_extract_or_null
<ConstantInt
>(
6990 MD
->getOperand(ImmutabilityFlagOpNo
));
6991 CheckTBAA(IsImmutableCI
,
6992 "Immutability tag on struct tag metadata must be a constant", &I
,
6995 IsImmutableCI
->isZero() || IsImmutableCI
->isOne(),
6996 "Immutability part of the struct tag metadata must be either 0 or 1",
7000 CheckTBAA(BaseNode
&& AccessType
,
7001 "Malformed struct tag metadata: base and access-type "
7002 "should be non-null and point to Metadata nodes",
7003 &I
, MD
, BaseNode
, AccessType
);
7006 CheckTBAA(isValidScalarTBAANode(AccessType
),
7007 "Access type node must be a valid scalar type", &I
, MD
,
7011 auto *OffsetCI
= mdconst::dyn_extract_or_null
<ConstantInt
>(MD
->getOperand(2));
7012 CheckTBAA(OffsetCI
, "Offset must be constant integer", &I
, MD
);
7014 APInt Offset
= OffsetCI
->getValue();
7015 bool SeenAccessTypeInPath
= false;
7017 SmallPtrSet
<MDNode
*, 4> StructPath
;
7019 for (/* empty */; BaseNode
&& !IsRootTBAANode(BaseNode
);
7020 BaseNode
= getFieldNodeFromTBAABaseNode(I
, BaseNode
, Offset
,
7022 if (!StructPath
.insert(BaseNode
).second
) {
7023 CheckFailed("Cycle detected in struct path", &I
, MD
);
7028 unsigned BaseNodeBitWidth
;
7029 std::tie(Invalid
, BaseNodeBitWidth
) = verifyTBAABaseNode(I
, BaseNode
,
7032 // If the base node is invalid in itself, then we've already printed all the
7033 // errors we wanted to print.
7037 SeenAccessTypeInPath
|= BaseNode
== AccessType
;
7039 if (isValidScalarTBAANode(BaseNode
) || BaseNode
== AccessType
)
7040 CheckTBAA(Offset
== 0, "Offset not zero at the point of scalar access",
7043 CheckTBAA(BaseNodeBitWidth
== Offset
.getBitWidth() ||
7044 (BaseNodeBitWidth
== 0 && Offset
== 0) ||
7045 (IsNewFormat
&& BaseNodeBitWidth
== ~0u),
7046 "Access bit-width not the same as description bit-width", &I
, MD
,
7047 BaseNodeBitWidth
, Offset
.getBitWidth());
7049 if (IsNewFormat
&& SeenAccessTypeInPath
)
7053 CheckTBAA(SeenAccessTypeInPath
, "Did not see access type in access path!", &I
,
7058 char VerifierLegacyPass::ID
= 0;
7059 INITIALIZE_PASS(VerifierLegacyPass
, "verify", "Module Verifier", false, false)
7061 FunctionPass
*llvm::createVerifierPass(bool FatalErrors
) {
7062 return new VerifierLegacyPass(FatalErrors
);
7065 AnalysisKey
VerifierAnalysis::Key
;
7066 VerifierAnalysis::Result
VerifierAnalysis::run(Module
&M
,
7067 ModuleAnalysisManager
&) {
7069 Res
.IRBroken
= llvm::verifyModule(M
, &dbgs(), &Res
.DebugInfoBroken
);
7073 VerifierAnalysis::Result
VerifierAnalysis::run(Function
&F
,
7074 FunctionAnalysisManager
&) {
7075 return { llvm::verifyFunction(F
, &dbgs()), false };
7078 PreservedAnalyses
VerifierPass::run(Module
&M
, ModuleAnalysisManager
&AM
) {
7079 auto Res
= AM
.getResult
<VerifierAnalysis
>(M
);
7080 if (FatalErrors
&& (Res
.IRBroken
|| Res
.DebugInfoBroken
))
7081 report_fatal_error("Broken module found, compilation aborted!");
7083 return PreservedAnalyses::all();
7086 PreservedAnalyses
VerifierPass::run(Function
&F
, FunctionAnalysisManager
&AM
) {
7087 auto res
= AM
.getResult
<VerifierAnalysis
>(F
);
7088 if (res
.IRBroken
&& FatalErrors
)
7089 report_fatal_error("Broken function found, compilation aborted!");
7091 return PreservedAnalyses::all();