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
) || isa
<DIType
>(Op
)),
1408 "invalid retained nodes, expected DILocalVariable, DILabel, "
1409 "DIImportedEntity or DIType",
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 AttributeMask IncompatibleAttrs
= AttributeFuncs::typeIncompatible(Ty
);
1931 for (Attribute Attr
: Attrs
) {
1932 if (!Attr
.isStringAttribute() &&
1933 IncompatibleAttrs
.contains(Attr
.getKindAsEnum())) {
1934 CheckFailed("Attribute '" + Attr
.getAsString() +
1935 "' applied to incompatible type!", V
);
1940 if (isa
<PointerType
>(Ty
)) {
1941 if (Attrs
.hasAttribute(Attribute::ByVal
)) {
1942 if (Attrs
.hasAttribute(Attribute::Alignment
)) {
1943 Align AttrAlign
= Attrs
.getAlignment().valueOrOne();
1944 Align
MaxAlign(ParamMaxAlignment
);
1945 Check(AttrAlign
<= MaxAlign
,
1946 "Attribute 'align' exceed the max size 2^14", V
);
1948 SmallPtrSet
<Type
*, 4> Visited
;
1949 Check(Attrs
.getByValType()->isSized(&Visited
),
1950 "Attribute 'byval' does not support unsized types!", V
);
1952 if (Attrs
.hasAttribute(Attribute::ByRef
)) {
1953 SmallPtrSet
<Type
*, 4> Visited
;
1954 Check(Attrs
.getByRefType()->isSized(&Visited
),
1955 "Attribute 'byref' does not support unsized types!", V
);
1957 if (Attrs
.hasAttribute(Attribute::InAlloca
)) {
1958 SmallPtrSet
<Type
*, 4> Visited
;
1959 Check(Attrs
.getInAllocaType()->isSized(&Visited
),
1960 "Attribute 'inalloca' does not support unsized types!", V
);
1962 if (Attrs
.hasAttribute(Attribute::Preallocated
)) {
1963 SmallPtrSet
<Type
*, 4> Visited
;
1964 Check(Attrs
.getPreallocatedType()->isSized(&Visited
),
1965 "Attribute 'preallocated' does not support unsized types!", V
);
1969 if (Attrs
.hasAttribute(Attribute::NoFPClass
)) {
1970 uint64_t Val
= Attrs
.getAttribute(Attribute::NoFPClass
).getValueAsInt();
1971 Check(Val
!= 0, "Attribute 'nofpclass' must have at least one test bit set",
1973 Check((Val
& ~static_cast<unsigned>(fcAllFlags
)) == 0,
1974 "Invalid value for 'nofpclass' test mask", V
);
1978 void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs
, StringRef Attr
,
1980 if (Attrs
.hasFnAttr(Attr
)) {
1981 StringRef S
= Attrs
.getFnAttr(Attr
).getValueAsString();
1983 if (S
.getAsInteger(10, N
))
1984 CheckFailed("\"" + Attr
+ "\" takes an unsigned integer: " + S
, V
);
1988 // Check parameter attributes against a function type.
1989 // The value V is printed in error messages.
1990 void Verifier::verifyFunctionAttrs(FunctionType
*FT
, AttributeList Attrs
,
1991 const Value
*V
, bool IsIntrinsic
,
1993 if (Attrs
.isEmpty())
1996 if (AttributeListsVisited
.insert(Attrs
.getRawPointer()).second
) {
1997 Check(Attrs
.hasParentContext(Context
),
1998 "Attribute list does not match Module context!", &Attrs
, V
);
1999 for (const auto &AttrSet
: Attrs
) {
2000 Check(!AttrSet
.hasAttributes() || AttrSet
.hasParentContext(Context
),
2001 "Attribute set does not match Module context!", &AttrSet
, V
);
2002 for (const auto &A
: AttrSet
) {
2003 Check(A
.hasParentContext(Context
),
2004 "Attribute does not match Module context!", &A
, V
);
2009 bool SawNest
= false;
2010 bool SawReturned
= false;
2011 bool SawSRet
= false;
2012 bool SawSwiftSelf
= false;
2013 bool SawSwiftAsync
= false;
2014 bool SawSwiftError
= false;
2016 // Verify return value attributes.
2017 AttributeSet RetAttrs
= Attrs
.getRetAttrs();
2018 for (Attribute RetAttr
: RetAttrs
)
2019 Check(RetAttr
.isStringAttribute() ||
2020 Attribute::canUseAsRetAttr(RetAttr
.getKindAsEnum()),
2021 "Attribute '" + RetAttr
.getAsString() +
2022 "' does not apply to function return values",
2025 unsigned MaxParameterWidth
= 0;
2026 auto GetMaxParameterWidth
= [&MaxParameterWidth
](Type
*Ty
) {
2027 if (Ty
->isVectorTy()) {
2028 if (auto *VT
= dyn_cast
<FixedVectorType
>(Ty
)) {
2029 unsigned Size
= VT
->getPrimitiveSizeInBits().getFixedValue();
2030 if (Size
> MaxParameterWidth
)
2031 MaxParameterWidth
= Size
;
2035 GetMaxParameterWidth(FT
->getReturnType());
2036 verifyParameterAttrs(RetAttrs
, FT
->getReturnType(), V
);
2038 // Verify parameter attributes.
2039 for (unsigned i
= 0, e
= FT
->getNumParams(); i
!= e
; ++i
) {
2040 Type
*Ty
= FT
->getParamType(i
);
2041 AttributeSet ArgAttrs
= Attrs
.getParamAttrs(i
);
2044 Check(!ArgAttrs
.hasAttribute(Attribute::ImmArg
),
2045 "immarg attribute only applies to intrinsics", V
);
2047 Check(!ArgAttrs
.hasAttribute(Attribute::ElementType
),
2048 "Attribute 'elementtype' can only be applied to intrinsics"
2053 verifyParameterAttrs(ArgAttrs
, Ty
, V
);
2054 GetMaxParameterWidth(Ty
);
2056 if (ArgAttrs
.hasAttribute(Attribute::Nest
)) {
2057 Check(!SawNest
, "More than one parameter has attribute nest!", V
);
2061 if (ArgAttrs
.hasAttribute(Attribute::Returned
)) {
2062 Check(!SawReturned
, "More than one parameter has attribute returned!", V
);
2063 Check(Ty
->canLosslesslyBitCastTo(FT
->getReturnType()),
2064 "Incompatible argument and return types for 'returned' attribute",
2069 if (ArgAttrs
.hasAttribute(Attribute::StructRet
)) {
2070 Check(!SawSRet
, "Cannot have multiple 'sret' parameters!", V
);
2071 Check(i
== 0 || i
== 1,
2072 "Attribute 'sret' is not on first or second parameter!", V
);
2076 if (ArgAttrs
.hasAttribute(Attribute::SwiftSelf
)) {
2077 Check(!SawSwiftSelf
, "Cannot have multiple 'swiftself' parameters!", V
);
2078 SawSwiftSelf
= true;
2081 if (ArgAttrs
.hasAttribute(Attribute::SwiftAsync
)) {
2082 Check(!SawSwiftAsync
, "Cannot have multiple 'swiftasync' parameters!", V
);
2083 SawSwiftAsync
= true;
2086 if (ArgAttrs
.hasAttribute(Attribute::SwiftError
)) {
2087 Check(!SawSwiftError
, "Cannot have multiple 'swifterror' parameters!", V
);
2088 SawSwiftError
= true;
2091 if (ArgAttrs
.hasAttribute(Attribute::InAlloca
)) {
2092 Check(i
== FT
->getNumParams() - 1,
2093 "inalloca isn't on the last parameter!", V
);
2097 if (!Attrs
.hasFnAttrs())
2100 verifyAttributeTypes(Attrs
.getFnAttrs(), V
);
2101 for (Attribute FnAttr
: Attrs
.getFnAttrs())
2102 Check(FnAttr
.isStringAttribute() ||
2103 Attribute::canUseAsFnAttr(FnAttr
.getKindAsEnum()),
2104 "Attribute '" + FnAttr
.getAsString() +
2105 "' does not apply to functions!",
2108 Check(!(Attrs
.hasFnAttr(Attribute::NoInline
) &&
2109 Attrs
.hasFnAttr(Attribute::AlwaysInline
)),
2110 "Attributes 'noinline and alwaysinline' are incompatible!", V
);
2112 if (Attrs
.hasFnAttr(Attribute::OptimizeNone
)) {
2113 Check(Attrs
.hasFnAttr(Attribute::NoInline
),
2114 "Attribute 'optnone' requires 'noinline'!", V
);
2116 Check(!Attrs
.hasFnAttr(Attribute::OptimizeForSize
),
2117 "Attributes 'optsize and optnone' are incompatible!", V
);
2119 Check(!Attrs
.hasFnAttr(Attribute::MinSize
),
2120 "Attributes 'minsize and optnone' are incompatible!", V
);
2123 if (Attrs
.hasFnAttr("aarch64_pstate_sm_enabled")) {
2124 Check(!Attrs
.hasFnAttr("aarch64_pstate_sm_compatible"),
2125 "Attributes 'aarch64_pstate_sm_enabled and "
2126 "aarch64_pstate_sm_compatible' are incompatible!",
2130 if (Attrs
.hasFnAttr("aarch64_pstate_za_new")) {
2131 Check(!Attrs
.hasFnAttr("aarch64_pstate_za_preserved"),
2132 "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_preserved' "
2133 "are incompatible!",
2136 Check(!Attrs
.hasFnAttr("aarch64_pstate_za_shared"),
2137 "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_shared' "
2138 "are incompatible!",
2142 if (Attrs
.hasFnAttr(Attribute::JumpTable
)) {
2143 const GlobalValue
*GV
= cast
<GlobalValue
>(V
);
2144 Check(GV
->hasGlobalUnnamedAddr(),
2145 "Attribute 'jumptable' requires 'unnamed_addr'", V
);
2148 if (auto Args
= Attrs
.getFnAttrs().getAllocSizeArgs()) {
2149 auto CheckParam
= [&](StringRef Name
, unsigned ParamNo
) {
2150 if (ParamNo
>= FT
->getNumParams()) {
2151 CheckFailed("'allocsize' " + Name
+ " argument is out of bounds", V
);
2155 if (!FT
->getParamType(ParamNo
)->isIntegerTy()) {
2156 CheckFailed("'allocsize' " + Name
+
2157 " argument must refer to an integer parameter",
2165 if (!CheckParam("element size", Args
->first
))
2168 if (Args
->second
&& !CheckParam("number of elements", *Args
->second
))
2172 if (Attrs
.hasFnAttr(Attribute::AllocKind
)) {
2173 AllocFnKind K
= Attrs
.getAllocKind();
2175 K
& (AllocFnKind::Alloc
| AllocFnKind::Realloc
| AllocFnKind::Free
);
2177 {AllocFnKind::Alloc
, AllocFnKind::Realloc
, AllocFnKind::Free
},
2180 "'allockind()' requires exactly one of alloc, realloc, and free");
2181 if ((Type
== AllocFnKind::Free
) &&
2182 ((K
& (AllocFnKind::Uninitialized
| AllocFnKind::Zeroed
|
2183 AllocFnKind::Aligned
)) != AllocFnKind::Unknown
))
2184 CheckFailed("'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2185 "or aligned modifiers.");
2186 AllocFnKind ZeroedUninit
= AllocFnKind::Uninitialized
| AllocFnKind::Zeroed
;
2187 if ((K
& ZeroedUninit
) == ZeroedUninit
)
2188 CheckFailed("'allockind()' can't be both zeroed and uninitialized");
2191 if (Attrs
.hasFnAttr(Attribute::VScaleRange
)) {
2192 unsigned VScaleMin
= Attrs
.getFnAttrs().getVScaleRangeMin();
2194 CheckFailed("'vscale_range' minimum must be greater than 0", V
);
2195 else if (!isPowerOf2_32(VScaleMin
))
2196 CheckFailed("'vscale_range' minimum must be power-of-two value", V
);
2197 std::optional
<unsigned> VScaleMax
= Attrs
.getFnAttrs().getVScaleRangeMax();
2198 if (VScaleMax
&& VScaleMin
> VScaleMax
)
2199 CheckFailed("'vscale_range' minimum cannot be greater than maximum", V
);
2200 else if (VScaleMax
&& !isPowerOf2_32(*VScaleMax
))
2201 CheckFailed("'vscale_range' maximum must be power-of-two value", V
);
2204 if (Attrs
.hasFnAttr("frame-pointer")) {
2205 StringRef FP
= Attrs
.getFnAttr("frame-pointer").getValueAsString();
2206 if (FP
!= "all" && FP
!= "non-leaf" && FP
!= "none")
2207 CheckFailed("invalid value for 'frame-pointer' attribute: " + FP
, V
);
2210 // Check EVEX512 feature.
2211 if (MaxParameterWidth
>= 512 && Attrs
.hasFnAttr("target-features")) {
2212 Triple
T(M
.getTargetTriple());
2214 StringRef TF
= Attrs
.getFnAttr("target-features").getValueAsString();
2215 Check(!TF
.contains("+avx512f") || !TF
.contains("-evex512"),
2216 "512-bit vector arguments require 'evex512' for AVX512", V
);
2220 checkUnsignedBaseTenFuncAttr(Attrs
, "patchable-function-prefix", V
);
2221 checkUnsignedBaseTenFuncAttr(Attrs
, "patchable-function-entry", V
);
2222 checkUnsignedBaseTenFuncAttr(Attrs
, "warn-stack-size", V
);
2225 void Verifier::verifyFunctionMetadata(
2226 ArrayRef
<std::pair
<unsigned, MDNode
*>> MDs
) {
2227 for (const auto &Pair
: MDs
) {
2228 if (Pair
.first
== LLVMContext::MD_prof
) {
2229 MDNode
*MD
= Pair
.second
;
2230 Check(MD
->getNumOperands() >= 2,
2231 "!prof annotations should have no less than 2 operands", MD
);
2233 // Check first operand.
2234 Check(MD
->getOperand(0) != nullptr, "first operand should not be null",
2236 Check(isa
<MDString
>(MD
->getOperand(0)),
2237 "expected string with name of the !prof annotation", MD
);
2238 MDString
*MDS
= cast
<MDString
>(MD
->getOperand(0));
2239 StringRef ProfName
= MDS
->getString();
2240 Check(ProfName
.equals("function_entry_count") ||
2241 ProfName
.equals("synthetic_function_entry_count"),
2242 "first operand should be 'function_entry_count'"
2243 " or 'synthetic_function_entry_count'",
2246 // Check second operand.
2247 Check(MD
->getOperand(1) != nullptr, "second operand should not be null",
2249 Check(isa
<ConstantAsMetadata
>(MD
->getOperand(1)),
2250 "expected integer argument to function_entry_count", MD
);
2251 } else if (Pair
.first
== LLVMContext::MD_kcfi_type
) {
2252 MDNode
*MD
= Pair
.second
;
2253 Check(MD
->getNumOperands() == 1,
2254 "!kcfi_type must have exactly one operand", MD
);
2255 Check(MD
->getOperand(0) != nullptr, "!kcfi_type operand must not be null",
2257 Check(isa
<ConstantAsMetadata
>(MD
->getOperand(0)),
2258 "expected a constant operand for !kcfi_type", MD
);
2259 Constant
*C
= cast
<ConstantAsMetadata
>(MD
->getOperand(0))->getValue();
2260 Check(isa
<ConstantInt
>(C
),
2261 "expected a constant integer operand for !kcfi_type", MD
);
2262 IntegerType
*Type
= cast
<ConstantInt
>(C
)->getType();
2263 Check(Type
->getBitWidth() == 32,
2264 "expected a 32-bit integer constant operand for !kcfi_type", MD
);
2269 void Verifier::visitConstantExprsRecursively(const Constant
*EntryC
) {
2270 if (!ConstantExprVisited
.insert(EntryC
).second
)
2273 SmallVector
<const Constant
*, 16> Stack
;
2274 Stack
.push_back(EntryC
);
2276 while (!Stack
.empty()) {
2277 const Constant
*C
= Stack
.pop_back_val();
2279 // Check this constant expression.
2280 if (const auto *CE
= dyn_cast
<ConstantExpr
>(C
))
2281 visitConstantExpr(CE
);
2283 if (const auto *GV
= dyn_cast
<GlobalValue
>(C
)) {
2284 // Global Values get visited separately, but we do need to make sure
2285 // that the global value is in the correct module
2286 Check(GV
->getParent() == &M
, "Referencing global in another module!",
2287 EntryC
, &M
, GV
, GV
->getParent());
2291 // Visit all sub-expressions.
2292 for (const Use
&U
: C
->operands()) {
2293 const auto *OpC
= dyn_cast
<Constant
>(U
);
2296 if (!ConstantExprVisited
.insert(OpC
).second
)
2298 Stack
.push_back(OpC
);
2303 void Verifier::visitConstantExpr(const ConstantExpr
*CE
) {
2304 if (CE
->getOpcode() == Instruction::BitCast
)
2305 Check(CastInst::castIsValid(Instruction::BitCast
, CE
->getOperand(0),
2307 "Invalid bitcast", CE
);
2310 bool Verifier::verifyAttributeCount(AttributeList Attrs
, unsigned Params
) {
2311 // There shouldn't be more attribute sets than there are parameters plus the
2312 // function and return value.
2313 return Attrs
.getNumAttrSets() <= Params
+ 2;
2316 void Verifier::verifyInlineAsmCall(const CallBase
&Call
) {
2317 const InlineAsm
*IA
= cast
<InlineAsm
>(Call
.getCalledOperand());
2319 unsigned LabelNo
= 0;
2320 for (const InlineAsm::ConstraintInfo
&CI
: IA
->ParseConstraints()) {
2321 if (CI
.Type
== InlineAsm::isLabel
) {
2326 // Only deal with constraints that correspond to call arguments.
2330 if (CI
.isIndirect
) {
2331 const Value
*Arg
= Call
.getArgOperand(ArgNo
);
2332 Check(Arg
->getType()->isPointerTy(),
2333 "Operand for indirect constraint must have pointer type", &Call
);
2335 Check(Call
.getParamElementType(ArgNo
),
2336 "Operand for indirect constraint must have elementtype attribute",
2339 Check(!Call
.paramHasAttr(ArgNo
, Attribute::ElementType
),
2340 "Elementtype attribute can only be applied for indirect "
2348 if (auto *CallBr
= dyn_cast
<CallBrInst
>(&Call
)) {
2349 Check(LabelNo
== CallBr
->getNumIndirectDests(),
2350 "Number of label constraints does not match number of callbr dests",
2353 Check(LabelNo
== 0, "Label constraints can only be used with callbr",
2358 /// Verify that statepoint intrinsic is well formed.
2359 void Verifier::verifyStatepoint(const CallBase
&Call
) {
2360 assert(Call
.getCalledFunction() &&
2361 Call
.getCalledFunction()->getIntrinsicID() ==
2362 Intrinsic::experimental_gc_statepoint
);
2364 Check(!Call
.doesNotAccessMemory() && !Call
.onlyReadsMemory() &&
2365 !Call
.onlyAccessesArgMemory(),
2366 "gc.statepoint must read and write all memory to preserve "
2367 "reordering restrictions required by safepoint semantics",
2370 const int64_t NumPatchBytes
=
2371 cast
<ConstantInt
>(Call
.getArgOperand(1))->getSExtValue();
2372 assert(isInt
<32>(NumPatchBytes
) && "NumPatchBytesV is an i32!");
2373 Check(NumPatchBytes
>= 0,
2374 "gc.statepoint number of patchable bytes must be "
2378 Type
*TargetElemType
= Call
.getParamElementType(2);
2379 Check(TargetElemType
,
2380 "gc.statepoint callee argument must have elementtype attribute", Call
);
2381 FunctionType
*TargetFuncType
= dyn_cast
<FunctionType
>(TargetElemType
);
2382 Check(TargetFuncType
,
2383 "gc.statepoint callee elementtype must be function type", Call
);
2385 const int NumCallArgs
= cast
<ConstantInt
>(Call
.getArgOperand(3))->getZExtValue();
2386 Check(NumCallArgs
>= 0,
2387 "gc.statepoint number of arguments to underlying call "
2390 const int NumParams
= (int)TargetFuncType
->getNumParams();
2391 if (TargetFuncType
->isVarArg()) {
2392 Check(NumCallArgs
>= NumParams
,
2393 "gc.statepoint mismatch in number of vararg call args", Call
);
2395 // TODO: Remove this limitation
2396 Check(TargetFuncType
->getReturnType()->isVoidTy(),
2397 "gc.statepoint doesn't support wrapping non-void "
2398 "vararg functions yet",
2401 Check(NumCallArgs
== NumParams
,
2402 "gc.statepoint mismatch in number of call args", Call
);
2404 const uint64_t Flags
2405 = cast
<ConstantInt
>(Call
.getArgOperand(4))->getZExtValue();
2406 Check((Flags
& ~(uint64_t)StatepointFlags::MaskAll
) == 0,
2407 "unknown flag used in gc.statepoint flags argument", Call
);
2409 // Verify that the types of the call parameter arguments match
2410 // the type of the wrapped callee.
2411 AttributeList Attrs
= Call
.getAttributes();
2412 for (int i
= 0; i
< NumParams
; i
++) {
2413 Type
*ParamType
= TargetFuncType
->getParamType(i
);
2414 Type
*ArgType
= Call
.getArgOperand(5 + i
)->getType();
2415 Check(ArgType
== ParamType
,
2416 "gc.statepoint call argument does not match wrapped "
2420 if (TargetFuncType
->isVarArg()) {
2421 AttributeSet ArgAttrs
= Attrs
.getParamAttrs(5 + i
);
2422 Check(!ArgAttrs
.hasAttribute(Attribute::StructRet
),
2423 "Attribute 'sret' cannot be used for vararg call arguments!", Call
);
2427 const int EndCallArgsInx
= 4 + NumCallArgs
;
2429 const Value
*NumTransitionArgsV
= Call
.getArgOperand(EndCallArgsInx
+ 1);
2430 Check(isa
<ConstantInt
>(NumTransitionArgsV
),
2431 "gc.statepoint number of transition arguments "
2432 "must be constant integer",
2434 const int NumTransitionArgs
=
2435 cast
<ConstantInt
>(NumTransitionArgsV
)->getZExtValue();
2436 Check(NumTransitionArgs
== 0,
2437 "gc.statepoint w/inline transition bundle is deprecated", Call
);
2438 const int EndTransitionArgsInx
= EndCallArgsInx
+ 1 + NumTransitionArgs
;
2440 const Value
*NumDeoptArgsV
= Call
.getArgOperand(EndTransitionArgsInx
+ 1);
2441 Check(isa
<ConstantInt
>(NumDeoptArgsV
),
2442 "gc.statepoint number of deoptimization arguments "
2443 "must be constant integer",
2445 const int NumDeoptArgs
= cast
<ConstantInt
>(NumDeoptArgsV
)->getZExtValue();
2446 Check(NumDeoptArgs
== 0,
2447 "gc.statepoint w/inline deopt operands is deprecated", Call
);
2449 const int ExpectedNumArgs
= 7 + NumCallArgs
;
2450 Check(ExpectedNumArgs
== (int)Call
.arg_size(),
2451 "gc.statepoint too many arguments", Call
);
2453 // Check that the only uses of this gc.statepoint are gc.result or
2454 // gc.relocate calls which are tied to this statepoint and thus part
2455 // of the same statepoint sequence
2456 for (const User
*U
: Call
.users()) {
2457 const CallInst
*UserCall
= dyn_cast
<const CallInst
>(U
);
2458 Check(UserCall
, "illegal use of statepoint token", Call
, U
);
2461 Check(isa
<GCRelocateInst
>(UserCall
) || isa
<GCResultInst
>(UserCall
),
2462 "gc.result or gc.relocate are the only value uses "
2463 "of a gc.statepoint",
2465 if (isa
<GCResultInst
>(UserCall
)) {
2466 Check(UserCall
->getArgOperand(0) == &Call
,
2467 "gc.result connected to wrong gc.statepoint", Call
, UserCall
);
2468 } else if (isa
<GCRelocateInst
>(Call
)) {
2469 Check(UserCall
->getArgOperand(0) == &Call
,
2470 "gc.relocate connected to wrong gc.statepoint", Call
, UserCall
);
2474 // Note: It is legal for a single derived pointer to be listed multiple
2475 // times. It's non-optimal, but it is legal. It can also happen after
2476 // insertion if we strip a bitcast away.
2477 // Note: It is really tempting to check that each base is relocated and
2478 // that a derived pointer is never reused as a base pointer. This turns
2479 // out to be problematic since optimizations run after safepoint insertion
2480 // can recognize equality properties that the insertion logic doesn't know
2481 // about. See example statepoint.ll in the verifier subdirectory
2484 void Verifier::verifyFrameRecoverIndices() {
2485 for (auto &Counts
: FrameEscapeInfo
) {
2486 Function
*F
= Counts
.first
;
2487 unsigned EscapedObjectCount
= Counts
.second
.first
;
2488 unsigned MaxRecoveredIndex
= Counts
.second
.second
;
2489 Check(MaxRecoveredIndex
<= EscapedObjectCount
,
2490 "all indices passed to llvm.localrecover must be less than the "
2491 "number of arguments passed to llvm.localescape in the parent "
2497 static Instruction
*getSuccPad(Instruction
*Terminator
) {
2498 BasicBlock
*UnwindDest
;
2499 if (auto *II
= dyn_cast
<InvokeInst
>(Terminator
))
2500 UnwindDest
= II
->getUnwindDest();
2501 else if (auto *CSI
= dyn_cast
<CatchSwitchInst
>(Terminator
))
2502 UnwindDest
= CSI
->getUnwindDest();
2504 UnwindDest
= cast
<CleanupReturnInst
>(Terminator
)->getUnwindDest();
2505 return UnwindDest
->getFirstNonPHI();
2508 void Verifier::verifySiblingFuncletUnwinds() {
2509 SmallPtrSet
<Instruction
*, 8> Visited
;
2510 SmallPtrSet
<Instruction
*, 8> Active
;
2511 for (const auto &Pair
: SiblingFuncletInfo
) {
2512 Instruction
*PredPad
= Pair
.first
;
2513 if (Visited
.count(PredPad
))
2515 Active
.insert(PredPad
);
2516 Instruction
*Terminator
= Pair
.second
;
2518 Instruction
*SuccPad
= getSuccPad(Terminator
);
2519 if (Active
.count(SuccPad
)) {
2520 // Found a cycle; report error
2521 Instruction
*CyclePad
= SuccPad
;
2522 SmallVector
<Instruction
*, 8> CycleNodes
;
2524 CycleNodes
.push_back(CyclePad
);
2525 Instruction
*CycleTerminator
= SiblingFuncletInfo
[CyclePad
];
2526 if (CycleTerminator
!= CyclePad
)
2527 CycleNodes
.push_back(CycleTerminator
);
2528 CyclePad
= getSuccPad(CycleTerminator
);
2529 } while (CyclePad
!= SuccPad
);
2530 Check(false, "EH pads can't handle each other's exceptions",
2531 ArrayRef
<Instruction
*>(CycleNodes
));
2533 // Don't re-walk a node we've already checked
2534 if (!Visited
.insert(SuccPad
).second
)
2536 // Walk to this successor if it has a map entry.
2538 auto TermI
= SiblingFuncletInfo
.find(PredPad
);
2539 if (TermI
== SiblingFuncletInfo
.end())
2541 Terminator
= TermI
->second
;
2542 Active
.insert(PredPad
);
2544 // Each node only has one successor, so we've walked all the active
2545 // nodes' successors.
2550 // visitFunction - Verify that a function is ok.
2552 void Verifier::visitFunction(const Function
&F
) {
2553 visitGlobalValue(F
);
2555 // Check function arguments.
2556 FunctionType
*FT
= F
.getFunctionType();
2557 unsigned NumArgs
= F
.arg_size();
2559 Check(&Context
== &F
.getContext(),
2560 "Function context does not match Module context!", &F
);
2562 Check(!F
.hasCommonLinkage(), "Functions may not have common linkage", &F
);
2563 Check(FT
->getNumParams() == NumArgs
,
2564 "# formal arguments must match # of arguments for function type!", &F
,
2566 Check(F
.getReturnType()->isFirstClassType() ||
2567 F
.getReturnType()->isVoidTy() || F
.getReturnType()->isStructTy(),
2568 "Functions cannot return aggregate values!", &F
);
2570 Check(!F
.hasStructRetAttr() || F
.getReturnType()->isVoidTy(),
2571 "Invalid struct return type!", &F
);
2573 AttributeList Attrs
= F
.getAttributes();
2575 Check(verifyAttributeCount(Attrs
, FT
->getNumParams()),
2576 "Attribute after last parameter!", &F
);
2578 bool IsIntrinsic
= F
.isIntrinsic();
2580 // Check function attributes.
2581 verifyFunctionAttrs(FT
, Attrs
, &F
, IsIntrinsic
, /* IsInlineAsm */ false);
2583 // On function declarations/definitions, we do not support the builtin
2584 // attribute. We do not check this in VerifyFunctionAttrs since that is
2585 // checking for Attributes that can/can not ever be on functions.
2586 Check(!Attrs
.hasFnAttr(Attribute::Builtin
),
2587 "Attribute 'builtin' can only be applied to a callsite.", &F
);
2589 Check(!Attrs
.hasAttrSomewhere(Attribute::ElementType
),
2590 "Attribute 'elementtype' can only be applied to a callsite.", &F
);
2592 // Check that this function meets the restrictions on this calling convention.
2593 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
2594 // restrictions can be lifted.
2595 switch (F
.getCallingConv()) {
2597 case CallingConv::C
:
2599 case CallingConv::X86_INTR
: {
2600 Check(F
.arg_empty() || Attrs
.hasParamAttr(0, Attribute::ByVal
),
2601 "Calling convention parameter requires byval", &F
);
2604 case CallingConv::AMDGPU_KERNEL
:
2605 case CallingConv::SPIR_KERNEL
:
2606 case CallingConv::AMDGPU_CS_Chain
:
2607 case CallingConv::AMDGPU_CS_ChainPreserve
:
2608 Check(F
.getReturnType()->isVoidTy(),
2609 "Calling convention requires void return type", &F
);
2611 case CallingConv::AMDGPU_VS
:
2612 case CallingConv::AMDGPU_HS
:
2613 case CallingConv::AMDGPU_GS
:
2614 case CallingConv::AMDGPU_PS
:
2615 case CallingConv::AMDGPU_CS
:
2616 Check(!F
.hasStructRetAttr(), "Calling convention does not allow sret", &F
);
2617 if (F
.getCallingConv() != CallingConv::SPIR_KERNEL
) {
2618 const unsigned StackAS
= DL
.getAllocaAddrSpace();
2620 for (const Argument
&Arg
: F
.args()) {
2621 Check(!Attrs
.hasParamAttr(i
, Attribute::ByVal
),
2622 "Calling convention disallows byval", &F
);
2623 Check(!Attrs
.hasParamAttr(i
, Attribute::Preallocated
),
2624 "Calling convention disallows preallocated", &F
);
2625 Check(!Attrs
.hasParamAttr(i
, Attribute::InAlloca
),
2626 "Calling convention disallows inalloca", &F
);
2628 if (Attrs
.hasParamAttr(i
, Attribute::ByRef
)) {
2629 // FIXME: Should also disallow LDS and GDS, but we don't have the enum
2631 Check(Arg
.getType()->getPointerAddressSpace() != StackAS
,
2632 "Calling convention disallows stack byref", &F
);
2640 case CallingConv::Fast
:
2641 case CallingConv::Cold
:
2642 case CallingConv::Intel_OCL_BI
:
2643 case CallingConv::PTX_Kernel
:
2644 case CallingConv::PTX_Device
:
2645 Check(!F
.isVarArg(),
2646 "Calling convention does not support varargs or "
2647 "perfect forwarding!",
2652 // Check that the argument values match the function type for this function...
2654 for (const Argument
&Arg
: F
.args()) {
2655 Check(Arg
.getType() == FT
->getParamType(i
),
2656 "Argument value does not match function argument type!", &Arg
,
2657 FT
->getParamType(i
));
2658 Check(Arg
.getType()->isFirstClassType(),
2659 "Function arguments must have first-class types!", &Arg
);
2661 Check(!Arg
.getType()->isMetadataTy(),
2662 "Function takes metadata but isn't an intrinsic", &Arg
, &F
);
2663 Check(!Arg
.getType()->isTokenTy(),
2664 "Function takes token but isn't an intrinsic", &Arg
, &F
);
2665 Check(!Arg
.getType()->isX86_AMXTy(),
2666 "Function takes x86_amx but isn't an intrinsic", &Arg
, &F
);
2669 // Check that swifterror argument is only used by loads and stores.
2670 if (Attrs
.hasParamAttr(i
, Attribute::SwiftError
)) {
2671 verifySwiftErrorValue(&Arg
);
2677 Check(!F
.getReturnType()->isTokenTy(),
2678 "Function returns a token but isn't an intrinsic", &F
);
2679 Check(!F
.getReturnType()->isX86_AMXTy(),
2680 "Function returns a x86_amx but isn't an intrinsic", &F
);
2683 // Get the function metadata attachments.
2684 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
2685 F
.getAllMetadata(MDs
);
2686 assert(F
.hasMetadata() != MDs
.empty() && "Bit out-of-sync");
2687 verifyFunctionMetadata(MDs
);
2689 // Check validity of the personality function
2690 if (F
.hasPersonalityFn()) {
2691 auto *Per
= dyn_cast
<Function
>(F
.getPersonalityFn()->stripPointerCasts());
2693 Check(Per
->getParent() == F
.getParent(),
2694 "Referencing personality function in another module!", &F
,
2695 F
.getParent(), Per
, Per
->getParent());
2698 // EH funclet coloring can be expensive, recompute on-demand
2699 BlockEHFuncletColors
.clear();
2701 if (F
.isMaterializable()) {
2702 // Function has a body somewhere we can't see.
2703 Check(MDs
.empty(), "unmaterialized function cannot have metadata", &F
,
2704 MDs
.empty() ? nullptr : MDs
.front().second
);
2705 } else if (F
.isDeclaration()) {
2706 for (const auto &I
: MDs
) {
2707 // This is used for call site debug information.
2708 CheckDI(I
.first
!= LLVMContext::MD_dbg
||
2709 !cast
<DISubprogram
>(I
.second
)->isDistinct(),
2710 "function declaration may only have a unique !dbg attachment",
2712 Check(I
.first
!= LLVMContext::MD_prof
,
2713 "function declaration may not have a !prof attachment", &F
);
2715 // Verify the metadata itself.
2716 visitMDNode(*I
.second
, AreDebugLocsAllowed::Yes
);
2718 Check(!F
.hasPersonalityFn(),
2719 "Function declaration shouldn't have a personality routine", &F
);
2721 // Verify that this function (which has a body) is not named "llvm.*". It
2722 // is not legal to define intrinsics.
2723 Check(!IsIntrinsic
, "llvm intrinsics cannot be defined!", &F
);
2725 // Check the entry node
2726 const BasicBlock
*Entry
= &F
.getEntryBlock();
2727 Check(pred_empty(Entry
),
2728 "Entry block to function must not have predecessors!", Entry
);
2730 // The address of the entry block cannot be taken, unless it is dead.
2731 if (Entry
->hasAddressTaken()) {
2732 Check(!BlockAddress::lookup(Entry
)->isConstantUsed(),
2733 "blockaddress may not be used with the entry block!", Entry
);
2736 unsigned NumDebugAttachments
= 0, NumProfAttachments
= 0,
2737 NumKCFIAttachments
= 0;
2738 // Visit metadata attachments.
2739 for (const auto &I
: MDs
) {
2740 // Verify that the attachment is legal.
2741 auto AllowLocs
= AreDebugLocsAllowed::No
;
2745 case LLVMContext::MD_dbg
: {
2746 ++NumDebugAttachments
;
2747 CheckDI(NumDebugAttachments
== 1,
2748 "function must have a single !dbg attachment", &F
, I
.second
);
2749 CheckDI(isa
<DISubprogram
>(I
.second
),
2750 "function !dbg attachment must be a subprogram", &F
, I
.second
);
2751 CheckDI(cast
<DISubprogram
>(I
.second
)->isDistinct(),
2752 "function definition may only have a distinct !dbg attachment",
2755 auto *SP
= cast
<DISubprogram
>(I
.second
);
2756 const Function
*&AttachedTo
= DISubprogramAttachments
[SP
];
2757 CheckDI(!AttachedTo
|| AttachedTo
== &F
,
2758 "DISubprogram attached to more than one function", SP
, &F
);
2760 AllowLocs
= AreDebugLocsAllowed::Yes
;
2763 case LLVMContext::MD_prof
:
2764 ++NumProfAttachments
;
2765 Check(NumProfAttachments
== 1,
2766 "function must have a single !prof attachment", &F
, I
.second
);
2768 case LLVMContext::MD_kcfi_type
:
2769 ++NumKCFIAttachments
;
2770 Check(NumKCFIAttachments
== 1,
2771 "function must have a single !kcfi_type attachment", &F
,
2776 // Verify the metadata itself.
2777 visitMDNode(*I
.second
, AllowLocs
);
2781 // If this function is actually an intrinsic, verify that it is only used in
2782 // direct call/invokes, never having its "address taken".
2783 // Only do this if the module is materialized, otherwise we don't have all the
2785 if (F
.isIntrinsic() && F
.getParent()->isMaterialized()) {
2787 if (F
.hasAddressTaken(&U
, false, true, false,
2788 /*IgnoreARCAttachedCall=*/true))
2789 Check(false, "Invalid user of intrinsic instruction!", U
);
2792 // Check intrinsics' signatures.
2793 switch (F
.getIntrinsicID()) {
2794 case Intrinsic::experimental_gc_get_pointer_base
: {
2795 FunctionType
*FT
= F
.getFunctionType();
2796 Check(FT
->getNumParams() == 1, "wrong number of parameters", F
);
2797 Check(isa
<PointerType
>(F
.getReturnType()),
2798 "gc.get.pointer.base must return a pointer", F
);
2799 Check(FT
->getParamType(0) == F
.getReturnType(),
2800 "gc.get.pointer.base operand and result must be of the same type", F
);
2803 case Intrinsic::experimental_gc_get_pointer_offset
: {
2804 FunctionType
*FT
= F
.getFunctionType();
2805 Check(FT
->getNumParams() == 1, "wrong number of parameters", F
);
2806 Check(isa
<PointerType
>(FT
->getParamType(0)),
2807 "gc.get.pointer.offset operand must be a pointer", F
);
2808 Check(F
.getReturnType()->isIntegerTy(),
2809 "gc.get.pointer.offset must return integer", F
);
2814 auto *N
= F
.getSubprogram();
2815 HasDebugInfo
= (N
!= nullptr);
2819 // Check that all !dbg attachments lead to back to N.
2821 // FIXME: Check this incrementally while visiting !dbg attachments.
2822 // FIXME: Only check when N is the canonical subprogram for F.
2823 SmallPtrSet
<const MDNode
*, 32> Seen
;
2824 auto VisitDebugLoc
= [&](const Instruction
&I
, const MDNode
*Node
) {
2825 // Be careful about using DILocation here since we might be dealing with
2826 // broken code (this is the Verifier after all).
2827 const DILocation
*DL
= dyn_cast_or_null
<DILocation
>(Node
);
2830 if (!Seen
.insert(DL
).second
)
2833 Metadata
*Parent
= DL
->getRawScope();
2834 CheckDI(Parent
&& isa
<DILocalScope
>(Parent
),
2835 "DILocation's scope must be a DILocalScope", N
, &F
, &I
, DL
, Parent
);
2837 DILocalScope
*Scope
= DL
->getInlinedAtScope();
2838 Check(Scope
, "Failed to find DILocalScope", DL
);
2840 if (!Seen
.insert(Scope
).second
)
2843 DISubprogram
*SP
= Scope
->getSubprogram();
2845 // Scope and SP could be the same MDNode and we don't want to skip
2846 // validation in that case
2847 if (SP
&& ((Scope
!= SP
) && !Seen
.insert(SP
).second
))
2850 CheckDI(SP
->describes(&F
),
2851 "!dbg attachment points at wrong subprogram for function", N
, &F
,
2855 for (auto &I
: BB
) {
2856 VisitDebugLoc(I
, I
.getDebugLoc().getAsMDNode());
2857 // The llvm.loop annotations also contain two DILocations.
2858 if (auto MD
= I
.getMetadata(LLVMContext::MD_loop
))
2859 for (unsigned i
= 1; i
< MD
->getNumOperands(); ++i
)
2860 VisitDebugLoc(I
, dyn_cast_or_null
<MDNode
>(MD
->getOperand(i
)));
2861 if (BrokenDebugInfo
)
2866 // verifyBasicBlock - Verify that a basic block is well formed...
2868 void Verifier::visitBasicBlock(BasicBlock
&BB
) {
2869 InstsInThisBlock
.clear();
2870 ConvergenceVerifyHelper
.visit(BB
);
2872 // Ensure that basic blocks have terminators!
2873 Check(BB
.getTerminator(), "Basic Block does not have terminator!", &BB
);
2875 // Check constraints that this basic block imposes on all of the PHI nodes in
2877 if (isa
<PHINode
>(BB
.front())) {
2878 SmallVector
<BasicBlock
*, 8> Preds(predecessors(&BB
));
2879 SmallVector
<std::pair
<BasicBlock
*, Value
*>, 8> Values
;
2881 for (const PHINode
&PN
: BB
.phis()) {
2882 Check(PN
.getNumIncomingValues() == Preds
.size(),
2883 "PHINode should have one entry for each predecessor of its "
2884 "parent basic block!",
2887 // Get and sort all incoming values in the PHI node...
2889 Values
.reserve(PN
.getNumIncomingValues());
2890 for (unsigned i
= 0, e
= PN
.getNumIncomingValues(); i
!= e
; ++i
)
2892 std::make_pair(PN
.getIncomingBlock(i
), PN
.getIncomingValue(i
)));
2895 for (unsigned i
= 0, e
= Values
.size(); i
!= e
; ++i
) {
2896 // Check to make sure that if there is more than one entry for a
2897 // particular basic block in this PHI node, that the incoming values are
2900 Check(i
== 0 || Values
[i
].first
!= Values
[i
- 1].first
||
2901 Values
[i
].second
== Values
[i
- 1].second
,
2902 "PHI node has multiple entries for the same basic block with "
2903 "different incoming values!",
2904 &PN
, Values
[i
].first
, Values
[i
].second
, Values
[i
- 1].second
);
2906 // Check to make sure that the predecessors and PHI node entries are
2908 Check(Values
[i
].first
== Preds
[i
],
2909 "PHI node entries do not match predecessors!", &PN
,
2910 Values
[i
].first
, Preds
[i
]);
2915 // Check that all instructions have their parent pointers set up correctly.
2918 Check(I
.getParent() == &BB
, "Instruction has bogus parent pointer!");
2922 void Verifier::visitTerminator(Instruction
&I
) {
2923 // Ensure that terminators only exist at the end of the basic block.
2924 Check(&I
== I
.getParent()->getTerminator(),
2925 "Terminator found in the middle of a basic block!", I
.getParent());
2926 visitInstruction(I
);
2929 void Verifier::visitBranchInst(BranchInst
&BI
) {
2930 if (BI
.isConditional()) {
2931 Check(BI
.getCondition()->getType()->isIntegerTy(1),
2932 "Branch condition is not 'i1' type!", &BI
, BI
.getCondition());
2934 visitTerminator(BI
);
2937 void Verifier::visitReturnInst(ReturnInst
&RI
) {
2938 Function
*F
= RI
.getParent()->getParent();
2939 unsigned N
= RI
.getNumOperands();
2940 if (F
->getReturnType()->isVoidTy())
2942 "Found return instr that returns non-void in Function of void "
2944 &RI
, F
->getReturnType());
2946 Check(N
== 1 && F
->getReturnType() == RI
.getOperand(0)->getType(),
2947 "Function return type does not match operand "
2948 "type of return inst!",
2949 &RI
, F
->getReturnType());
2951 // Check to make sure that the return value has necessary properties for
2953 visitTerminator(RI
);
2956 void Verifier::visitSwitchInst(SwitchInst
&SI
) {
2957 Check(SI
.getType()->isVoidTy(), "Switch must have void result type!", &SI
);
2958 // Check to make sure that all of the constants in the switch instruction
2959 // have the same type as the switched-on value.
2960 Type
*SwitchTy
= SI
.getCondition()->getType();
2961 SmallPtrSet
<ConstantInt
*, 32> Constants
;
2962 for (auto &Case
: SI
.cases()) {
2963 Check(isa
<ConstantInt
>(SI
.getOperand(Case
.getCaseIndex() * 2 + 2)),
2964 "Case value is not a constant integer.", &SI
);
2965 Check(Case
.getCaseValue()->getType() == SwitchTy
,
2966 "Switch constants must all be same type as switch value!", &SI
);
2967 Check(Constants
.insert(Case
.getCaseValue()).second
,
2968 "Duplicate integer as switch case", &SI
, Case
.getCaseValue());
2971 visitTerminator(SI
);
2974 void Verifier::visitIndirectBrInst(IndirectBrInst
&BI
) {
2975 Check(BI
.getAddress()->getType()->isPointerTy(),
2976 "Indirectbr operand must have pointer type!", &BI
);
2977 for (unsigned i
= 0, e
= BI
.getNumDestinations(); i
!= e
; ++i
)
2978 Check(BI
.getDestination(i
)->getType()->isLabelTy(),
2979 "Indirectbr destinations must all have pointer type!", &BI
);
2981 visitTerminator(BI
);
2984 void Verifier::visitCallBrInst(CallBrInst
&CBI
) {
2985 Check(CBI
.isInlineAsm(), "Callbr is currently only used for asm-goto!", &CBI
);
2986 const InlineAsm
*IA
= cast
<InlineAsm
>(CBI
.getCalledOperand());
2987 Check(!IA
->canThrow(), "Unwinding from Callbr is not allowed");
2989 verifyInlineAsmCall(CBI
);
2990 visitTerminator(CBI
);
2993 void Verifier::visitSelectInst(SelectInst
&SI
) {
2994 Check(!SelectInst::areInvalidOperands(SI
.getOperand(0), SI
.getOperand(1),
2996 "Invalid operands for select instruction!", &SI
);
2998 Check(SI
.getTrueValue()->getType() == SI
.getType(),
2999 "Select values must have same type as select instruction!", &SI
);
3000 visitInstruction(SI
);
3003 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
3004 /// a pass, if any exist, it's an error.
3006 void Verifier::visitUserOp1(Instruction
&I
) {
3007 Check(false, "User-defined operators should not live outside of a pass!", &I
);
3010 void Verifier::visitTruncInst(TruncInst
&I
) {
3011 // Get the source and destination types
3012 Type
*SrcTy
= I
.getOperand(0)->getType();
3013 Type
*DestTy
= I
.getType();
3015 // Get the size of the types in bits, we'll need this later
3016 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
3017 unsigned DestBitSize
= DestTy
->getScalarSizeInBits();
3019 Check(SrcTy
->isIntOrIntVectorTy(), "Trunc only operates on integer", &I
);
3020 Check(DestTy
->isIntOrIntVectorTy(), "Trunc only produces integer", &I
);
3021 Check(SrcTy
->isVectorTy() == DestTy
->isVectorTy(),
3022 "trunc source and destination must both be a vector or neither", &I
);
3023 Check(SrcBitSize
> DestBitSize
, "DestTy too big for Trunc", &I
);
3025 visitInstruction(I
);
3028 void Verifier::visitZExtInst(ZExtInst
&I
) {
3029 // Get the source and destination types
3030 Type
*SrcTy
= I
.getOperand(0)->getType();
3031 Type
*DestTy
= I
.getType();
3033 // Get the size of the types in bits, we'll need this later
3034 Check(SrcTy
->isIntOrIntVectorTy(), "ZExt only operates on integer", &I
);
3035 Check(DestTy
->isIntOrIntVectorTy(), "ZExt only produces an integer", &I
);
3036 Check(SrcTy
->isVectorTy() == DestTy
->isVectorTy(),
3037 "zext source and destination must both be a vector or neither", &I
);
3038 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
3039 unsigned DestBitSize
= DestTy
->getScalarSizeInBits();
3041 Check(SrcBitSize
< DestBitSize
, "Type too small for ZExt", &I
);
3043 visitInstruction(I
);
3046 void Verifier::visitSExtInst(SExtInst
&I
) {
3047 // Get the source and destination types
3048 Type
*SrcTy
= I
.getOperand(0)->getType();
3049 Type
*DestTy
= I
.getType();
3051 // Get the size of the types in bits, we'll need this later
3052 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
3053 unsigned DestBitSize
= DestTy
->getScalarSizeInBits();
3055 Check(SrcTy
->isIntOrIntVectorTy(), "SExt only operates on integer", &I
);
3056 Check(DestTy
->isIntOrIntVectorTy(), "SExt only produces an integer", &I
);
3057 Check(SrcTy
->isVectorTy() == DestTy
->isVectorTy(),
3058 "sext source and destination must both be a vector or neither", &I
);
3059 Check(SrcBitSize
< DestBitSize
, "Type too small for SExt", &I
);
3061 visitInstruction(I
);
3064 void Verifier::visitFPTruncInst(FPTruncInst
&I
) {
3065 // Get the source and destination types
3066 Type
*SrcTy
= I
.getOperand(0)->getType();
3067 Type
*DestTy
= I
.getType();
3068 // Get the size of the types in bits, we'll need this later
3069 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
3070 unsigned DestBitSize
= DestTy
->getScalarSizeInBits();
3072 Check(SrcTy
->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I
);
3073 Check(DestTy
->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I
);
3074 Check(SrcTy
->isVectorTy() == DestTy
->isVectorTy(),
3075 "fptrunc source and destination must both be a vector or neither", &I
);
3076 Check(SrcBitSize
> DestBitSize
, "DestTy too big for FPTrunc", &I
);
3078 visitInstruction(I
);
3081 void Verifier::visitFPExtInst(FPExtInst
&I
) {
3082 // Get the source and destination types
3083 Type
*SrcTy
= I
.getOperand(0)->getType();
3084 Type
*DestTy
= I
.getType();
3086 // Get the size of the types in bits, we'll need this later
3087 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
3088 unsigned DestBitSize
= DestTy
->getScalarSizeInBits();
3090 Check(SrcTy
->isFPOrFPVectorTy(), "FPExt only operates on FP", &I
);
3091 Check(DestTy
->isFPOrFPVectorTy(), "FPExt only produces an FP", &I
);
3092 Check(SrcTy
->isVectorTy() == DestTy
->isVectorTy(),
3093 "fpext source and destination must both be a vector or neither", &I
);
3094 Check(SrcBitSize
< DestBitSize
, "DestTy too small for FPExt", &I
);
3096 visitInstruction(I
);
3099 void Verifier::visitUIToFPInst(UIToFPInst
&I
) {
3100 // Get the source and destination types
3101 Type
*SrcTy
= I
.getOperand(0)->getType();
3102 Type
*DestTy
= I
.getType();
3104 bool SrcVec
= SrcTy
->isVectorTy();
3105 bool DstVec
= DestTy
->isVectorTy();
3107 Check(SrcVec
== DstVec
,
3108 "UIToFP source and dest must both be vector or scalar", &I
);
3109 Check(SrcTy
->isIntOrIntVectorTy(),
3110 "UIToFP source must be integer or integer vector", &I
);
3111 Check(DestTy
->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
3114 if (SrcVec
&& DstVec
)
3115 Check(cast
<VectorType
>(SrcTy
)->getElementCount() ==
3116 cast
<VectorType
>(DestTy
)->getElementCount(),
3117 "UIToFP source and dest vector length mismatch", &I
);
3119 visitInstruction(I
);
3122 void Verifier::visitSIToFPInst(SIToFPInst
&I
) {
3123 // Get the source and destination types
3124 Type
*SrcTy
= I
.getOperand(0)->getType();
3125 Type
*DestTy
= I
.getType();
3127 bool SrcVec
= SrcTy
->isVectorTy();
3128 bool DstVec
= DestTy
->isVectorTy();
3130 Check(SrcVec
== DstVec
,
3131 "SIToFP source and dest must both be vector or scalar", &I
);
3132 Check(SrcTy
->isIntOrIntVectorTy(),
3133 "SIToFP source must be integer or integer vector", &I
);
3134 Check(DestTy
->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
3137 if (SrcVec
&& DstVec
)
3138 Check(cast
<VectorType
>(SrcTy
)->getElementCount() ==
3139 cast
<VectorType
>(DestTy
)->getElementCount(),
3140 "SIToFP source and dest vector length mismatch", &I
);
3142 visitInstruction(I
);
3145 void Verifier::visitFPToUIInst(FPToUIInst
&I
) {
3146 // Get the source and destination types
3147 Type
*SrcTy
= I
.getOperand(0)->getType();
3148 Type
*DestTy
= I
.getType();
3150 bool SrcVec
= SrcTy
->isVectorTy();
3151 bool DstVec
= DestTy
->isVectorTy();
3153 Check(SrcVec
== DstVec
,
3154 "FPToUI source and dest must both be vector or scalar", &I
);
3155 Check(SrcTy
->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", &I
);
3156 Check(DestTy
->isIntOrIntVectorTy(),
3157 "FPToUI result must be integer or integer vector", &I
);
3159 if (SrcVec
&& DstVec
)
3160 Check(cast
<VectorType
>(SrcTy
)->getElementCount() ==
3161 cast
<VectorType
>(DestTy
)->getElementCount(),
3162 "FPToUI source and dest vector length mismatch", &I
);
3164 visitInstruction(I
);
3167 void Verifier::visitFPToSIInst(FPToSIInst
&I
) {
3168 // Get the source and destination types
3169 Type
*SrcTy
= I
.getOperand(0)->getType();
3170 Type
*DestTy
= I
.getType();
3172 bool SrcVec
= SrcTy
->isVectorTy();
3173 bool DstVec
= DestTy
->isVectorTy();
3175 Check(SrcVec
== DstVec
,
3176 "FPToSI source and dest must both be vector or scalar", &I
);
3177 Check(SrcTy
->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", &I
);
3178 Check(DestTy
->isIntOrIntVectorTy(),
3179 "FPToSI result must be integer or integer vector", &I
);
3181 if (SrcVec
&& DstVec
)
3182 Check(cast
<VectorType
>(SrcTy
)->getElementCount() ==
3183 cast
<VectorType
>(DestTy
)->getElementCount(),
3184 "FPToSI source and dest vector length mismatch", &I
);
3186 visitInstruction(I
);
3189 void Verifier::visitPtrToIntInst(PtrToIntInst
&I
) {
3190 // Get the source and destination types
3191 Type
*SrcTy
= I
.getOperand(0)->getType();
3192 Type
*DestTy
= I
.getType();
3194 Check(SrcTy
->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I
);
3196 Check(DestTy
->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I
);
3197 Check(SrcTy
->isVectorTy() == DestTy
->isVectorTy(), "PtrToInt type mismatch",
3200 if (SrcTy
->isVectorTy()) {
3201 auto *VSrc
= cast
<VectorType
>(SrcTy
);
3202 auto *VDest
= cast
<VectorType
>(DestTy
);
3203 Check(VSrc
->getElementCount() == VDest
->getElementCount(),
3204 "PtrToInt Vector width mismatch", &I
);
3207 visitInstruction(I
);
3210 void Verifier::visitIntToPtrInst(IntToPtrInst
&I
) {
3211 // Get the source and destination types
3212 Type
*SrcTy
= I
.getOperand(0)->getType();
3213 Type
*DestTy
= I
.getType();
3215 Check(SrcTy
->isIntOrIntVectorTy(), "IntToPtr source must be an integral", &I
);
3216 Check(DestTy
->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I
);
3218 Check(SrcTy
->isVectorTy() == DestTy
->isVectorTy(), "IntToPtr type mismatch",
3220 if (SrcTy
->isVectorTy()) {
3221 auto *VSrc
= cast
<VectorType
>(SrcTy
);
3222 auto *VDest
= cast
<VectorType
>(DestTy
);
3223 Check(VSrc
->getElementCount() == VDest
->getElementCount(),
3224 "IntToPtr Vector width mismatch", &I
);
3226 visitInstruction(I
);
3229 void Verifier::visitBitCastInst(BitCastInst
&I
) {
3231 CastInst::castIsValid(Instruction::BitCast
, I
.getOperand(0), I
.getType()),
3232 "Invalid bitcast", &I
);
3233 visitInstruction(I
);
3236 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst
&I
) {
3237 Type
*SrcTy
= I
.getOperand(0)->getType();
3238 Type
*DestTy
= I
.getType();
3240 Check(SrcTy
->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
3242 Check(DestTy
->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
3244 Check(SrcTy
->getPointerAddressSpace() != DestTy
->getPointerAddressSpace(),
3245 "AddrSpaceCast must be between different address spaces", &I
);
3246 if (auto *SrcVTy
= dyn_cast
<VectorType
>(SrcTy
))
3247 Check(SrcVTy
->getElementCount() ==
3248 cast
<VectorType
>(DestTy
)->getElementCount(),
3249 "AddrSpaceCast vector pointer number of elements mismatch", &I
);
3250 visitInstruction(I
);
3253 /// visitPHINode - Ensure that a PHI node is well formed.
3255 void Verifier::visitPHINode(PHINode
&PN
) {
3256 // Ensure that the PHI nodes are all grouped together at the top of the block.
3257 // This can be tested by checking whether the instruction before this is
3258 // either nonexistent (because this is begin()) or is a PHI node. If not,
3259 // then there is some other instruction before a PHI.
3260 Check(&PN
== &PN
.getParent()->front() ||
3261 isa
<PHINode
>(--BasicBlock::iterator(&PN
)),
3262 "PHI nodes not grouped at top of basic block!", &PN
, PN
.getParent());
3264 // Check that a PHI doesn't yield a Token.
3265 Check(!PN
.getType()->isTokenTy(), "PHI nodes cannot have token type!");
3267 // Check that all of the values of the PHI node have the same type as the
3268 // result, and that the incoming blocks are really basic blocks.
3269 for (Value
*IncValue
: PN
.incoming_values()) {
3270 Check(PN
.getType() == IncValue
->getType(),
3271 "PHI node operands are not the same type as the result!", &PN
);
3274 // All other PHI node constraints are checked in the visitBasicBlock method.
3276 visitInstruction(PN
);
3279 void Verifier::visitCallBase(CallBase
&Call
) {
3280 Check(Call
.getCalledOperand()->getType()->isPointerTy(),
3281 "Called function must be a pointer!", Call
);
3282 FunctionType
*FTy
= Call
.getFunctionType();
3284 // Verify that the correct number of arguments are being passed
3285 if (FTy
->isVarArg())
3286 Check(Call
.arg_size() >= FTy
->getNumParams(),
3287 "Called function requires more parameters than were provided!", Call
);
3289 Check(Call
.arg_size() == FTy
->getNumParams(),
3290 "Incorrect number of arguments passed to called function!", Call
);
3292 // Verify that all arguments to the call match the function type.
3293 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
)
3294 Check(Call
.getArgOperand(i
)->getType() == FTy
->getParamType(i
),
3295 "Call parameter type does not match function signature!",
3296 Call
.getArgOperand(i
), FTy
->getParamType(i
), Call
);
3298 AttributeList Attrs
= Call
.getAttributes();
3300 Check(verifyAttributeCount(Attrs
, Call
.arg_size()),
3301 "Attribute after last parameter!", Call
);
3304 dyn_cast
<Function
>(Call
.getCalledOperand()->stripPointerCasts());
3305 bool IsIntrinsic
= Callee
&& Callee
->isIntrinsic();
3307 Check(Callee
->getValueType() == FTy
,
3308 "Intrinsic called with incompatible signature", Call
);
3310 // Disallow calls to functions with the amdgpu_cs_chain[_preserve] calling
3312 auto CC
= Call
.getCallingConv();
3313 Check(CC
!= CallingConv::AMDGPU_CS_Chain
&&
3314 CC
!= CallingConv::AMDGPU_CS_ChainPreserve
,
3315 "Direct calls to amdgpu_cs_chain/amdgpu_cs_chain_preserve functions "
3316 "not allowed. Please use the @llvm.amdgpu.cs.chain intrinsic instead.",
3319 auto VerifyTypeAlign
= [&](Type
*Ty
, const Twine
&Message
) {
3322 Align ABIAlign
= DL
.getABITypeAlign(Ty
);
3323 Align
MaxAlign(ParamMaxAlignment
);
3324 Check(ABIAlign
<= MaxAlign
,
3325 "Incorrect alignment of " + Message
+ " to called function!", Call
);
3329 VerifyTypeAlign(FTy
->getReturnType(), "return type");
3330 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
) {
3331 Type
*Ty
= FTy
->getParamType(i
);
3332 VerifyTypeAlign(Ty
, "argument passed");
3336 if (Attrs
.hasFnAttr(Attribute::Speculatable
)) {
3337 // Don't allow speculatable on call sites, unless the underlying function
3338 // declaration is also speculatable.
3339 Check(Callee
&& Callee
->isSpeculatable(),
3340 "speculatable attribute may not apply to call sites", Call
);
3343 if (Attrs
.hasFnAttr(Attribute::Preallocated
)) {
3344 Check(Call
.getCalledFunction()->getIntrinsicID() ==
3345 Intrinsic::call_preallocated_arg
,
3346 "preallocated as a call site attribute can only be on "
3347 "llvm.call.preallocated.arg");
3350 // Verify call attributes.
3351 verifyFunctionAttrs(FTy
, Attrs
, &Call
, IsIntrinsic
, Call
.isInlineAsm());
3353 // Conservatively check the inalloca argument.
3354 // We have a bug if we can find that there is an underlying alloca without
3356 if (Call
.hasInAllocaArgument()) {
3357 Value
*InAllocaArg
= Call
.getArgOperand(FTy
->getNumParams() - 1);
3358 if (auto AI
= dyn_cast
<AllocaInst
>(InAllocaArg
->stripInBoundsOffsets()))
3359 Check(AI
->isUsedWithInAlloca(),
3360 "inalloca argument for call has mismatched alloca", AI
, Call
);
3363 // For each argument of the callsite, if it has the swifterror argument,
3364 // make sure the underlying alloca/parameter it comes from has a swifterror as
3366 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
) {
3367 if (Call
.paramHasAttr(i
, Attribute::SwiftError
)) {
3368 Value
*SwiftErrorArg
= Call
.getArgOperand(i
);
3369 if (auto AI
= dyn_cast
<AllocaInst
>(SwiftErrorArg
->stripInBoundsOffsets())) {
3370 Check(AI
->isSwiftError(),
3371 "swifterror argument for call has mismatched alloca", AI
, Call
);
3374 auto ArgI
= dyn_cast
<Argument
>(SwiftErrorArg
);
3375 Check(ArgI
, "swifterror argument should come from an alloca or parameter",
3376 SwiftErrorArg
, Call
);
3377 Check(ArgI
->hasSwiftErrorAttr(),
3378 "swifterror argument for call has mismatched parameter", ArgI
,
3382 if (Attrs
.hasParamAttr(i
, Attribute::ImmArg
)) {
3383 // Don't allow immarg on call sites, unless the underlying declaration
3384 // also has the matching immarg.
3385 Check(Callee
&& Callee
->hasParamAttribute(i
, Attribute::ImmArg
),
3386 "immarg may not apply only to call sites", Call
.getArgOperand(i
),
3390 if (Call
.paramHasAttr(i
, Attribute::ImmArg
)) {
3391 Value
*ArgVal
= Call
.getArgOperand(i
);
3392 Check(isa
<ConstantInt
>(ArgVal
) || isa
<ConstantFP
>(ArgVal
),
3393 "immarg operand has non-immediate parameter", ArgVal
, Call
);
3396 if (Call
.paramHasAttr(i
, Attribute::Preallocated
)) {
3397 Value
*ArgVal
= Call
.getArgOperand(i
);
3399 Call
.countOperandBundlesOfType(LLVMContext::OB_preallocated
) != 0;
3400 bool isMustTail
= Call
.isMustTailCall();
3401 Check(hasOB
!= isMustTail
,
3402 "preallocated operand either requires a preallocated bundle or "
3403 "the call to be musttail (but not both)",
3408 if (FTy
->isVarArg()) {
3409 // FIXME? is 'nest' even legal here?
3410 bool SawNest
= false;
3411 bool SawReturned
= false;
3413 for (unsigned Idx
= 0; Idx
< FTy
->getNumParams(); ++Idx
) {
3414 if (Attrs
.hasParamAttr(Idx
, Attribute::Nest
))
3416 if (Attrs
.hasParamAttr(Idx
, Attribute::Returned
))
3420 // Check attributes on the varargs part.
3421 for (unsigned Idx
= FTy
->getNumParams(); Idx
< Call
.arg_size(); ++Idx
) {
3422 Type
*Ty
= Call
.getArgOperand(Idx
)->getType();
3423 AttributeSet ArgAttrs
= Attrs
.getParamAttrs(Idx
);
3424 verifyParameterAttrs(ArgAttrs
, Ty
, &Call
);
3426 if (ArgAttrs
.hasAttribute(Attribute::Nest
)) {
3427 Check(!SawNest
, "More than one parameter has attribute nest!", Call
);
3431 if (ArgAttrs
.hasAttribute(Attribute::Returned
)) {
3432 Check(!SawReturned
, "More than one parameter has attribute returned!",
3434 Check(Ty
->canLosslesslyBitCastTo(FTy
->getReturnType()),
3435 "Incompatible argument and return types for 'returned' "
3441 // Statepoint intrinsic is vararg but the wrapped function may be not.
3442 // Allow sret here and check the wrapped function in verifyStatepoint.
3443 if (!Call
.getCalledFunction() ||
3444 Call
.getCalledFunction()->getIntrinsicID() !=
3445 Intrinsic::experimental_gc_statepoint
)
3446 Check(!ArgAttrs
.hasAttribute(Attribute::StructRet
),
3447 "Attribute 'sret' cannot be used for vararg call arguments!",
3450 if (ArgAttrs
.hasAttribute(Attribute::InAlloca
))
3451 Check(Idx
== Call
.arg_size() - 1,
3452 "inalloca isn't on the last argument!", Call
);
3456 // Verify that there's no metadata unless it's a direct call to an intrinsic.
3458 for (Type
*ParamTy
: FTy
->params()) {
3459 Check(!ParamTy
->isMetadataTy(),
3460 "Function has metadata parameter but isn't an intrinsic", Call
);
3461 Check(!ParamTy
->isTokenTy(),
3462 "Function has token parameter but isn't an intrinsic", Call
);
3466 // Verify that indirect calls don't return tokens.
3467 if (!Call
.getCalledFunction()) {
3468 Check(!FTy
->getReturnType()->isTokenTy(),
3469 "Return type cannot be token for indirect call!");
3470 Check(!FTy
->getReturnType()->isX86_AMXTy(),
3471 "Return type cannot be x86_amx for indirect call!");
3474 if (Function
*F
= Call
.getCalledFunction())
3475 if (Intrinsic::ID ID
= (Intrinsic::ID
)F
->getIntrinsicID())
3476 visitIntrinsicCall(ID
, Call
);
3478 // Verify that a callsite has at most one "deopt", at most one "funclet", at
3479 // most one "gc-transition", at most one "cfguardtarget", at most one
3480 // "preallocated" operand bundle, and at most one "ptrauth" operand bundle.
3481 bool FoundDeoptBundle
= false, FoundFuncletBundle
= false,
3482 FoundGCTransitionBundle
= false, FoundCFGuardTargetBundle
= false,
3483 FoundPreallocatedBundle
= false, FoundGCLiveBundle
= false,
3484 FoundPtrauthBundle
= false, FoundKCFIBundle
= false,
3485 FoundAttachedCallBundle
= false;
3486 for (unsigned i
= 0, e
= Call
.getNumOperandBundles(); i
< e
; ++i
) {
3487 OperandBundleUse BU
= Call
.getOperandBundleAt(i
);
3488 uint32_t Tag
= BU
.getTagID();
3489 if (Tag
== LLVMContext::OB_deopt
) {
3490 Check(!FoundDeoptBundle
, "Multiple deopt operand bundles", Call
);
3491 FoundDeoptBundle
= true;
3492 } else if (Tag
== LLVMContext::OB_gc_transition
) {
3493 Check(!FoundGCTransitionBundle
, "Multiple gc-transition operand bundles",
3495 FoundGCTransitionBundle
= true;
3496 } else if (Tag
== LLVMContext::OB_funclet
) {
3497 Check(!FoundFuncletBundle
, "Multiple funclet operand bundles", Call
);
3498 FoundFuncletBundle
= true;
3499 Check(BU
.Inputs
.size() == 1,
3500 "Expected exactly one funclet bundle operand", Call
);
3501 Check(isa
<FuncletPadInst
>(BU
.Inputs
.front()),
3502 "Funclet bundle operands should correspond to a FuncletPadInst",
3504 } else if (Tag
== LLVMContext::OB_cfguardtarget
) {
3505 Check(!FoundCFGuardTargetBundle
, "Multiple CFGuardTarget operand bundles",
3507 FoundCFGuardTargetBundle
= true;
3508 Check(BU
.Inputs
.size() == 1,
3509 "Expected exactly one cfguardtarget bundle operand", Call
);
3510 } else if (Tag
== LLVMContext::OB_ptrauth
) {
3511 Check(!FoundPtrauthBundle
, "Multiple ptrauth operand bundles", Call
);
3512 FoundPtrauthBundle
= true;
3513 Check(BU
.Inputs
.size() == 2,
3514 "Expected exactly two ptrauth bundle operands", Call
);
3515 Check(isa
<ConstantInt
>(BU
.Inputs
[0]) &&
3516 BU
.Inputs
[0]->getType()->isIntegerTy(32),
3517 "Ptrauth bundle key operand must be an i32 constant", Call
);
3518 Check(BU
.Inputs
[1]->getType()->isIntegerTy(64),
3519 "Ptrauth bundle discriminator operand must be an i64", Call
);
3520 } else if (Tag
== LLVMContext::OB_kcfi
) {
3521 Check(!FoundKCFIBundle
, "Multiple kcfi operand bundles", Call
);
3522 FoundKCFIBundle
= true;
3523 Check(BU
.Inputs
.size() == 1, "Expected exactly one kcfi bundle operand",
3525 Check(isa
<ConstantInt
>(BU
.Inputs
[0]) &&
3526 BU
.Inputs
[0]->getType()->isIntegerTy(32),
3527 "Kcfi bundle operand must be an i32 constant", Call
);
3528 } else if (Tag
== LLVMContext::OB_preallocated
) {
3529 Check(!FoundPreallocatedBundle
, "Multiple preallocated operand bundles",
3531 FoundPreallocatedBundle
= true;
3532 Check(BU
.Inputs
.size() == 1,
3533 "Expected exactly one preallocated bundle operand", Call
);
3534 auto Input
= dyn_cast
<IntrinsicInst
>(BU
.Inputs
.front());
3536 Input
->getIntrinsicID() == Intrinsic::call_preallocated_setup
,
3537 "\"preallocated\" argument must be a token from "
3538 "llvm.call.preallocated.setup",
3540 } else if (Tag
== LLVMContext::OB_gc_live
) {
3541 Check(!FoundGCLiveBundle
, "Multiple gc-live operand bundles", Call
);
3542 FoundGCLiveBundle
= true;
3543 } else if (Tag
== LLVMContext::OB_clang_arc_attachedcall
) {
3544 Check(!FoundAttachedCallBundle
,
3545 "Multiple \"clang.arc.attachedcall\" operand bundles", Call
);
3546 FoundAttachedCallBundle
= true;
3547 verifyAttachedCallBundle(Call
, BU
);
3551 // Verify that callee and callsite agree on whether to use pointer auth.
3552 Check(!(Call
.getCalledFunction() && FoundPtrauthBundle
),
3553 "Direct call cannot have a ptrauth bundle", Call
);
3555 // Verify that each inlinable callsite of a debug-info-bearing function in a
3556 // debug-info-bearing function has a debug location attached to it. Failure to
3557 // do so causes assertion failures when the inliner sets up inline scope info
3558 // (Interposable functions are not inlinable, neither are functions without
3560 if (Call
.getFunction()->getSubprogram() && Call
.getCalledFunction() &&
3561 !Call
.getCalledFunction()->isInterposable() &&
3562 !Call
.getCalledFunction()->isDeclaration() &&
3563 Call
.getCalledFunction()->getSubprogram())
3564 CheckDI(Call
.getDebugLoc(),
3565 "inlinable function call in a function with "
3566 "debug info must have a !dbg location",
3569 if (Call
.isInlineAsm())
3570 verifyInlineAsmCall(Call
);
3572 ConvergenceVerifyHelper
.visit(Call
);
3574 visitInstruction(Call
);
3577 void Verifier::verifyTailCCMustTailAttrs(const AttrBuilder
&Attrs
,
3578 StringRef Context
) {
3579 Check(!Attrs
.contains(Attribute::InAlloca
),
3580 Twine("inalloca attribute not allowed in ") + Context
);
3581 Check(!Attrs
.contains(Attribute::InReg
),
3582 Twine("inreg attribute not allowed in ") + Context
);
3583 Check(!Attrs
.contains(Attribute::SwiftError
),
3584 Twine("swifterror attribute not allowed in ") + Context
);
3585 Check(!Attrs
.contains(Attribute::Preallocated
),
3586 Twine("preallocated attribute not allowed in ") + Context
);
3587 Check(!Attrs
.contains(Attribute::ByRef
),
3588 Twine("byref attribute not allowed in ") + Context
);
3591 /// Two types are "congruent" if they are identical, or if they are both pointer
3592 /// types with different pointee types and the same address space.
3593 static bool isTypeCongruent(Type
*L
, Type
*R
) {
3596 PointerType
*PL
= dyn_cast
<PointerType
>(L
);
3597 PointerType
*PR
= dyn_cast
<PointerType
>(R
);
3600 return PL
->getAddressSpace() == PR
->getAddressSpace();
3603 static AttrBuilder
getParameterABIAttributes(LLVMContext
& C
, unsigned I
, AttributeList Attrs
) {
3604 static const Attribute::AttrKind ABIAttrs
[] = {
3605 Attribute::StructRet
, Attribute::ByVal
, Attribute::InAlloca
,
3606 Attribute::InReg
, Attribute::StackAlignment
, Attribute::SwiftSelf
,
3607 Attribute::SwiftAsync
, Attribute::SwiftError
, Attribute::Preallocated
,
3609 AttrBuilder
Copy(C
);
3610 for (auto AK
: ABIAttrs
) {
3611 Attribute Attr
= Attrs
.getParamAttrs(I
).getAttribute(AK
);
3613 Copy
.addAttribute(Attr
);
3616 // `align` is ABI-affecting only in combination with `byval` or `byref`.
3617 if (Attrs
.hasParamAttr(I
, Attribute::Alignment
) &&
3618 (Attrs
.hasParamAttr(I
, Attribute::ByVal
) ||
3619 Attrs
.hasParamAttr(I
, Attribute::ByRef
)))
3620 Copy
.addAlignmentAttr(Attrs
.getParamAlignment(I
));
3624 void Verifier::verifyMustTailCall(CallInst
&CI
) {
3625 Check(!CI
.isInlineAsm(), "cannot use musttail call with inline asm", &CI
);
3627 Function
*F
= CI
.getParent()->getParent();
3628 FunctionType
*CallerTy
= F
->getFunctionType();
3629 FunctionType
*CalleeTy
= CI
.getFunctionType();
3630 Check(CallerTy
->isVarArg() == CalleeTy
->isVarArg(),
3631 "cannot guarantee tail call due to mismatched varargs", &CI
);
3632 Check(isTypeCongruent(CallerTy
->getReturnType(), CalleeTy
->getReturnType()),
3633 "cannot guarantee tail call due to mismatched return types", &CI
);
3635 // - The calling conventions of the caller and callee must match.
3636 Check(F
->getCallingConv() == CI
.getCallingConv(),
3637 "cannot guarantee tail call due to mismatched calling conv", &CI
);
3639 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
3640 // or a pointer bitcast followed by a ret instruction.
3641 // - The ret instruction must return the (possibly bitcasted) value
3642 // produced by the call or void.
3643 Value
*RetVal
= &CI
;
3644 Instruction
*Next
= CI
.getNextNode();
3646 // Handle the optional bitcast.
3647 if (BitCastInst
*BI
= dyn_cast_or_null
<BitCastInst
>(Next
)) {
3648 Check(BI
->getOperand(0) == RetVal
,
3649 "bitcast following musttail call must use the call", BI
);
3651 Next
= BI
->getNextNode();
3654 // Check the return.
3655 ReturnInst
*Ret
= dyn_cast_or_null
<ReturnInst
>(Next
);
3656 Check(Ret
, "musttail call must precede a ret with an optional bitcast", &CI
);
3657 Check(!Ret
->getReturnValue() || Ret
->getReturnValue() == RetVal
||
3658 isa
<UndefValue
>(Ret
->getReturnValue()),
3659 "musttail call result must be returned", Ret
);
3661 AttributeList CallerAttrs
= F
->getAttributes();
3662 AttributeList CalleeAttrs
= CI
.getAttributes();
3663 if (CI
.getCallingConv() == CallingConv::SwiftTail
||
3664 CI
.getCallingConv() == CallingConv::Tail
) {
3666 CI
.getCallingConv() == CallingConv::Tail
? "tailcc" : "swifttailcc";
3668 // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
3669 // are allowed in swifttailcc call
3670 for (unsigned I
= 0, E
= CallerTy
->getNumParams(); I
!= E
; ++I
) {
3671 AttrBuilder ABIAttrs
= getParameterABIAttributes(F
->getContext(), I
, CallerAttrs
);
3672 SmallString
<32> Context
{CCName
, StringRef(" musttail caller")};
3673 verifyTailCCMustTailAttrs(ABIAttrs
, Context
);
3675 for (unsigned I
= 0, E
= CalleeTy
->getNumParams(); I
!= E
; ++I
) {
3676 AttrBuilder ABIAttrs
= getParameterABIAttributes(F
->getContext(), I
, CalleeAttrs
);
3677 SmallString
<32> Context
{CCName
, StringRef(" musttail callee")};
3678 verifyTailCCMustTailAttrs(ABIAttrs
, Context
);
3680 // - Varargs functions are not allowed
3681 Check(!CallerTy
->isVarArg(), Twine("cannot guarantee ") + CCName
+
3682 " tail call for varargs function");
3686 // - The caller and callee prototypes must match. Pointer types of
3687 // parameters or return types may differ in pointee type, but not
3689 if (!CI
.getCalledFunction() || !CI
.getCalledFunction()->isIntrinsic()) {
3690 Check(CallerTy
->getNumParams() == CalleeTy
->getNumParams(),
3691 "cannot guarantee tail call due to mismatched parameter counts", &CI
);
3692 for (unsigned I
= 0, E
= CallerTy
->getNumParams(); I
!= E
; ++I
) {
3694 isTypeCongruent(CallerTy
->getParamType(I
), CalleeTy
->getParamType(I
)),
3695 "cannot guarantee tail call due to mismatched parameter types", &CI
);
3699 // - All ABI-impacting function attributes, such as sret, byval, inreg,
3700 // returned, preallocated, and inalloca, must match.
3701 for (unsigned I
= 0, E
= CallerTy
->getNumParams(); I
!= E
; ++I
) {
3702 AttrBuilder CallerABIAttrs
= getParameterABIAttributes(F
->getContext(), I
, CallerAttrs
);
3703 AttrBuilder CalleeABIAttrs
= getParameterABIAttributes(F
->getContext(), I
, CalleeAttrs
);
3704 Check(CallerABIAttrs
== CalleeABIAttrs
,
3705 "cannot guarantee tail call due to mismatched ABI impacting "
3706 "function attributes",
3707 &CI
, CI
.getOperand(I
));
3711 void Verifier::visitCallInst(CallInst
&CI
) {
3714 if (CI
.isMustTailCall())
3715 verifyMustTailCall(CI
);
3718 void Verifier::visitInvokeInst(InvokeInst
&II
) {
3721 // Verify that the first non-PHI instruction of the unwind destination is an
3722 // exception handling instruction.
3724 II
.getUnwindDest()->isEHPad(),
3725 "The unwind destination does not have an exception handling instruction!",
3728 visitTerminator(II
);
3731 /// visitUnaryOperator - Check the argument to the unary operator.
3733 void Verifier::visitUnaryOperator(UnaryOperator
&U
) {
3734 Check(U
.getType() == U
.getOperand(0)->getType(),
3735 "Unary operators must have same type for"
3736 "operands and result!",
3739 switch (U
.getOpcode()) {
3740 // Check that floating-point arithmetic operators are only used with
3741 // floating-point operands.
3742 case Instruction::FNeg
:
3743 Check(U
.getType()->isFPOrFPVectorTy(),
3744 "FNeg operator only works with float types!", &U
);
3747 llvm_unreachable("Unknown UnaryOperator opcode!");
3750 visitInstruction(U
);
3753 /// visitBinaryOperator - Check that both arguments to the binary operator are
3754 /// of the same type!
3756 void Verifier::visitBinaryOperator(BinaryOperator
&B
) {
3757 Check(B
.getOperand(0)->getType() == B
.getOperand(1)->getType(),
3758 "Both operands to a binary operator are not of the same type!", &B
);
3760 switch (B
.getOpcode()) {
3761 // Check that integer arithmetic operators are only used with
3762 // integral operands.
3763 case Instruction::Add
:
3764 case Instruction::Sub
:
3765 case Instruction::Mul
:
3766 case Instruction::SDiv
:
3767 case Instruction::UDiv
:
3768 case Instruction::SRem
:
3769 case Instruction::URem
:
3770 Check(B
.getType()->isIntOrIntVectorTy(),
3771 "Integer arithmetic operators only work with integral types!", &B
);
3772 Check(B
.getType() == B
.getOperand(0)->getType(),
3773 "Integer arithmetic operators must have same type "
3774 "for operands and result!",
3777 // Check that floating-point arithmetic operators are only used with
3778 // floating-point operands.
3779 case Instruction::FAdd
:
3780 case Instruction::FSub
:
3781 case Instruction::FMul
:
3782 case Instruction::FDiv
:
3783 case Instruction::FRem
:
3784 Check(B
.getType()->isFPOrFPVectorTy(),
3785 "Floating-point arithmetic operators only work with "
3786 "floating-point types!",
3788 Check(B
.getType() == B
.getOperand(0)->getType(),
3789 "Floating-point arithmetic operators must have same type "
3790 "for operands and result!",
3793 // Check that logical operators are only used with integral operands.
3794 case Instruction::And
:
3795 case Instruction::Or
:
3796 case Instruction::Xor
:
3797 Check(B
.getType()->isIntOrIntVectorTy(),
3798 "Logical operators only work with integral types!", &B
);
3799 Check(B
.getType() == B
.getOperand(0)->getType(),
3800 "Logical operators must have same type for operands and result!", &B
);
3802 case Instruction::Shl
:
3803 case Instruction::LShr
:
3804 case Instruction::AShr
:
3805 Check(B
.getType()->isIntOrIntVectorTy(),
3806 "Shifts only work with integral types!", &B
);
3807 Check(B
.getType() == B
.getOperand(0)->getType(),
3808 "Shift return type must be same as operands!", &B
);
3811 llvm_unreachable("Unknown BinaryOperator opcode!");
3814 visitInstruction(B
);
3817 void Verifier::visitICmpInst(ICmpInst
&IC
) {
3818 // Check that the operands are the same type
3819 Type
*Op0Ty
= IC
.getOperand(0)->getType();
3820 Type
*Op1Ty
= IC
.getOperand(1)->getType();
3821 Check(Op0Ty
== Op1Ty
,
3822 "Both operands to ICmp instruction are not of the same type!", &IC
);
3823 // Check that the operands are the right type
3824 Check(Op0Ty
->isIntOrIntVectorTy() || Op0Ty
->isPtrOrPtrVectorTy(),
3825 "Invalid operand types for ICmp instruction", &IC
);
3826 // Check that the predicate is valid.
3827 Check(IC
.isIntPredicate(), "Invalid predicate in ICmp instruction!", &IC
);
3829 visitInstruction(IC
);
3832 void Verifier::visitFCmpInst(FCmpInst
&FC
) {
3833 // Check that the operands are the same type
3834 Type
*Op0Ty
= FC
.getOperand(0)->getType();
3835 Type
*Op1Ty
= FC
.getOperand(1)->getType();
3836 Check(Op0Ty
== Op1Ty
,
3837 "Both operands to FCmp instruction are not of the same type!", &FC
);
3838 // Check that the operands are the right type
3839 Check(Op0Ty
->isFPOrFPVectorTy(), "Invalid operand types for FCmp instruction",
3841 // Check that the predicate is valid.
3842 Check(FC
.isFPPredicate(), "Invalid predicate in FCmp instruction!", &FC
);
3844 visitInstruction(FC
);
3847 void Verifier::visitExtractElementInst(ExtractElementInst
&EI
) {
3848 Check(ExtractElementInst::isValidOperands(EI
.getOperand(0), EI
.getOperand(1)),
3849 "Invalid extractelement operands!", &EI
);
3850 visitInstruction(EI
);
3853 void Verifier::visitInsertElementInst(InsertElementInst
&IE
) {
3854 Check(InsertElementInst::isValidOperands(IE
.getOperand(0), IE
.getOperand(1),
3856 "Invalid insertelement operands!", &IE
);
3857 visitInstruction(IE
);
3860 void Verifier::visitShuffleVectorInst(ShuffleVectorInst
&SV
) {
3861 Check(ShuffleVectorInst::isValidOperands(SV
.getOperand(0), SV
.getOperand(1),
3862 SV
.getShuffleMask()),
3863 "Invalid shufflevector operands!", &SV
);
3864 visitInstruction(SV
);
3867 void Verifier::visitGetElementPtrInst(GetElementPtrInst
&GEP
) {
3868 Type
*TargetTy
= GEP
.getPointerOperandType()->getScalarType();
3870 Check(isa
<PointerType
>(TargetTy
),
3871 "GEP base pointer is not a vector or a vector of pointers", &GEP
);
3872 Check(GEP
.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP
);
3874 if (auto *STy
= dyn_cast
<StructType
>(GEP
.getSourceElementType())) {
3875 SmallPtrSet
<Type
*, 4> Visited
;
3876 Check(!STy
->containsScalableVectorType(&Visited
),
3877 "getelementptr cannot target structure that contains scalable vector"
3882 SmallVector
<Value
*, 16> Idxs(GEP
.indices());
3884 all_of(Idxs
, [](Value
*V
) { return V
->getType()->isIntOrIntVectorTy(); }),
3885 "GEP indexes must be integers", &GEP
);
3887 GetElementPtrInst::getIndexedType(GEP
.getSourceElementType(), Idxs
);
3888 Check(ElTy
, "Invalid indices for GEP pointer type!", &GEP
);
3890 Check(GEP
.getType()->isPtrOrPtrVectorTy() &&
3891 GEP
.getResultElementType() == ElTy
,
3892 "GEP is not of right type for indices!", &GEP
, ElTy
);
3894 if (auto *GEPVTy
= dyn_cast
<VectorType
>(GEP
.getType())) {
3895 // Additional checks for vector GEPs.
3896 ElementCount GEPWidth
= GEPVTy
->getElementCount();
3897 if (GEP
.getPointerOperandType()->isVectorTy())
3900 cast
<VectorType
>(GEP
.getPointerOperandType())->getElementCount(),
3901 "Vector GEP result width doesn't match operand's", &GEP
);
3902 for (Value
*Idx
: Idxs
) {
3903 Type
*IndexTy
= Idx
->getType();
3904 if (auto *IndexVTy
= dyn_cast
<VectorType
>(IndexTy
)) {
3905 ElementCount IndexWidth
= IndexVTy
->getElementCount();
3906 Check(IndexWidth
== GEPWidth
, "Invalid GEP index vector width", &GEP
);
3908 Check(IndexTy
->isIntOrIntVectorTy(),
3909 "All GEP indices should be of integer type");
3913 if (auto *PTy
= dyn_cast
<PointerType
>(GEP
.getType())) {
3914 Check(GEP
.getAddressSpace() == PTy
->getAddressSpace(),
3915 "GEP address space doesn't match type", &GEP
);
3918 visitInstruction(GEP
);
3921 static bool isContiguous(const ConstantRange
&A
, const ConstantRange
&B
) {
3922 return A
.getUpper() == B
.getLower() || A
.getLower() == B
.getUpper();
3925 /// Verify !range and !absolute_symbol metadata. These have the same
3926 /// restrictions, except !absolute_symbol allows the full set.
3927 void Verifier::verifyRangeMetadata(const Value
&I
, const MDNode
*Range
,
3928 Type
*Ty
, bool IsAbsoluteSymbol
) {
3929 unsigned NumOperands
= Range
->getNumOperands();
3930 Check(NumOperands
% 2 == 0, "Unfinished range!", Range
);
3931 unsigned NumRanges
= NumOperands
/ 2;
3932 Check(NumRanges
>= 1, "It should have at least one range!", Range
);
3934 ConstantRange
LastRange(1, true); // Dummy initial value
3935 for (unsigned i
= 0; i
< NumRanges
; ++i
) {
3937 mdconst::dyn_extract
<ConstantInt
>(Range
->getOperand(2 * i
));
3938 Check(Low
, "The lower limit must be an integer!", Low
);
3940 mdconst::dyn_extract
<ConstantInt
>(Range
->getOperand(2 * i
+ 1));
3941 Check(High
, "The upper limit must be an integer!", High
);
3942 Check(High
->getType() == Low
->getType() &&
3943 High
->getType() == Ty
->getScalarType(),
3944 "Range types must match instruction type!", &I
);
3946 APInt HighV
= High
->getValue();
3947 APInt LowV
= Low
->getValue();
3949 // ConstantRange asserts if the ranges are the same except for the min/max
3950 // value. Leave the cases it tolerates for the empty range error below.
3951 Check(LowV
!= HighV
|| LowV
.isMaxValue() || LowV
.isMinValue(),
3952 "The upper and lower limits cannot be the same value", &I
);
3954 ConstantRange
CurRange(LowV
, HighV
);
3955 Check(!CurRange
.isEmptySet() && (IsAbsoluteSymbol
|| !CurRange
.isFullSet()),
3956 "Range must not be empty!", Range
);
3958 Check(CurRange
.intersectWith(LastRange
).isEmptySet(),
3959 "Intervals are overlapping", Range
);
3960 Check(LowV
.sgt(LastRange
.getLower()), "Intervals are not in order",
3962 Check(!isContiguous(CurRange
, LastRange
), "Intervals are contiguous",
3965 LastRange
= ConstantRange(LowV
, HighV
);
3967 if (NumRanges
> 2) {
3969 mdconst::dyn_extract
<ConstantInt
>(Range
->getOperand(0))->getValue();
3971 mdconst::dyn_extract
<ConstantInt
>(Range
->getOperand(1))->getValue();
3972 ConstantRange
FirstRange(FirstLow
, FirstHigh
);
3973 Check(FirstRange
.intersectWith(LastRange
).isEmptySet(),
3974 "Intervals are overlapping", Range
);
3975 Check(!isContiguous(FirstRange
, LastRange
), "Intervals are contiguous",
3980 void Verifier::visitRangeMetadata(Instruction
&I
, MDNode
*Range
, Type
*Ty
) {
3981 assert(Range
&& Range
== I
.getMetadata(LLVMContext::MD_range
) &&
3982 "precondition violation");
3983 verifyRangeMetadata(I
, Range
, Ty
, false);
3986 void Verifier::checkAtomicMemAccessSize(Type
*Ty
, const Instruction
*I
) {
3987 unsigned Size
= DL
.getTypeSizeInBits(Ty
);
3988 Check(Size
>= 8, "atomic memory access' size must be byte-sized", Ty
, I
);
3989 Check(!(Size
& (Size
- 1)),
3990 "atomic memory access' operand must have a power-of-two size", Ty
, I
);
3993 void Verifier::visitLoadInst(LoadInst
&LI
) {
3994 PointerType
*PTy
= dyn_cast
<PointerType
>(LI
.getOperand(0)->getType());
3995 Check(PTy
, "Load operand must be a pointer.", &LI
);
3996 Type
*ElTy
= LI
.getType();
3997 if (MaybeAlign A
= LI
.getAlign()) {
3998 Check(A
->value() <= Value::MaximumAlignment
,
3999 "huge alignment values are unsupported", &LI
);
4001 Check(ElTy
->isSized(), "loading unsized types is not allowed", &LI
);
4002 if (LI
.isAtomic()) {
4003 Check(LI
.getOrdering() != AtomicOrdering::Release
&&
4004 LI
.getOrdering() != AtomicOrdering::AcquireRelease
,
4005 "Load cannot have Release ordering", &LI
);
4006 Check(ElTy
->isIntOrPtrTy() || ElTy
->isFloatingPointTy(),
4007 "atomic load operand must have integer, pointer, or floating point "
4010 checkAtomicMemAccessSize(ElTy
, &LI
);
4012 Check(LI
.getSyncScopeID() == SyncScope::System
,
4013 "Non-atomic load cannot have SynchronizationScope specified", &LI
);
4016 visitInstruction(LI
);
4019 void Verifier::visitStoreInst(StoreInst
&SI
) {
4020 PointerType
*PTy
= dyn_cast
<PointerType
>(SI
.getOperand(1)->getType());
4021 Check(PTy
, "Store operand must be a pointer.", &SI
);
4022 Type
*ElTy
= SI
.getOperand(0)->getType();
4023 if (MaybeAlign A
= SI
.getAlign()) {
4024 Check(A
->value() <= Value::MaximumAlignment
,
4025 "huge alignment values are unsupported", &SI
);
4027 Check(ElTy
->isSized(), "storing unsized types is not allowed", &SI
);
4028 if (SI
.isAtomic()) {
4029 Check(SI
.getOrdering() != AtomicOrdering::Acquire
&&
4030 SI
.getOrdering() != AtomicOrdering::AcquireRelease
,
4031 "Store cannot have Acquire ordering", &SI
);
4032 Check(ElTy
->isIntOrPtrTy() || ElTy
->isFloatingPointTy(),
4033 "atomic store operand must have integer, pointer, or floating point "
4036 checkAtomicMemAccessSize(ElTy
, &SI
);
4038 Check(SI
.getSyncScopeID() == SyncScope::System
,
4039 "Non-atomic store cannot have SynchronizationScope specified", &SI
);
4041 visitInstruction(SI
);
4044 /// Check that SwiftErrorVal is used as a swifterror argument in CS.
4045 void Verifier::verifySwiftErrorCall(CallBase
&Call
,
4046 const Value
*SwiftErrorVal
) {
4047 for (const auto &I
: llvm::enumerate(Call
.args())) {
4048 if (I
.value() == SwiftErrorVal
) {
4049 Check(Call
.paramHasAttr(I
.index(), Attribute::SwiftError
),
4050 "swifterror value when used in a callsite should be marked "
4051 "with swifterror attribute",
4052 SwiftErrorVal
, Call
);
4057 void Verifier::verifySwiftErrorValue(const Value
*SwiftErrorVal
) {
4058 // Check that swifterror value is only used by loads, stores, or as
4059 // a swifterror argument.
4060 for (const User
*U
: SwiftErrorVal
->users()) {
4061 Check(isa
<LoadInst
>(U
) || isa
<StoreInst
>(U
) || isa
<CallInst
>(U
) ||
4063 "swifterror value can only be loaded and stored from, or "
4064 "as a swifterror argument!",
4066 // If it is used by a store, check it is the second operand.
4067 if (auto StoreI
= dyn_cast
<StoreInst
>(U
))
4068 Check(StoreI
->getOperand(1) == SwiftErrorVal
,
4069 "swifterror value should be the second operand when used "
4072 if (auto *Call
= dyn_cast
<CallBase
>(U
))
4073 verifySwiftErrorCall(*const_cast<CallBase
*>(Call
), SwiftErrorVal
);
4077 void Verifier::visitAllocaInst(AllocaInst
&AI
) {
4078 SmallPtrSet
<Type
*, 4> Visited
;
4079 Check(AI
.getAllocatedType()->isSized(&Visited
),
4080 "Cannot allocate unsized type", &AI
);
4081 Check(AI
.getArraySize()->getType()->isIntegerTy(),
4082 "Alloca array size must have integer type", &AI
);
4083 if (MaybeAlign A
= AI
.getAlign()) {
4084 Check(A
->value() <= Value::MaximumAlignment
,
4085 "huge alignment values are unsupported", &AI
);
4088 if (AI
.isSwiftError()) {
4089 Check(AI
.getAllocatedType()->isPointerTy(),
4090 "swifterror alloca must have pointer type", &AI
);
4091 Check(!AI
.isArrayAllocation(),
4092 "swifterror alloca must not be array allocation", &AI
);
4093 verifySwiftErrorValue(&AI
);
4096 visitInstruction(AI
);
4099 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst
&CXI
) {
4100 Type
*ElTy
= CXI
.getOperand(1)->getType();
4101 Check(ElTy
->isIntOrPtrTy(),
4102 "cmpxchg operand must have integer or pointer type", ElTy
, &CXI
);
4103 checkAtomicMemAccessSize(ElTy
, &CXI
);
4104 visitInstruction(CXI
);
4107 void Verifier::visitAtomicRMWInst(AtomicRMWInst
&RMWI
) {
4108 Check(RMWI
.getOrdering() != AtomicOrdering::Unordered
,
4109 "atomicrmw instructions cannot be unordered.", &RMWI
);
4110 auto Op
= RMWI
.getOperation();
4111 Type
*ElTy
= RMWI
.getOperand(1)->getType();
4112 if (Op
== AtomicRMWInst::Xchg
) {
4113 Check(ElTy
->isIntegerTy() || ElTy
->isFloatingPointTy() ||
4114 ElTy
->isPointerTy(),
4115 "atomicrmw " + AtomicRMWInst::getOperationName(Op
) +
4116 " operand must have integer or floating point type!",
4118 } else if (AtomicRMWInst::isFPOperation(Op
)) {
4119 Check(ElTy
->isFloatingPointTy(),
4120 "atomicrmw " + AtomicRMWInst::getOperationName(Op
) +
4121 " operand must have floating point type!",
4124 Check(ElTy
->isIntegerTy(),
4125 "atomicrmw " + AtomicRMWInst::getOperationName(Op
) +
4126 " operand must have integer type!",
4129 checkAtomicMemAccessSize(ElTy
, &RMWI
);
4130 Check(AtomicRMWInst::FIRST_BINOP
<= Op
&& Op
<= AtomicRMWInst::LAST_BINOP
,
4131 "Invalid binary operation!", &RMWI
);
4132 visitInstruction(RMWI
);
4135 void Verifier::visitFenceInst(FenceInst
&FI
) {
4136 const AtomicOrdering Ordering
= FI
.getOrdering();
4137 Check(Ordering
== AtomicOrdering::Acquire
||
4138 Ordering
== AtomicOrdering::Release
||
4139 Ordering
== AtomicOrdering::AcquireRelease
||
4140 Ordering
== AtomicOrdering::SequentiallyConsistent
,
4141 "fence instructions may only have acquire, release, acq_rel, or "
4142 "seq_cst ordering.",
4144 visitInstruction(FI
);
4147 void Verifier::visitExtractValueInst(ExtractValueInst
&EVI
) {
4148 Check(ExtractValueInst::getIndexedType(EVI
.getAggregateOperand()->getType(),
4149 EVI
.getIndices()) == EVI
.getType(),
4150 "Invalid ExtractValueInst operands!", &EVI
);
4152 visitInstruction(EVI
);
4155 void Verifier::visitInsertValueInst(InsertValueInst
&IVI
) {
4156 Check(ExtractValueInst::getIndexedType(IVI
.getAggregateOperand()->getType(),
4157 IVI
.getIndices()) ==
4158 IVI
.getOperand(1)->getType(),
4159 "Invalid InsertValueInst operands!", &IVI
);
4161 visitInstruction(IVI
);
4164 static Value
*getParentPad(Value
*EHPad
) {
4165 if (auto *FPI
= dyn_cast
<FuncletPadInst
>(EHPad
))
4166 return FPI
->getParentPad();
4168 return cast
<CatchSwitchInst
>(EHPad
)->getParentPad();
4171 void Verifier::visitEHPadPredecessors(Instruction
&I
) {
4172 assert(I
.isEHPad());
4174 BasicBlock
*BB
= I
.getParent();
4175 Function
*F
= BB
->getParent();
4177 Check(BB
!= &F
->getEntryBlock(), "EH pad cannot be in entry block.", &I
);
4179 if (auto *LPI
= dyn_cast
<LandingPadInst
>(&I
)) {
4180 // The landingpad instruction defines its parent as a landing pad block. The
4181 // landing pad block may be branched to only by the unwind edge of an
4183 for (BasicBlock
*PredBB
: predecessors(BB
)) {
4184 const auto *II
= dyn_cast
<InvokeInst
>(PredBB
->getTerminator());
4185 Check(II
&& II
->getUnwindDest() == BB
&& II
->getNormalDest() != BB
,
4186 "Block containing LandingPadInst must be jumped to "
4187 "only by the unwind edge of an invoke.",
4192 if (auto *CPI
= dyn_cast
<CatchPadInst
>(&I
)) {
4193 if (!pred_empty(BB
))
4194 Check(BB
->getUniquePredecessor() == CPI
->getCatchSwitch()->getParent(),
4195 "Block containg CatchPadInst must be jumped to "
4196 "only by its catchswitch.",
4198 Check(BB
!= CPI
->getCatchSwitch()->getUnwindDest(),
4199 "Catchswitch cannot unwind to one of its catchpads",
4200 CPI
->getCatchSwitch(), CPI
);
4204 // Verify that each pred has a legal terminator with a legal to/from EH
4205 // pad relationship.
4206 Instruction
*ToPad
= &I
;
4207 Value
*ToPadParent
= getParentPad(ToPad
);
4208 for (BasicBlock
*PredBB
: predecessors(BB
)) {
4209 Instruction
*TI
= PredBB
->getTerminator();
4211 if (auto *II
= dyn_cast
<InvokeInst
>(TI
)) {
4212 Check(II
->getUnwindDest() == BB
&& II
->getNormalDest() != BB
,
4213 "EH pad must be jumped to via an unwind edge", ToPad
, II
);
4214 if (auto Bundle
= II
->getOperandBundle(LLVMContext::OB_funclet
))
4215 FromPad
= Bundle
->Inputs
[0];
4217 FromPad
= ConstantTokenNone::get(II
->getContext());
4218 } else if (auto *CRI
= dyn_cast
<CleanupReturnInst
>(TI
)) {
4219 FromPad
= CRI
->getOperand(0);
4220 Check(FromPad
!= ToPadParent
, "A cleanupret must exit its cleanup", CRI
);
4221 } else if (auto *CSI
= dyn_cast
<CatchSwitchInst
>(TI
)) {
4224 Check(false, "EH pad must be jumped to via an unwind edge", ToPad
, TI
);
4227 // The edge may exit from zero or more nested pads.
4228 SmallSet
<Value
*, 8> Seen
;
4229 for (;; FromPad
= getParentPad(FromPad
)) {
4230 Check(FromPad
!= ToPad
,
4231 "EH pad cannot handle exceptions raised within it", FromPad
, TI
);
4232 if (FromPad
== ToPadParent
) {
4233 // This is a legal unwind edge.
4236 Check(!isa
<ConstantTokenNone
>(FromPad
),
4237 "A single unwind edge may only enter one EH pad", TI
);
4238 Check(Seen
.insert(FromPad
).second
, "EH pad jumps through a cycle of pads",
4241 // This will be diagnosed on the corresponding instruction already. We
4242 // need the extra check here to make sure getParentPad() works.
4243 Check(isa
<FuncletPadInst
>(FromPad
) || isa
<CatchSwitchInst
>(FromPad
),
4244 "Parent pad must be catchpad/cleanuppad/catchswitch", TI
);
4249 void Verifier::visitLandingPadInst(LandingPadInst
&LPI
) {
4250 // The landingpad instruction is ill-formed if it doesn't have any clauses and
4252 Check(LPI
.getNumClauses() > 0 || LPI
.isCleanup(),
4253 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI
);
4255 visitEHPadPredecessors(LPI
);
4257 if (!LandingPadResultTy
)
4258 LandingPadResultTy
= LPI
.getType();
4260 Check(LandingPadResultTy
== LPI
.getType(),
4261 "The landingpad instruction should have a consistent result type "
4262 "inside a function.",
4265 Function
*F
= LPI
.getParent()->getParent();
4266 Check(F
->hasPersonalityFn(),
4267 "LandingPadInst needs to be in a function with a personality.", &LPI
);
4269 // The landingpad instruction must be the first non-PHI instruction in the
4271 Check(LPI
.getParent()->getLandingPadInst() == &LPI
,
4272 "LandingPadInst not the first non-PHI instruction in the block.", &LPI
);
4274 for (unsigned i
= 0, e
= LPI
.getNumClauses(); i
< e
; ++i
) {
4275 Constant
*Clause
= LPI
.getClause(i
);
4276 if (LPI
.isCatch(i
)) {
4277 Check(isa
<PointerType
>(Clause
->getType()),
4278 "Catch operand does not have pointer type!", &LPI
);
4280 Check(LPI
.isFilter(i
), "Clause is neither catch nor filter!", &LPI
);
4281 Check(isa
<ConstantArray
>(Clause
) || isa
<ConstantAggregateZero
>(Clause
),
4282 "Filter operand is not an array of constants!", &LPI
);
4286 visitInstruction(LPI
);
4289 void Verifier::visitResumeInst(ResumeInst
&RI
) {
4290 Check(RI
.getFunction()->hasPersonalityFn(),
4291 "ResumeInst needs to be in a function with a personality.", &RI
);
4293 if (!LandingPadResultTy
)
4294 LandingPadResultTy
= RI
.getValue()->getType();
4296 Check(LandingPadResultTy
== RI
.getValue()->getType(),
4297 "The resume instruction should have a consistent result type "
4298 "inside a function.",
4301 visitTerminator(RI
);
4304 void Verifier::visitCatchPadInst(CatchPadInst
&CPI
) {
4305 BasicBlock
*BB
= CPI
.getParent();
4307 Function
*F
= BB
->getParent();
4308 Check(F
->hasPersonalityFn(),
4309 "CatchPadInst needs to be in a function with a personality.", &CPI
);
4311 Check(isa
<CatchSwitchInst
>(CPI
.getParentPad()),
4312 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4313 CPI
.getParentPad());
4315 // The catchpad instruction must be the first non-PHI instruction in the
4317 Check(BB
->getFirstNonPHI() == &CPI
,
4318 "CatchPadInst not the first non-PHI instruction in the block.", &CPI
);
4320 visitEHPadPredecessors(CPI
);
4321 visitFuncletPadInst(CPI
);
4324 void Verifier::visitCatchReturnInst(CatchReturnInst
&CatchReturn
) {
4325 Check(isa
<CatchPadInst
>(CatchReturn
.getOperand(0)),
4326 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn
,
4327 CatchReturn
.getOperand(0));
4329 visitTerminator(CatchReturn
);
4332 void Verifier::visitCleanupPadInst(CleanupPadInst
&CPI
) {
4333 BasicBlock
*BB
= CPI
.getParent();
4335 Function
*F
= BB
->getParent();
4336 Check(F
->hasPersonalityFn(),
4337 "CleanupPadInst needs to be in a function with a personality.", &CPI
);
4339 // The cleanuppad instruction must be the first non-PHI instruction in the
4341 Check(BB
->getFirstNonPHI() == &CPI
,
4342 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI
);
4344 auto *ParentPad
= CPI
.getParentPad();
4345 Check(isa
<ConstantTokenNone
>(ParentPad
) || isa
<FuncletPadInst
>(ParentPad
),
4346 "CleanupPadInst has an invalid parent.", &CPI
);
4348 visitEHPadPredecessors(CPI
);
4349 visitFuncletPadInst(CPI
);
4352 void Verifier::visitFuncletPadInst(FuncletPadInst
&FPI
) {
4353 User
*FirstUser
= nullptr;
4354 Value
*FirstUnwindPad
= nullptr;
4355 SmallVector
<FuncletPadInst
*, 8> Worklist({&FPI
});
4356 SmallSet
<FuncletPadInst
*, 8> Seen
;
4358 while (!Worklist
.empty()) {
4359 FuncletPadInst
*CurrentPad
= Worklist
.pop_back_val();
4360 Check(Seen
.insert(CurrentPad
).second
,
4361 "FuncletPadInst must not be nested within itself", CurrentPad
);
4362 Value
*UnresolvedAncestorPad
= nullptr;
4363 for (User
*U
: CurrentPad
->users()) {
4364 BasicBlock
*UnwindDest
;
4365 if (auto *CRI
= dyn_cast
<CleanupReturnInst
>(U
)) {
4366 UnwindDest
= CRI
->getUnwindDest();
4367 } else if (auto *CSI
= dyn_cast
<CatchSwitchInst
>(U
)) {
4368 // We allow catchswitch unwind to caller to nest
4369 // within an outer pad that unwinds somewhere else,
4370 // because catchswitch doesn't have a nounwind variant.
4371 // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
4372 if (CSI
->unwindsToCaller())
4374 UnwindDest
= CSI
->getUnwindDest();
4375 } else if (auto *II
= dyn_cast
<InvokeInst
>(U
)) {
4376 UnwindDest
= II
->getUnwindDest();
4377 } else if (isa
<CallInst
>(U
)) {
4378 // Calls which don't unwind may be found inside funclet
4379 // pads that unwind somewhere else. We don't *require*
4380 // such calls to be annotated nounwind.
4382 } else if (auto *CPI
= dyn_cast
<CleanupPadInst
>(U
)) {
4383 // The unwind dest for a cleanup can only be found by
4384 // recursive search. Add it to the worklist, and we'll
4385 // search for its first use that determines where it unwinds.
4386 Worklist
.push_back(CPI
);
4389 Check(isa
<CatchReturnInst
>(U
), "Bogus funclet pad use", U
);
4396 UnwindPad
= UnwindDest
->getFirstNonPHI();
4397 if (!cast
<Instruction
>(UnwindPad
)->isEHPad())
4399 Value
*UnwindParent
= getParentPad(UnwindPad
);
4400 // Ignore unwind edges that don't exit CurrentPad.
4401 if (UnwindParent
== CurrentPad
)
4403 // Determine whether the original funclet pad is exited,
4404 // and if we are scanning nested pads determine how many
4405 // of them are exited so we can stop searching their
4407 Value
*ExitedPad
= CurrentPad
;
4410 if (ExitedPad
== &FPI
) {
4412 // Now we can resolve any ancestors of CurrentPad up to
4413 // FPI, but not including FPI since we need to make sure
4414 // to check all direct users of FPI for consistency.
4415 UnresolvedAncestorPad
= &FPI
;
4418 Value
*ExitedParent
= getParentPad(ExitedPad
);
4419 if (ExitedParent
== UnwindParent
) {
4420 // ExitedPad is the ancestor-most pad which this unwind
4421 // edge exits, so we can resolve up to it, meaning that
4422 // ExitedParent is the first ancestor still unresolved.
4423 UnresolvedAncestorPad
= ExitedParent
;
4426 ExitedPad
= ExitedParent
;
4427 } while (!isa
<ConstantTokenNone
>(ExitedPad
));
4429 // Unwinding to caller exits all pads.
4430 UnwindPad
= ConstantTokenNone::get(FPI
.getContext());
4432 UnresolvedAncestorPad
= &FPI
;
4436 // This unwind edge exits FPI. Make sure it agrees with other
4439 Check(UnwindPad
== FirstUnwindPad
,
4440 "Unwind edges out of a funclet "
4441 "pad must have the same unwind "
4443 &FPI
, U
, FirstUser
);
4446 FirstUnwindPad
= UnwindPad
;
4447 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
4448 if (isa
<CleanupPadInst
>(&FPI
) && !isa
<ConstantTokenNone
>(UnwindPad
) &&
4449 getParentPad(UnwindPad
) == getParentPad(&FPI
))
4450 SiblingFuncletInfo
[&FPI
] = cast
<Instruction
>(U
);
4453 // Make sure we visit all uses of FPI, but for nested pads stop as
4454 // soon as we know where they unwind to.
4455 if (CurrentPad
!= &FPI
)
4458 if (UnresolvedAncestorPad
) {
4459 if (CurrentPad
== UnresolvedAncestorPad
) {
4460 // When CurrentPad is FPI itself, we don't mark it as resolved even if
4461 // we've found an unwind edge that exits it, because we need to verify
4462 // all direct uses of FPI.
4463 assert(CurrentPad
== &FPI
);
4466 // Pop off the worklist any nested pads that we've found an unwind
4467 // destination for. The pads on the worklist are the uncles,
4468 // great-uncles, etc. of CurrentPad. We've found an unwind destination
4469 // for all ancestors of CurrentPad up to but not including
4470 // UnresolvedAncestorPad.
4471 Value
*ResolvedPad
= CurrentPad
;
4472 while (!Worklist
.empty()) {
4473 Value
*UnclePad
= Worklist
.back();
4474 Value
*AncestorPad
= getParentPad(UnclePad
);
4475 // Walk ResolvedPad up the ancestor list until we either find the
4476 // uncle's parent or the last resolved ancestor.
4477 while (ResolvedPad
!= AncestorPad
) {
4478 Value
*ResolvedParent
= getParentPad(ResolvedPad
);
4479 if (ResolvedParent
== UnresolvedAncestorPad
) {
4482 ResolvedPad
= ResolvedParent
;
4484 // If the resolved ancestor search didn't find the uncle's parent,
4485 // then the uncle is not yet resolved.
4486 if (ResolvedPad
!= AncestorPad
)
4488 // This uncle is resolved, so pop it from the worklist.
4489 Worklist
.pop_back();
4494 if (FirstUnwindPad
) {
4495 if (auto *CatchSwitch
= dyn_cast
<CatchSwitchInst
>(FPI
.getParentPad())) {
4496 BasicBlock
*SwitchUnwindDest
= CatchSwitch
->getUnwindDest();
4497 Value
*SwitchUnwindPad
;
4498 if (SwitchUnwindDest
)
4499 SwitchUnwindPad
= SwitchUnwindDest
->getFirstNonPHI();
4501 SwitchUnwindPad
= ConstantTokenNone::get(FPI
.getContext());
4502 Check(SwitchUnwindPad
== FirstUnwindPad
,
4503 "Unwind edges out of a catch must have the same unwind dest as "
4504 "the parent catchswitch",
4505 &FPI
, FirstUser
, CatchSwitch
);
4509 visitInstruction(FPI
);
4512 void Verifier::visitCatchSwitchInst(CatchSwitchInst
&CatchSwitch
) {
4513 BasicBlock
*BB
= CatchSwitch
.getParent();
4515 Function
*F
= BB
->getParent();
4516 Check(F
->hasPersonalityFn(),
4517 "CatchSwitchInst needs to be in a function with a personality.",
4520 // The catchswitch instruction must be the first non-PHI instruction in the
4522 Check(BB
->getFirstNonPHI() == &CatchSwitch
,
4523 "CatchSwitchInst not the first non-PHI instruction in the block.",
4526 auto *ParentPad
= CatchSwitch
.getParentPad();
4527 Check(isa
<ConstantTokenNone
>(ParentPad
) || isa
<FuncletPadInst
>(ParentPad
),
4528 "CatchSwitchInst has an invalid parent.", ParentPad
);
4530 if (BasicBlock
*UnwindDest
= CatchSwitch
.getUnwindDest()) {
4531 Instruction
*I
= UnwindDest
->getFirstNonPHI();
4532 Check(I
->isEHPad() && !isa
<LandingPadInst
>(I
),
4533 "CatchSwitchInst must unwind to an EH block which is not a "
4537 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
4538 if (getParentPad(I
) == ParentPad
)
4539 SiblingFuncletInfo
[&CatchSwitch
] = &CatchSwitch
;
4542 Check(CatchSwitch
.getNumHandlers() != 0,
4543 "CatchSwitchInst cannot have empty handler list", &CatchSwitch
);
4545 for (BasicBlock
*Handler
: CatchSwitch
.handlers()) {
4546 Check(isa
<CatchPadInst
>(Handler
->getFirstNonPHI()),
4547 "CatchSwitchInst handlers must be catchpads", &CatchSwitch
, Handler
);
4550 visitEHPadPredecessors(CatchSwitch
);
4551 visitTerminator(CatchSwitch
);
4554 void Verifier::visitCleanupReturnInst(CleanupReturnInst
&CRI
) {
4555 Check(isa
<CleanupPadInst
>(CRI
.getOperand(0)),
4556 "CleanupReturnInst needs to be provided a CleanupPad", &CRI
,
4559 if (BasicBlock
*UnwindDest
= CRI
.getUnwindDest()) {
4560 Instruction
*I
= UnwindDest
->getFirstNonPHI();
4561 Check(I
->isEHPad() && !isa
<LandingPadInst
>(I
),
4562 "CleanupReturnInst must unwind to an EH block which is not a "
4567 visitTerminator(CRI
);
4570 void Verifier::verifyDominatesUse(Instruction
&I
, unsigned i
) {
4571 Instruction
*Op
= cast
<Instruction
>(I
.getOperand(i
));
4572 // If the we have an invalid invoke, don't try to compute the dominance.
4573 // We already reject it in the invoke specific checks and the dominance
4574 // computation doesn't handle multiple edges.
4575 if (InvokeInst
*II
= dyn_cast
<InvokeInst
>(Op
)) {
4576 if (II
->getNormalDest() == II
->getUnwindDest())
4580 // Quick check whether the def has already been encountered in the same block.
4581 // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
4582 // uses are defined to happen on the incoming edge, not at the instruction.
4584 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
4585 // wrapping an SSA value, assert that we've already encountered it. See
4586 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
4587 if (!isa
<PHINode
>(I
) && InstsInThisBlock
.count(Op
))
4590 const Use
&U
= I
.getOperandUse(i
);
4591 Check(DT
.dominates(Op
, U
), "Instruction does not dominate all uses!", Op
, &I
);
4594 void Verifier::visitDereferenceableMetadata(Instruction
& I
, MDNode
* MD
) {
4595 Check(I
.getType()->isPointerTy(),
4596 "dereferenceable, dereferenceable_or_null "
4597 "apply only to pointer types",
4599 Check((isa
<LoadInst
>(I
) || isa
<IntToPtrInst
>(I
)),
4600 "dereferenceable, dereferenceable_or_null apply only to load"
4601 " and inttoptr instructions, use attributes for calls or invokes",
4603 Check(MD
->getNumOperands() == 1,
4604 "dereferenceable, dereferenceable_or_null "
4605 "take one operand!",
4607 ConstantInt
*CI
= mdconst::dyn_extract
<ConstantInt
>(MD
->getOperand(0));
4608 Check(CI
&& CI
->getType()->isIntegerTy(64),
4610 "dereferenceable_or_null metadata value must be an i64!",
4614 void Verifier::visitProfMetadata(Instruction
&I
, MDNode
*MD
) {
4615 Check(MD
->getNumOperands() >= 2,
4616 "!prof annotations should have no less than 2 operands", MD
);
4618 // Check first operand.
4619 Check(MD
->getOperand(0) != nullptr, "first operand should not be null", MD
);
4620 Check(isa
<MDString
>(MD
->getOperand(0)),
4621 "expected string with name of the !prof annotation", MD
);
4622 MDString
*MDS
= cast
<MDString
>(MD
->getOperand(0));
4623 StringRef ProfName
= MDS
->getString();
4625 // Check consistency of !prof branch_weights metadata.
4626 if (ProfName
.equals("branch_weights")) {
4627 if (isa
<InvokeInst
>(&I
)) {
4628 Check(MD
->getNumOperands() == 2 || MD
->getNumOperands() == 3,
4629 "Wrong number of InvokeInst branch_weights operands", MD
);
4631 unsigned ExpectedNumOperands
= 0;
4632 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(&I
))
4633 ExpectedNumOperands
= BI
->getNumSuccessors();
4634 else if (SwitchInst
*SI
= dyn_cast
<SwitchInst
>(&I
))
4635 ExpectedNumOperands
= SI
->getNumSuccessors();
4636 else if (isa
<CallInst
>(&I
))
4637 ExpectedNumOperands
= 1;
4638 else if (IndirectBrInst
*IBI
= dyn_cast
<IndirectBrInst
>(&I
))
4639 ExpectedNumOperands
= IBI
->getNumDestinations();
4640 else if (isa
<SelectInst
>(&I
))
4641 ExpectedNumOperands
= 2;
4642 else if (CallBrInst
*CI
= dyn_cast
<CallBrInst
>(&I
))
4643 ExpectedNumOperands
= CI
->getNumSuccessors();
4645 CheckFailed("!prof branch_weights are not allowed for this instruction",
4648 Check(MD
->getNumOperands() == 1 + ExpectedNumOperands
,
4649 "Wrong number of operands", MD
);
4651 for (unsigned i
= 1; i
< MD
->getNumOperands(); ++i
) {
4652 auto &MDO
= MD
->getOperand(i
);
4653 Check(MDO
, "second operand should not be null", MD
);
4654 Check(mdconst::dyn_extract
<ConstantInt
>(MDO
),
4655 "!prof brunch_weights operand is not a const int");
4660 void Verifier::visitDIAssignIDMetadata(Instruction
&I
, MDNode
*MD
) {
4661 assert(I
.hasMetadata(LLVMContext::MD_DIAssignID
));
4662 bool ExpectedInstTy
=
4663 isa
<AllocaInst
>(I
) || isa
<StoreInst
>(I
) || isa
<MemIntrinsic
>(I
);
4664 CheckDI(ExpectedInstTy
, "!DIAssignID attached to unexpected instruction kind",
4666 // Iterate over the MetadataAsValue uses of the DIAssignID - these should
4667 // only be found as DbgAssignIntrinsic operands.
4668 if (auto *AsValue
= MetadataAsValue::getIfExists(Context
, MD
)) {
4669 for (auto *User
: AsValue
->users()) {
4670 CheckDI(isa
<DbgAssignIntrinsic
>(User
),
4671 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
4673 // All of the dbg.assign intrinsics should be in the same function as I.
4674 if (auto *DAI
= dyn_cast
<DbgAssignIntrinsic
>(User
))
4675 CheckDI(DAI
->getFunction() == I
.getFunction(),
4676 "dbg.assign not in same function as inst", DAI
, &I
);
4681 void Verifier::visitCallStackMetadata(MDNode
*MD
) {
4682 // Call stack metadata should consist of a list of at least 1 constant int
4683 // (representing a hash of the location).
4684 Check(MD
->getNumOperands() >= 1,
4685 "call stack metadata should have at least 1 operand", MD
);
4687 for (const auto &Op
: MD
->operands())
4688 Check(mdconst::dyn_extract_or_null
<ConstantInt
>(Op
),
4689 "call stack metadata operand should be constant integer", Op
);
4692 void Verifier::visitMemProfMetadata(Instruction
&I
, MDNode
*MD
) {
4693 Check(isa
<CallBase
>(I
), "!memprof metadata should only exist on calls", &I
);
4694 Check(MD
->getNumOperands() >= 1,
4695 "!memprof annotations should have at least 1 metadata operand "
4700 for (auto &MIBOp
: MD
->operands()) {
4701 MDNode
*MIB
= dyn_cast
<MDNode
>(MIBOp
);
4702 // The first operand of an MIB should be the call stack metadata.
4703 // There rest of the operands should be MDString tags, and there should be
4705 Check(MIB
->getNumOperands() >= 2,
4706 "Each !memprof MemInfoBlock should have at least 2 operands", MIB
);
4708 // Check call stack metadata (first operand).
4709 Check(MIB
->getOperand(0) != nullptr,
4710 "!memprof MemInfoBlock first operand should not be null", MIB
);
4711 Check(isa
<MDNode
>(MIB
->getOperand(0)),
4712 "!memprof MemInfoBlock first operand should be an MDNode", MIB
);
4713 MDNode
*StackMD
= dyn_cast
<MDNode
>(MIB
->getOperand(0));
4714 visitCallStackMetadata(StackMD
);
4716 // Check that remaining operands are MDString.
4717 Check(llvm::all_of(llvm::drop_begin(MIB
->operands()),
4718 [](const MDOperand
&Op
) { return isa
<MDString
>(Op
); }),
4719 "Not all !memprof MemInfoBlock operands 1 to N are MDString", MIB
);
4723 void Verifier::visitCallsiteMetadata(Instruction
&I
, MDNode
*MD
) {
4724 Check(isa
<CallBase
>(I
), "!callsite metadata should only exist on calls", &I
);
4725 // Verify the partial callstack annotated from memprof profiles. This callsite
4726 // is a part of a profiled allocation callstack.
4727 visitCallStackMetadata(MD
);
4730 void Verifier::visitAnnotationMetadata(MDNode
*Annotation
) {
4731 Check(isa
<MDTuple
>(Annotation
), "annotation must be a tuple");
4732 Check(Annotation
->getNumOperands() >= 1,
4733 "annotation must have at least one operand");
4734 for (const MDOperand
&Op
: Annotation
->operands()) {
4735 bool TupleOfStrings
=
4736 isa
<MDTuple
>(Op
.get()) &&
4737 all_of(cast
<MDTuple
>(Op
)->operands(), [](auto &Annotation
) {
4738 return isa
<MDString
>(Annotation
.get());
4740 Check(isa
<MDString
>(Op
.get()) || TupleOfStrings
,
4741 "operands must be a string or a tuple of strings");
4745 void Verifier::visitAliasScopeMetadata(const MDNode
*MD
) {
4746 unsigned NumOps
= MD
->getNumOperands();
4747 Check(NumOps
>= 2 && NumOps
<= 3, "scope must have two or three operands",
4749 Check(MD
->getOperand(0).get() == MD
|| isa
<MDString
>(MD
->getOperand(0)),
4750 "first scope operand must be self-referential or string", MD
);
4752 Check(isa
<MDString
>(MD
->getOperand(2)),
4753 "third scope operand must be string (if used)", MD
);
4755 MDNode
*Domain
= dyn_cast
<MDNode
>(MD
->getOperand(1));
4756 Check(Domain
!= nullptr, "second scope operand must be MDNode", MD
);
4758 unsigned NumDomainOps
= Domain
->getNumOperands();
4759 Check(NumDomainOps
>= 1 && NumDomainOps
<= 2,
4760 "domain must have one or two operands", Domain
);
4761 Check(Domain
->getOperand(0).get() == Domain
||
4762 isa
<MDString
>(Domain
->getOperand(0)),
4763 "first domain operand must be self-referential or string", Domain
);
4764 if (NumDomainOps
== 2)
4765 Check(isa
<MDString
>(Domain
->getOperand(1)),
4766 "second domain operand must be string (if used)", Domain
);
4769 void Verifier::visitAliasScopeListMetadata(const MDNode
*MD
) {
4770 for (const MDOperand
&Op
: MD
->operands()) {
4771 const MDNode
*OpMD
= dyn_cast
<MDNode
>(Op
);
4772 Check(OpMD
!= nullptr, "scope list must consist of MDNodes", MD
);
4773 visitAliasScopeMetadata(OpMD
);
4777 void Verifier::visitAccessGroupMetadata(const MDNode
*MD
) {
4778 auto IsValidAccessScope
= [](const MDNode
*MD
) {
4779 return MD
->getNumOperands() == 0 && MD
->isDistinct();
4782 // It must be either an access scope itself...
4783 if (IsValidAccessScope(MD
))
4786 // ...or a list of access scopes.
4787 for (const MDOperand
&Op
: MD
->operands()) {
4788 const MDNode
*OpMD
= dyn_cast
<MDNode
>(Op
);
4789 Check(OpMD
!= nullptr, "Access scope list must consist of MDNodes", MD
);
4790 Check(IsValidAccessScope(OpMD
),
4791 "Access scope list contains invalid access scope", MD
);
4795 /// verifyInstruction - Verify that an instruction is well formed.
4797 void Verifier::visitInstruction(Instruction
&I
) {
4798 BasicBlock
*BB
= I
.getParent();
4799 Check(BB
, "Instruction not embedded in basic block!", &I
);
4801 if (!isa
<PHINode
>(I
)) { // Check that non-phi nodes are not self referential
4802 for (User
*U
: I
.users()) {
4803 Check(U
!= (User
*)&I
|| !DT
.isReachableFromEntry(BB
),
4804 "Only PHI nodes may reference their own value!", &I
);
4808 // Check that void typed values don't have names
4809 Check(!I
.getType()->isVoidTy() || !I
.hasName(),
4810 "Instruction has a name, but provides a void value!", &I
);
4812 // Check that the return value of the instruction is either void or a legal
4814 Check(I
.getType()->isVoidTy() || I
.getType()->isFirstClassType(),
4815 "Instruction returns a non-scalar type!", &I
);
4817 // Check that the instruction doesn't produce metadata. Calls are already
4818 // checked against the callee type.
4819 Check(!I
.getType()->isMetadataTy() || isa
<CallInst
>(I
) || isa
<InvokeInst
>(I
),
4820 "Invalid use of metadata!", &I
);
4822 // Check that all uses of the instruction, if they are instructions
4823 // themselves, actually have parent basic blocks. If the use is not an
4824 // instruction, it is an error!
4825 for (Use
&U
: I
.uses()) {
4826 if (Instruction
*Used
= dyn_cast
<Instruction
>(U
.getUser()))
4827 Check(Used
->getParent() != nullptr,
4828 "Instruction referencing"
4829 " instruction not embedded in a basic block!",
4832 CheckFailed("Use of instruction is not an instruction!", U
);
4837 // Get a pointer to the call base of the instruction if it is some form of
4839 const CallBase
*CBI
= dyn_cast
<CallBase
>(&I
);
4841 for (unsigned i
= 0, e
= I
.getNumOperands(); i
!= e
; ++i
) {
4842 Check(I
.getOperand(i
) != nullptr, "Instruction has null operand!", &I
);
4844 // Check to make sure that only first-class-values are operands to
4846 if (!I
.getOperand(i
)->getType()->isFirstClassType()) {
4847 Check(false, "Instruction operands must be first-class values!", &I
);
4850 if (Function
*F
= dyn_cast
<Function
>(I
.getOperand(i
))) {
4851 // This code checks whether the function is used as the operand of a
4852 // clang_arc_attachedcall operand bundle.
4853 auto IsAttachedCallOperand
= [](Function
*F
, const CallBase
*CBI
,
4855 return CBI
&& CBI
->isOperandBundleOfType(
4856 LLVMContext::OB_clang_arc_attachedcall
, Idx
);
4859 // Check to make sure that the "address of" an intrinsic function is never
4860 // taken. Ignore cases where the address of the intrinsic function is used
4861 // as the argument of operand bundle "clang.arc.attachedcall" as those
4862 // cases are handled in verifyAttachedCallBundle.
4863 Check((!F
->isIntrinsic() ||
4864 (CBI
&& &CBI
->getCalledOperandUse() == &I
.getOperandUse(i
)) ||
4865 IsAttachedCallOperand(F
, CBI
, i
)),
4866 "Cannot take the address of an intrinsic!", &I
);
4867 Check(!F
->isIntrinsic() || isa
<CallInst
>(I
) ||
4868 F
->getIntrinsicID() == Intrinsic::donothing
||
4869 F
->getIntrinsicID() == Intrinsic::seh_try_begin
||
4870 F
->getIntrinsicID() == Intrinsic::seh_try_end
||
4871 F
->getIntrinsicID() == Intrinsic::seh_scope_begin
||
4872 F
->getIntrinsicID() == Intrinsic::seh_scope_end
||
4873 F
->getIntrinsicID() == Intrinsic::coro_resume
||
4874 F
->getIntrinsicID() == Intrinsic::coro_destroy
||
4875 F
->getIntrinsicID() ==
4876 Intrinsic::experimental_patchpoint_void
||
4877 F
->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64
||
4878 F
->getIntrinsicID() == Intrinsic::experimental_gc_statepoint
||
4879 F
->getIntrinsicID() == Intrinsic::wasm_rethrow
||
4880 IsAttachedCallOperand(F
, CBI
, i
),
4881 "Cannot invoke an intrinsic other than donothing, patchpoint, "
4882 "statepoint, coro_resume, coro_destroy or clang.arc.attachedcall",
4884 Check(F
->getParent() == &M
, "Referencing function in another module!", &I
,
4885 &M
, F
, F
->getParent());
4886 } else if (BasicBlock
*OpBB
= dyn_cast
<BasicBlock
>(I
.getOperand(i
))) {
4887 Check(OpBB
->getParent() == BB
->getParent(),
4888 "Referring to a basic block in another function!", &I
);
4889 } else if (Argument
*OpArg
= dyn_cast
<Argument
>(I
.getOperand(i
))) {
4890 Check(OpArg
->getParent() == BB
->getParent(),
4891 "Referring to an argument in another function!", &I
);
4892 } else if (GlobalValue
*GV
= dyn_cast
<GlobalValue
>(I
.getOperand(i
))) {
4893 Check(GV
->getParent() == &M
, "Referencing global in another module!", &I
,
4894 &M
, GV
, GV
->getParent());
4895 } else if (isa
<Instruction
>(I
.getOperand(i
))) {
4896 verifyDominatesUse(I
, i
);
4897 } else if (isa
<InlineAsm
>(I
.getOperand(i
))) {
4898 Check(CBI
&& &CBI
->getCalledOperandUse() == &I
.getOperandUse(i
),
4899 "Cannot take the address of an inline asm!", &I
);
4900 } else if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(I
.getOperand(i
))) {
4901 if (CE
->getType()->isPtrOrPtrVectorTy()) {
4902 // If we have a ConstantExpr pointer, we need to see if it came from an
4904 visitConstantExprsRecursively(CE
);
4909 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_fpmath
)) {
4910 Check(I
.getType()->isFPOrFPVectorTy(),
4911 "fpmath requires a floating point result!", &I
);
4912 Check(MD
->getNumOperands() == 1, "fpmath takes one operand!", &I
);
4913 if (ConstantFP
*CFP0
=
4914 mdconst::dyn_extract_or_null
<ConstantFP
>(MD
->getOperand(0))) {
4915 const APFloat
&Accuracy
= CFP0
->getValueAPF();
4916 Check(&Accuracy
.getSemantics() == &APFloat::IEEEsingle(),
4917 "fpmath accuracy must have float type", &I
);
4918 Check(Accuracy
.isFiniteNonZero() && !Accuracy
.isNegative(),
4919 "fpmath accuracy not a positive number!", &I
);
4921 Check(false, "invalid fpmath accuracy!", &I
);
4925 if (MDNode
*Range
= I
.getMetadata(LLVMContext::MD_range
)) {
4926 Check(isa
<LoadInst
>(I
) || isa
<CallInst
>(I
) || isa
<InvokeInst
>(I
),
4927 "Ranges are only for loads, calls and invokes!", &I
);
4928 visitRangeMetadata(I
, Range
, I
.getType());
4931 if (I
.hasMetadata(LLVMContext::MD_invariant_group
)) {
4932 Check(isa
<LoadInst
>(I
) || isa
<StoreInst
>(I
),
4933 "invariant.group metadata is only for loads and stores", &I
);
4936 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_nonnull
)) {
4937 Check(I
.getType()->isPointerTy(), "nonnull applies only to pointer types",
4939 Check(isa
<LoadInst
>(I
),
4940 "nonnull applies only to load instructions, use attributes"
4941 " for calls or invokes",
4943 Check(MD
->getNumOperands() == 0, "nonnull metadata must be empty", &I
);
4946 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_dereferenceable
))
4947 visitDereferenceableMetadata(I
, MD
);
4949 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_dereferenceable_or_null
))
4950 visitDereferenceableMetadata(I
, MD
);
4952 if (MDNode
*TBAA
= I
.getMetadata(LLVMContext::MD_tbaa
))
4953 TBAAVerifyHelper
.visitTBAAMetadata(I
, TBAA
);
4955 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_noalias
))
4956 visitAliasScopeListMetadata(MD
);
4957 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_alias_scope
))
4958 visitAliasScopeListMetadata(MD
);
4960 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_access_group
))
4961 visitAccessGroupMetadata(MD
);
4963 if (MDNode
*AlignMD
= I
.getMetadata(LLVMContext::MD_align
)) {
4964 Check(I
.getType()->isPointerTy(), "align applies only to pointer types",
4966 Check(isa
<LoadInst
>(I
),
4967 "align applies only to load instructions, "
4968 "use attributes for calls or invokes",
4970 Check(AlignMD
->getNumOperands() == 1, "align takes one operand!", &I
);
4971 ConstantInt
*CI
= mdconst::dyn_extract
<ConstantInt
>(AlignMD
->getOperand(0));
4972 Check(CI
&& CI
->getType()->isIntegerTy(64),
4973 "align metadata value must be an i64!", &I
);
4974 uint64_t Align
= CI
->getZExtValue();
4975 Check(isPowerOf2_64(Align
), "align metadata value must be a power of 2!",
4977 Check(Align
<= Value::MaximumAlignment
,
4978 "alignment is larger that implementation defined limit", &I
);
4981 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_prof
))
4982 visitProfMetadata(I
, MD
);
4984 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_memprof
))
4985 visitMemProfMetadata(I
, MD
);
4987 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_callsite
))
4988 visitCallsiteMetadata(I
, MD
);
4990 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_DIAssignID
))
4991 visitDIAssignIDMetadata(I
, MD
);
4993 if (MDNode
*Annotation
= I
.getMetadata(LLVMContext::MD_annotation
))
4994 visitAnnotationMetadata(Annotation
);
4996 if (MDNode
*N
= I
.getDebugLoc().getAsMDNode()) {
4997 CheckDI(isa
<DILocation
>(N
), "invalid !dbg metadata attachment", &I
, N
);
4998 visitMDNode(*N
, AreDebugLocsAllowed::Yes
);
5001 if (auto *DII
= dyn_cast
<DbgVariableIntrinsic
>(&I
)) {
5002 verifyFragmentExpression(*DII
);
5003 verifyNotEntryValue(*DII
);
5006 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
5007 I
.getAllMetadata(MDs
);
5008 for (auto Attachment
: MDs
) {
5009 unsigned Kind
= Attachment
.first
;
5011 (Kind
== LLVMContext::MD_dbg
|| Kind
== LLVMContext::MD_loop
)
5012 ? AreDebugLocsAllowed::Yes
5013 : AreDebugLocsAllowed::No
;
5014 visitMDNode(*Attachment
.second
, AllowLocs
);
5017 InstsInThisBlock
.insert(&I
);
5020 /// Allow intrinsics to be verified in different ways.
5021 void Verifier::visitIntrinsicCall(Intrinsic::ID ID
, CallBase
&Call
) {
5022 Function
*IF
= Call
.getCalledFunction();
5023 Check(IF
->isDeclaration(), "Intrinsic functions should never be defined!",
5026 // Verify that the intrinsic prototype lines up with what the .td files
5028 FunctionType
*IFTy
= IF
->getFunctionType();
5029 bool IsVarArg
= IFTy
->isVarArg();
5031 SmallVector
<Intrinsic::IITDescriptor
, 8> Table
;
5032 getIntrinsicInfoTableEntries(ID
, Table
);
5033 ArrayRef
<Intrinsic::IITDescriptor
> TableRef
= Table
;
5035 // Walk the descriptors to extract overloaded types.
5036 SmallVector
<Type
*, 4> ArgTys
;
5037 Intrinsic::MatchIntrinsicTypesResult Res
=
5038 Intrinsic::matchIntrinsicSignature(IFTy
, TableRef
, ArgTys
);
5039 Check(Res
!= Intrinsic::MatchIntrinsicTypes_NoMatchRet
,
5040 "Intrinsic has incorrect return type!", IF
);
5041 Check(Res
!= Intrinsic::MatchIntrinsicTypes_NoMatchArg
,
5042 "Intrinsic has incorrect argument type!", IF
);
5044 // Verify if the intrinsic call matches the vararg property.
5046 Check(!Intrinsic::matchIntrinsicVarArg(IsVarArg
, TableRef
),
5047 "Intrinsic was not defined with variable arguments!", IF
);
5049 Check(!Intrinsic::matchIntrinsicVarArg(IsVarArg
, TableRef
),
5050 "Callsite was not defined with variable arguments!", IF
);
5052 // All descriptors should be absorbed by now.
5053 Check(TableRef
.empty(), "Intrinsic has too few arguments!", IF
);
5055 // Now that we have the intrinsic ID and the actual argument types (and we
5056 // know they are legal for the intrinsic!) get the intrinsic name through the
5057 // usual means. This allows us to verify the mangling of argument types into
5059 const std::string ExpectedName
=
5060 Intrinsic::getName(ID
, ArgTys
, IF
->getParent(), IFTy
);
5061 Check(ExpectedName
== IF
->getName(),
5062 "Intrinsic name not mangled correctly for type arguments! "
5067 // If the intrinsic takes MDNode arguments, verify that they are either global
5068 // or are local to *this* function.
5069 for (Value
*V
: Call
.args()) {
5070 if (auto *MD
= dyn_cast
<MetadataAsValue
>(V
))
5071 visitMetadataAsValue(*MD
, Call
.getCaller());
5072 if (auto *Const
= dyn_cast
<Constant
>(V
))
5073 Check(!Const
->getType()->isX86_AMXTy(),
5074 "const x86_amx is not allowed in argument!");
5080 case Intrinsic::assume
: {
5081 for (auto &Elem
: Call
.bundle_op_infos()) {
5082 unsigned ArgCount
= Elem
.End
- Elem
.Begin
;
5083 // Separate storage assumptions are special insofar as they're the only
5084 // operand bundles allowed on assumes that aren't parameter attributes.
5085 if (Elem
.Tag
->getKey() == "separate_storage") {
5086 Check(ArgCount
== 2,
5087 "separate_storage assumptions should have 2 arguments", Call
);
5088 Check(Call
.getOperand(Elem
.Begin
)->getType()->isPointerTy() &&
5089 Call
.getOperand(Elem
.Begin
+ 1)->getType()->isPointerTy(),
5090 "arguments to separate_storage assumptions should be pointers",
5094 Check(Elem
.Tag
->getKey() == "ignore" ||
5095 Attribute::isExistingAttribute(Elem
.Tag
->getKey()),
5096 "tags must be valid attribute names", Call
);
5097 Attribute::AttrKind Kind
=
5098 Attribute::getAttrKindFromName(Elem
.Tag
->getKey());
5099 if (Kind
== Attribute::Alignment
) {
5100 Check(ArgCount
<= 3 && ArgCount
>= 2,
5101 "alignment assumptions should have 2 or 3 arguments", Call
);
5102 Check(Call
.getOperand(Elem
.Begin
)->getType()->isPointerTy(),
5103 "first argument should be a pointer", Call
);
5104 Check(Call
.getOperand(Elem
.Begin
+ 1)->getType()->isIntegerTy(),
5105 "second argument should be an integer", Call
);
5107 Check(Call
.getOperand(Elem
.Begin
+ 2)->getType()->isIntegerTy(),
5108 "third argument should be an integer if present", Call
);
5111 Check(ArgCount
<= 2, "too many arguments", Call
);
5112 if (Kind
== Attribute::None
)
5114 if (Attribute::isIntAttrKind(Kind
)) {
5115 Check(ArgCount
== 2, "this attribute should have 2 arguments", Call
);
5116 Check(isa
<ConstantInt
>(Call
.getOperand(Elem
.Begin
+ 1)),
5117 "the second argument should be a constant integral value", Call
);
5118 } else if (Attribute::canUseAsParamAttr(Kind
)) {
5119 Check((ArgCount
) == 1, "this attribute should have one argument", Call
);
5120 } else if (Attribute::canUseAsFnAttr(Kind
)) {
5121 Check((ArgCount
) == 0, "this attribute has no argument", Call
);
5126 case Intrinsic::coro_id
: {
5127 auto *InfoArg
= Call
.getArgOperand(3)->stripPointerCasts();
5128 if (isa
<ConstantPointerNull
>(InfoArg
))
5130 auto *GV
= dyn_cast
<GlobalVariable
>(InfoArg
);
5131 Check(GV
&& GV
->isConstant() && GV
->hasDefinitiveInitializer(),
5132 "info argument of llvm.coro.id must refer to an initialized "
5134 Constant
*Init
= GV
->getInitializer();
5135 Check(isa
<ConstantStruct
>(Init
) || isa
<ConstantArray
>(Init
),
5136 "info argument of llvm.coro.id must refer to either a struct or "
5140 case Intrinsic::is_fpclass
: {
5141 const ConstantInt
*TestMask
= cast
<ConstantInt
>(Call
.getOperand(1));
5142 Check((TestMask
->getZExtValue() & ~static_cast<unsigned>(fcAllFlags
)) == 0,
5143 "unsupported bits for llvm.is.fpclass test mask");
5146 case Intrinsic::fptrunc_round
: {
5147 // Check the rounding mode
5148 Metadata
*MD
= nullptr;
5149 auto *MAV
= dyn_cast
<MetadataAsValue
>(Call
.getOperand(1));
5151 MD
= MAV
->getMetadata();
5153 Check(MD
!= nullptr, "missing rounding mode argument", Call
);
5155 Check(isa
<MDString
>(MD
),
5156 ("invalid value for llvm.fptrunc.round metadata operand"
5157 " (the operand should be a string)"),
5160 std::optional
<RoundingMode
> RoundMode
=
5161 convertStrToRoundingMode(cast
<MDString
>(MD
)->getString());
5162 Check(RoundMode
&& *RoundMode
!= RoundingMode::Dynamic
,
5163 "unsupported rounding mode argument", Call
);
5166 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
5167 #include "llvm/IR/VPIntrinsics.def"
5168 visitVPIntrinsic(cast
<VPIntrinsic
>(Call
));
5170 #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
5171 case Intrinsic::INTRINSIC:
5172 #include "llvm/IR/ConstrainedOps.def"
5173 visitConstrainedFPIntrinsic(cast
<ConstrainedFPIntrinsic
>(Call
));
5175 case Intrinsic::dbg_declare
: // llvm.dbg.declare
5176 Check(isa
<MetadataAsValue
>(Call
.getArgOperand(0)),
5177 "invalid llvm.dbg.declare intrinsic call 1", Call
);
5178 visitDbgIntrinsic("declare", cast
<DbgVariableIntrinsic
>(Call
));
5180 case Intrinsic::dbg_value
: // llvm.dbg.value
5181 visitDbgIntrinsic("value", cast
<DbgVariableIntrinsic
>(Call
));
5183 case Intrinsic::dbg_assign
: // llvm.dbg.assign
5184 visitDbgIntrinsic("assign", cast
<DbgVariableIntrinsic
>(Call
));
5186 case Intrinsic::dbg_label
: // llvm.dbg.label
5187 visitDbgLabelIntrinsic("label", cast
<DbgLabelInst
>(Call
));
5189 case Intrinsic::memcpy
:
5190 case Intrinsic::memcpy_inline
:
5191 case Intrinsic::memmove
:
5192 case Intrinsic::memset
:
5193 case Intrinsic::memset_inline
: {
5196 case Intrinsic::memcpy_element_unordered_atomic
:
5197 case Intrinsic::memmove_element_unordered_atomic
:
5198 case Intrinsic::memset_element_unordered_atomic
: {
5199 const auto *AMI
= cast
<AtomicMemIntrinsic
>(&Call
);
5201 ConstantInt
*ElementSizeCI
=
5202 cast
<ConstantInt
>(AMI
->getRawElementSizeInBytes());
5203 const APInt
&ElementSizeVal
= ElementSizeCI
->getValue();
5204 Check(ElementSizeVal
.isPowerOf2(),
5205 "element size of the element-wise atomic memory intrinsic "
5206 "must be a power of 2",
5209 auto IsValidAlignment
= [&](MaybeAlign Alignment
) {
5210 return Alignment
&& ElementSizeVal
.ule(Alignment
->value());
5212 Check(IsValidAlignment(AMI
->getDestAlign()),
5213 "incorrect alignment of the destination argument", Call
);
5214 if (const auto *AMT
= dyn_cast
<AtomicMemTransferInst
>(AMI
)) {
5215 Check(IsValidAlignment(AMT
->getSourceAlign()),
5216 "incorrect alignment of the source argument", Call
);
5220 case Intrinsic::call_preallocated_setup
: {
5221 auto *NumArgs
= dyn_cast
<ConstantInt
>(Call
.getArgOperand(0));
5222 Check(NumArgs
!= nullptr,
5223 "llvm.call.preallocated.setup argument must be a constant");
5224 bool FoundCall
= false;
5225 for (User
*U
: Call
.users()) {
5226 auto *UseCall
= dyn_cast
<CallBase
>(U
);
5227 Check(UseCall
!= nullptr,
5228 "Uses of llvm.call.preallocated.setup must be calls");
5229 const Function
*Fn
= UseCall
->getCalledFunction();
5230 if (Fn
&& Fn
->getIntrinsicID() == Intrinsic::call_preallocated_arg
) {
5231 auto *AllocArgIndex
= dyn_cast
<ConstantInt
>(UseCall
->getArgOperand(1));
5232 Check(AllocArgIndex
!= nullptr,
5233 "llvm.call.preallocated.alloc arg index must be a constant");
5234 auto AllocArgIndexInt
= AllocArgIndex
->getValue();
5235 Check(AllocArgIndexInt
.sge(0) &&
5236 AllocArgIndexInt
.slt(NumArgs
->getValue()),
5237 "llvm.call.preallocated.alloc arg index must be between 0 and "
5239 "llvm.call.preallocated.setup's argument count");
5240 } else if (Fn
&& Fn
->getIntrinsicID() ==
5241 Intrinsic::call_preallocated_teardown
) {
5244 Check(!FoundCall
, "Can have at most one call corresponding to a "
5245 "llvm.call.preallocated.setup");
5247 size_t NumPreallocatedArgs
= 0;
5248 for (unsigned i
= 0; i
< UseCall
->arg_size(); i
++) {
5249 if (UseCall
->paramHasAttr(i
, Attribute::Preallocated
)) {
5250 ++NumPreallocatedArgs
;
5253 Check(NumPreallocatedArgs
!= 0,
5254 "cannot use preallocated intrinsics on a call without "
5255 "preallocated arguments");
5256 Check(NumArgs
->equalsInt(NumPreallocatedArgs
),
5257 "llvm.call.preallocated.setup arg size must be equal to number "
5258 "of preallocated arguments "
5261 // getOperandBundle() cannot be called if more than one of the operand
5262 // bundle exists. There is already a check elsewhere for this, so skip
5263 // here if we see more than one.
5264 if (UseCall
->countOperandBundlesOfType(LLVMContext::OB_preallocated
) >
5268 auto PreallocatedBundle
=
5269 UseCall
->getOperandBundle(LLVMContext::OB_preallocated
);
5270 Check(PreallocatedBundle
,
5271 "Use of llvm.call.preallocated.setup outside intrinsics "
5272 "must be in \"preallocated\" operand bundle");
5273 Check(PreallocatedBundle
->Inputs
.front().get() == &Call
,
5274 "preallocated bundle must have token from corresponding "
5275 "llvm.call.preallocated.setup");
5280 case Intrinsic::call_preallocated_arg
: {
5281 auto *Token
= dyn_cast
<CallBase
>(Call
.getArgOperand(0));
5282 Check(Token
&& Token
->getCalledFunction()->getIntrinsicID() ==
5283 Intrinsic::call_preallocated_setup
,
5284 "llvm.call.preallocated.arg token argument must be a "
5285 "llvm.call.preallocated.setup");
5286 Check(Call
.hasFnAttr(Attribute::Preallocated
),
5287 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
5288 "call site attribute");
5291 case Intrinsic::call_preallocated_teardown
: {
5292 auto *Token
= dyn_cast
<CallBase
>(Call
.getArgOperand(0));
5293 Check(Token
&& Token
->getCalledFunction()->getIntrinsicID() ==
5294 Intrinsic::call_preallocated_setup
,
5295 "llvm.call.preallocated.teardown token argument must be a "
5296 "llvm.call.preallocated.setup");
5299 case Intrinsic::gcroot
:
5300 case Intrinsic::gcwrite
:
5301 case Intrinsic::gcread
:
5302 if (ID
== Intrinsic::gcroot
) {
5304 dyn_cast
<AllocaInst
>(Call
.getArgOperand(0)->stripPointerCasts());
5305 Check(AI
, "llvm.gcroot parameter #1 must be an alloca.", Call
);
5306 Check(isa
<Constant
>(Call
.getArgOperand(1)),
5307 "llvm.gcroot parameter #2 must be a constant.", Call
);
5308 if (!AI
->getAllocatedType()->isPointerTy()) {
5309 Check(!isa
<ConstantPointerNull
>(Call
.getArgOperand(1)),
5310 "llvm.gcroot parameter #1 must either be a pointer alloca, "
5311 "or argument #2 must be a non-null constant.",
5316 Check(Call
.getParent()->getParent()->hasGC(),
5317 "Enclosing function does not use GC.", Call
);
5319 case Intrinsic::init_trampoline
:
5320 Check(isa
<Function
>(Call
.getArgOperand(1)->stripPointerCasts()),
5321 "llvm.init_trampoline parameter #2 must resolve to a function.",
5324 case Intrinsic::prefetch
:
5325 Check(cast
<ConstantInt
>(Call
.getArgOperand(1))->getZExtValue() < 2,
5326 "rw argument to llvm.prefetch must be 0-1", Call
);
5327 Check(cast
<ConstantInt
>(Call
.getArgOperand(2))->getZExtValue() < 4,
5328 "locality argument to llvm.prefetch must be 0-4", Call
);
5329 Check(cast
<ConstantInt
>(Call
.getArgOperand(3))->getZExtValue() < 2,
5330 "cache type argument to llvm.prefetch must be 0-1", Call
);
5332 case Intrinsic::stackprotector
:
5333 Check(isa
<AllocaInst
>(Call
.getArgOperand(1)->stripPointerCasts()),
5334 "llvm.stackprotector parameter #2 must resolve to an alloca.", Call
);
5336 case Intrinsic::localescape
: {
5337 BasicBlock
*BB
= Call
.getParent();
5338 Check(BB
->isEntryBlock(), "llvm.localescape used outside of entry block",
5340 Check(!SawFrameEscape
, "multiple calls to llvm.localescape in one function",
5342 for (Value
*Arg
: Call
.args()) {
5343 if (isa
<ConstantPointerNull
>(Arg
))
5344 continue; // Null values are allowed as placeholders.
5345 auto *AI
= dyn_cast
<AllocaInst
>(Arg
->stripPointerCasts());
5346 Check(AI
&& AI
->isStaticAlloca(),
5347 "llvm.localescape only accepts static allocas", Call
);
5349 FrameEscapeInfo
[BB
->getParent()].first
= Call
.arg_size();
5350 SawFrameEscape
= true;
5353 case Intrinsic::localrecover
: {
5354 Value
*FnArg
= Call
.getArgOperand(0)->stripPointerCasts();
5355 Function
*Fn
= dyn_cast
<Function
>(FnArg
);
5356 Check(Fn
&& !Fn
->isDeclaration(),
5357 "llvm.localrecover first "
5358 "argument must be function defined in this module",
5360 auto *IdxArg
= cast
<ConstantInt
>(Call
.getArgOperand(2));
5361 auto &Entry
= FrameEscapeInfo
[Fn
];
5362 Entry
.second
= unsigned(
5363 std::max(uint64_t(Entry
.second
), IdxArg
->getLimitedValue(~0U) + 1));
5367 case Intrinsic::experimental_gc_statepoint
:
5368 if (auto *CI
= dyn_cast
<CallInst
>(&Call
))
5369 Check(!CI
->isInlineAsm(),
5370 "gc.statepoint support for inline assembly unimplemented", CI
);
5371 Check(Call
.getParent()->getParent()->hasGC(),
5372 "Enclosing function does not use GC.", Call
);
5374 verifyStatepoint(Call
);
5376 case Intrinsic::experimental_gc_result
: {
5377 Check(Call
.getParent()->getParent()->hasGC(),
5378 "Enclosing function does not use GC.", Call
);
5380 auto *Statepoint
= Call
.getArgOperand(0);
5381 if (isa
<UndefValue
>(Statepoint
))
5384 // Are we tied to a statepoint properly?
5385 const auto *StatepointCall
= dyn_cast
<CallBase
>(Statepoint
);
5386 const Function
*StatepointFn
=
5387 StatepointCall
? StatepointCall
->getCalledFunction() : nullptr;
5388 Check(StatepointFn
&& StatepointFn
->isDeclaration() &&
5389 StatepointFn
->getIntrinsicID() ==
5390 Intrinsic::experimental_gc_statepoint
,
5391 "gc.result operand #1 must be from a statepoint", Call
,
5392 Call
.getArgOperand(0));
5394 // Check that result type matches wrapped callee.
5395 auto *TargetFuncType
=
5396 cast
<FunctionType
>(StatepointCall
->getParamElementType(2));
5397 Check(Call
.getType() == TargetFuncType
->getReturnType(),
5398 "gc.result result type does not match wrapped callee", Call
);
5401 case Intrinsic::experimental_gc_relocate
: {
5402 Check(Call
.arg_size() == 3, "wrong number of arguments", Call
);
5404 Check(isa
<PointerType
>(Call
.getType()->getScalarType()),
5405 "gc.relocate must return a pointer or a vector of pointers", Call
);
5407 // Check that this relocate is correctly tied to the statepoint
5409 // This is case for relocate on the unwinding path of an invoke statepoint
5410 if (LandingPadInst
*LandingPad
=
5411 dyn_cast
<LandingPadInst
>(Call
.getArgOperand(0))) {
5413 const BasicBlock
*InvokeBB
=
5414 LandingPad
->getParent()->getUniquePredecessor();
5416 // Landingpad relocates should have only one predecessor with invoke
5417 // statepoint terminator
5418 Check(InvokeBB
, "safepoints should have unique landingpads",
5419 LandingPad
->getParent());
5420 Check(InvokeBB
->getTerminator(), "safepoint block should be well formed",
5422 Check(isa
<GCStatepointInst
>(InvokeBB
->getTerminator()),
5423 "gc relocate should be linked to a statepoint", InvokeBB
);
5425 // In all other cases relocate should be tied to the statepoint directly.
5426 // This covers relocates on a normal return path of invoke statepoint and
5427 // relocates of a call statepoint.
5428 auto *Token
= Call
.getArgOperand(0);
5429 Check(isa
<GCStatepointInst
>(Token
) || isa
<UndefValue
>(Token
),
5430 "gc relocate is incorrectly tied to the statepoint", Call
, Token
);
5433 // Verify rest of the relocate arguments.
5434 const Value
&StatepointCall
= *cast
<GCRelocateInst
>(Call
).getStatepoint();
5436 // Both the base and derived must be piped through the safepoint.
5437 Value
*Base
= Call
.getArgOperand(1);
5438 Check(isa
<ConstantInt
>(Base
),
5439 "gc.relocate operand #2 must be integer offset", Call
);
5441 Value
*Derived
= Call
.getArgOperand(2);
5442 Check(isa
<ConstantInt
>(Derived
),
5443 "gc.relocate operand #3 must be integer offset", Call
);
5445 const uint64_t BaseIndex
= cast
<ConstantInt
>(Base
)->getZExtValue();
5446 const uint64_t DerivedIndex
= cast
<ConstantInt
>(Derived
)->getZExtValue();
5449 if (isa
<UndefValue
>(StatepointCall
))
5451 if (auto Opt
= cast
<GCStatepointInst
>(StatepointCall
)
5452 .getOperandBundle(LLVMContext::OB_gc_live
)) {
5453 Check(BaseIndex
< Opt
->Inputs
.size(),
5454 "gc.relocate: statepoint base index out of bounds", Call
);
5455 Check(DerivedIndex
< Opt
->Inputs
.size(),
5456 "gc.relocate: statepoint derived index out of bounds", Call
);
5459 // Relocated value must be either a pointer type or vector-of-pointer type,
5460 // but gc_relocate does not need to return the same pointer type as the
5461 // relocated pointer. It can be casted to the correct type later if it's
5462 // desired. However, they must have the same address space and 'vectorness'
5463 GCRelocateInst
&Relocate
= cast
<GCRelocateInst
>(Call
);
5464 auto *ResultType
= Call
.getType();
5465 auto *DerivedType
= Relocate
.getDerivedPtr()->getType();
5466 auto *BaseType
= Relocate
.getBasePtr()->getType();
5468 Check(BaseType
->isPtrOrPtrVectorTy(),
5469 "gc.relocate: relocated value must be a pointer", Call
);
5470 Check(DerivedType
->isPtrOrPtrVectorTy(),
5471 "gc.relocate: relocated value must be a pointer", Call
);
5473 Check(ResultType
->isVectorTy() == DerivedType
->isVectorTy(),
5474 "gc.relocate: vector relocates to vector and pointer to pointer",
5477 ResultType
->getPointerAddressSpace() ==
5478 DerivedType
->getPointerAddressSpace(),
5479 "gc.relocate: relocating a pointer shouldn't change its address space",
5482 auto GC
= llvm::getGCStrategy(Relocate
.getFunction()->getGC());
5483 Check(GC
, "gc.relocate: calling function must have GCStrategy",
5484 Call
.getFunction());
5486 auto isGCPtr
= [&GC
](Type
*PTy
) {
5487 return GC
->isGCManagedPointer(PTy
->getScalarType()).value_or(true);
5489 Check(isGCPtr(ResultType
), "gc.relocate: must return gc pointer", Call
);
5490 Check(isGCPtr(BaseType
),
5491 "gc.relocate: relocated value must be a gc pointer", Call
);
5492 Check(isGCPtr(DerivedType
),
5493 "gc.relocate: relocated value must be a gc pointer", Call
);
5497 case Intrinsic::eh_exceptioncode
:
5498 case Intrinsic::eh_exceptionpointer
: {
5499 Check(isa
<CatchPadInst
>(Call
.getArgOperand(0)),
5500 "eh.exceptionpointer argument must be a catchpad", Call
);
5503 case Intrinsic::get_active_lane_mask
: {
5504 Check(Call
.getType()->isVectorTy(),
5505 "get_active_lane_mask: must return a "
5508 auto *ElemTy
= Call
.getType()->getScalarType();
5509 Check(ElemTy
->isIntegerTy(1),
5510 "get_active_lane_mask: element type is not "
5515 case Intrinsic::experimental_get_vector_length
: {
5516 ConstantInt
*VF
= cast
<ConstantInt
>(Call
.getArgOperand(1));
5517 Check(!VF
->isNegative() && !VF
->isZero(),
5518 "get_vector_length: VF must be positive", Call
);
5521 case Intrinsic::masked_load
: {
5522 Check(Call
.getType()->isVectorTy(), "masked_load: must return a vector",
5525 ConstantInt
*Alignment
= cast
<ConstantInt
>(Call
.getArgOperand(1));
5526 Value
*Mask
= Call
.getArgOperand(2);
5527 Value
*PassThru
= Call
.getArgOperand(3);
5528 Check(Mask
->getType()->isVectorTy(), "masked_load: mask must be vector",
5530 Check(Alignment
->getValue().isPowerOf2(),
5531 "masked_load: alignment must be a power of 2", Call
);
5532 Check(PassThru
->getType() == Call
.getType(),
5533 "masked_load: pass through and return type must match", Call
);
5534 Check(cast
<VectorType
>(Mask
->getType())->getElementCount() ==
5535 cast
<VectorType
>(Call
.getType())->getElementCount(),
5536 "masked_load: vector mask must be same length as return", Call
);
5539 case Intrinsic::masked_store
: {
5540 Value
*Val
= Call
.getArgOperand(0);
5541 ConstantInt
*Alignment
= cast
<ConstantInt
>(Call
.getArgOperand(2));
5542 Value
*Mask
= Call
.getArgOperand(3);
5543 Check(Mask
->getType()->isVectorTy(), "masked_store: mask must be vector",
5545 Check(Alignment
->getValue().isPowerOf2(),
5546 "masked_store: alignment must be a power of 2", Call
);
5547 Check(cast
<VectorType
>(Mask
->getType())->getElementCount() ==
5548 cast
<VectorType
>(Val
->getType())->getElementCount(),
5549 "masked_store: vector mask must be same length as value", Call
);
5553 case Intrinsic::masked_gather
: {
5554 const APInt
&Alignment
=
5555 cast
<ConstantInt
>(Call
.getArgOperand(1))->getValue();
5556 Check(Alignment
.isZero() || Alignment
.isPowerOf2(),
5557 "masked_gather: alignment must be 0 or a power of 2", Call
);
5560 case Intrinsic::masked_scatter
: {
5561 const APInt
&Alignment
=
5562 cast
<ConstantInt
>(Call
.getArgOperand(2))->getValue();
5563 Check(Alignment
.isZero() || Alignment
.isPowerOf2(),
5564 "masked_scatter: alignment must be 0 or a power of 2", Call
);
5568 case Intrinsic::experimental_guard
: {
5569 Check(isa
<CallInst
>(Call
), "experimental_guard cannot be invoked", Call
);
5570 Check(Call
.countOperandBundlesOfType(LLVMContext::OB_deopt
) == 1,
5571 "experimental_guard must have exactly one "
5572 "\"deopt\" operand bundle");
5576 case Intrinsic::experimental_deoptimize
: {
5577 Check(isa
<CallInst
>(Call
), "experimental_deoptimize cannot be invoked",
5579 Check(Call
.countOperandBundlesOfType(LLVMContext::OB_deopt
) == 1,
5580 "experimental_deoptimize must have exactly one "
5581 "\"deopt\" operand bundle");
5582 Check(Call
.getType() == Call
.getFunction()->getReturnType(),
5583 "experimental_deoptimize return type must match caller return type");
5585 if (isa
<CallInst
>(Call
)) {
5586 auto *RI
= dyn_cast
<ReturnInst
>(Call
.getNextNode());
5588 "calls to experimental_deoptimize must be followed by a return");
5590 if (!Call
.getType()->isVoidTy() && RI
)
5591 Check(RI
->getReturnValue() == &Call
,
5592 "calls to experimental_deoptimize must be followed by a return "
5593 "of the value computed by experimental_deoptimize");
5598 case Intrinsic::vector_reduce_and
:
5599 case Intrinsic::vector_reduce_or
:
5600 case Intrinsic::vector_reduce_xor
:
5601 case Intrinsic::vector_reduce_add
:
5602 case Intrinsic::vector_reduce_mul
:
5603 case Intrinsic::vector_reduce_smax
:
5604 case Intrinsic::vector_reduce_smin
:
5605 case Intrinsic::vector_reduce_umax
:
5606 case Intrinsic::vector_reduce_umin
: {
5607 Type
*ArgTy
= Call
.getArgOperand(0)->getType();
5608 Check(ArgTy
->isIntOrIntVectorTy() && ArgTy
->isVectorTy(),
5609 "Intrinsic has incorrect argument type!");
5612 case Intrinsic::vector_reduce_fmax
:
5613 case Intrinsic::vector_reduce_fmin
: {
5614 Type
*ArgTy
= Call
.getArgOperand(0)->getType();
5615 Check(ArgTy
->isFPOrFPVectorTy() && ArgTy
->isVectorTy(),
5616 "Intrinsic has incorrect argument type!");
5619 case Intrinsic::vector_reduce_fadd
:
5620 case Intrinsic::vector_reduce_fmul
: {
5621 // Unlike the other reductions, the first argument is a start value. The
5622 // second argument is the vector to be reduced.
5623 Type
*ArgTy
= Call
.getArgOperand(1)->getType();
5624 Check(ArgTy
->isFPOrFPVectorTy() && ArgTy
->isVectorTy(),
5625 "Intrinsic has incorrect argument type!");
5628 case Intrinsic::smul_fix
:
5629 case Intrinsic::smul_fix_sat
:
5630 case Intrinsic::umul_fix
:
5631 case Intrinsic::umul_fix_sat
:
5632 case Intrinsic::sdiv_fix
:
5633 case Intrinsic::sdiv_fix_sat
:
5634 case Intrinsic::udiv_fix
:
5635 case Intrinsic::udiv_fix_sat
: {
5636 Value
*Op1
= Call
.getArgOperand(0);
5637 Value
*Op2
= Call
.getArgOperand(1);
5638 Check(Op1
->getType()->isIntOrIntVectorTy(),
5639 "first operand of [us][mul|div]_fix[_sat] must be an int type or "
5641 Check(Op2
->getType()->isIntOrIntVectorTy(),
5642 "second operand of [us][mul|div]_fix[_sat] must be an int type or "
5645 auto *Op3
= cast
<ConstantInt
>(Call
.getArgOperand(2));
5646 Check(Op3
->getType()->getBitWidth() <= 32,
5647 "third argument of [us][mul|div]_fix[_sat] must fit within 32 bits");
5649 if (ID
== Intrinsic::smul_fix
|| ID
== Intrinsic::smul_fix_sat
||
5650 ID
== Intrinsic::sdiv_fix
|| ID
== Intrinsic::sdiv_fix_sat
) {
5651 Check(Op3
->getZExtValue() < Op1
->getType()->getScalarSizeInBits(),
5652 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
5655 Check(Op3
->getZExtValue() <= Op1
->getType()->getScalarSizeInBits(),
5656 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
5657 "to the width of the operands");
5661 case Intrinsic::lround
:
5662 case Intrinsic::llround
:
5663 case Intrinsic::lrint
:
5664 case Intrinsic::llrint
: {
5665 Type
*ValTy
= Call
.getArgOperand(0)->getType();
5666 Type
*ResultTy
= Call
.getType();
5667 Check(!ValTy
->isVectorTy() && !ResultTy
->isVectorTy(),
5668 "Intrinsic does not support vectors", &Call
);
5671 case Intrinsic::bswap
: {
5672 Type
*Ty
= Call
.getType();
5673 unsigned Size
= Ty
->getScalarSizeInBits();
5674 Check(Size
% 16 == 0, "bswap must be an even number of bytes", &Call
);
5677 case Intrinsic::invariant_start
: {
5678 ConstantInt
*InvariantSize
= dyn_cast
<ConstantInt
>(Call
.getArgOperand(0));
5679 Check(InvariantSize
&&
5680 (!InvariantSize
->isNegative() || InvariantSize
->isMinusOne()),
5681 "invariant_start parameter must be -1, 0 or a positive number",
5685 case Intrinsic::matrix_multiply
:
5686 case Intrinsic::matrix_transpose
:
5687 case Intrinsic::matrix_column_major_load
:
5688 case Intrinsic::matrix_column_major_store
: {
5689 Function
*IF
= Call
.getCalledFunction();
5690 ConstantInt
*Stride
= nullptr;
5691 ConstantInt
*NumRows
;
5692 ConstantInt
*NumColumns
;
5693 VectorType
*ResultTy
;
5694 Type
*Op0ElemTy
= nullptr;
5695 Type
*Op1ElemTy
= nullptr;
5697 case Intrinsic::matrix_multiply
: {
5698 NumRows
= cast
<ConstantInt
>(Call
.getArgOperand(2));
5699 ConstantInt
*N
= cast
<ConstantInt
>(Call
.getArgOperand(3));
5700 NumColumns
= cast
<ConstantInt
>(Call
.getArgOperand(4));
5701 Check(cast
<FixedVectorType
>(Call
.getArgOperand(0)->getType())
5702 ->getNumElements() ==
5703 NumRows
->getZExtValue() * N
->getZExtValue(),
5704 "First argument of a matrix operation does not match specified "
5706 Check(cast
<FixedVectorType
>(Call
.getArgOperand(1)->getType())
5707 ->getNumElements() ==
5708 N
->getZExtValue() * NumColumns
->getZExtValue(),
5709 "Second argument of a matrix operation does not match specified "
5712 ResultTy
= cast
<VectorType
>(Call
.getType());
5714 cast
<VectorType
>(Call
.getArgOperand(0)->getType())->getElementType();
5716 cast
<VectorType
>(Call
.getArgOperand(1)->getType())->getElementType();
5719 case Intrinsic::matrix_transpose
:
5720 NumRows
= cast
<ConstantInt
>(Call
.getArgOperand(1));
5721 NumColumns
= cast
<ConstantInt
>(Call
.getArgOperand(2));
5722 ResultTy
= cast
<VectorType
>(Call
.getType());
5724 cast
<VectorType
>(Call
.getArgOperand(0)->getType())->getElementType();
5726 case Intrinsic::matrix_column_major_load
: {
5727 Stride
= dyn_cast
<ConstantInt
>(Call
.getArgOperand(1));
5728 NumRows
= cast
<ConstantInt
>(Call
.getArgOperand(3));
5729 NumColumns
= cast
<ConstantInt
>(Call
.getArgOperand(4));
5730 ResultTy
= cast
<VectorType
>(Call
.getType());
5733 case Intrinsic::matrix_column_major_store
: {
5734 Stride
= dyn_cast
<ConstantInt
>(Call
.getArgOperand(2));
5735 NumRows
= cast
<ConstantInt
>(Call
.getArgOperand(4));
5736 NumColumns
= cast
<ConstantInt
>(Call
.getArgOperand(5));
5737 ResultTy
= cast
<VectorType
>(Call
.getArgOperand(0)->getType());
5739 cast
<VectorType
>(Call
.getArgOperand(0)->getType())->getElementType();
5743 llvm_unreachable("unexpected intrinsic");
5746 Check(ResultTy
->getElementType()->isIntegerTy() ||
5747 ResultTy
->getElementType()->isFloatingPointTy(),
5748 "Result type must be an integer or floating-point type!", IF
);
5751 Check(ResultTy
->getElementType() == Op0ElemTy
,
5752 "Vector element type mismatch of the result and first operand "
5757 Check(ResultTy
->getElementType() == Op1ElemTy
,
5758 "Vector element type mismatch of the result and second operand "
5762 Check(cast
<FixedVectorType
>(ResultTy
)->getNumElements() ==
5763 NumRows
->getZExtValue() * NumColumns
->getZExtValue(),
5764 "Result of a matrix operation does not fit in the returned vector!");
5767 Check(Stride
->getZExtValue() >= NumRows
->getZExtValue(),
5768 "Stride must be greater or equal than the number of rows!", IF
);
5772 case Intrinsic::experimental_vector_splice
: {
5773 VectorType
*VecTy
= cast
<VectorType
>(Call
.getType());
5774 int64_t Idx
= cast
<ConstantInt
>(Call
.getArgOperand(2))->getSExtValue();
5775 int64_t KnownMinNumElements
= VecTy
->getElementCount().getKnownMinValue();
5776 if (Call
.getParent() && Call
.getParent()->getParent()) {
5777 AttributeList Attrs
= Call
.getParent()->getParent()->getAttributes();
5778 if (Attrs
.hasFnAttr(Attribute::VScaleRange
))
5779 KnownMinNumElements
*= Attrs
.getFnAttrs().getVScaleRangeMin();
5781 Check((Idx
< 0 && std::abs(Idx
) <= KnownMinNumElements
) ||
5782 (Idx
>= 0 && Idx
< KnownMinNumElements
),
5783 "The splice index exceeds the range [-VL, VL-1] where VL is the "
5784 "known minimum number of elements in the vector. For scalable "
5785 "vectors the minimum number of elements is determined from "
5790 case Intrinsic::experimental_stepvector
: {
5791 VectorType
*VecTy
= dyn_cast
<VectorType
>(Call
.getType());
5792 Check(VecTy
&& VecTy
->getScalarType()->isIntegerTy() &&
5793 VecTy
->getScalarSizeInBits() >= 8,
5794 "experimental_stepvector only supported for vectors of integers "
5795 "with a bitwidth of at least 8.",
5799 case Intrinsic::vector_insert
: {
5800 Value
*Vec
= Call
.getArgOperand(0);
5801 Value
*SubVec
= Call
.getArgOperand(1);
5802 Value
*Idx
= Call
.getArgOperand(2);
5803 unsigned IdxN
= cast
<ConstantInt
>(Idx
)->getZExtValue();
5805 VectorType
*VecTy
= cast
<VectorType
>(Vec
->getType());
5806 VectorType
*SubVecTy
= cast
<VectorType
>(SubVec
->getType());
5808 ElementCount VecEC
= VecTy
->getElementCount();
5809 ElementCount SubVecEC
= SubVecTy
->getElementCount();
5810 Check(VecTy
->getElementType() == SubVecTy
->getElementType(),
5811 "vector_insert parameters must have the same element "
5814 Check(IdxN
% SubVecEC
.getKnownMinValue() == 0,
5815 "vector_insert index must be a constant multiple of "
5816 "the subvector's known minimum vector length.");
5818 // If this insertion is not the 'mixed' case where a fixed vector is
5819 // inserted into a scalable vector, ensure that the insertion of the
5820 // subvector does not overrun the parent vector.
5821 if (VecEC
.isScalable() == SubVecEC
.isScalable()) {
5822 Check(IdxN
< VecEC
.getKnownMinValue() &&
5823 IdxN
+ SubVecEC
.getKnownMinValue() <= VecEC
.getKnownMinValue(),
5824 "subvector operand of vector_insert would overrun the "
5825 "vector being inserted into.");
5829 case Intrinsic::vector_extract
: {
5830 Value
*Vec
= Call
.getArgOperand(0);
5831 Value
*Idx
= Call
.getArgOperand(1);
5832 unsigned IdxN
= cast
<ConstantInt
>(Idx
)->getZExtValue();
5834 VectorType
*ResultTy
= cast
<VectorType
>(Call
.getType());
5835 VectorType
*VecTy
= cast
<VectorType
>(Vec
->getType());
5837 ElementCount VecEC
= VecTy
->getElementCount();
5838 ElementCount ResultEC
= ResultTy
->getElementCount();
5840 Check(ResultTy
->getElementType() == VecTy
->getElementType(),
5841 "vector_extract result must have the same element "
5842 "type as the input vector.",
5844 Check(IdxN
% ResultEC
.getKnownMinValue() == 0,
5845 "vector_extract index must be a constant multiple of "
5846 "the result type's known minimum vector length.");
5848 // If this extraction is not the 'mixed' case where a fixed vector is
5849 // extracted from a scalable vector, ensure that the extraction does not
5850 // overrun the parent vector.
5851 if (VecEC
.isScalable() == ResultEC
.isScalable()) {
5852 Check(IdxN
< VecEC
.getKnownMinValue() &&
5853 IdxN
+ ResultEC
.getKnownMinValue() <= VecEC
.getKnownMinValue(),
5854 "vector_extract would overrun.");
5858 case Intrinsic::experimental_noalias_scope_decl
: {
5859 NoAliasScopeDecls
.push_back(cast
<IntrinsicInst
>(&Call
));
5862 case Intrinsic::preserve_array_access_index
:
5863 case Intrinsic::preserve_struct_access_index
:
5864 case Intrinsic::aarch64_ldaxr
:
5865 case Intrinsic::aarch64_ldxr
:
5866 case Intrinsic::arm_ldaex
:
5867 case Intrinsic::arm_ldrex
: {
5868 Type
*ElemTy
= Call
.getParamElementType(0);
5869 Check(ElemTy
, "Intrinsic requires elementtype attribute on first argument.",
5873 case Intrinsic::aarch64_stlxr
:
5874 case Intrinsic::aarch64_stxr
:
5875 case Intrinsic::arm_stlex
:
5876 case Intrinsic::arm_strex
: {
5877 Type
*ElemTy
= Call
.getAttributes().getParamElementType(1);
5879 "Intrinsic requires elementtype attribute on second argument.",
5883 case Intrinsic::aarch64_prefetch
: {
5884 Check(cast
<ConstantInt
>(Call
.getArgOperand(1))->getZExtValue() < 2,
5885 "write argument to llvm.aarch64.prefetch must be 0 or 1", Call
);
5886 Check(cast
<ConstantInt
>(Call
.getArgOperand(2))->getZExtValue() < 4,
5887 "target argument to llvm.aarch64.prefetch must be 0-3", Call
);
5888 Check(cast
<ConstantInt
>(Call
.getArgOperand(3))->getZExtValue() < 2,
5889 "stream argument to llvm.aarch64.prefetch must be 0 or 1", Call
);
5890 Check(cast
<ConstantInt
>(Call
.getArgOperand(4))->getZExtValue() < 2,
5891 "isdata argument to llvm.aarch64.prefetch must be 0 or 1", Call
);
5894 case Intrinsic::callbr_landingpad
: {
5895 const auto *CBR
= dyn_cast
<CallBrInst
>(Call
.getOperand(0));
5896 Check(CBR
, "intrinstic requires callbr operand", &Call
);
5900 const BasicBlock
*LandingPadBB
= Call
.getParent();
5901 const BasicBlock
*PredBB
= LandingPadBB
->getUniquePredecessor();
5903 CheckFailed("Intrinsic in block must have 1 unique predecessor", &Call
);
5906 if (!isa
<CallBrInst
>(PredBB
->getTerminator())) {
5907 CheckFailed("Intrinsic must have corresponding callbr in predecessor",
5911 Check(llvm::any_of(CBR
->getIndirectDests(),
5912 [LandingPadBB
](const BasicBlock
*IndDest
) {
5913 return IndDest
== LandingPadBB
;
5915 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
5916 "block in indirect destination list",
5918 const Instruction
&First
= *LandingPadBB
->begin();
5919 Check(&First
== &Call
, "No other instructions may proceed intrinsic",
5923 case Intrinsic::amdgcn_cs_chain
: {
5924 auto CallerCC
= Call
.getCaller()->getCallingConv();
5926 case CallingConv::AMDGPU_CS
:
5927 case CallingConv::AMDGPU_CS_Chain
:
5928 case CallingConv::AMDGPU_CS_ChainPreserve
:
5931 CheckFailed("Intrinsic can only be used from functions with the "
5932 "amdgpu_cs, amdgpu_cs_chain or amdgpu_cs_chain_preserve "
5933 "calling conventions",
5938 Check(Call
.paramHasAttr(2, Attribute::InReg
),
5939 "SGPR arguments must have the `inreg` attribute", &Call
);
5940 Check(!Call
.paramHasAttr(3, Attribute::InReg
),
5941 "VGPR arguments must not have the `inreg` attribute", &Call
);
5944 case Intrinsic::experimental_convergence_entry
:
5946 case Intrinsic::experimental_convergence_anchor
:
5948 case Intrinsic::experimental_convergence_loop
:
5952 // Verify that there aren't any unmediated control transfers between funclets.
5953 if (IntrinsicInst::mayLowerToFunctionCall(ID
)) {
5954 Function
*F
= Call
.getParent()->getParent();
5955 if (F
->hasPersonalityFn() &&
5956 isScopedEHPersonality(classifyEHPersonality(F
->getPersonalityFn()))) {
5957 // Run EH funclet coloring on-demand and cache results for other intrinsic
5958 // calls in this function
5959 if (BlockEHFuncletColors
.empty())
5960 BlockEHFuncletColors
= colorEHFunclets(*F
);
5962 // Check for catch-/cleanup-pad in first funclet block
5963 bool InEHFunclet
= false;
5964 BasicBlock
*CallBB
= Call
.getParent();
5965 const ColorVector
&CV
= BlockEHFuncletColors
.find(CallBB
)->second
;
5966 assert(CV
.size() > 0 && "Uncolored block");
5967 for (BasicBlock
*ColorFirstBB
: CV
)
5968 if (dyn_cast_or_null
<FuncletPadInst
>(ColorFirstBB
->getFirstNonPHI()))
5971 // Check for funclet operand bundle
5972 bool HasToken
= false;
5973 for (unsigned I
= 0, E
= Call
.getNumOperandBundles(); I
!= E
; ++I
)
5974 if (Call
.getOperandBundleAt(I
).getTagID() == LLVMContext::OB_funclet
)
5977 // This would cause silent code truncation in WinEHPrepare
5979 Check(HasToken
, "Missing funclet token on intrinsic call", &Call
);
5984 /// Carefully grab the subprogram from a local scope.
5986 /// This carefully grabs the subprogram from a local scope, avoiding the
5987 /// built-in assertions that would typically fire.
5988 static DISubprogram
*getSubprogram(Metadata
*LocalScope
) {
5992 if (auto *SP
= dyn_cast
<DISubprogram
>(LocalScope
))
5995 if (auto *LB
= dyn_cast
<DILexicalBlockBase
>(LocalScope
))
5996 return getSubprogram(LB
->getRawScope());
5998 // Just return null; broken scope chains are checked elsewhere.
5999 assert(!isa
<DILocalScope
>(LocalScope
) && "Unknown type of local scope");
6003 void Verifier::visitVPIntrinsic(VPIntrinsic
&VPI
) {
6004 if (auto *VPCast
= dyn_cast
<VPCastIntrinsic
>(&VPI
)) {
6005 auto *RetTy
= cast
<VectorType
>(VPCast
->getType());
6006 auto *ValTy
= cast
<VectorType
>(VPCast
->getOperand(0)->getType());
6007 Check(RetTy
->getElementCount() == ValTy
->getElementCount(),
6008 "VP cast intrinsic first argument and result vector lengths must be "
6012 switch (VPCast
->getIntrinsicID()) {
6014 llvm_unreachable("Unknown VP cast intrinsic");
6015 case Intrinsic::vp_trunc
:
6016 Check(RetTy
->isIntOrIntVectorTy() && ValTy
->isIntOrIntVectorTy(),
6017 "llvm.vp.trunc intrinsic first argument and result element type "
6020 Check(RetTy
->getScalarSizeInBits() < ValTy
->getScalarSizeInBits(),
6021 "llvm.vp.trunc intrinsic the bit size of first argument must be "
6022 "larger than the bit size of the return type",
6025 case Intrinsic::vp_zext
:
6026 case Intrinsic::vp_sext
:
6027 Check(RetTy
->isIntOrIntVectorTy() && ValTy
->isIntOrIntVectorTy(),
6028 "llvm.vp.zext or llvm.vp.sext intrinsic first argument and result "
6029 "element type must be integer",
6031 Check(RetTy
->getScalarSizeInBits() > ValTy
->getScalarSizeInBits(),
6032 "llvm.vp.zext or llvm.vp.sext intrinsic the bit size of first "
6033 "argument must be smaller than the bit size of the return type",
6036 case Intrinsic::vp_fptoui
:
6037 case Intrinsic::vp_fptosi
:
6039 RetTy
->isIntOrIntVectorTy() && ValTy
->isFPOrFPVectorTy(),
6040 "llvm.vp.fptoui or llvm.vp.fptosi intrinsic first argument element "
6041 "type must be floating-point and result element type must be integer",
6044 case Intrinsic::vp_uitofp
:
6045 case Intrinsic::vp_sitofp
:
6047 RetTy
->isFPOrFPVectorTy() && ValTy
->isIntOrIntVectorTy(),
6048 "llvm.vp.uitofp or llvm.vp.sitofp intrinsic first argument element "
6049 "type must be integer and result element type must be floating-point",
6052 case Intrinsic::vp_fptrunc
:
6053 Check(RetTy
->isFPOrFPVectorTy() && ValTy
->isFPOrFPVectorTy(),
6054 "llvm.vp.fptrunc intrinsic first argument and result element type "
6055 "must be floating-point",
6057 Check(RetTy
->getScalarSizeInBits() < ValTy
->getScalarSizeInBits(),
6058 "llvm.vp.fptrunc intrinsic the bit size of first argument must be "
6059 "larger than the bit size of the return type",
6062 case Intrinsic::vp_fpext
:
6063 Check(RetTy
->isFPOrFPVectorTy() && ValTy
->isFPOrFPVectorTy(),
6064 "llvm.vp.fpext intrinsic first argument and result element type "
6065 "must be floating-point",
6067 Check(RetTy
->getScalarSizeInBits() > ValTy
->getScalarSizeInBits(),
6068 "llvm.vp.fpext intrinsic the bit size of first argument must be "
6069 "smaller than the bit size of the return type",
6072 case Intrinsic::vp_ptrtoint
:
6073 Check(RetTy
->isIntOrIntVectorTy() && ValTy
->isPtrOrPtrVectorTy(),
6074 "llvm.vp.ptrtoint intrinsic first argument element type must be "
6075 "pointer and result element type must be integer",
6078 case Intrinsic::vp_inttoptr
:
6079 Check(RetTy
->isPtrOrPtrVectorTy() && ValTy
->isIntOrIntVectorTy(),
6080 "llvm.vp.inttoptr intrinsic first argument element type must be "
6081 "integer and result element type must be pointer",
6086 if (VPI
.getIntrinsicID() == Intrinsic::vp_fcmp
) {
6087 auto Pred
= cast
<VPCmpIntrinsic
>(&VPI
)->getPredicate();
6088 Check(CmpInst::isFPPredicate(Pred
),
6089 "invalid predicate for VP FP comparison intrinsic", &VPI
);
6091 if (VPI
.getIntrinsicID() == Intrinsic::vp_icmp
) {
6092 auto Pred
= cast
<VPCmpIntrinsic
>(&VPI
)->getPredicate();
6093 Check(CmpInst::isIntPredicate(Pred
),
6094 "invalid predicate for VP integer comparison intrinsic", &VPI
);
6096 if (VPI
.getIntrinsicID() == Intrinsic::vp_is_fpclass
) {
6097 auto TestMask
= cast
<ConstantInt
>(VPI
.getOperand(1));
6098 Check((TestMask
->getZExtValue() & ~static_cast<unsigned>(fcAllFlags
)) == 0,
6099 "unsupported bits for llvm.vp.is.fpclass test mask");
6103 void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic
&FPI
) {
6104 unsigned NumOperands
;
6106 switch (FPI
.getIntrinsicID()) {
6107 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
6108 case Intrinsic::INTRINSIC: \
6109 NumOperands = NARG; \
6110 HasRoundingMD = ROUND_MODE; \
6112 #include "llvm/IR/ConstrainedOps.def"
6114 llvm_unreachable("Invalid constrained FP intrinsic!");
6116 NumOperands
+= (1 + HasRoundingMD
);
6117 // Compare intrinsics carry an extra predicate metadata operand.
6118 if (isa
<ConstrainedFPCmpIntrinsic
>(FPI
))
6120 Check((FPI
.arg_size() == NumOperands
),
6121 "invalid arguments for constrained FP intrinsic", &FPI
);
6123 switch (FPI
.getIntrinsicID()) {
6124 case Intrinsic::experimental_constrained_lrint
:
6125 case Intrinsic::experimental_constrained_llrint
: {
6126 Type
*ValTy
= FPI
.getArgOperand(0)->getType();
6127 Type
*ResultTy
= FPI
.getType();
6128 Check(!ValTy
->isVectorTy() && !ResultTy
->isVectorTy(),
6129 "Intrinsic does not support vectors", &FPI
);
6133 case Intrinsic::experimental_constrained_lround
:
6134 case Intrinsic::experimental_constrained_llround
: {
6135 Type
*ValTy
= FPI
.getArgOperand(0)->getType();
6136 Type
*ResultTy
= FPI
.getType();
6137 Check(!ValTy
->isVectorTy() && !ResultTy
->isVectorTy(),
6138 "Intrinsic does not support vectors", &FPI
);
6142 case Intrinsic::experimental_constrained_fcmp
:
6143 case Intrinsic::experimental_constrained_fcmps
: {
6144 auto Pred
= cast
<ConstrainedFPCmpIntrinsic
>(&FPI
)->getPredicate();
6145 Check(CmpInst::isFPPredicate(Pred
),
6146 "invalid predicate for constrained FP comparison intrinsic", &FPI
);
6150 case Intrinsic::experimental_constrained_fptosi
:
6151 case Intrinsic::experimental_constrained_fptoui
: {
6152 Value
*Operand
= FPI
.getArgOperand(0);
6154 Check(Operand
->getType()->isFPOrFPVectorTy(),
6155 "Intrinsic first argument must be floating point", &FPI
);
6156 if (auto *OperandT
= dyn_cast
<VectorType
>(Operand
->getType())) {
6157 SrcEC
= cast
<VectorType
>(OperandT
)->getElementCount();
6161 Check(SrcEC
.isNonZero() == Operand
->getType()->isVectorTy(),
6162 "Intrinsic first argument and result disagree on vector use", &FPI
);
6163 Check(Operand
->getType()->isIntOrIntVectorTy(),
6164 "Intrinsic result must be an integer", &FPI
);
6165 if (auto *OperandT
= dyn_cast
<VectorType
>(Operand
->getType())) {
6166 Check(SrcEC
== cast
<VectorType
>(OperandT
)->getElementCount(),
6167 "Intrinsic first argument and result vector lengths must be equal",
6173 case Intrinsic::experimental_constrained_sitofp
:
6174 case Intrinsic::experimental_constrained_uitofp
: {
6175 Value
*Operand
= FPI
.getArgOperand(0);
6177 Check(Operand
->getType()->isIntOrIntVectorTy(),
6178 "Intrinsic first argument must be integer", &FPI
);
6179 if (auto *OperandT
= dyn_cast
<VectorType
>(Operand
->getType())) {
6180 SrcEC
= cast
<VectorType
>(OperandT
)->getElementCount();
6184 Check(SrcEC
.isNonZero() == Operand
->getType()->isVectorTy(),
6185 "Intrinsic first argument and result disagree on vector use", &FPI
);
6186 Check(Operand
->getType()->isFPOrFPVectorTy(),
6187 "Intrinsic result must be a floating point", &FPI
);
6188 if (auto *OperandT
= dyn_cast
<VectorType
>(Operand
->getType())) {
6189 Check(SrcEC
== cast
<VectorType
>(OperandT
)->getElementCount(),
6190 "Intrinsic first argument and result vector lengths must be equal",
6195 case Intrinsic::experimental_constrained_fptrunc
:
6196 case Intrinsic::experimental_constrained_fpext
: {
6197 Value
*Operand
= FPI
.getArgOperand(0);
6198 Type
*OperandTy
= Operand
->getType();
6199 Value
*Result
= &FPI
;
6200 Type
*ResultTy
= Result
->getType();
6201 Check(OperandTy
->isFPOrFPVectorTy(),
6202 "Intrinsic first argument must be FP or FP vector", &FPI
);
6203 Check(ResultTy
->isFPOrFPVectorTy(),
6204 "Intrinsic result must be FP or FP vector", &FPI
);
6205 Check(OperandTy
->isVectorTy() == ResultTy
->isVectorTy(),
6206 "Intrinsic first argument and result disagree on vector use", &FPI
);
6207 if (OperandTy
->isVectorTy()) {
6208 Check(cast
<VectorType
>(OperandTy
)->getElementCount() ==
6209 cast
<VectorType
>(ResultTy
)->getElementCount(),
6210 "Intrinsic first argument and result vector lengths must be equal",
6213 if (FPI
.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc
) {
6214 Check(OperandTy
->getScalarSizeInBits() > ResultTy
->getScalarSizeInBits(),
6215 "Intrinsic first argument's type must be larger than result type",
6218 Check(OperandTy
->getScalarSizeInBits() < ResultTy
->getScalarSizeInBits(),
6219 "Intrinsic first argument's type must be smaller than result type",
6229 // If a non-metadata argument is passed in a metadata slot then the
6230 // error will be caught earlier when the incorrect argument doesn't
6231 // match the specification in the intrinsic call table. Thus, no
6232 // argument type check is needed here.
6234 Check(FPI
.getExceptionBehavior().has_value(),
6235 "invalid exception behavior argument", &FPI
);
6236 if (HasRoundingMD
) {
6237 Check(FPI
.getRoundingMode().has_value(), "invalid rounding mode argument",
6242 void Verifier::visitDbgIntrinsic(StringRef Kind
, DbgVariableIntrinsic
&DII
) {
6243 auto *MD
= DII
.getRawLocation();
6244 CheckDI(isa
<ValueAsMetadata
>(MD
) || isa
<DIArgList
>(MD
) ||
6245 (isa
<MDNode
>(MD
) && !cast
<MDNode
>(MD
)->getNumOperands()),
6246 "invalid llvm.dbg." + Kind
+ " intrinsic address/value", &DII
, MD
);
6247 CheckDI(isa
<DILocalVariable
>(DII
.getRawVariable()),
6248 "invalid llvm.dbg." + Kind
+ " intrinsic variable", &DII
,
6249 DII
.getRawVariable());
6250 CheckDI(isa
<DIExpression
>(DII
.getRawExpression()),
6251 "invalid llvm.dbg." + Kind
+ " intrinsic expression", &DII
,
6252 DII
.getRawExpression());
6254 if (auto *DAI
= dyn_cast
<DbgAssignIntrinsic
>(&DII
)) {
6255 CheckDI(isa
<DIAssignID
>(DAI
->getRawAssignID()),
6256 "invalid llvm.dbg.assign intrinsic DIAssignID", &DII
,
6257 DAI
->getRawAssignID());
6258 const auto *RawAddr
= DAI
->getRawAddress();
6260 isa
<ValueAsMetadata
>(RawAddr
) ||
6261 (isa
<MDNode
>(RawAddr
) && !cast
<MDNode
>(RawAddr
)->getNumOperands()),
6262 "invalid llvm.dbg.assign intrinsic address", &DII
,
6263 DAI
->getRawAddress());
6264 CheckDI(isa
<DIExpression
>(DAI
->getRawAddressExpression()),
6265 "invalid llvm.dbg.assign intrinsic address expression", &DII
,
6266 DAI
->getRawAddressExpression());
6267 // All of the linked instructions should be in the same function as DII.
6268 for (Instruction
*I
: at::getAssignmentInsts(DAI
))
6269 CheckDI(DAI
->getFunction() == I
->getFunction(),
6270 "inst not in same function as dbg.assign", I
, DAI
);
6273 // Ignore broken !dbg attachments; they're checked elsewhere.
6274 if (MDNode
*N
= DII
.getDebugLoc().getAsMDNode())
6275 if (!isa
<DILocation
>(N
))
6278 BasicBlock
*BB
= DII
.getParent();
6279 Function
*F
= BB
? BB
->getParent() : nullptr;
6281 // The scopes for variables and !dbg attachments must agree.
6282 DILocalVariable
*Var
= DII
.getVariable();
6283 DILocation
*Loc
= DII
.getDebugLoc();
6284 CheckDI(Loc
, "llvm.dbg." + Kind
+ " intrinsic requires a !dbg attachment",
6287 DISubprogram
*VarSP
= getSubprogram(Var
->getRawScope());
6288 DISubprogram
*LocSP
= getSubprogram(Loc
->getRawScope());
6289 if (!VarSP
|| !LocSP
)
6290 return; // Broken scope chains are checked elsewhere.
6292 CheckDI(VarSP
== LocSP
,
6293 "mismatched subprogram between llvm.dbg." + Kind
+
6294 " variable and !dbg attachment",
6295 &DII
, BB
, F
, Var
, Var
->getScope()->getSubprogram(), Loc
,
6296 Loc
->getScope()->getSubprogram());
6298 // This check is redundant with one in visitLocalVariable().
6299 CheckDI(isType(Var
->getRawType()), "invalid type ref", Var
,
6304 void Verifier::visitDbgLabelIntrinsic(StringRef Kind
, DbgLabelInst
&DLI
) {
6305 CheckDI(isa
<DILabel
>(DLI
.getRawLabel()),
6306 "invalid llvm.dbg." + Kind
+ " intrinsic variable", &DLI
,
6309 // Ignore broken !dbg attachments; they're checked elsewhere.
6310 if (MDNode
*N
= DLI
.getDebugLoc().getAsMDNode())
6311 if (!isa
<DILocation
>(N
))
6314 BasicBlock
*BB
= DLI
.getParent();
6315 Function
*F
= BB
? BB
->getParent() : nullptr;
6317 // The scopes for variables and !dbg attachments must agree.
6318 DILabel
*Label
= DLI
.getLabel();
6319 DILocation
*Loc
= DLI
.getDebugLoc();
6320 Check(Loc
, "llvm.dbg." + Kind
+ " intrinsic requires a !dbg attachment", &DLI
,
6323 DISubprogram
*LabelSP
= getSubprogram(Label
->getRawScope());
6324 DISubprogram
*LocSP
= getSubprogram(Loc
->getRawScope());
6325 if (!LabelSP
|| !LocSP
)
6328 CheckDI(LabelSP
== LocSP
,
6329 "mismatched subprogram between llvm.dbg." + Kind
+
6330 " label and !dbg attachment",
6331 &DLI
, BB
, F
, Label
, Label
->getScope()->getSubprogram(), Loc
,
6332 Loc
->getScope()->getSubprogram());
6335 void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic
&I
) {
6336 DILocalVariable
*V
= dyn_cast_or_null
<DILocalVariable
>(I
.getRawVariable());
6337 DIExpression
*E
= dyn_cast_or_null
<DIExpression
>(I
.getRawExpression());
6339 // We don't know whether this intrinsic verified correctly.
6340 if (!V
|| !E
|| !E
->isValid())
6343 // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
6344 auto Fragment
= E
->getFragmentInfo();
6348 // The frontend helps out GDB by emitting the members of local anonymous
6349 // unions as artificial local variables with shared storage. When SROA splits
6350 // the storage for artificial local variables that are smaller than the entire
6351 // union, the overhang piece will be outside of the allotted space for the
6352 // variable and this check fails.
6353 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
6354 if (V
->isArtificial())
6357 verifyFragmentExpression(*V
, *Fragment
, &I
);
6360 template <typename ValueOrMetadata
>
6361 void Verifier::verifyFragmentExpression(const DIVariable
&V
,
6362 DIExpression::FragmentInfo Fragment
,
6363 ValueOrMetadata
*Desc
) {
6364 // If there's no size, the type is broken, but that should be checked
6366 auto VarSize
= V
.getSizeInBits();
6370 unsigned FragSize
= Fragment
.SizeInBits
;
6371 unsigned FragOffset
= Fragment
.OffsetInBits
;
6372 CheckDI(FragSize
+ FragOffset
<= *VarSize
,
6373 "fragment is larger than or outside of variable", Desc
, &V
);
6374 CheckDI(FragSize
!= *VarSize
, "fragment covers entire variable", Desc
, &V
);
6377 void Verifier::verifyFnArgs(const DbgVariableIntrinsic
&I
) {
6378 // This function does not take the scope of noninlined function arguments into
6379 // account. Don't run it if current function is nodebug, because it may
6380 // contain inlined debug intrinsics.
6384 // For performance reasons only check non-inlined ones.
6385 if (I
.getDebugLoc()->getInlinedAt())
6388 DILocalVariable
*Var
= I
.getVariable();
6389 CheckDI(Var
, "dbg intrinsic without variable");
6391 unsigned ArgNo
= Var
->getArg();
6395 // Verify there are no duplicate function argument debug info entries.
6396 // These will cause hard-to-debug assertions in the DWARF backend.
6397 if (DebugFnArgs
.size() < ArgNo
)
6398 DebugFnArgs
.resize(ArgNo
, nullptr);
6400 auto *Prev
= DebugFnArgs
[ArgNo
- 1];
6401 DebugFnArgs
[ArgNo
- 1] = Var
;
6402 CheckDI(!Prev
|| (Prev
== Var
), "conflicting debug info for argument", &I
,
6406 void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic
&I
) {
6407 DIExpression
*E
= dyn_cast_or_null
<DIExpression
>(I
.getRawExpression());
6409 // We don't know whether this intrinsic verified correctly.
6410 if (!E
|| !E
->isValid())
6413 if (isa
<ValueAsMetadata
>(I
.getRawLocation())) {
6414 Value
*VarValue
= I
.getVariableLocationOp(0);
6415 if (isa
<UndefValue
>(VarValue
) || isa
<PoisonValue
>(VarValue
))
6417 // We allow EntryValues for swift async arguments, as they have an
6418 // ABI-guarantee to be turned into a specific register.
6419 if (auto *ArgLoc
= dyn_cast_or_null
<Argument
>(VarValue
);
6420 ArgLoc
&& ArgLoc
->hasAttribute(Attribute::SwiftAsync
))
6424 CheckDI(!E
->isEntryValue(),
6425 "Entry values are only allowed in MIR unless they target a "
6426 "swiftasync Argument",
6430 void Verifier::verifyCompileUnits() {
6431 // When more than one Module is imported into the same context, such as during
6432 // an LTO build before linking the modules, ODR type uniquing may cause types
6433 // to point to a different CU. This check does not make sense in this case.
6434 if (M
.getContext().isODRUniquingDebugTypes())
6436 auto *CUs
= M
.getNamedMetadata("llvm.dbg.cu");
6437 SmallPtrSet
<const Metadata
*, 2> Listed
;
6439 Listed
.insert(CUs
->op_begin(), CUs
->op_end());
6440 for (const auto *CU
: CUVisited
)
6441 CheckDI(Listed
.count(CU
), "DICompileUnit not listed in llvm.dbg.cu", CU
);
6445 void Verifier::verifyDeoptimizeCallingConvs() {
6446 if (DeoptimizeDeclarations
.empty())
6449 const Function
*First
= DeoptimizeDeclarations
[0];
6450 for (const auto *F
: ArrayRef(DeoptimizeDeclarations
).slice(1)) {
6451 Check(First
->getCallingConv() == F
->getCallingConv(),
6452 "All llvm.experimental.deoptimize declarations must have the same "
6453 "calling convention",
6458 void Verifier::verifyAttachedCallBundle(const CallBase
&Call
,
6459 const OperandBundleUse
&BU
) {
6460 FunctionType
*FTy
= Call
.getFunctionType();
6462 Check((FTy
->getReturnType()->isPointerTy() ||
6463 (Call
.doesNotReturn() && FTy
->getReturnType()->isVoidTy())),
6464 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
6465 "function returning a pointer or a non-returning function that has a "
6469 Check(BU
.Inputs
.size() == 1 && isa
<Function
>(BU
.Inputs
.front()),
6470 "operand bundle \"clang.arc.attachedcall\" requires one function as "
6474 auto *Fn
= cast
<Function
>(BU
.Inputs
.front());
6475 Intrinsic::ID IID
= Fn
->getIntrinsicID();
6478 Check((IID
== Intrinsic::objc_retainAutoreleasedReturnValue
||
6479 IID
== Intrinsic::objc_unsafeClaimAutoreleasedReturnValue
),
6480 "invalid function argument", Call
);
6482 StringRef FnName
= Fn
->getName();
6483 Check((FnName
== "objc_retainAutoreleasedReturnValue" ||
6484 FnName
== "objc_unsafeClaimAutoreleasedReturnValue"),
6485 "invalid function argument", Call
);
6489 void Verifier::verifySourceDebugInfo(const DICompileUnit
&U
, const DIFile
&F
) {
6490 bool HasSource
= F
.getSource().has_value();
6491 if (!HasSourceDebugInfo
.count(&U
))
6492 HasSourceDebugInfo
[&U
] = HasSource
;
6493 CheckDI(HasSource
== HasSourceDebugInfo
[&U
],
6494 "inconsistent use of embedded source");
6497 void Verifier::verifyNoAliasScopeDecl() {
6498 if (NoAliasScopeDecls
.empty())
6501 // only a single scope must be declared at a time.
6502 for (auto *II
: NoAliasScopeDecls
) {
6503 assert(II
->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl
&&
6504 "Not a llvm.experimental.noalias.scope.decl ?");
6505 const auto *ScopeListMV
= dyn_cast
<MetadataAsValue
>(
6506 II
->getOperand(Intrinsic::NoAliasScopeDeclScopeArg
));
6507 Check(ScopeListMV
!= nullptr,
6508 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
6512 const auto *ScopeListMD
= dyn_cast
<MDNode
>(ScopeListMV
->getMetadata());
6513 Check(ScopeListMD
!= nullptr, "!id.scope.list must point to an MDNode", II
);
6514 Check(ScopeListMD
->getNumOperands() == 1,
6515 "!id.scope.list must point to a list with a single scope", II
);
6516 visitAliasScopeListMetadata(ScopeListMD
);
6519 // Only check the domination rule when requested. Once all passes have been
6520 // adapted this option can go away.
6521 if (!VerifyNoAliasScopeDomination
)
6524 // Now sort the intrinsics based on the scope MDNode so that declarations of
6525 // the same scopes are next to each other.
6526 auto GetScope
= [](IntrinsicInst
*II
) {
6527 const auto *ScopeListMV
= cast
<MetadataAsValue
>(
6528 II
->getOperand(Intrinsic::NoAliasScopeDeclScopeArg
));
6529 return &cast
<MDNode
>(ScopeListMV
->getMetadata())->getOperand(0);
6532 // We are sorting on MDNode pointers here. For valid input IR this is ok.
6533 // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
6534 auto Compare
= [GetScope
](IntrinsicInst
*Lhs
, IntrinsicInst
*Rhs
) {
6535 return GetScope(Lhs
) < GetScope(Rhs
);
6538 llvm::sort(NoAliasScopeDecls
, Compare
);
6540 // Go over the intrinsics and check that for the same scope, they are not
6541 // dominating each other.
6542 auto ItCurrent
= NoAliasScopeDecls
.begin();
6543 while (ItCurrent
!= NoAliasScopeDecls
.end()) {
6544 auto CurScope
= GetScope(*ItCurrent
);
6545 auto ItNext
= ItCurrent
;
6548 } while (ItNext
!= NoAliasScopeDecls
.end() &&
6549 GetScope(*ItNext
) == CurScope
);
6551 // [ItCurrent, ItNext) represents the declarations for the same scope.
6552 // Ensure they are not dominating each other.. but only if it is not too
6554 if (ItNext
- ItCurrent
< 32)
6555 for (auto *I
: llvm::make_range(ItCurrent
, ItNext
))
6556 for (auto *J
: llvm::make_range(ItCurrent
, ItNext
))
6558 Check(!DT
.dominates(I
, J
),
6559 "llvm.experimental.noalias.scope.decl dominates another one "
6560 "with the same scope",
6566 //===----------------------------------------------------------------------===//
6567 // Implement the public interfaces to this file...
6568 //===----------------------------------------------------------------------===//
6570 bool llvm::verifyFunction(const Function
&f
, raw_ostream
*OS
) {
6571 Function
&F
= const_cast<Function
&>(f
);
6573 // Don't use a raw_null_ostream. Printing IR is expensive.
6574 Verifier
V(OS
, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f
.getParent());
6576 // Note that this function's return value is inverted from what you would
6577 // expect of a function called "verify".
6578 return !V
.verify(F
);
6581 bool llvm::verifyModule(const Module
&M
, raw_ostream
*OS
,
6582 bool *BrokenDebugInfo
) {
6583 // Don't use a raw_null_ostream. Printing IR is expensive.
6584 Verifier
V(OS
, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo
, M
);
6586 bool Broken
= false;
6587 for (const Function
&F
: M
)
6588 Broken
|= !V
.verify(F
);
6590 Broken
|= !V
.verify();
6591 if (BrokenDebugInfo
)
6592 *BrokenDebugInfo
= V
.hasBrokenDebugInfo();
6593 // Note that this function's return value is inverted from what you would
6594 // expect of a function called "verify".
6600 struct VerifierLegacyPass
: public FunctionPass
{
6603 std::unique_ptr
<Verifier
> V
;
6604 bool FatalErrors
= true;
6606 VerifierLegacyPass() : FunctionPass(ID
) {
6607 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
6609 explicit VerifierLegacyPass(bool FatalErrors
)
6611 FatalErrors(FatalErrors
) {
6612 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
6615 bool doInitialization(Module
&M
) override
{
6616 V
= std::make_unique
<Verifier
>(
6617 &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M
);
6621 bool runOnFunction(Function
&F
) override
{
6622 if (!V
->verify(F
) && FatalErrors
) {
6623 errs() << "in function " << F
.getName() << '\n';
6624 report_fatal_error("Broken function found, compilation aborted!");
6629 bool doFinalization(Module
&M
) override
{
6630 bool HasErrors
= false;
6631 for (Function
&F
: M
)
6632 if (F
.isDeclaration())
6633 HasErrors
|= !V
->verify(F
);
6635 HasErrors
|= !V
->verify();
6636 if (FatalErrors
&& (HasErrors
|| V
->hasBrokenDebugInfo()))
6637 report_fatal_error("Broken module found, compilation aborted!");
6641 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
6642 AU
.setPreservesAll();
6646 } // end anonymous namespace
6648 /// Helper to issue failure from the TBAA verification
6649 template <typename
... Tys
> void TBAAVerifier::CheckFailed(Tys
&&... Args
) {
6651 return Diagnostic
->CheckFailed(Args
...);
6654 #define CheckTBAA(C, ...) \
6657 CheckFailed(__VA_ARGS__); \
6662 /// Verify that \p BaseNode can be used as the "base type" in the struct-path
6663 /// TBAA scheme. This means \p BaseNode is either a scalar node, or a
6664 /// struct-type node describing an aggregate data structure (like a struct).
6665 TBAAVerifier::TBAABaseNodeSummary
6666 TBAAVerifier::verifyTBAABaseNode(Instruction
&I
, const MDNode
*BaseNode
,
6668 if (BaseNode
->getNumOperands() < 2) {
6669 CheckFailed("Base nodes must have at least two operands", &I
, BaseNode
);
6673 auto Itr
= TBAABaseNodes
.find(BaseNode
);
6674 if (Itr
!= TBAABaseNodes
.end())
6677 auto Result
= verifyTBAABaseNodeImpl(I
, BaseNode
, IsNewFormat
);
6678 auto InsertResult
= TBAABaseNodes
.insert({BaseNode
, Result
});
6680 assert(InsertResult
.second
&& "We just checked!");
6684 TBAAVerifier::TBAABaseNodeSummary
6685 TBAAVerifier::verifyTBAABaseNodeImpl(Instruction
&I
, const MDNode
*BaseNode
,
6687 const TBAAVerifier::TBAABaseNodeSummary InvalidNode
= {true, ~0u};
6689 if (BaseNode
->getNumOperands() == 2) {
6690 // Scalar nodes can only be accessed at offset 0.
6691 return isValidScalarTBAANode(BaseNode
)
6692 ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
6697 if (BaseNode
->getNumOperands() % 3 != 0) {
6698 CheckFailed("Access tag nodes must have the number of operands that is a "
6699 "multiple of 3!", BaseNode
);
6703 if (BaseNode
->getNumOperands() % 2 != 1) {
6704 CheckFailed("Struct tag nodes must have an odd number of operands!",
6710 // Check the type size field.
6712 auto *TypeSizeNode
= mdconst::dyn_extract_or_null
<ConstantInt
>(
6713 BaseNode
->getOperand(1));
6714 if (!TypeSizeNode
) {
6715 CheckFailed("Type size nodes must be constants!", &I
, BaseNode
);
6720 // Check the type name field. In the new format it can be anything.
6721 if (!IsNewFormat
&& !isa
<MDString
>(BaseNode
->getOperand(0))) {
6722 CheckFailed("Struct tag nodes have a string as their first operand",
6727 bool Failed
= false;
6729 std::optional
<APInt
> PrevOffset
;
6730 unsigned BitWidth
= ~0u;
6732 // We've already checked that BaseNode is not a degenerate root node with one
6733 // operand in \c verifyTBAABaseNode, so this loop should run at least once.
6734 unsigned FirstFieldOpNo
= IsNewFormat
? 3 : 1;
6735 unsigned NumOpsPerField
= IsNewFormat
? 3 : 2;
6736 for (unsigned Idx
= FirstFieldOpNo
; Idx
< BaseNode
->getNumOperands();
6737 Idx
+= NumOpsPerField
) {
6738 const MDOperand
&FieldTy
= BaseNode
->getOperand(Idx
);
6739 const MDOperand
&FieldOffset
= BaseNode
->getOperand(Idx
+ 1);
6740 if (!isa
<MDNode
>(FieldTy
)) {
6741 CheckFailed("Incorrect field entry in struct type node!", &I
, BaseNode
);
6746 auto *OffsetEntryCI
=
6747 mdconst::dyn_extract_or_null
<ConstantInt
>(FieldOffset
);
6748 if (!OffsetEntryCI
) {
6749 CheckFailed("Offset entries must be constants!", &I
, BaseNode
);
6754 if (BitWidth
== ~0u)
6755 BitWidth
= OffsetEntryCI
->getBitWidth();
6757 if (OffsetEntryCI
->getBitWidth() != BitWidth
) {
6759 "Bitwidth between the offsets and struct type entries must match", &I
,
6765 // NB! As far as I can tell, we generate a non-strictly increasing offset
6766 // sequence only from structs that have zero size bit fields. When
6767 // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
6768 // pick the field lexically the latest in struct type metadata node. This
6769 // mirrors the actual behavior of the alias analysis implementation.
6771 !PrevOffset
|| PrevOffset
->ule(OffsetEntryCI
->getValue());
6774 CheckFailed("Offsets must be increasing!", &I
, BaseNode
);
6778 PrevOffset
= OffsetEntryCI
->getValue();
6781 auto *MemberSizeNode
= mdconst::dyn_extract_or_null
<ConstantInt
>(
6782 BaseNode
->getOperand(Idx
+ 2));
6783 if (!MemberSizeNode
) {
6784 CheckFailed("Member size entries must be constants!", &I
, BaseNode
);
6791 return Failed
? InvalidNode
6792 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth
);
6795 static bool IsRootTBAANode(const MDNode
*MD
) {
6796 return MD
->getNumOperands() < 2;
6799 static bool IsScalarTBAANodeImpl(const MDNode
*MD
,
6800 SmallPtrSetImpl
<const MDNode
*> &Visited
) {
6801 if (MD
->getNumOperands() != 2 && MD
->getNumOperands() != 3)
6804 if (!isa
<MDString
>(MD
->getOperand(0)))
6807 if (MD
->getNumOperands() == 3) {
6808 auto *Offset
= mdconst::dyn_extract
<ConstantInt
>(MD
->getOperand(2));
6809 if (!(Offset
&& Offset
->isZero() && isa
<MDString
>(MD
->getOperand(0))))
6813 auto *Parent
= dyn_cast_or_null
<MDNode
>(MD
->getOperand(1));
6814 return Parent
&& Visited
.insert(Parent
).second
&&
6815 (IsRootTBAANode(Parent
) || IsScalarTBAANodeImpl(Parent
, Visited
));
6818 bool TBAAVerifier::isValidScalarTBAANode(const MDNode
*MD
) {
6819 auto ResultIt
= TBAAScalarNodes
.find(MD
);
6820 if (ResultIt
!= TBAAScalarNodes
.end())
6821 return ResultIt
->second
;
6823 SmallPtrSet
<const MDNode
*, 4> Visited
;
6824 bool Result
= IsScalarTBAANodeImpl(MD
, Visited
);
6825 auto InsertResult
= TBAAScalarNodes
.insert({MD
, Result
});
6827 assert(InsertResult
.second
&& "Just checked!");
6832 /// Returns the field node at the offset \p Offset in \p BaseNode. Update \p
6833 /// Offset in place to be the offset within the field node returned.
6835 /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
6836 MDNode
*TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction
&I
,
6837 const MDNode
*BaseNode
,
6840 assert(BaseNode
->getNumOperands() >= 2 && "Invalid base node!");
6842 // Scalar nodes have only one possible "field" -- their parent in the access
6843 // hierarchy. Offset must be zero at this point, but our caller is supposed
6845 if (BaseNode
->getNumOperands() == 2)
6846 return cast
<MDNode
>(BaseNode
->getOperand(1));
6848 unsigned FirstFieldOpNo
= IsNewFormat
? 3 : 1;
6849 unsigned NumOpsPerField
= IsNewFormat
? 3 : 2;
6850 for (unsigned Idx
= FirstFieldOpNo
; Idx
< BaseNode
->getNumOperands();
6851 Idx
+= NumOpsPerField
) {
6852 auto *OffsetEntryCI
=
6853 mdconst::extract
<ConstantInt
>(BaseNode
->getOperand(Idx
+ 1));
6854 if (OffsetEntryCI
->getValue().ugt(Offset
)) {
6855 if (Idx
== FirstFieldOpNo
) {
6856 CheckFailed("Could not find TBAA parent in struct type node", &I
,
6861 unsigned PrevIdx
= Idx
- NumOpsPerField
;
6862 auto *PrevOffsetEntryCI
=
6863 mdconst::extract
<ConstantInt
>(BaseNode
->getOperand(PrevIdx
+ 1));
6864 Offset
-= PrevOffsetEntryCI
->getValue();
6865 return cast
<MDNode
>(BaseNode
->getOperand(PrevIdx
));
6869 unsigned LastIdx
= BaseNode
->getNumOperands() - NumOpsPerField
;
6870 auto *LastOffsetEntryCI
= mdconst::extract
<ConstantInt
>(
6871 BaseNode
->getOperand(LastIdx
+ 1));
6872 Offset
-= LastOffsetEntryCI
->getValue();
6873 return cast
<MDNode
>(BaseNode
->getOperand(LastIdx
));
6876 static bool isNewFormatTBAATypeNode(llvm::MDNode
*Type
) {
6877 if (!Type
|| Type
->getNumOperands() < 3)
6880 // In the new format type nodes shall have a reference to the parent type as
6881 // its first operand.
6882 return isa_and_nonnull
<MDNode
>(Type
->getOperand(0));
6885 bool TBAAVerifier::visitTBAAMetadata(Instruction
&I
, const MDNode
*MD
) {
6886 CheckTBAA(MD
->getNumOperands() > 0, "TBAA metadata cannot have 0 operands",
6889 CheckTBAA(isa
<LoadInst
>(I
) || isa
<StoreInst
>(I
) || isa
<CallInst
>(I
) ||
6890 isa
<VAArgInst
>(I
) || isa
<AtomicRMWInst
>(I
) ||
6891 isa
<AtomicCmpXchgInst
>(I
),
6892 "This instruction shall not have a TBAA access tag!", &I
);
6894 bool IsStructPathTBAA
=
6895 isa
<MDNode
>(MD
->getOperand(0)) && MD
->getNumOperands() >= 3;
6897 CheckTBAA(IsStructPathTBAA
,
6898 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
6901 MDNode
*BaseNode
= dyn_cast_or_null
<MDNode
>(MD
->getOperand(0));
6902 MDNode
*AccessType
= dyn_cast_or_null
<MDNode
>(MD
->getOperand(1));
6904 bool IsNewFormat
= isNewFormatTBAATypeNode(AccessType
);
6907 CheckTBAA(MD
->getNumOperands() == 4 || MD
->getNumOperands() == 5,
6908 "Access tag metadata must have either 4 or 5 operands", &I
, MD
);
6910 CheckTBAA(MD
->getNumOperands() < 5,
6911 "Struct tag metadata must have either 3 or 4 operands", &I
, MD
);
6914 // Check the access size field.
6916 auto *AccessSizeNode
= mdconst::dyn_extract_or_null
<ConstantInt
>(
6918 CheckTBAA(AccessSizeNode
, "Access size field must be a constant", &I
, MD
);
6921 // Check the immutability flag.
6922 unsigned ImmutabilityFlagOpNo
= IsNewFormat
? 4 : 3;
6923 if (MD
->getNumOperands() == ImmutabilityFlagOpNo
+ 1) {
6924 auto *IsImmutableCI
= mdconst::dyn_extract_or_null
<ConstantInt
>(
6925 MD
->getOperand(ImmutabilityFlagOpNo
));
6926 CheckTBAA(IsImmutableCI
,
6927 "Immutability tag on struct tag metadata must be a constant", &I
,
6930 IsImmutableCI
->isZero() || IsImmutableCI
->isOne(),
6931 "Immutability part of the struct tag metadata must be either 0 or 1",
6935 CheckTBAA(BaseNode
&& AccessType
,
6936 "Malformed struct tag metadata: base and access-type "
6937 "should be non-null and point to Metadata nodes",
6938 &I
, MD
, BaseNode
, AccessType
);
6941 CheckTBAA(isValidScalarTBAANode(AccessType
),
6942 "Access type node must be a valid scalar type", &I
, MD
,
6946 auto *OffsetCI
= mdconst::dyn_extract_or_null
<ConstantInt
>(MD
->getOperand(2));
6947 CheckTBAA(OffsetCI
, "Offset must be constant integer", &I
, MD
);
6949 APInt Offset
= OffsetCI
->getValue();
6950 bool SeenAccessTypeInPath
= false;
6952 SmallPtrSet
<MDNode
*, 4> StructPath
;
6954 for (/* empty */; BaseNode
&& !IsRootTBAANode(BaseNode
);
6955 BaseNode
= getFieldNodeFromTBAABaseNode(I
, BaseNode
, Offset
,
6957 if (!StructPath
.insert(BaseNode
).second
) {
6958 CheckFailed("Cycle detected in struct path", &I
, MD
);
6963 unsigned BaseNodeBitWidth
;
6964 std::tie(Invalid
, BaseNodeBitWidth
) = verifyTBAABaseNode(I
, BaseNode
,
6967 // If the base node is invalid in itself, then we've already printed all the
6968 // errors we wanted to print.
6972 SeenAccessTypeInPath
|= BaseNode
== AccessType
;
6974 if (isValidScalarTBAANode(BaseNode
) || BaseNode
== AccessType
)
6975 CheckTBAA(Offset
== 0, "Offset not zero at the point of scalar access",
6978 CheckTBAA(BaseNodeBitWidth
== Offset
.getBitWidth() ||
6979 (BaseNodeBitWidth
== 0 && Offset
== 0) ||
6980 (IsNewFormat
&& BaseNodeBitWidth
== ~0u),
6981 "Access bit-width not the same as description bit-width", &I
, MD
,
6982 BaseNodeBitWidth
, Offset
.getBitWidth());
6984 if (IsNewFormat
&& SeenAccessTypeInPath
)
6988 CheckTBAA(SeenAccessTypeInPath
, "Did not see access type in access path!", &I
,
6993 char VerifierLegacyPass::ID
= 0;
6994 INITIALIZE_PASS(VerifierLegacyPass
, "verify", "Module Verifier", false, false)
6996 FunctionPass
*llvm::createVerifierPass(bool FatalErrors
) {
6997 return new VerifierLegacyPass(FatalErrors
);
7000 AnalysisKey
VerifierAnalysis::Key
;
7001 VerifierAnalysis::Result
VerifierAnalysis::run(Module
&M
,
7002 ModuleAnalysisManager
&) {
7004 Res
.IRBroken
= llvm::verifyModule(M
, &dbgs(), &Res
.DebugInfoBroken
);
7008 VerifierAnalysis::Result
VerifierAnalysis::run(Function
&F
,
7009 FunctionAnalysisManager
&) {
7010 return { llvm::verifyFunction(F
, &dbgs()), false };
7013 PreservedAnalyses
VerifierPass::run(Module
&M
, ModuleAnalysisManager
&AM
) {
7014 auto Res
= AM
.getResult
<VerifierAnalysis
>(M
);
7015 if (FatalErrors
&& (Res
.IRBroken
|| Res
.DebugInfoBroken
))
7016 report_fatal_error("Broken module found, compilation aborted!");
7018 return PreservedAnalyses::all();
7021 PreservedAnalyses
VerifierPass::run(Function
&F
, FunctionAnalysisManager
&AM
) {
7022 auto res
= AM
.getResult
<VerifierAnalysis
>(F
);
7023 if (res
.IRBroken
&& FatalErrors
)
7024 report_fatal_error("Broken function found, compilation aborted!");
7026 return PreservedAnalyses::all();