1 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the function verifier interface, that can be used for some
11 // sanity checking of input to the system.
13 // Note that this does not provide full `Java style' security and verifications,
14 // instead it just tries to ensure that code is well-formed.
16 // * Both of a binary operator's parameters are of the same type
17 // * Verify that the indices of mem access instructions match other operands
18 // * Verify that arithmetic and other things are only performed on first-class
19 // types. Verify that shifts & logicals only happen on integrals f.e.
20 // * All of the constants in a switch statement are of the correct type
21 // * The code is in valid SSA form
22 // * It should be illegal to put a label into any other type (like a structure)
23 // or to return one. [except constant arrays!]
24 // * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
25 // * PHI nodes must have an entry for each predecessor, with no extras.
26 // * PHI nodes must be the first thing in a basic block, all grouped together
27 // * PHI nodes must have at least one entry
28 // * All basic blocks should only end with terminator insts, not contain them
29 // * The entry node to a function must not have predecessors
30 // * All Instructions must be embedded into a basic block
31 // * Functions cannot take a void-typed parameter
32 // * Verify that a function's argument list agrees with it's declared type.
33 // * It is illegal to specify a name for a void value.
34 // * It is illegal to have a internal global value with no initializer
35 // * It is illegal to have a ret instruction that returns a value that does not
36 // agree with the function return value type.
37 // * Function call argument types match the function prototype
38 // * A landing pad is defined by a landingpad instruction, and can be jumped to
39 // only by the unwind edge of an invoke instruction.
40 // * A landingpad instruction must be the first non-PHI instruction in the
42 // * All landingpad instructions must use the same personality function with
44 // * All other things that are tested by asserts spread about the code...
46 //===----------------------------------------------------------------------===//
48 #include "llvm/IR/Verifier.h"
49 #include "llvm/ADT/STLExtras.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallVector.h"
53 #include "llvm/ADT/StringExtras.h"
54 #include "llvm/IR/CFG.h"
55 #include "llvm/IR/CallSite.h"
56 #include "llvm/IR/CallingConv.h"
57 #include "llvm/IR/ConstantRange.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugInfo.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/Dominators.h"
63 #include "llvm/IR/InlineAsm.h"
64 #include "llvm/IR/InstIterator.h"
65 #include "llvm/IR/InstVisitor.h"
66 #include "llvm/IR/IntrinsicInst.h"
67 #include "llvm/IR/LLVMContext.h"
68 #include "llvm/IR/Metadata.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/PassManager.h"
71 #include "llvm/IR/Statepoint.h"
72 #include "llvm/Pass.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/raw_ostream.h"
81 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true));
84 struct VerifierSupport {
88 /// \brief Track the brokenness of the module while recursively visiting.
91 explicit VerifierSupport(raw_ostream &OS)
92 : OS(OS), M(nullptr), Broken(false) {}
95 void Write(const Value *V) {
98 if (isa<Instruction>(V)) {
101 V->printAsOperand(OS, true, M);
106 void Write(const Metadata *MD) {
113 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
117 void Write(const NamedMDNode *NMD) {
124 void Write(Type *T) {
130 void Write(const Comdat *C) {
136 template <typename T1, typename... Ts>
137 void WriteTs(const T1 &V1, const Ts &... Vs) {
142 template <typename... Ts> void WriteTs() {}
145 /// \brief A check failed, so printout out the condition and the message.
147 /// This provides a nice place to put a breakpoint if you want to see why
148 /// something is not correct.
149 void CheckFailed(const Twine &Message) {
150 OS << Message << '\n';
154 /// \brief A check failed (with values to print).
156 /// This calls the Message-only version so that the above is easier to set a
158 template <typename T1, typename... Ts>
159 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
160 CheckFailed(Message);
165 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
166 friend class InstVisitor<Verifier>;
168 LLVMContext *Context;
171 /// \brief When verifying a basic block, keep track of all of the
172 /// instructions we have seen so far.
174 /// This allows us to do efficient dominance checks for the case when an
175 /// instruction has an operand that is an instruction in the same block.
176 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
178 /// \brief Keep track of the metadata nodes that have been checked already.
179 SmallPtrSet<const Metadata *, 32> MDNodes;
181 /// \brief Track unresolved string-based type references.
182 SmallDenseMap<const MDString *, const MDNode *, 32> UnresolvedTypeRefs;
184 /// \brief Track queue of bit piece expressions to verify.
185 SmallVector<const DbgInfoIntrinsic *, 32> QueuedBitPieceExpressions;
187 /// \brief The personality function referenced by the LandingPadInsts.
188 /// All LandingPadInsts within the same function must use the same
189 /// personality function.
190 const Value *PersonalityFn;
192 /// \brief Whether we've seen a call to @llvm.frameescape in this function
196 /// Stores the count of how many objects were passed to llvm.frameescape for a
197 /// given function and the largest index passed to llvm.framerecover.
198 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
201 explicit Verifier(raw_ostream &OS)
202 : VerifierSupport(OS), Context(nullptr), PersonalityFn(nullptr),
203 SawFrameEscape(false) {}
205 bool verify(const Function &F) {
207 Context = &M->getContext();
209 // First ensure the function is well-enough formed to compute dominance
212 OS << "Function '" << F.getName()
213 << "' does not contain an entry block!\n";
216 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
217 if (I->empty() || !I->back().isTerminator()) {
218 OS << "Basic Block in function '" << F.getName()
219 << "' does not have terminator!\n";
220 I->printAsOperand(OS, true);
226 // Now directly compute a dominance tree. We don't rely on the pass
227 // manager to provide this as it isolates us from a potentially
228 // out-of-date dominator tree and makes it significantly more complex to
229 // run this code outside of a pass manager.
230 // FIXME: It's really gross that we have to cast away constness here.
231 DT.recalculate(const_cast<Function &>(F));
234 // FIXME: We strip const here because the inst visitor strips const.
235 visit(const_cast<Function &>(F));
236 InstsInThisBlock.clear();
237 PersonalityFn = nullptr;
238 SawFrameEscape = false;
243 bool verify(const Module &M) {
245 Context = &M.getContext();
248 // Scan through, checking all of the external function's linkage now...
249 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
250 visitGlobalValue(*I);
252 // Check to make sure function prototypes are okay.
253 if (I->isDeclaration())
257 // Now that we've visited every function, verify that we never asked to
258 // recover a frame index that wasn't escaped.
259 verifyFrameRecoverIndices();
261 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
263 visitGlobalVariable(*I);
265 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
267 visitGlobalAlias(*I);
269 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
270 E = M.named_metadata_end();
272 visitNamedMDNode(*I);
274 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
275 visitComdat(SMEC.getValue());
278 visitModuleIdents(M);
280 // Verify type referneces last.
287 // Verification methods...
288 void visitGlobalValue(const GlobalValue &GV);
289 void visitGlobalVariable(const GlobalVariable &GV);
290 void visitGlobalAlias(const GlobalAlias &GA);
291 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
292 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
293 const GlobalAlias &A, const Constant &C);
294 void visitNamedMDNode(const NamedMDNode &NMD);
295 void visitMDNode(const MDNode &MD);
296 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
297 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
298 void visitComdat(const Comdat &C);
299 void visitModuleIdents(const Module &M);
300 void visitModuleFlags(const Module &M);
301 void visitModuleFlag(const MDNode *Op,
302 DenseMap<const MDString *, const MDNode *> &SeenIDs,
303 SmallVectorImpl<const MDNode *> &Requirements);
304 void visitFunction(const Function &F);
305 void visitBasicBlock(BasicBlock &BB);
306 void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty);
308 template <class Ty> bool isValidMetadataArray(const MDTuple &N);
309 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
310 #include "llvm/IR/Metadata.def"
311 void visitMDScope(const MDScope &N);
312 void visitMDDerivedTypeBase(const MDDerivedTypeBase &N);
313 void visitMDVariable(const MDVariable &N);
314 void visitMDLexicalBlockBase(const MDLexicalBlockBase &N);
315 void visitMDTemplateParameter(const MDTemplateParameter &N);
317 void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
319 /// \brief Check for a valid string-based type reference.
321 /// Checks if \c MD is a string-based type reference. If it is, keeps track
322 /// of it (and its user, \c N) for error messages later.
323 bool isValidUUID(const MDNode &N, const Metadata *MD);
325 /// \brief Check for a valid type reference.
327 /// Checks for subclasses of \a MDType, or \a isValidUUID().
328 bool isTypeRef(const MDNode &N, const Metadata *MD);
330 /// \brief Check for a valid scope reference.
332 /// Checks for subclasses of \a MDScope, or \a isValidUUID().
333 bool isScopeRef(const MDNode &N, const Metadata *MD);
335 /// \brief Check for a valid debug info reference.
337 /// Checks for subclasses of \a DebugNode, or \a isValidUUID().
338 bool isDIRef(const MDNode &N, const Metadata *MD);
340 // InstVisitor overrides...
341 using InstVisitor<Verifier>::visit;
342 void visit(Instruction &I);
344 void visitTruncInst(TruncInst &I);
345 void visitZExtInst(ZExtInst &I);
346 void visitSExtInst(SExtInst &I);
347 void visitFPTruncInst(FPTruncInst &I);
348 void visitFPExtInst(FPExtInst &I);
349 void visitFPToUIInst(FPToUIInst &I);
350 void visitFPToSIInst(FPToSIInst &I);
351 void visitUIToFPInst(UIToFPInst &I);
352 void visitSIToFPInst(SIToFPInst &I);
353 void visitIntToPtrInst(IntToPtrInst &I);
354 void visitPtrToIntInst(PtrToIntInst &I);
355 void visitBitCastInst(BitCastInst &I);
356 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
357 void visitPHINode(PHINode &PN);
358 void visitBinaryOperator(BinaryOperator &B);
359 void visitICmpInst(ICmpInst &IC);
360 void visitFCmpInst(FCmpInst &FC);
361 void visitExtractElementInst(ExtractElementInst &EI);
362 void visitInsertElementInst(InsertElementInst &EI);
363 void visitShuffleVectorInst(ShuffleVectorInst &EI);
364 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
365 void visitCallInst(CallInst &CI);
366 void visitInvokeInst(InvokeInst &II);
367 void visitGetElementPtrInst(GetElementPtrInst &GEP);
368 void visitLoadInst(LoadInst &LI);
369 void visitStoreInst(StoreInst &SI);
370 void verifyDominatesUse(Instruction &I, unsigned i);
371 void visitInstruction(Instruction &I);
372 void visitTerminatorInst(TerminatorInst &I);
373 void visitBranchInst(BranchInst &BI);
374 void visitReturnInst(ReturnInst &RI);
375 void visitSwitchInst(SwitchInst &SI);
376 void visitIndirectBrInst(IndirectBrInst &BI);
377 void visitSelectInst(SelectInst &SI);
378 void visitUserOp1(Instruction &I);
379 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
380 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
381 template <class DbgIntrinsicTy>
382 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
383 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
384 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
385 void visitFenceInst(FenceInst &FI);
386 void visitAllocaInst(AllocaInst &AI);
387 void visitExtractValueInst(ExtractValueInst &EVI);
388 void visitInsertValueInst(InsertValueInst &IVI);
389 void visitLandingPadInst(LandingPadInst &LPI);
391 void VerifyCallSite(CallSite CS);
392 void verifyMustTailCall(CallInst &CI);
393 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
394 unsigned ArgNo, std::string &Suffix);
395 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
396 SmallVectorImpl<Type *> &ArgTys);
397 bool VerifyIntrinsicIsVarArg(bool isVarArg,
398 ArrayRef<Intrinsic::IITDescriptor> &Infos);
399 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
400 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
402 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
403 bool isReturnValue, const Value *V);
404 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
407 void VerifyConstantExprBitcastType(const ConstantExpr *CE);
408 void VerifyStatepoint(ImmutableCallSite CS);
409 void verifyFrameRecoverIndices();
411 // Module-level debug info verification...
412 void verifyTypeRefs();
413 template <class MapTy>
414 void verifyBitPieceExpression(const DbgInfoIntrinsic &I,
415 const MapTy &TypeRefs);
416 void visitUnresolvedTypeRef(const MDString *S, const MDNode *N);
418 } // End anonymous namespace
420 // Assert - We know that cond should be true, if not print an error message.
421 #define Assert(C, ...) \
422 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
424 void Verifier::visit(Instruction &I) {
425 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
426 Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
427 InstVisitor<Verifier>::visit(I);
431 void Verifier::visitGlobalValue(const GlobalValue &GV) {
432 Assert(!GV.isDeclaration() || GV.hasExternalLinkage() ||
433 GV.hasExternalWeakLinkage(),
434 "Global is external, but doesn't have external or weak linkage!", &GV);
436 Assert(GV.getAlignment() <= Value::MaximumAlignment,
437 "huge alignment values are unsupported", &GV);
438 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
439 "Only global variables can have appending linkage!", &GV);
441 if (GV.hasAppendingLinkage()) {
442 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
443 Assert(GVar && GVar->getType()->getElementType()->isArrayTy(),
444 "Only global arrays can have appending linkage!", GVar);
448 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
449 if (GV.hasInitializer()) {
450 Assert(GV.getInitializer()->getType() == GV.getType()->getElementType(),
451 "Global variable initializer type does not match global "
455 // If the global has common linkage, it must have a zero initializer and
456 // cannot be constant.
457 if (GV.hasCommonLinkage()) {
458 Assert(GV.getInitializer()->isNullValue(),
459 "'common' global must have a zero initializer!", &GV);
460 Assert(!GV.isConstant(), "'common' global may not be marked constant!",
462 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
465 Assert(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
466 "invalid linkage type for global declaration", &GV);
469 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
470 GV.getName() == "llvm.global_dtors")) {
471 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
472 "invalid linkage for intrinsic global variable", &GV);
473 // Don't worry about emitting an error for it not being an array,
474 // visitGlobalValue will complain on appending non-array.
475 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType()->getElementType())) {
476 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
477 PointerType *FuncPtrTy =
478 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
479 // FIXME: Reject the 2-field form in LLVM 4.0.
481 (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
482 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
483 STy->getTypeAtIndex(1) == FuncPtrTy,
484 "wrong type for intrinsic global variable", &GV);
485 if (STy->getNumElements() == 3) {
486 Type *ETy = STy->getTypeAtIndex(2);
487 Assert(ETy->isPointerTy() &&
488 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
489 "wrong type for intrinsic global variable", &GV);
494 if (GV.hasName() && (GV.getName() == "llvm.used" ||
495 GV.getName() == "llvm.compiler.used")) {
496 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
497 "invalid linkage for intrinsic global variable", &GV);
498 Type *GVType = GV.getType()->getElementType();
499 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
500 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
501 Assert(PTy, "wrong type for intrinsic global variable", &GV);
502 if (GV.hasInitializer()) {
503 const Constant *Init = GV.getInitializer();
504 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
505 Assert(InitArray, "wrong initalizer for intrinsic global variable",
507 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
508 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
509 Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
511 "invalid llvm.used member", V);
512 Assert(V->hasName(), "members of llvm.used must be named", V);
518 Assert(!GV.hasDLLImportStorageClass() ||
519 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
520 GV.hasAvailableExternallyLinkage(),
521 "Global is marked as dllimport, but not external", &GV);
523 if (!GV.hasInitializer()) {
524 visitGlobalValue(GV);
528 // Walk any aggregate initializers looking for bitcasts between address spaces
529 SmallPtrSet<const Value *, 4> Visited;
530 SmallVector<const Value *, 4> WorkStack;
531 WorkStack.push_back(cast<Value>(GV.getInitializer()));
533 while (!WorkStack.empty()) {
534 const Value *V = WorkStack.pop_back_val();
535 if (!Visited.insert(V).second)
538 if (const User *U = dyn_cast<User>(V)) {
539 WorkStack.append(U->op_begin(), U->op_end());
542 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
543 VerifyConstantExprBitcastType(CE);
549 visitGlobalValue(GV);
552 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
553 SmallPtrSet<const GlobalAlias*, 4> Visited;
555 visitAliaseeSubExpr(Visited, GA, C);
558 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
559 const GlobalAlias &GA, const Constant &C) {
560 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
561 Assert(!GV->isDeclaration(), "Alias must point to a definition", &GA);
563 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
564 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
566 Assert(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
569 // Only continue verifying subexpressions of GlobalAliases.
570 // Do not recurse into global initializers.
575 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
576 VerifyConstantExprBitcastType(CE);
578 for (const Use &U : C.operands()) {
580 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
581 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
582 else if (const auto *C2 = dyn_cast<Constant>(V))
583 visitAliaseeSubExpr(Visited, GA, *C2);
587 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
588 Assert(!GA.getName().empty(), "Alias name cannot be empty!", &GA);
589 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
590 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
591 "weak_odr, or external linkage!",
593 const Constant *Aliasee = GA.getAliasee();
594 Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
595 Assert(GA.getType() == Aliasee->getType(),
596 "Alias and aliasee types should match!", &GA);
598 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
599 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
601 visitAliaseeSubExpr(GA, *Aliasee);
603 visitGlobalValue(GA);
606 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
607 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
608 MDNode *MD = NMD.getOperand(i);
610 if (NMD.getName() == "llvm.dbg.cu") {
611 Assert(MD && isa<MDCompileUnit>(MD), "invalid compile unit", &NMD, MD);
621 void Verifier::visitMDNode(const MDNode &MD) {
622 // Only visit each node once. Metadata can be mutually recursive, so this
623 // avoids infinite recursion here, as well as being an optimization.
624 if (!MDNodes.insert(&MD).second)
627 switch (MD.getMetadataID()) {
629 llvm_unreachable("Invalid MDNode subclass");
630 case Metadata::MDTupleKind:
632 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
633 case Metadata::CLASS##Kind: \
634 visit##CLASS(cast<CLASS>(MD)); \
636 #include "llvm/IR/Metadata.def"
639 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
640 Metadata *Op = MD.getOperand(i);
643 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
645 if (auto *N = dyn_cast<MDNode>(Op)) {
649 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
650 visitValueAsMetadata(*V, nullptr);
655 // Check these last, so we diagnose problems in operands first.
656 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
657 Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
660 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
661 Assert(MD.getValue(), "Expected valid value", &MD);
662 Assert(!MD.getValue()->getType()->isMetadataTy(),
663 "Unexpected metadata round-trip through values", &MD, MD.getValue());
665 auto *L = dyn_cast<LocalAsMetadata>(&MD);
669 Assert(F, "function-local metadata used outside a function", L);
671 // If this was an instruction, bb, or argument, verify that it is in the
672 // function that we expect.
673 Function *ActualF = nullptr;
674 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
675 Assert(I->getParent(), "function-local metadata not in basic block", L, I);
676 ActualF = I->getParent()->getParent();
677 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
678 ActualF = BB->getParent();
679 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
680 ActualF = A->getParent();
681 assert(ActualF && "Unimplemented function local metadata case!");
683 Assert(ActualF == F, "function-local metadata used in wrong function", L);
686 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
687 Metadata *MD = MDV.getMetadata();
688 if (auto *N = dyn_cast<MDNode>(MD)) {
693 // Only visit each node once. Metadata can be mutually recursive, so this
694 // avoids infinite recursion here, as well as being an optimization.
695 if (!MDNodes.insert(MD).second)
698 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
699 visitValueAsMetadata(*V, F);
702 bool Verifier::isValidUUID(const MDNode &N, const Metadata *MD) {
703 auto *S = dyn_cast<MDString>(MD);
706 if (S->getString().empty())
709 // Keep track of names of types referenced via UUID so we can check that they
711 UnresolvedTypeRefs.insert(std::make_pair(S, &N));
715 /// \brief Check if a value can be a reference to a type.
716 bool Verifier::isTypeRef(const MDNode &N, const Metadata *MD) {
717 return !MD || isValidUUID(N, MD) || isa<MDType>(MD);
720 /// \brief Check if a value can be a ScopeRef.
721 bool Verifier::isScopeRef(const MDNode &N, const Metadata *MD) {
722 return !MD || isValidUUID(N, MD) || isa<MDScope>(MD);
725 /// \brief Check if a value can be a debug info ref.
726 bool Verifier::isDIRef(const MDNode &N, const Metadata *MD) {
727 return !MD || isValidUUID(N, MD) || isa<DebugNode>(MD);
731 bool isValidMetadataArrayImpl(const MDTuple &N, bool AllowNull) {
732 for (Metadata *MD : N.operands()) {
745 bool isValidMetadataArray(const MDTuple &N) {
746 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ false);
750 bool isValidMetadataNullArray(const MDTuple &N) {
751 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ true);
754 void Verifier::visitMDLocation(const MDLocation &N) {
755 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
756 "location requires a valid scope", &N, N.getRawScope());
757 if (auto *IA = N.getRawInlinedAt())
758 Assert(isa<MDLocation>(IA), "inlined-at should be a location", &N, IA);
761 void Verifier::visitGenericDebugNode(const GenericDebugNode &N) {
762 Assert(N.getTag(), "invalid tag", &N);
765 void Verifier::visitMDScope(const MDScope &N) {
766 if (auto *F = N.getRawFile())
767 Assert(isa<MDFile>(F), "invalid file", &N, F);
770 void Verifier::visitMDSubrange(const MDSubrange &N) {
771 Assert(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
772 Assert(N.getCount() >= -1, "invalid subrange count", &N);
775 void Verifier::visitMDEnumerator(const MDEnumerator &N) {
776 Assert(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
779 void Verifier::visitMDBasicType(const MDBasicType &N) {
780 Assert(N.getTag() == dwarf::DW_TAG_base_type ||
781 N.getTag() == dwarf::DW_TAG_unspecified_type,
785 void Verifier::visitMDDerivedTypeBase(const MDDerivedTypeBase &N) {
786 // Common scope checks.
789 Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope());
790 Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N,
793 // FIXME: Sink this into the subclass verifies.
794 if (!N.getFile() || N.getFile()->getFilename().empty()) {
795 // Check whether the filename is allowed to be empty.
796 uint16_t Tag = N.getTag();
798 Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
799 Tag == dwarf::DW_TAG_pointer_type ||
800 Tag == dwarf::DW_TAG_ptr_to_member_type ||
801 Tag == dwarf::DW_TAG_reference_type ||
802 Tag == dwarf::DW_TAG_rvalue_reference_type ||
803 Tag == dwarf::DW_TAG_restrict_type ||
804 Tag == dwarf::DW_TAG_array_type ||
805 Tag == dwarf::DW_TAG_enumeration_type ||
806 Tag == dwarf::DW_TAG_subroutine_type ||
807 Tag == dwarf::DW_TAG_inheritance || Tag == dwarf::DW_TAG_friend ||
808 Tag == dwarf::DW_TAG_structure_type ||
809 Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef,
810 "derived/composite type requires a filename", &N, N.getFile());
814 void Verifier::visitMDDerivedType(const MDDerivedType &N) {
815 // Common derived type checks.
816 visitMDDerivedTypeBase(N);
818 Assert(N.getTag() == dwarf::DW_TAG_typedef ||
819 N.getTag() == dwarf::DW_TAG_pointer_type ||
820 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
821 N.getTag() == dwarf::DW_TAG_reference_type ||
822 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
823 N.getTag() == dwarf::DW_TAG_const_type ||
824 N.getTag() == dwarf::DW_TAG_volatile_type ||
825 N.getTag() == dwarf::DW_TAG_restrict_type ||
826 N.getTag() == dwarf::DW_TAG_member ||
827 N.getTag() == dwarf::DW_TAG_inheritance ||
828 N.getTag() == dwarf::DW_TAG_friend,
830 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
831 Assert(isTypeRef(N, N.getExtraData()), "invalid pointer to member type", &N,
836 static bool hasConflictingReferenceFlags(unsigned Flags) {
837 return (Flags & DebugNode::FlagLValueReference) &&
838 (Flags & DebugNode::FlagRValueReference);
841 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
842 auto *Params = dyn_cast<MDTuple>(&RawParams);
843 Assert(Params, "invalid template params", &N, &RawParams);
844 for (Metadata *Op : Params->operands()) {
845 Assert(Op && isa<MDTemplateParameter>(Op), "invalid template parameter", &N,
850 void Verifier::visitMDCompositeType(const MDCompositeType &N) {
851 // Common derived type checks.
852 visitMDDerivedTypeBase(N);
854 Assert(N.getTag() == dwarf::DW_TAG_array_type ||
855 N.getTag() == dwarf::DW_TAG_structure_type ||
856 N.getTag() == dwarf::DW_TAG_union_type ||
857 N.getTag() == dwarf::DW_TAG_enumeration_type ||
858 N.getTag() == dwarf::DW_TAG_subroutine_type ||
859 N.getTag() == dwarf::DW_TAG_class_type,
862 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
863 "invalid composite elements", &N, N.getRawElements());
864 Assert(isTypeRef(N, N.getRawVTableHolder()), "invalid vtable holder", &N,
865 N.getRawVTableHolder());
866 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
867 "invalid composite elements", &N, N.getRawElements());
868 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
870 if (auto *Params = N.getRawTemplateParams())
871 visitTemplateParams(N, *Params);
874 void Verifier::visitMDSubroutineType(const MDSubroutineType &N) {
875 Assert(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
876 if (auto *Types = N.getRawTypeArray()) {
877 Assert(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
878 for (Metadata *Ty : N.getTypeArray()->operands()) {
879 Assert(isTypeRef(N, Ty), "invalid subroutine type ref", &N, Types, Ty);
882 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
886 void Verifier::visitMDFile(const MDFile &N) {
887 Assert(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
890 void Verifier::visitMDCompileUnit(const MDCompileUnit &N) {
891 Assert(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
893 // Don't bother verifying the compilation directory or producer string
894 // as those could be empty.
895 Assert(N.getRawFile() && isa<MDFile>(N.getRawFile()),
896 "invalid file", &N, N.getRawFile());
897 Assert(!N.getFile()->getFilename().empty(), "invalid filename", &N,
900 if (auto *Array = N.getRawEnumTypes()) {
901 Assert(isa<MDTuple>(Array), "invalid enum list", &N, Array);
902 for (Metadata *Op : N.getEnumTypes()->operands()) {
903 auto *Enum = dyn_cast_or_null<MDCompositeType>(Op);
904 Assert(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
905 "invalid enum type", &N, N.getEnumTypes(), Op);
908 if (auto *Array = N.getRawRetainedTypes()) {
909 Assert(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
910 for (Metadata *Op : N.getRetainedTypes()->operands()) {
911 Assert(Op && isa<MDType>(Op), "invalid retained type", &N, Op);
914 if (auto *Array = N.getRawSubprograms()) {
915 Assert(isa<MDTuple>(Array), "invalid subprogram list", &N, Array);
916 for (Metadata *Op : N.getSubprograms()->operands()) {
917 Assert(Op && isa<MDSubprogram>(Op), "invalid subprogram ref", &N, Op);
920 if (auto *Array = N.getRawGlobalVariables()) {
921 Assert(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
922 for (Metadata *Op : N.getGlobalVariables()->operands()) {
923 Assert(Op && isa<MDGlobalVariable>(Op), "invalid global variable ref", &N,
927 if (auto *Array = N.getRawImportedEntities()) {
928 Assert(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
929 for (Metadata *Op : N.getImportedEntities()->operands()) {
930 Assert(Op && isa<MDImportedEntity>(Op), "invalid imported entity ref", &N,
936 void Verifier::visitMDSubprogram(const MDSubprogram &N) {
937 Assert(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
938 Assert(isScopeRef(N, N.getRawScope()), "invalid scope", &N, N.getRawScope());
939 if (auto *T = N.getRawType())
940 Assert(isa<MDSubroutineType>(T), "invalid subroutine type", &N, T);
941 Assert(isTypeRef(N, N.getRawContainingType()), "invalid containing type", &N,
942 N.getRawContainingType());
943 if (auto *RawF = N.getRawFunction()) {
944 auto *FMD = dyn_cast<ConstantAsMetadata>(RawF);
945 auto *F = FMD ? FMD->getValue() : nullptr;
946 auto *FT = F ? dyn_cast<PointerType>(F->getType()) : nullptr;
947 Assert(F && FT && isa<FunctionType>(FT->getElementType()),
948 "invalid function", &N, F, FT);
950 if (auto *Params = N.getRawTemplateParams())
951 visitTemplateParams(N, *Params);
952 if (auto *S = N.getRawDeclaration()) {
953 Assert(isa<MDSubprogram>(S) && !cast<MDSubprogram>(S)->isDefinition(),
954 "invalid subprogram declaration", &N, S);
956 if (auto *RawVars = N.getRawVariables()) {
957 auto *Vars = dyn_cast<MDTuple>(RawVars);
958 Assert(Vars, "invalid variable list", &N, RawVars);
959 for (Metadata *Op : Vars->operands()) {
960 Assert(Op && isa<MDLocalVariable>(Op), "invalid local variable", &N, Vars,
964 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
967 if (!N.getFunction())
970 // FIXME: Should this be looking through bitcasts?
971 auto *F = dyn_cast<Function>(N.getFunction()->getValue());
975 // Check that all !dbg attachments lead to back to N (or, at least, another
976 // subprogram that describes the same function).
978 // FIXME: Check this incrementally while visiting !dbg attachments.
979 // FIXME: Only check when N is the canonical subprogram for F.
980 SmallPtrSet<const MDNode *, 32> Seen;
983 // Be careful about using MDLocation here since we might be dealing with
984 // broken code (this is the Verifier after all).
986 dyn_cast_or_null<MDLocation>(I.getDebugLoc().getAsMDNode());
989 if (!Seen.insert(DL).second)
992 MDLocalScope *Scope = DL->getInlinedAtScope();
993 if (Scope && !Seen.insert(Scope).second)
996 MDSubprogram *SP = Scope ? Scope->getSubprogram() : nullptr;
997 if (SP && !Seen.insert(SP).second)
1000 // FIXME: Once N is canonical, check "SP == &N".
1001 Assert(DISubprogram(SP).describes(F),
1002 "!dbg attachment points at wrong subprogram for function", &N, F,
1007 void Verifier::visitMDLexicalBlockBase(const MDLexicalBlockBase &N) {
1008 Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
1009 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
1010 "invalid local scope", &N, N.getRawScope());
1013 void Verifier::visitMDLexicalBlock(const MDLexicalBlock &N) {
1014 visitMDLexicalBlockBase(N);
1016 Assert(N.getLine() || !N.getColumn(),
1017 "cannot have column info without line info", &N);
1020 void Verifier::visitMDLexicalBlockFile(const MDLexicalBlockFile &N) {
1021 visitMDLexicalBlockBase(N);
1024 void Verifier::visitMDNamespace(const MDNamespace &N) {
1025 Assert(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
1026 if (auto *S = N.getRawScope())
1027 Assert(isa<MDScope>(S), "invalid scope ref", &N, S);
1030 void Verifier::visitMDTemplateParameter(const MDTemplateParameter &N) {
1031 Assert(isTypeRef(N, N.getType()), "invalid type ref", &N, N.getType());
1034 void Verifier::visitMDTemplateTypeParameter(const MDTemplateTypeParameter &N) {
1035 visitMDTemplateParameter(N);
1037 Assert(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1041 void Verifier::visitMDTemplateValueParameter(
1042 const MDTemplateValueParameter &N) {
1043 visitMDTemplateParameter(N);
1045 Assert(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1046 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1047 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1051 void Verifier::visitMDVariable(const MDVariable &N) {
1052 if (auto *S = N.getRawScope())
1053 Assert(isa<MDScope>(S), "invalid scope", &N, S);
1054 Assert(isTypeRef(N, N.getRawType()), "invalid type ref", &N, N.getRawType());
1055 if (auto *F = N.getRawFile())
1056 Assert(isa<MDFile>(F), "invalid file", &N, F);
1059 void Verifier::visitMDGlobalVariable(const MDGlobalVariable &N) {
1060 // Checks common to all variables.
1063 Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1064 Assert(!N.getName().empty(), "missing global variable name", &N);
1065 if (auto *V = N.getRawVariable()) {
1066 Assert(isa<ConstantAsMetadata>(V) &&
1067 !isa<Function>(cast<ConstantAsMetadata>(V)->getValue()),
1068 "invalid global varaible ref", &N, V);
1070 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1071 Assert(isa<MDDerivedType>(Member), "invalid static data member declaration",
1076 void Verifier::visitMDLocalVariable(const MDLocalVariable &N) {
1077 // Checks common to all variables.
1080 Assert(N.getTag() == dwarf::DW_TAG_auto_variable ||
1081 N.getTag() == dwarf::DW_TAG_arg_variable,
1083 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
1084 "local variable requires a valid scope", &N, N.getRawScope());
1085 if (auto *IA = N.getRawInlinedAt())
1086 Assert(isa<MDLocation>(IA), "local variable requires a valid scope", &N,
1090 void Verifier::visitMDExpression(const MDExpression &N) {
1091 Assert(N.isValid(), "invalid expression", &N);
1094 void Verifier::visitMDObjCProperty(const MDObjCProperty &N) {
1095 Assert(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1096 if (auto *T = N.getRawType())
1097 Assert(isa<MDType>(T), "invalid type ref", &N, T);
1098 if (auto *F = N.getRawFile())
1099 Assert(isa<MDFile>(F), "invalid file", &N, F);
1102 void Verifier::visitMDImportedEntity(const MDImportedEntity &N) {
1103 Assert(N.getTag() == dwarf::DW_TAG_imported_module ||
1104 N.getTag() == dwarf::DW_TAG_imported_declaration,
1106 if (auto *S = N.getRawScope())
1107 Assert(isa<MDScope>(S), "invalid scope for imported entity", &N, S);
1108 Assert(isDIRef(N, N.getEntity()), "invalid imported entity", &N,
1112 void Verifier::visitComdat(const Comdat &C) {
1113 // The Module is invalid if the GlobalValue has private linkage. Entities
1114 // with private linkage don't have entries in the symbol table.
1115 if (const GlobalValue *GV = M->getNamedValue(C.getName()))
1116 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1120 void Verifier::visitModuleIdents(const Module &M) {
1121 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1125 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1126 // Scan each llvm.ident entry and make sure that this requirement is met.
1127 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
1128 const MDNode *N = Idents->getOperand(i);
1129 Assert(N->getNumOperands() == 1,
1130 "incorrect number of operands in llvm.ident metadata", N);
1131 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1132 ("invalid value for llvm.ident metadata entry operand"
1133 "(the operand should be a string)"),
1138 void Verifier::visitModuleFlags(const Module &M) {
1139 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1142 // Scan each flag, and track the flags and requirements.
1143 DenseMap<const MDString*, const MDNode*> SeenIDs;
1144 SmallVector<const MDNode*, 16> Requirements;
1145 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
1146 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
1149 // Validate that the requirements in the module are valid.
1150 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1151 const MDNode *Requirement = Requirements[I];
1152 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1153 const Metadata *ReqValue = Requirement->getOperand(1);
1155 const MDNode *Op = SeenIDs.lookup(Flag);
1157 CheckFailed("invalid requirement on flag, flag is not present in module",
1162 if (Op->getOperand(2) != ReqValue) {
1163 CheckFailed(("invalid requirement on flag, "
1164 "flag does not have the required value"),
1172 Verifier::visitModuleFlag(const MDNode *Op,
1173 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1174 SmallVectorImpl<const MDNode *> &Requirements) {
1175 // Each module flag should have three arguments, the merge behavior (a
1176 // constant int), the flag ID (an MDString), and the value.
1177 Assert(Op->getNumOperands() == 3,
1178 "incorrect number of operands in module flag", Op);
1179 Module::ModFlagBehavior MFB;
1180 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1182 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1183 "invalid behavior operand in module flag (expected constant integer)",
1186 "invalid behavior operand in module flag (unexpected constant)",
1189 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1190 Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1193 // Sanity check the values for behaviors with additional requirements.
1196 case Module::Warning:
1197 case Module::Override:
1198 // These behavior types accept any value.
1201 case Module::Require: {
1202 // The value should itself be an MDNode with two operands, a flag ID (an
1203 // MDString), and a value.
1204 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1205 Assert(Value && Value->getNumOperands() == 2,
1206 "invalid value for 'require' module flag (expected metadata pair)",
1208 Assert(isa<MDString>(Value->getOperand(0)),
1209 ("invalid value for 'require' module flag "
1210 "(first value operand should be a string)"),
1211 Value->getOperand(0));
1213 // Append it to the list of requirements, to check once all module flags are
1215 Requirements.push_back(Value);
1219 case Module::Append:
1220 case Module::AppendUnique: {
1221 // These behavior types require the operand be an MDNode.
1222 Assert(isa<MDNode>(Op->getOperand(2)),
1223 "invalid value for 'append'-type module flag "
1224 "(expected a metadata node)",
1230 // Unless this is a "requires" flag, check the ID is unique.
1231 if (MFB != Module::Require) {
1232 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1234 "module flag identifiers must be unique (or of 'require' type)", ID);
1238 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
1239 bool isFunction, const Value *V) {
1240 unsigned Slot = ~0U;
1241 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
1242 if (Attrs.getSlotIndex(I) == Idx) {
1247 assert(Slot != ~0U && "Attribute set inconsistency!");
1249 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
1251 if (I->isStringAttribute())
1254 if (I->getKindAsEnum() == Attribute::NoReturn ||
1255 I->getKindAsEnum() == Attribute::NoUnwind ||
1256 I->getKindAsEnum() == Attribute::NoInline ||
1257 I->getKindAsEnum() == Attribute::AlwaysInline ||
1258 I->getKindAsEnum() == Attribute::OptimizeForSize ||
1259 I->getKindAsEnum() == Attribute::StackProtect ||
1260 I->getKindAsEnum() == Attribute::StackProtectReq ||
1261 I->getKindAsEnum() == Attribute::StackProtectStrong ||
1262 I->getKindAsEnum() == Attribute::NoRedZone ||
1263 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
1264 I->getKindAsEnum() == Attribute::Naked ||
1265 I->getKindAsEnum() == Attribute::InlineHint ||
1266 I->getKindAsEnum() == Attribute::StackAlignment ||
1267 I->getKindAsEnum() == Attribute::UWTable ||
1268 I->getKindAsEnum() == Attribute::NonLazyBind ||
1269 I->getKindAsEnum() == Attribute::ReturnsTwice ||
1270 I->getKindAsEnum() == Attribute::SanitizeAddress ||
1271 I->getKindAsEnum() == Attribute::SanitizeThread ||
1272 I->getKindAsEnum() == Attribute::SanitizeMemory ||
1273 I->getKindAsEnum() == Attribute::MinSize ||
1274 I->getKindAsEnum() == Attribute::NoDuplicate ||
1275 I->getKindAsEnum() == Attribute::Builtin ||
1276 I->getKindAsEnum() == Attribute::NoBuiltin ||
1277 I->getKindAsEnum() == Attribute::Cold ||
1278 I->getKindAsEnum() == Attribute::OptimizeNone ||
1279 I->getKindAsEnum() == Attribute::JumpTable) {
1281 CheckFailed("Attribute '" + I->getAsString() +
1282 "' only applies to functions!", V);
1285 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
1286 I->getKindAsEnum() == Attribute::ReadNone) {
1288 CheckFailed("Attribute '" + I->getAsString() +
1289 "' does not apply to function returns");
1292 } else if (isFunction) {
1293 CheckFailed("Attribute '" + I->getAsString() +
1294 "' does not apply to functions!", V);
1300 // VerifyParameterAttrs - Check the given attributes for an argument or return
1301 // value of the specified type. The value V is printed in error messages.
1302 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
1303 bool isReturnValue, const Value *V) {
1304 if (!Attrs.hasAttributes(Idx))
1307 VerifyAttributeTypes(Attrs, Idx, false, V);
1310 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1311 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
1312 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1313 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
1314 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
1315 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1316 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
1317 "'returned' do not apply to return values!",
1320 // Check for mutually incompatible attributes. Only inreg is compatible with
1322 unsigned AttrCount = 0;
1323 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
1324 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
1325 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
1326 Attrs.hasAttribute(Idx, Attribute::InReg);
1327 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
1328 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1329 "and 'sret' are incompatible!",
1332 Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
1333 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1335 "'inalloca and readonly' are incompatible!",
1338 Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1339 Attrs.hasAttribute(Idx, Attribute::Returned)),
1341 "'sret and returned' are incompatible!",
1344 Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
1345 Attrs.hasAttribute(Idx, Attribute::SExt)),
1347 "'zeroext and signext' are incompatible!",
1350 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1351 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1353 "'readnone and readonly' are incompatible!",
1356 Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1357 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)),
1359 "'noinline and alwaysinline' are incompatible!",
1362 Assert(!AttrBuilder(Attrs, Idx)
1363 .hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
1364 "Wrong types for attribute: " +
1365 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx),
1368 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1369 SmallPtrSet<const Type*, 4> Visited;
1370 if (!PTy->getElementType()->isSized(&Visited)) {
1371 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1372 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1373 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1377 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal),
1378 "Attribute 'byval' only applies to parameters with pointer type!",
1383 // VerifyFunctionAttrs - Check parameter attributes against a function type.
1384 // The value V is printed in error messages.
1385 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
1387 if (Attrs.isEmpty())
1390 bool SawNest = false;
1391 bool SawReturned = false;
1392 bool SawSRet = false;
1394 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1395 unsigned Idx = Attrs.getSlotIndex(i);
1399 Ty = FT->getReturnType();
1400 else if (Idx-1 < FT->getNumParams())
1401 Ty = FT->getParamType(Idx-1);
1403 break; // VarArgs attributes, verified elsewhere.
1405 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
1410 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1411 Assert(!SawNest, "More than one parameter has attribute nest!", V);
1415 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1416 Assert(!SawReturned, "More than one parameter has attribute returned!",
1418 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1420 "argument and return types for 'returned' attribute",
1425 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
1426 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1427 Assert(Idx == 1 || Idx == 2,
1428 "Attribute 'sret' is not on first or second parameter!", V);
1432 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
1433 Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!",
1438 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
1441 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
1444 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1445 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)),
1446 "Attributes 'readnone and readonly' are incompatible!", V);
1449 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) &&
1450 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1451 Attribute::AlwaysInline)),
1452 "Attributes 'noinline and alwaysinline' are incompatible!", V);
1454 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1455 Attribute::OptimizeNone)) {
1456 Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline),
1457 "Attribute 'optnone' requires 'noinline'!", V);
1459 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1460 Attribute::OptimizeForSize),
1461 "Attributes 'optsize and optnone' are incompatible!", V);
1463 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize),
1464 "Attributes 'minsize and optnone' are incompatible!", V);
1467 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1468 Attribute::JumpTable)) {
1469 const GlobalValue *GV = cast<GlobalValue>(V);
1470 Assert(GV->hasUnnamedAddr(),
1471 "Attribute 'jumptable' requires 'unnamed_addr'", V);
1475 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
1476 if (CE->getOpcode() != Instruction::BitCast)
1479 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1481 "Invalid bitcast", CE);
1484 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
1485 if (Attrs.getNumSlots() == 0)
1488 unsigned LastSlot = Attrs.getNumSlots() - 1;
1489 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
1490 if (LastIndex <= Params
1491 || (LastIndex == AttributeSet::FunctionIndex
1492 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1498 /// \brief Verify that statepoint intrinsic is well formed.
1499 void Verifier::VerifyStatepoint(ImmutableCallSite CS) {
1500 assert(CS.getCalledFunction() &&
1501 CS.getCalledFunction()->getIntrinsicID() ==
1502 Intrinsic::experimental_gc_statepoint);
1504 const Instruction &CI = *CS.getInstruction();
1506 Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory(),
1507 "gc.statepoint must read and write memory to preserve "
1508 "reordering restrictions required by safepoint semantics",
1511 const Value *Target = CS.getArgument(0);
1512 const PointerType *PT = dyn_cast<PointerType>(Target->getType());
1513 Assert(PT && PT->getElementType()->isFunctionTy(),
1514 "gc.statepoint callee must be of function pointer type", &CI, Target);
1515 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1517 const Value *NumCallArgsV = CS.getArgument(1);
1518 Assert(isa<ConstantInt>(NumCallArgsV),
1519 "gc.statepoint number of arguments to underlying call "
1520 "must be constant integer",
1522 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1523 Assert(NumCallArgs >= 0,
1524 "gc.statepoint number of arguments to underlying call "
1527 const int NumParams = (int)TargetFuncType->getNumParams();
1528 if (TargetFuncType->isVarArg()) {
1529 Assert(NumCallArgs >= NumParams,
1530 "gc.statepoint mismatch in number of vararg call args", &CI);
1532 // TODO: Remove this limitation
1533 Assert(TargetFuncType->getReturnType()->isVoidTy(),
1534 "gc.statepoint doesn't support wrapping non-void "
1535 "vararg functions yet",
1538 Assert(NumCallArgs == NumParams,
1539 "gc.statepoint mismatch in number of call args", &CI);
1541 const Value *Unused = CS.getArgument(2);
1542 Assert(isa<ConstantInt>(Unused) && cast<ConstantInt>(Unused)->isNullValue(),
1543 "gc.statepoint parameter #3 must be zero", &CI);
1545 // Verify that the types of the call parameter arguments match
1546 // the type of the wrapped callee.
1547 for (int i = 0; i < NumParams; i++) {
1548 Type *ParamType = TargetFuncType->getParamType(i);
1549 Type *ArgType = CS.getArgument(3+i)->getType();
1550 Assert(ArgType == ParamType,
1551 "gc.statepoint call argument does not match wrapped "
1555 const int EndCallArgsInx = 2+NumCallArgs;
1556 const Value *NumDeoptArgsV = CS.getArgument(EndCallArgsInx+1);
1557 Assert(isa<ConstantInt>(NumDeoptArgsV),
1558 "gc.statepoint number of deoptimization arguments "
1559 "must be constant integer",
1561 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1562 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1566 Assert(4 + NumCallArgs + NumDeoptArgs <= (int)CS.arg_size(),
1567 "gc.statepoint too few arguments according to length fields", &CI);
1569 // Check that the only uses of this gc.statepoint are gc.result or
1570 // gc.relocate calls which are tied to this statepoint and thus part
1571 // of the same statepoint sequence
1572 for (const User *U : CI.users()) {
1573 const CallInst *Call = dyn_cast<const CallInst>(U);
1574 Assert(Call, "illegal use of statepoint token", &CI, U);
1575 if (!Call) continue;
1576 Assert(isGCRelocate(Call) || isGCResult(Call),
1577 "gc.result or gc.relocate are the only value uses"
1578 "of a gc.statepoint",
1580 if (isGCResult(Call)) {
1581 Assert(Call->getArgOperand(0) == &CI,
1582 "gc.result connected to wrong gc.statepoint", &CI, Call);
1583 } else if (isGCRelocate(Call)) {
1584 Assert(Call->getArgOperand(0) == &CI,
1585 "gc.relocate connected to wrong gc.statepoint", &CI, Call);
1589 // Note: It is legal for a single derived pointer to be listed multiple
1590 // times. It's non-optimal, but it is legal. It can also happen after
1591 // insertion if we strip a bitcast away.
1592 // Note: It is really tempting to check that each base is relocated and
1593 // that a derived pointer is never reused as a base pointer. This turns
1594 // out to be problematic since optimizations run after safepoint insertion
1595 // can recognize equality properties that the insertion logic doesn't know
1596 // about. See example statepoint.ll in the verifier subdirectory
1599 void Verifier::verifyFrameRecoverIndices() {
1600 for (auto &Counts : FrameEscapeInfo) {
1601 Function *F = Counts.first;
1602 unsigned EscapedObjectCount = Counts.second.first;
1603 unsigned MaxRecoveredIndex = Counts.second.second;
1604 Assert(MaxRecoveredIndex <= EscapedObjectCount,
1605 "all indices passed to llvm.framerecover must be less than the "
1606 "number of arguments passed ot llvm.frameescape in the parent "
1612 // visitFunction - Verify that a function is ok.
1614 void Verifier::visitFunction(const Function &F) {
1615 // Check function arguments.
1616 FunctionType *FT = F.getFunctionType();
1617 unsigned NumArgs = F.arg_size();
1619 Assert(Context == &F.getContext(),
1620 "Function context does not match Module context!", &F);
1622 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1623 Assert(FT->getNumParams() == NumArgs,
1624 "# formal arguments must match # of arguments for function type!", &F,
1626 Assert(F.getReturnType()->isFirstClassType() ||
1627 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1628 "Functions cannot return aggregate values!", &F);
1630 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1631 "Invalid struct return type!", &F);
1633 AttributeSet Attrs = F.getAttributes();
1635 Assert(VerifyAttributeCount(Attrs, FT->getNumParams()),
1636 "Attribute after last parameter!", &F);
1638 // Check function attributes.
1639 VerifyFunctionAttrs(FT, Attrs, &F);
1641 // On function declarations/definitions, we do not support the builtin
1642 // attribute. We do not check this in VerifyFunctionAttrs since that is
1643 // checking for Attributes that can/can not ever be on functions.
1644 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin),
1645 "Attribute 'builtin' can only be applied to a callsite.", &F);
1647 // Check that this function meets the restrictions on this calling convention.
1648 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1649 // restrictions can be lifted.
1650 switch (F.getCallingConv()) {
1652 case CallingConv::C:
1654 case CallingConv::Fast:
1655 case CallingConv::Cold:
1656 case CallingConv::Intel_OCL_BI:
1657 case CallingConv::PTX_Kernel:
1658 case CallingConv::PTX_Device:
1659 Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1660 "perfect forwarding!",
1665 bool isLLVMdotName = F.getName().size() >= 5 &&
1666 F.getName().substr(0, 5) == "llvm.";
1668 // Check that the argument values match the function type for this function...
1670 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1672 Assert(I->getType() == FT->getParamType(i),
1673 "Argument value does not match function argument type!", I,
1674 FT->getParamType(i));
1675 Assert(I->getType()->isFirstClassType(),
1676 "Function arguments must have first-class types!", I);
1678 Assert(!I->getType()->isMetadataTy(),
1679 "Function takes metadata but isn't an intrinsic", I, &F);
1682 if (F.isMaterializable()) {
1683 // Function has a body somewhere we can't see.
1684 } else if (F.isDeclaration()) {
1685 Assert(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1686 "invalid linkage type for function declaration", &F);
1688 // Verify that this function (which has a body) is not named "llvm.*". It
1689 // is not legal to define intrinsics.
1690 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1692 // Check the entry node
1693 const BasicBlock *Entry = &F.getEntryBlock();
1694 Assert(pred_empty(Entry),
1695 "Entry block to function must not have predecessors!", Entry);
1697 // The address of the entry block cannot be taken, unless it is dead.
1698 if (Entry->hasAddressTaken()) {
1699 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
1700 "blockaddress may not be used with the entry block!", Entry);
1704 // If this function is actually an intrinsic, verify that it is only used in
1705 // direct call/invokes, never having its "address taken".
1706 if (F.getIntrinsicID()) {
1708 if (F.hasAddressTaken(&U))
1709 Assert(0, "Invalid user of intrinsic instruction!", U);
1712 Assert(!F.hasDLLImportStorageClass() ||
1713 (F.isDeclaration() && F.hasExternalLinkage()) ||
1714 F.hasAvailableExternallyLinkage(),
1715 "Function is marked as dllimport, but not external.", &F);
1718 // verifyBasicBlock - Verify that a basic block is well formed...
1720 void Verifier::visitBasicBlock(BasicBlock &BB) {
1721 InstsInThisBlock.clear();
1723 // Ensure that basic blocks have terminators!
1724 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1726 // Check constraints that this basic block imposes on all of the PHI nodes in
1728 if (isa<PHINode>(BB.front())) {
1729 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1730 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1731 std::sort(Preds.begin(), Preds.end());
1733 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1734 // Ensure that PHI nodes have at least one entry!
1735 Assert(PN->getNumIncomingValues() != 0,
1736 "PHI nodes must have at least one entry. If the block is dead, "
1737 "the PHI should be removed!",
1739 Assert(PN->getNumIncomingValues() == Preds.size(),
1740 "PHINode should have one entry for each predecessor of its "
1741 "parent basic block!",
1744 // Get and sort all incoming values in the PHI node...
1746 Values.reserve(PN->getNumIncomingValues());
1747 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1748 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1749 PN->getIncomingValue(i)));
1750 std::sort(Values.begin(), Values.end());
1752 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1753 // Check to make sure that if there is more than one entry for a
1754 // particular basic block in this PHI node, that the incoming values are
1757 Assert(i == 0 || Values[i].first != Values[i - 1].first ||
1758 Values[i].second == Values[i - 1].second,
1759 "PHI node has multiple entries for the same basic block with "
1760 "different incoming values!",
1761 PN, Values[i].first, Values[i].second, Values[i - 1].second);
1763 // Check to make sure that the predecessors and PHI node entries are
1765 Assert(Values[i].first == Preds[i],
1766 "PHI node entries do not match predecessors!", PN,
1767 Values[i].first, Preds[i]);
1772 // Check that all instructions have their parent pointers set up correctly.
1775 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
1779 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1780 // Ensure that terminators only exist at the end of the basic block.
1781 Assert(&I == I.getParent()->getTerminator(),
1782 "Terminator found in the middle of a basic block!", I.getParent());
1783 visitInstruction(I);
1786 void Verifier::visitBranchInst(BranchInst &BI) {
1787 if (BI.isConditional()) {
1788 Assert(BI.getCondition()->getType()->isIntegerTy(1),
1789 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1791 visitTerminatorInst(BI);
1794 void Verifier::visitReturnInst(ReturnInst &RI) {
1795 Function *F = RI.getParent()->getParent();
1796 unsigned N = RI.getNumOperands();
1797 if (F->getReturnType()->isVoidTy())
1799 "Found return instr that returns non-void in Function of void "
1801 &RI, F->getReturnType());
1803 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1804 "Function return type does not match operand "
1805 "type of return inst!",
1806 &RI, F->getReturnType());
1808 // Check to make sure that the return value has necessary properties for
1810 visitTerminatorInst(RI);
1813 void Verifier::visitSwitchInst(SwitchInst &SI) {
1814 // Check to make sure that all of the constants in the switch instruction
1815 // have the same type as the switched-on value.
1816 Type *SwitchTy = SI.getCondition()->getType();
1817 SmallPtrSet<ConstantInt*, 32> Constants;
1818 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1819 Assert(i.getCaseValue()->getType() == SwitchTy,
1820 "Switch constants must all be same type as switch value!", &SI);
1821 Assert(Constants.insert(i.getCaseValue()).second,
1822 "Duplicate integer as switch case", &SI, i.getCaseValue());
1825 visitTerminatorInst(SI);
1828 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1829 Assert(BI.getAddress()->getType()->isPointerTy(),
1830 "Indirectbr operand must have pointer type!", &BI);
1831 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1832 Assert(BI.getDestination(i)->getType()->isLabelTy(),
1833 "Indirectbr destinations must all have pointer type!", &BI);
1835 visitTerminatorInst(BI);
1838 void Verifier::visitSelectInst(SelectInst &SI) {
1839 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1841 "Invalid operands for select instruction!", &SI);
1843 Assert(SI.getTrueValue()->getType() == SI.getType(),
1844 "Select values must have same type as select instruction!", &SI);
1845 visitInstruction(SI);
1848 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1849 /// a pass, if any exist, it's an error.
1851 void Verifier::visitUserOp1(Instruction &I) {
1852 Assert(0, "User-defined operators should not live outside of a pass!", &I);
1855 void Verifier::visitTruncInst(TruncInst &I) {
1856 // Get the source and destination types
1857 Type *SrcTy = I.getOperand(0)->getType();
1858 Type *DestTy = I.getType();
1860 // Get the size of the types in bits, we'll need this later
1861 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1862 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1864 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1865 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1866 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1867 "trunc source and destination must both be a vector or neither", &I);
1868 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
1870 visitInstruction(I);
1873 void Verifier::visitZExtInst(ZExtInst &I) {
1874 // Get the source and destination types
1875 Type *SrcTy = I.getOperand(0)->getType();
1876 Type *DestTy = I.getType();
1878 // Get the size of the types in bits, we'll need this later
1879 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1880 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1881 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1882 "zext source and destination must both be a vector or neither", &I);
1883 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1884 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1886 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
1888 visitInstruction(I);
1891 void Verifier::visitSExtInst(SExtInst &I) {
1892 // Get the source and destination types
1893 Type *SrcTy = I.getOperand(0)->getType();
1894 Type *DestTy = I.getType();
1896 // Get the size of the types in bits, we'll need this later
1897 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1898 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1900 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1901 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1902 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1903 "sext source and destination must both be a vector or neither", &I);
1904 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
1906 visitInstruction(I);
1909 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1910 // Get the source and destination types
1911 Type *SrcTy = I.getOperand(0)->getType();
1912 Type *DestTy = I.getType();
1913 // Get the size of the types in bits, we'll need this later
1914 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1915 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1917 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
1918 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
1919 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1920 "fptrunc source and destination must both be a vector or neither", &I);
1921 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
1923 visitInstruction(I);
1926 void Verifier::visitFPExtInst(FPExtInst &I) {
1927 // Get the source and destination types
1928 Type *SrcTy = I.getOperand(0)->getType();
1929 Type *DestTy = I.getType();
1931 // Get the size of the types in bits, we'll need this later
1932 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1933 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1935 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
1936 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
1937 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1938 "fpext source and destination must both be a vector or neither", &I);
1939 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
1941 visitInstruction(I);
1944 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1945 // Get the source and destination types
1946 Type *SrcTy = I.getOperand(0)->getType();
1947 Type *DestTy = I.getType();
1949 bool SrcVec = SrcTy->isVectorTy();
1950 bool DstVec = DestTy->isVectorTy();
1952 Assert(SrcVec == DstVec,
1953 "UIToFP source and dest must both be vector or scalar", &I);
1954 Assert(SrcTy->isIntOrIntVectorTy(),
1955 "UIToFP source must be integer or integer vector", &I);
1956 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
1959 if (SrcVec && DstVec)
1960 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1961 cast<VectorType>(DestTy)->getNumElements(),
1962 "UIToFP source and dest vector length mismatch", &I);
1964 visitInstruction(I);
1967 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1968 // Get the source and destination types
1969 Type *SrcTy = I.getOperand(0)->getType();
1970 Type *DestTy = I.getType();
1972 bool SrcVec = SrcTy->isVectorTy();
1973 bool DstVec = DestTy->isVectorTy();
1975 Assert(SrcVec == DstVec,
1976 "SIToFP source and dest must both be vector or scalar", &I);
1977 Assert(SrcTy->isIntOrIntVectorTy(),
1978 "SIToFP source must be integer or integer vector", &I);
1979 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
1982 if (SrcVec && DstVec)
1983 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1984 cast<VectorType>(DestTy)->getNumElements(),
1985 "SIToFP source and dest vector length mismatch", &I);
1987 visitInstruction(I);
1990 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1991 // Get the source and destination types
1992 Type *SrcTy = I.getOperand(0)->getType();
1993 Type *DestTy = I.getType();
1995 bool SrcVec = SrcTy->isVectorTy();
1996 bool DstVec = DestTy->isVectorTy();
1998 Assert(SrcVec == DstVec,
1999 "FPToUI source and dest must both be vector or scalar", &I);
2000 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
2002 Assert(DestTy->isIntOrIntVectorTy(),
2003 "FPToUI result must be integer or integer vector", &I);
2005 if (SrcVec && DstVec)
2006 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2007 cast<VectorType>(DestTy)->getNumElements(),
2008 "FPToUI source and dest vector length mismatch", &I);
2010 visitInstruction(I);
2013 void Verifier::visitFPToSIInst(FPToSIInst &I) {
2014 // Get the source and destination types
2015 Type *SrcTy = I.getOperand(0)->getType();
2016 Type *DestTy = I.getType();
2018 bool SrcVec = SrcTy->isVectorTy();
2019 bool DstVec = DestTy->isVectorTy();
2021 Assert(SrcVec == DstVec,
2022 "FPToSI source and dest must both be vector or scalar", &I);
2023 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2025 Assert(DestTy->isIntOrIntVectorTy(),
2026 "FPToSI result must be integer or integer vector", &I);
2028 if (SrcVec && DstVec)
2029 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2030 cast<VectorType>(DestTy)->getNumElements(),
2031 "FPToSI source and dest vector length mismatch", &I);
2033 visitInstruction(I);
2036 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2037 // Get the source and destination types
2038 Type *SrcTy = I.getOperand(0)->getType();
2039 Type *DestTy = I.getType();
2041 Assert(SrcTy->getScalarType()->isPointerTy(),
2042 "PtrToInt source must be pointer", &I);
2043 Assert(DestTy->getScalarType()->isIntegerTy(),
2044 "PtrToInt result must be integral", &I);
2045 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
2048 if (SrcTy->isVectorTy()) {
2049 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2050 VectorType *VDest = dyn_cast<VectorType>(DestTy);
2051 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2052 "PtrToInt Vector width mismatch", &I);
2055 visitInstruction(I);
2058 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
2059 // Get the source and destination types
2060 Type *SrcTy = I.getOperand(0)->getType();
2061 Type *DestTy = I.getType();
2063 Assert(SrcTy->getScalarType()->isIntegerTy(),
2064 "IntToPtr source must be an integral", &I);
2065 Assert(DestTy->getScalarType()->isPointerTy(),
2066 "IntToPtr result must be a pointer", &I);
2067 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
2069 if (SrcTy->isVectorTy()) {
2070 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2071 VectorType *VDest = dyn_cast<VectorType>(DestTy);
2072 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2073 "IntToPtr Vector width mismatch", &I);
2075 visitInstruction(I);
2078 void Verifier::visitBitCastInst(BitCastInst &I) {
2080 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
2081 "Invalid bitcast", &I);
2082 visitInstruction(I);
2085 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2086 Type *SrcTy = I.getOperand(0)->getType();
2087 Type *DestTy = I.getType();
2089 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
2091 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
2093 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
2094 "AddrSpaceCast must be between different address spaces", &I);
2095 if (SrcTy->isVectorTy())
2096 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
2097 "AddrSpaceCast vector pointer number of elements mismatch", &I);
2098 visitInstruction(I);
2101 /// visitPHINode - Ensure that a PHI node is well formed.
2103 void Verifier::visitPHINode(PHINode &PN) {
2104 // Ensure that the PHI nodes are all grouped together at the top of the block.
2105 // This can be tested by checking whether the instruction before this is
2106 // either nonexistent (because this is begin()) or is a PHI node. If not,
2107 // then there is some other instruction before a PHI.
2108 Assert(&PN == &PN.getParent()->front() ||
2109 isa<PHINode>(--BasicBlock::iterator(&PN)),
2110 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
2112 // Check that all of the values of the PHI node have the same type as the
2113 // result, and that the incoming blocks are really basic blocks.
2114 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2115 Assert(PN.getType() == PN.getIncomingValue(i)->getType(),
2116 "PHI node operands are not the same type as the result!", &PN);
2119 // All other PHI node constraints are checked in the visitBasicBlock method.
2121 visitInstruction(PN);
2124 void Verifier::VerifyCallSite(CallSite CS) {
2125 Instruction *I = CS.getInstruction();
2127 Assert(CS.getCalledValue()->getType()->isPointerTy(),
2128 "Called function must be a pointer!", I);
2129 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
2131 Assert(FPTy->getElementType()->isFunctionTy(),
2132 "Called function is not pointer to function type!", I);
2133 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
2135 // Verify that the correct number of arguments are being passed
2136 if (FTy->isVarArg())
2137 Assert(CS.arg_size() >= FTy->getNumParams(),
2138 "Called function requires more parameters than were provided!", I);
2140 Assert(CS.arg_size() == FTy->getNumParams(),
2141 "Incorrect number of arguments passed to called function!", I);
2143 // Verify that all arguments to the call match the function type.
2144 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2145 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
2146 "Call parameter type does not match function signature!",
2147 CS.getArgument(i), FTy->getParamType(i), I);
2149 AttributeSet Attrs = CS.getAttributes();
2151 Assert(VerifyAttributeCount(Attrs, CS.arg_size()),
2152 "Attribute after last parameter!", I);
2154 // Verify call attributes.
2155 VerifyFunctionAttrs(FTy, Attrs, I);
2157 // Conservatively check the inalloca argument.
2158 // We have a bug if we can find that there is an underlying alloca without
2160 if (CS.hasInAllocaArgument()) {
2161 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
2162 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
2163 Assert(AI->isUsedWithInAlloca(),
2164 "inalloca argument for call has mismatched alloca", AI, I);
2167 if (FTy->isVarArg()) {
2168 // FIXME? is 'nest' even legal here?
2169 bool SawNest = false;
2170 bool SawReturned = false;
2172 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
2173 if (Attrs.hasAttribute(Idx, Attribute::Nest))
2175 if (Attrs.hasAttribute(Idx, Attribute::Returned))
2179 // Check attributes on the varargs part.
2180 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
2181 Type *Ty = CS.getArgument(Idx-1)->getType();
2182 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
2184 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
2185 Assert(!SawNest, "More than one parameter has attribute nest!", I);
2189 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
2190 Assert(!SawReturned, "More than one parameter has attribute returned!",
2192 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
2193 "Incompatible argument and return types for 'returned' "
2199 Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet),
2200 "Attribute 'sret' cannot be used for vararg call arguments!", I);
2202 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
2203 Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I);
2207 // Verify that there's no metadata unless it's a direct call to an intrinsic.
2208 if (CS.getCalledFunction() == nullptr ||
2209 !CS.getCalledFunction()->getName().startswith("llvm.")) {
2210 for (FunctionType::param_iterator PI = FTy->param_begin(),
2211 PE = FTy->param_end(); PI != PE; ++PI)
2212 Assert(!(*PI)->isMetadataTy(),
2213 "Function has metadata parameter but isn't an intrinsic", I);
2216 visitInstruction(*I);
2219 /// Two types are "congruent" if they are identical, or if they are both pointer
2220 /// types with different pointee types and the same address space.
2221 static bool isTypeCongruent(Type *L, Type *R) {
2224 PointerType *PL = dyn_cast<PointerType>(L);
2225 PointerType *PR = dyn_cast<PointerType>(R);
2228 return PL->getAddressSpace() == PR->getAddressSpace();
2231 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
2232 static const Attribute::AttrKind ABIAttrs[] = {
2233 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
2234 Attribute::InReg, Attribute::Returned};
2236 for (auto AK : ABIAttrs) {
2237 if (Attrs.hasAttribute(I + 1, AK))
2238 Copy.addAttribute(AK);
2240 if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
2241 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
2245 void Verifier::verifyMustTailCall(CallInst &CI) {
2246 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
2248 // - The caller and callee prototypes must match. Pointer types of
2249 // parameters or return types may differ in pointee type, but not
2251 Function *F = CI.getParent()->getParent();
2252 auto GetFnTy = [](Value *V) {
2253 return cast<FunctionType>(
2254 cast<PointerType>(V->getType())->getElementType());
2256 FunctionType *CallerTy = GetFnTy(F);
2257 FunctionType *CalleeTy = GetFnTy(CI.getCalledValue());
2258 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
2259 "cannot guarantee tail call due to mismatched parameter counts", &CI);
2260 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
2261 "cannot guarantee tail call due to mismatched varargs", &CI);
2262 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
2263 "cannot guarantee tail call due to mismatched return types", &CI);
2264 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2266 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
2267 "cannot guarantee tail call due to mismatched parameter types", &CI);
2270 // - The calling conventions of the caller and callee must match.
2271 Assert(F->getCallingConv() == CI.getCallingConv(),
2272 "cannot guarantee tail call due to mismatched calling conv", &CI);
2274 // - All ABI-impacting function attributes, such as sret, byval, inreg,
2275 // returned, and inalloca, must match.
2276 AttributeSet CallerAttrs = F->getAttributes();
2277 AttributeSet CalleeAttrs = CI.getAttributes();
2278 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2279 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
2280 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
2281 Assert(CallerABIAttrs == CalleeABIAttrs,
2282 "cannot guarantee tail call due to mismatched ABI impacting "
2283 "function attributes",
2284 &CI, CI.getOperand(I));
2287 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
2288 // or a pointer bitcast followed by a ret instruction.
2289 // - The ret instruction must return the (possibly bitcasted) value
2290 // produced by the call or void.
2291 Value *RetVal = &CI;
2292 Instruction *Next = CI.getNextNode();
2294 // Handle the optional bitcast.
2295 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
2296 Assert(BI->getOperand(0) == RetVal,
2297 "bitcast following musttail call must use the call", BI);
2299 Next = BI->getNextNode();
2302 // Check the return.
2303 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
2304 Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
2306 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
2307 "musttail call result must be returned", Ret);
2310 void Verifier::visitCallInst(CallInst &CI) {
2311 VerifyCallSite(&CI);
2313 if (CI.isMustTailCall())
2314 verifyMustTailCall(CI);
2316 if (Function *F = CI.getCalledFunction())
2317 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2318 visitIntrinsicFunctionCall(ID, CI);
2321 void Verifier::visitInvokeInst(InvokeInst &II) {
2322 VerifyCallSite(&II);
2324 // Verify that there is a landingpad instruction as the first non-PHI
2325 // instruction of the 'unwind' destination.
2326 Assert(II.getUnwindDest()->isLandingPad(),
2327 "The unwind destination does not have a landingpad instruction!", &II);
2329 if (Function *F = II.getCalledFunction())
2330 // TODO: Ideally we should use visitIntrinsicFunction here. But it uses
2331 // CallInst as an input parameter. It not woth updating this whole
2332 // function only to support statepoint verification.
2333 if (F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint)
2334 VerifyStatepoint(ImmutableCallSite(&II));
2336 visitTerminatorInst(II);
2339 /// visitBinaryOperator - Check that both arguments to the binary operator are
2340 /// of the same type!
2342 void Verifier::visitBinaryOperator(BinaryOperator &B) {
2343 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2344 "Both operands to a binary operator are not of the same type!", &B);
2346 switch (B.getOpcode()) {
2347 // Check that integer arithmetic operators are only used with
2348 // integral operands.
2349 case Instruction::Add:
2350 case Instruction::Sub:
2351 case Instruction::Mul:
2352 case Instruction::SDiv:
2353 case Instruction::UDiv:
2354 case Instruction::SRem:
2355 case Instruction::URem:
2356 Assert(B.getType()->isIntOrIntVectorTy(),
2357 "Integer arithmetic operators only work with integral types!", &B);
2358 Assert(B.getType() == B.getOperand(0)->getType(),
2359 "Integer arithmetic operators must have same type "
2360 "for operands and result!",
2363 // Check that floating-point arithmetic operators are only used with
2364 // floating-point operands.
2365 case Instruction::FAdd:
2366 case Instruction::FSub:
2367 case Instruction::FMul:
2368 case Instruction::FDiv:
2369 case Instruction::FRem:
2370 Assert(B.getType()->isFPOrFPVectorTy(),
2371 "Floating-point arithmetic operators only work with "
2372 "floating-point types!",
2374 Assert(B.getType() == B.getOperand(0)->getType(),
2375 "Floating-point arithmetic operators must have same type "
2376 "for operands and result!",
2379 // Check that logical operators are only used with integral operands.
2380 case Instruction::And:
2381 case Instruction::Or:
2382 case Instruction::Xor:
2383 Assert(B.getType()->isIntOrIntVectorTy(),
2384 "Logical operators only work with integral types!", &B);
2385 Assert(B.getType() == B.getOperand(0)->getType(),
2386 "Logical operators must have same type for operands and result!",
2389 case Instruction::Shl:
2390 case Instruction::LShr:
2391 case Instruction::AShr:
2392 Assert(B.getType()->isIntOrIntVectorTy(),
2393 "Shifts only work with integral types!", &B);
2394 Assert(B.getType() == B.getOperand(0)->getType(),
2395 "Shift return type must be same as operands!", &B);
2398 llvm_unreachable("Unknown BinaryOperator opcode!");
2401 visitInstruction(B);
2404 void Verifier::visitICmpInst(ICmpInst &IC) {
2405 // Check that the operands are the same type
2406 Type *Op0Ty = IC.getOperand(0)->getType();
2407 Type *Op1Ty = IC.getOperand(1)->getType();
2408 Assert(Op0Ty == Op1Ty,
2409 "Both operands to ICmp instruction are not of the same type!", &IC);
2410 // Check that the operands are the right type
2411 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2412 "Invalid operand types for ICmp instruction", &IC);
2413 // Check that the predicate is valid.
2414 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2415 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2416 "Invalid predicate in ICmp instruction!", &IC);
2418 visitInstruction(IC);
2421 void Verifier::visitFCmpInst(FCmpInst &FC) {
2422 // Check that the operands are the same type
2423 Type *Op0Ty = FC.getOperand(0)->getType();
2424 Type *Op1Ty = FC.getOperand(1)->getType();
2425 Assert(Op0Ty == Op1Ty,
2426 "Both operands to FCmp instruction are not of the same type!", &FC);
2427 // Check that the operands are the right type
2428 Assert(Op0Ty->isFPOrFPVectorTy(),
2429 "Invalid operand types for FCmp instruction", &FC);
2430 // Check that the predicate is valid.
2431 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2432 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2433 "Invalid predicate in FCmp instruction!", &FC);
2435 visitInstruction(FC);
2438 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
2440 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2441 "Invalid extractelement operands!", &EI);
2442 visitInstruction(EI);
2445 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
2446 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2448 "Invalid insertelement operands!", &IE);
2449 visitInstruction(IE);
2452 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
2453 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2455 "Invalid shufflevector operands!", &SV);
2456 visitInstruction(SV);
2459 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2460 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
2462 Assert(isa<PointerType>(TargetTy),
2463 "GEP base pointer is not a vector or a vector of pointers", &GEP);
2464 Assert(cast<PointerType>(TargetTy)->getElementType()->isSized(),
2465 "GEP into unsized type!", &GEP);
2466 Assert(GEP.getPointerOperandType()->isVectorTy() ==
2467 GEP.getType()->isVectorTy(),
2468 "Vector GEP must return a vector value", &GEP);
2470 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
2472 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
2473 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
2475 Assert(GEP.getType()->getScalarType()->isPointerTy() &&
2476 cast<PointerType>(GEP.getType()->getScalarType())
2477 ->getElementType() == ElTy,
2478 "GEP is not of right type for indices!", &GEP, ElTy);
2480 if (GEP.getPointerOperandType()->isVectorTy()) {
2481 // Additional checks for vector GEPs.
2482 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
2483 Assert(GepWidth == GEP.getType()->getVectorNumElements(),
2484 "Vector GEP result width doesn't match operand's", &GEP);
2485 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2486 Type *IndexTy = Idxs[i]->getType();
2487 Assert(IndexTy->isVectorTy(), "Vector GEP must have vector indices!",
2489 unsigned IndexWidth = IndexTy->getVectorNumElements();
2490 Assert(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
2493 visitInstruction(GEP);
2496 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2497 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2500 void Verifier::visitRangeMetadata(Instruction& I,
2501 MDNode* Range, Type* Ty) {
2503 Range == I.getMetadata(LLVMContext::MD_range) &&
2504 "precondition violation");
2506 unsigned NumOperands = Range->getNumOperands();
2507 Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
2508 unsigned NumRanges = NumOperands / 2;
2509 Assert(NumRanges >= 1, "It should have at least one range!", Range);
2511 ConstantRange LastRange(1); // Dummy initial value
2512 for (unsigned i = 0; i < NumRanges; ++i) {
2514 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
2515 Assert(Low, "The lower limit must be an integer!", Low);
2517 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
2518 Assert(High, "The upper limit must be an integer!", High);
2519 Assert(High->getType() == Low->getType() && High->getType() == Ty,
2520 "Range types must match instruction type!", &I);
2522 APInt HighV = High->getValue();
2523 APInt LowV = Low->getValue();
2524 ConstantRange CurRange(LowV, HighV);
2525 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
2526 "Range must not be empty!", Range);
2528 Assert(CurRange.intersectWith(LastRange).isEmptySet(),
2529 "Intervals are overlapping", Range);
2530 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
2532 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
2535 LastRange = ConstantRange(LowV, HighV);
2537 if (NumRanges > 2) {
2539 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
2541 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
2542 ConstantRange FirstRange(FirstLow, FirstHigh);
2543 Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
2544 "Intervals are overlapping", Range);
2545 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
2550 void Verifier::visitLoadInst(LoadInst &LI) {
2551 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
2552 Assert(PTy, "Load operand must be a pointer.", &LI);
2553 Type *ElTy = LI.getType();
2554 Assert(LI.getAlignment() <= Value::MaximumAlignment,
2555 "huge alignment values are unsupported", &LI);
2556 if (LI.isAtomic()) {
2557 Assert(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
2558 "Load cannot have Release ordering", &LI);
2559 Assert(LI.getAlignment() != 0,
2560 "Atomic load must specify explicit alignment", &LI);
2561 if (!ElTy->isPointerTy()) {
2562 Assert(ElTy->isIntegerTy(), "atomic load operand must have integer type!",
2564 unsigned Size = ElTy->getPrimitiveSizeInBits();
2565 Assert(Size >= 8 && !(Size & (Size - 1)),
2566 "atomic load operand must be power-of-two byte-sized integer", &LI,
2570 Assert(LI.getSynchScope() == CrossThread,
2571 "Non-atomic load cannot have SynchronizationScope specified", &LI);
2574 visitInstruction(LI);
2577 void Verifier::visitStoreInst(StoreInst &SI) {
2578 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
2579 Assert(PTy, "Store operand must be a pointer.", &SI);
2580 Type *ElTy = PTy->getElementType();
2581 Assert(ElTy == SI.getOperand(0)->getType(),
2582 "Stored value type does not match pointer operand type!", &SI, ElTy);
2583 Assert(SI.getAlignment() <= Value::MaximumAlignment,
2584 "huge alignment values are unsupported", &SI);
2585 if (SI.isAtomic()) {
2586 Assert(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
2587 "Store cannot have Acquire ordering", &SI);
2588 Assert(SI.getAlignment() != 0,
2589 "Atomic store must specify explicit alignment", &SI);
2590 if (!ElTy->isPointerTy()) {
2591 Assert(ElTy->isIntegerTy(),
2592 "atomic store operand must have integer type!", &SI, ElTy);
2593 unsigned Size = ElTy->getPrimitiveSizeInBits();
2594 Assert(Size >= 8 && !(Size & (Size - 1)),
2595 "atomic store operand must be power-of-two byte-sized integer",
2599 Assert(SI.getSynchScope() == CrossThread,
2600 "Non-atomic store cannot have SynchronizationScope specified", &SI);
2602 visitInstruction(SI);
2605 void Verifier::visitAllocaInst(AllocaInst &AI) {
2606 SmallPtrSet<const Type*, 4> Visited;
2607 PointerType *PTy = AI.getType();
2608 Assert(PTy->getAddressSpace() == 0,
2609 "Allocation instruction pointer not in the generic address space!",
2611 Assert(PTy->getElementType()->isSized(&Visited),
2612 "Cannot allocate unsized type", &AI);
2613 Assert(AI.getArraySize()->getType()->isIntegerTy(),
2614 "Alloca array size must have integer type", &AI);
2615 Assert(AI.getAlignment() <= Value::MaximumAlignment,
2616 "huge alignment values are unsupported", &AI);
2618 visitInstruction(AI);
2621 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
2623 // FIXME: more conditions???
2624 Assert(CXI.getSuccessOrdering() != NotAtomic,
2625 "cmpxchg instructions must be atomic.", &CXI);
2626 Assert(CXI.getFailureOrdering() != NotAtomic,
2627 "cmpxchg instructions must be atomic.", &CXI);
2628 Assert(CXI.getSuccessOrdering() != Unordered,
2629 "cmpxchg instructions cannot be unordered.", &CXI);
2630 Assert(CXI.getFailureOrdering() != Unordered,
2631 "cmpxchg instructions cannot be unordered.", &CXI);
2632 Assert(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
2633 "cmpxchg instructions be at least as constrained on success as fail",
2635 Assert(CXI.getFailureOrdering() != Release &&
2636 CXI.getFailureOrdering() != AcquireRelease,
2637 "cmpxchg failure ordering cannot include release semantics", &CXI);
2639 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
2640 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
2641 Type *ElTy = PTy->getElementType();
2642 Assert(ElTy->isIntegerTy(), "cmpxchg operand must have integer type!", &CXI,
2644 unsigned Size = ElTy->getPrimitiveSizeInBits();
2645 Assert(Size >= 8 && !(Size & (Size - 1)),
2646 "cmpxchg operand must be power-of-two byte-sized integer", &CXI, ElTy);
2647 Assert(ElTy == CXI.getOperand(1)->getType(),
2648 "Expected value type does not match pointer operand type!", &CXI,
2650 Assert(ElTy == CXI.getOperand(2)->getType(),
2651 "Stored value type does not match pointer operand type!", &CXI, ElTy);
2652 visitInstruction(CXI);
2655 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2656 Assert(RMWI.getOrdering() != NotAtomic,
2657 "atomicrmw instructions must be atomic.", &RMWI);
2658 Assert(RMWI.getOrdering() != Unordered,
2659 "atomicrmw instructions cannot be unordered.", &RMWI);
2660 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2661 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2662 Type *ElTy = PTy->getElementType();
2663 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
2665 unsigned Size = ElTy->getPrimitiveSizeInBits();
2666 Assert(Size >= 8 && !(Size & (Size - 1)),
2667 "atomicrmw operand must be power-of-two byte-sized integer", &RMWI,
2669 Assert(ElTy == RMWI.getOperand(1)->getType(),
2670 "Argument value type does not match pointer operand type!", &RMWI,
2672 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2673 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2674 "Invalid binary operation!", &RMWI);
2675 visitInstruction(RMWI);
2678 void Verifier::visitFenceInst(FenceInst &FI) {
2679 const AtomicOrdering Ordering = FI.getOrdering();
2680 Assert(Ordering == Acquire || Ordering == Release ||
2681 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2682 "fence instructions may only have "
2683 "acquire, release, acq_rel, or seq_cst ordering.",
2685 visitInstruction(FI);
2688 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2689 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2690 EVI.getIndices()) == EVI.getType(),
2691 "Invalid ExtractValueInst operands!", &EVI);
2693 visitInstruction(EVI);
2696 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2697 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2698 IVI.getIndices()) ==
2699 IVI.getOperand(1)->getType(),
2700 "Invalid InsertValueInst operands!", &IVI);
2702 visitInstruction(IVI);
2705 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2706 BasicBlock *BB = LPI.getParent();
2708 // The landingpad instruction is ill-formed if it doesn't have any clauses and
2710 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2711 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2713 // The landingpad instruction defines its parent as a landing pad block. The
2714 // landing pad block may be branched to only by the unwind edge of an invoke.
2715 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
2716 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
2717 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2718 "Block containing LandingPadInst must be jumped to "
2719 "only by the unwind edge of an invoke.",
2723 // The landingpad instruction must be the first non-PHI instruction in the
2725 Assert(LPI.getParent()->getLandingPadInst() == &LPI,
2726 "LandingPadInst not the first non-PHI instruction in the block.",
2729 // The personality functions for all landingpad instructions within the same
2730 // function should match.
2732 Assert(LPI.getPersonalityFn() == PersonalityFn,
2733 "Personality function doesn't match others in function", &LPI);
2734 PersonalityFn = LPI.getPersonalityFn();
2736 // All operands must be constants.
2737 Assert(isa<Constant>(PersonalityFn), "Personality function is not constant!",
2739 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2740 Constant *Clause = LPI.getClause(i);
2741 if (LPI.isCatch(i)) {
2742 Assert(isa<PointerType>(Clause->getType()),
2743 "Catch operand does not have pointer type!", &LPI);
2745 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
2746 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
2747 "Filter operand is not an array of constants!", &LPI);
2751 visitInstruction(LPI);
2754 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
2755 Instruction *Op = cast<Instruction>(I.getOperand(i));
2756 // If the we have an invalid invoke, don't try to compute the dominance.
2757 // We already reject it in the invoke specific checks and the dominance
2758 // computation doesn't handle multiple edges.
2759 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
2760 if (II->getNormalDest() == II->getUnwindDest())
2764 const Use &U = I.getOperandUse(i);
2765 Assert(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
2766 "Instruction does not dominate all uses!", Op, &I);
2769 /// verifyInstruction - Verify that an instruction is well formed.
2771 void Verifier::visitInstruction(Instruction &I) {
2772 BasicBlock *BB = I.getParent();
2773 Assert(BB, "Instruction not embedded in basic block!", &I);
2775 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
2776 for (User *U : I.users()) {
2777 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
2778 "Only PHI nodes may reference their own value!", &I);
2782 // Check that void typed values don't have names
2783 Assert(!I.getType()->isVoidTy() || !I.hasName(),
2784 "Instruction has a name, but provides a void value!", &I);
2786 // Check that the return value of the instruction is either void or a legal
2788 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
2789 "Instruction returns a non-scalar type!", &I);
2791 // Check that the instruction doesn't produce metadata. Calls are already
2792 // checked against the callee type.
2793 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
2794 "Invalid use of metadata!", &I);
2796 // Check that all uses of the instruction, if they are instructions
2797 // themselves, actually have parent basic blocks. If the use is not an
2798 // instruction, it is an error!
2799 for (Use &U : I.uses()) {
2800 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
2801 Assert(Used->getParent() != nullptr,
2802 "Instruction referencing"
2803 " instruction not embedded in a basic block!",
2806 CheckFailed("Use of instruction is not an instruction!", U);
2811 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2812 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
2814 // Check to make sure that only first-class-values are operands to
2816 if (!I.getOperand(i)->getType()->isFirstClassType()) {
2817 Assert(0, "Instruction operands must be first-class values!", &I);
2820 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2821 // Check to make sure that the "address of" an intrinsic function is never
2824 !F->isIntrinsic() ||
2825 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
2826 "Cannot take the address of an intrinsic!", &I);
2828 !F->isIntrinsic() || isa<CallInst>(I) ||
2829 F->getIntrinsicID() == Intrinsic::donothing ||
2830 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
2831 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
2832 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
2833 "Cannot invoke an intrinsinc other than"
2834 " donothing or patchpoint",
2836 Assert(F->getParent() == M, "Referencing function in another module!",
2838 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2839 Assert(OpBB->getParent() == BB->getParent(),
2840 "Referring to a basic block in another function!", &I);
2841 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2842 Assert(OpArg->getParent() == BB->getParent(),
2843 "Referring to an argument in another function!", &I);
2844 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2845 Assert(GV->getParent() == M, "Referencing global in another module!", &I);
2846 } else if (isa<Instruction>(I.getOperand(i))) {
2847 verifyDominatesUse(I, i);
2848 } else if (isa<InlineAsm>(I.getOperand(i))) {
2849 Assert((i + 1 == e && isa<CallInst>(I)) ||
2850 (i + 3 == e && isa<InvokeInst>(I)),
2851 "Cannot take the address of an inline asm!", &I);
2852 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2853 if (CE->getType()->isPtrOrPtrVectorTy()) {
2854 // If we have a ConstantExpr pointer, we need to see if it came from an
2855 // illegal bitcast (inttoptr <constant int> )
2856 SmallVector<const ConstantExpr *, 4> Stack;
2857 SmallPtrSet<const ConstantExpr *, 4> Visited;
2858 Stack.push_back(CE);
2860 while (!Stack.empty()) {
2861 const ConstantExpr *V = Stack.pop_back_val();
2862 if (!Visited.insert(V).second)
2865 VerifyConstantExprBitcastType(V);
2867 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2868 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2869 Stack.push_back(Op);
2876 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2877 Assert(I.getType()->isFPOrFPVectorTy(),
2878 "fpmath requires a floating point result!", &I);
2879 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2880 if (ConstantFP *CFP0 =
2881 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
2882 APFloat Accuracy = CFP0->getValueAPF();
2883 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2884 "fpmath accuracy not a positive number!", &I);
2886 Assert(false, "invalid fpmath accuracy!", &I);
2890 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
2891 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
2892 "Ranges are only for loads, calls and invokes!", &I);
2893 visitRangeMetadata(I, Range, I.getType());
2896 if (I.getMetadata(LLVMContext::MD_nonnull)) {
2897 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
2899 Assert(isa<LoadInst>(I),
2900 "nonnull applies only to load instructions, use attributes"
2901 " for calls or invokes",
2905 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
2906 Assert(isa<MDLocation>(N), "invalid !dbg metadata attachment", &I, N);
2910 InstsInThisBlock.insert(&I);
2913 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2914 /// intrinsic argument or return value) matches the type constraints specified
2915 /// by the .td file (e.g. an "any integer" argument really is an integer).
2917 /// This return true on error but does not print a message.
2918 bool Verifier::VerifyIntrinsicType(Type *Ty,
2919 ArrayRef<Intrinsic::IITDescriptor> &Infos,
2920 SmallVectorImpl<Type*> &ArgTys) {
2921 using namespace Intrinsic;
2923 // If we ran out of descriptors, there are too many arguments.
2924 if (Infos.empty()) return true;
2925 IITDescriptor D = Infos.front();
2926 Infos = Infos.slice(1);
2929 case IITDescriptor::Void: return !Ty->isVoidTy();
2930 case IITDescriptor::VarArg: return true;
2931 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
2932 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2933 case IITDescriptor::Half: return !Ty->isHalfTy();
2934 case IITDescriptor::Float: return !Ty->isFloatTy();
2935 case IITDescriptor::Double: return !Ty->isDoubleTy();
2936 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2937 case IITDescriptor::Vector: {
2938 VectorType *VT = dyn_cast<VectorType>(Ty);
2939 return !VT || VT->getNumElements() != D.Vector_Width ||
2940 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2942 case IITDescriptor::Pointer: {
2943 PointerType *PT = dyn_cast<PointerType>(Ty);
2944 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2945 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2948 case IITDescriptor::Struct: {
2949 StructType *ST = dyn_cast<StructType>(Ty);
2950 if (!ST || ST->getNumElements() != D.Struct_NumElements)
2953 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2954 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2959 case IITDescriptor::Argument:
2960 // Two cases here - If this is the second occurrence of an argument, verify
2961 // that the later instance matches the previous instance.
2962 if (D.getArgumentNumber() < ArgTys.size())
2963 return Ty != ArgTys[D.getArgumentNumber()];
2965 // Otherwise, if this is the first instance of an argument, record it and
2966 // verify the "Any" kind.
2967 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2968 ArgTys.push_back(Ty);
2970 switch (D.getArgumentKind()) {
2971 case IITDescriptor::AK_Any: return false; // Success
2972 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2973 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
2974 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
2975 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2977 llvm_unreachable("all argument kinds not covered");
2979 case IITDescriptor::ExtendArgument: {
2980 // This may only be used when referring to a previous vector argument.
2981 if (D.getArgumentNumber() >= ArgTys.size())
2984 Type *NewTy = ArgTys[D.getArgumentNumber()];
2985 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2986 NewTy = VectorType::getExtendedElementVectorType(VTy);
2987 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2988 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
2994 case IITDescriptor::TruncArgument: {
2995 // This may only be used when referring to a previous vector argument.
2996 if (D.getArgumentNumber() >= ArgTys.size())
2999 Type *NewTy = ArgTys[D.getArgumentNumber()];
3000 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
3001 NewTy = VectorType::getTruncatedElementVectorType(VTy);
3002 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
3003 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
3009 case IITDescriptor::HalfVecArgument:
3010 // This may only be used when referring to a previous vector argument.
3011 return D.getArgumentNumber() >= ArgTys.size() ||
3012 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
3013 VectorType::getHalfElementsVectorType(
3014 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
3015 case IITDescriptor::SameVecWidthArgument: {
3016 if (D.getArgumentNumber() >= ArgTys.size())
3018 VectorType * ReferenceType =
3019 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
3020 VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
3021 if (!ThisArgType || !ReferenceType ||
3022 (ReferenceType->getVectorNumElements() !=
3023 ThisArgType->getVectorNumElements()))
3025 return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
3028 case IITDescriptor::PtrToArgument: {
3029 if (D.getArgumentNumber() >= ArgTys.size())
3031 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
3032 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
3033 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
3035 case IITDescriptor::VecOfPtrsToElt: {
3036 if (D.getArgumentNumber() >= ArgTys.size())
3038 VectorType * ReferenceType =
3039 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
3040 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
3041 if (!ThisArgVecTy || !ReferenceType ||
3042 (ReferenceType->getVectorNumElements() !=
3043 ThisArgVecTy->getVectorNumElements()))
3045 PointerType *ThisArgEltTy =
3046 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
3049 return (!(ThisArgEltTy->getElementType() ==
3050 ReferenceType->getVectorElementType()));
3053 llvm_unreachable("unhandled");
3056 /// \brief Verify if the intrinsic has variable arguments.
3057 /// This method is intended to be called after all the fixed arguments have been
3060 /// This method returns true on error and does not print an error message.
3062 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
3063 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
3064 using namespace Intrinsic;
3066 // If there are no descriptors left, then it can't be a vararg.
3070 // There should be only one descriptor remaining at this point.
3071 if (Infos.size() != 1)
3074 // Check and verify the descriptor.
3075 IITDescriptor D = Infos.front();
3076 Infos = Infos.slice(1);
3077 if (D.Kind == IITDescriptor::VarArg)
3083 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
3085 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
3086 Function *IF = CI.getCalledFunction();
3087 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
3090 // Verify that the intrinsic prototype lines up with what the .td files
3092 FunctionType *IFTy = IF->getFunctionType();
3093 bool IsVarArg = IFTy->isVarArg();
3095 SmallVector<Intrinsic::IITDescriptor, 8> Table;
3096 getIntrinsicInfoTableEntries(ID, Table);
3097 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
3099 SmallVector<Type *, 4> ArgTys;
3100 Assert(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
3101 "Intrinsic has incorrect return type!", IF);
3102 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
3103 Assert(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
3104 "Intrinsic has incorrect argument type!", IF);
3106 // Verify if the intrinsic call matches the vararg property.
3108 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3109 "Intrinsic was not defined with variable arguments!", IF);
3111 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3112 "Callsite was not defined with variable arguments!", IF);
3114 // All descriptors should be absorbed by now.
3115 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
3117 // Now that we have the intrinsic ID and the actual argument types (and we
3118 // know they are legal for the intrinsic!) get the intrinsic name through the
3119 // usual means. This allows us to verify the mangling of argument types into
3121 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
3122 Assert(ExpectedName == IF->getName(),
3123 "Intrinsic name not mangled correctly for type arguments! "
3128 // If the intrinsic takes MDNode arguments, verify that they are either global
3129 // or are local to *this* function.
3130 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
3131 if (auto *MD = dyn_cast<MetadataAsValue>(CI.getArgOperand(i)))
3132 visitMetadataAsValue(*MD, CI.getParent()->getParent());
3137 case Intrinsic::ctlz: // llvm.ctlz
3138 case Intrinsic::cttz: // llvm.cttz
3139 Assert(isa<ConstantInt>(CI.getArgOperand(1)),
3140 "is_zero_undef argument of bit counting intrinsics must be a "
3144 case Intrinsic::dbg_declare: // llvm.dbg.declare
3145 Assert(isa<MetadataAsValue>(CI.getArgOperand(0)),
3146 "invalid llvm.dbg.declare intrinsic call 1", &CI);
3147 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(CI));
3149 case Intrinsic::dbg_value: // llvm.dbg.value
3150 visitDbgIntrinsic("value", cast<DbgValueInst>(CI));
3152 case Intrinsic::memcpy:
3153 case Intrinsic::memmove:
3154 case Intrinsic::memset: {
3155 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CI.getArgOperand(3));
3157 "alignment argument of memory intrinsics must be a constant int",
3159 const APInt &AlignVal = AlignCI->getValue();
3160 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
3161 "alignment argument of memory intrinsics must be a power of 2", &CI);
3162 Assert(isa<ConstantInt>(CI.getArgOperand(4)),
3163 "isvolatile argument of memory intrinsics must be a constant int",
3167 case Intrinsic::gcroot:
3168 case Intrinsic::gcwrite:
3169 case Intrinsic::gcread:
3170 if (ID == Intrinsic::gcroot) {
3172 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
3173 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
3174 Assert(isa<Constant>(CI.getArgOperand(1)),
3175 "llvm.gcroot parameter #2 must be a constant.", &CI);
3176 if (!AI->getType()->getElementType()->isPointerTy()) {
3177 Assert(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
3178 "llvm.gcroot parameter #1 must either be a pointer alloca, "
3179 "or argument #2 must be a non-null constant.",
3184 Assert(CI.getParent()->getParent()->hasGC(),
3185 "Enclosing function does not use GC.", &CI);
3187 case Intrinsic::init_trampoline:
3188 Assert(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
3189 "llvm.init_trampoline parameter #2 must resolve to a function.",
3192 case Intrinsic::prefetch:
3193 Assert(isa<ConstantInt>(CI.getArgOperand(1)) &&
3194 isa<ConstantInt>(CI.getArgOperand(2)) &&
3195 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
3196 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
3197 "invalid arguments to llvm.prefetch", &CI);
3199 case Intrinsic::stackprotector:
3200 Assert(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
3201 "llvm.stackprotector parameter #2 must resolve to an alloca.", &CI);
3203 case Intrinsic::lifetime_start:
3204 case Intrinsic::lifetime_end:
3205 case Intrinsic::invariant_start:
3206 Assert(isa<ConstantInt>(CI.getArgOperand(0)),
3207 "size argument of memory use markers must be a constant integer",
3210 case Intrinsic::invariant_end:
3211 Assert(isa<ConstantInt>(CI.getArgOperand(1)),
3212 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
3215 case Intrinsic::frameescape: {
3216 BasicBlock *BB = CI.getParent();
3217 Assert(BB == &BB->getParent()->front(),
3218 "llvm.frameescape used outside of entry block", &CI);
3219 Assert(!SawFrameEscape,
3220 "multiple calls to llvm.frameescape in one function", &CI);
3221 for (Value *Arg : CI.arg_operands()) {
3222 if (isa<ConstantPointerNull>(Arg))
3223 continue; // Null values are allowed as placeholders.
3224 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
3225 Assert(AI && AI->isStaticAlloca(),
3226 "llvm.frameescape only accepts static allocas", &CI);
3228 FrameEscapeInfo[BB->getParent()].first = CI.getNumArgOperands();
3229 SawFrameEscape = true;
3232 case Intrinsic::framerecover: {
3233 Value *FnArg = CI.getArgOperand(0)->stripPointerCasts();
3234 Function *Fn = dyn_cast<Function>(FnArg);
3235 Assert(Fn && !Fn->isDeclaration(),
3236 "llvm.framerecover first "
3237 "argument must be function defined in this module",
3239 auto *IdxArg = dyn_cast<ConstantInt>(CI.getArgOperand(2));
3240 Assert(IdxArg, "idx argument of llvm.framerecover must be a constant int",
3242 auto &Entry = FrameEscapeInfo[Fn];
3243 Entry.second = unsigned(
3244 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
3248 case Intrinsic::experimental_gc_statepoint:
3249 Assert(!CI.isInlineAsm(),
3250 "gc.statepoint support for inline assembly unimplemented", &CI);
3251 Assert(CI.getParent()->getParent()->hasGC(),
3252 "Enclosing function does not use GC.", &CI);
3254 VerifyStatepoint(ImmutableCallSite(&CI));
3256 case Intrinsic::experimental_gc_result_int:
3257 case Intrinsic::experimental_gc_result_float:
3258 case Intrinsic::experimental_gc_result_ptr:
3259 case Intrinsic::experimental_gc_result: {
3260 Assert(CI.getParent()->getParent()->hasGC(),
3261 "Enclosing function does not use GC.", &CI);
3262 // Are we tied to a statepoint properly?
3263 CallSite StatepointCS(CI.getArgOperand(0));
3264 const Function *StatepointFn =
3265 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
3266 Assert(StatepointFn && StatepointFn->isDeclaration() &&
3267 StatepointFn->getIntrinsicID() ==
3268 Intrinsic::experimental_gc_statepoint,
3269 "gc.result operand #1 must be from a statepoint", &CI,
3270 CI.getArgOperand(0));
3272 // Assert that result type matches wrapped callee.
3273 const Value *Target = StatepointCS.getArgument(0);
3274 const PointerType *PT = cast<PointerType>(Target->getType());
3275 const FunctionType *TargetFuncType =
3276 cast<FunctionType>(PT->getElementType());
3277 Assert(CI.getType() == TargetFuncType->getReturnType(),
3278 "gc.result result type does not match wrapped callee", &CI);
3281 case Intrinsic::experimental_gc_relocate: {
3282 Assert(CI.getNumArgOperands() == 3, "wrong number of arguments", &CI);
3284 // Check that this relocate is correctly tied to the statepoint
3286 // This is case for relocate on the unwinding path of an invoke statepoint
3287 if (ExtractValueInst *ExtractValue =
3288 dyn_cast<ExtractValueInst>(CI.getArgOperand(0))) {
3289 Assert(isa<LandingPadInst>(ExtractValue->getAggregateOperand()),
3290 "gc relocate on unwind path incorrectly linked to the statepoint",
3293 const BasicBlock *invokeBB =
3294 ExtractValue->getParent()->getUniquePredecessor();
3296 // Landingpad relocates should have only one predecessor with invoke
3297 // statepoint terminator
3298 Assert(invokeBB, "safepoints should have unique landingpads",
3299 ExtractValue->getParent());
3300 Assert(invokeBB->getTerminator(), "safepoint block should be well formed",
3302 Assert(isStatepoint(invokeBB->getTerminator()),
3303 "gc relocate should be linked to a statepoint", invokeBB);
3306 // In all other cases relocate should be tied to the statepoint directly.
3307 // This covers relocates on a normal return path of invoke statepoint and
3308 // relocates of a call statepoint
3309 auto Token = CI.getArgOperand(0);
3310 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
3311 "gc relocate is incorrectly tied to the statepoint", &CI, Token);
3314 // Verify rest of the relocate arguments
3316 GCRelocateOperands ops(&CI);
3317 ImmutableCallSite StatepointCS(ops.statepoint());
3319 // Both the base and derived must be piped through the safepoint
3320 Value* Base = CI.getArgOperand(1);
3321 Assert(isa<ConstantInt>(Base),
3322 "gc.relocate operand #2 must be integer offset", &CI);
3324 Value* Derived = CI.getArgOperand(2);
3325 Assert(isa<ConstantInt>(Derived),
3326 "gc.relocate operand #3 must be integer offset", &CI);
3328 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
3329 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
3331 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
3332 "gc.relocate: statepoint base index out of bounds", &CI);
3333 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
3334 "gc.relocate: statepoint derived index out of bounds", &CI);
3336 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
3337 // section of the statepoint's argument
3338 Assert(StatepointCS.arg_size() > 0,
3339 "gc.statepoint: insufficient arguments");
3340 Assert(isa<ConstantInt>(StatepointCS.getArgument(1)),
3341 "gc.statement: number of call arguments must be constant integer");
3342 const unsigned NumCallArgs =
3343 cast<ConstantInt>(StatepointCS.getArgument(1))->getZExtValue();
3344 Assert(StatepointCS.arg_size() > NumCallArgs+3,
3345 "gc.statepoint: mismatch in number of call arguments");
3346 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs+3)),
3347 "gc.statepoint: number of deoptimization arguments must be "
3348 "a constant integer");
3349 const int NumDeoptArgs =
3350 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 3))->getZExtValue();
3351 const int GCParamArgsStart = NumCallArgs + NumDeoptArgs + 4;
3352 const int GCParamArgsEnd = StatepointCS.arg_size();
3353 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
3354 "gc.relocate: statepoint base index doesn't fall within the "
3355 "'gc parameters' section of the statepoint call",
3357 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
3358 "gc.relocate: statepoint derived index doesn't fall within the "
3359 "'gc parameters' section of the statepoint call",
3362 // Assert that the result type matches the type of the relocated pointer
3363 GCRelocateOperands Operands(&CI);
3364 Assert(Operands.derivedPtr()->getType() == CI.getType(),
3365 "gc.relocate: relocating a pointer shouldn't change its type", &CI);
3371 template <class DbgIntrinsicTy>
3372 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
3373 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
3374 Assert(isa<ValueAsMetadata>(MD) ||
3375 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
3376 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
3377 Assert(isa<MDLocalVariable>(DII.getRawVariable()),
3378 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
3379 DII.getRawVariable());
3380 Assert(isa<MDExpression>(DII.getRawExpression()),
3381 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
3382 DII.getRawExpression());
3384 // Queue up bit piece expressions to be verified once we can resolve
3386 if (DII.getExpression()->isValid() && DII.getExpression()->isBitPiece())
3387 QueuedBitPieceExpressions.push_back(&DII);
3389 // Ignore broken !dbg attachments; they're checked elsewhere.
3390 if (MDNode *N = DII.getDebugLoc().getAsMDNode())
3391 if (!isa<MDLocation>(N))
3394 // The inlined-at attachments for variables and !dbg attachments must agree.
3395 MDLocalVariable *Var = DII.getVariable();
3396 MDLocation *VarIA = Var->getInlinedAt();
3397 MDLocation *Loc = DII.getDebugLoc();
3398 MDLocation *LocIA = Loc ? Loc->getInlinedAt() : nullptr;
3399 BasicBlock *BB = DII.getParent();
3400 Assert(VarIA == LocIA, "mismatched variable and !dbg inlined-at", &DII, BB,
3401 BB ? BB->getParent() : nullptr, Var, VarIA, Loc, LocIA);
3404 template <class MapTy>
3405 static uint64_t getVariableSize(const MDLocalVariable &V, const MapTy &Map) {
3406 // Be careful of broken types (checked elsewhere).
3407 const Metadata *RawType = V.getRawType();
3409 // Try to get the size directly.
3410 if (auto *T = dyn_cast<MDType>(RawType))
3411 if (uint64_t Size = T->getSizeInBits())
3414 if (auto *DT = dyn_cast<MDDerivedType>(RawType)) {
3415 // Look at the base type.
3416 RawType = DT->getRawBaseType();
3420 if (auto *S = dyn_cast<MDString>(RawType)) {
3421 // Don't error on missing types (checked elsewhere).
3422 RawType = Map.lookup(S);
3426 // Missing type or size.
3434 template <class MapTy>
3435 void Verifier::verifyBitPieceExpression(const DbgInfoIntrinsic &I,
3436 const MapTy &TypeRefs) {
3439 if (auto *DVI = dyn_cast<DbgValueInst>(&I)) {
3440 V = DVI->getVariable();
3441 E = DVI->getExpression();
3443 auto *DDI = cast<DbgDeclareInst>(&I);
3444 V = DDI->getVariable();
3445 E = DDI->getExpression();
3448 assert(V && E->isValid() && E->isBitPiece() &&
3449 "Expected valid bitpieces here");
3451 // If there's no size, the type is broken, but that should be checked
3453 uint64_t VarSize = getVariableSize(*V, TypeRefs);
3457 unsigned PieceSize = E->getBitPieceSize();
3458 unsigned PieceOffset = E->getBitPieceOffset();
3459 Assert(PieceSize + PieceOffset <= VarSize,
3460 "piece is larger than or outside of variable", &I, V, E);
3461 Assert(PieceSize != VarSize, "piece covers entire variable", &I, V, E);
3464 void Verifier::visitUnresolvedTypeRef(const MDString *S, const MDNode *N) {
3465 // This is in its own function so we get an error for each bad type ref (not
3467 Assert(false, "unresolved type ref", S, N);
3470 void Verifier::verifyTypeRefs() {
3471 auto *CUs = M->getNamedMetadata("llvm.dbg.cu");
3475 // Visit all the compile units again to map the type references.
3476 SmallDenseMap<const MDString *, const MDType *, 32> TypeRefs;
3477 for (auto *CU : CUs->operands())
3478 if (auto Ts = cast<MDCompileUnit>(CU)->getRetainedTypes())
3479 for (MDType *Op : Ts)
3480 if (auto *T = dyn_cast<MDCompositeType>(Op))
3481 if (auto *S = T->getRawIdentifier()) {
3482 UnresolvedTypeRefs.erase(S);
3483 TypeRefs.insert(std::make_pair(S, T));
3486 // Verify debug intrinsic bit piece expressions.
3487 for (auto *DII : QueuedBitPieceExpressions)
3488 verifyBitPieceExpression(*DII, TypeRefs);
3490 // Return early if all typerefs were resolved.
3491 if (UnresolvedTypeRefs.empty())
3494 // Sort the unresolved references by name so the output is deterministic.
3495 typedef std::pair<const MDString *, const MDNode *> TypeRef;
3496 SmallVector<TypeRef, 32> Unresolved(UnresolvedTypeRefs.begin(),
3497 UnresolvedTypeRefs.end());
3498 std::sort(Unresolved.begin(), Unresolved.end(),
3499 [](const TypeRef &LHS, const TypeRef &RHS) {
3500 return LHS.first->getString() < RHS.first->getString();
3503 // Visit the unresolved refs (printing out the errors).
3504 for (const TypeRef &TR : Unresolved)
3505 visitUnresolvedTypeRef(TR.first, TR.second);
3508 //===----------------------------------------------------------------------===//
3509 // Implement the public interfaces to this file...
3510 //===----------------------------------------------------------------------===//
3512 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
3513 Function &F = const_cast<Function &>(f);
3514 assert(!F.isDeclaration() && "Cannot verify external functions");
3516 raw_null_ostream NullStr;
3517 Verifier V(OS ? *OS : NullStr);
3519 // Note that this function's return value is inverted from what you would
3520 // expect of a function called "verify".
3521 return !V.verify(F);
3524 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
3525 raw_null_ostream NullStr;
3526 Verifier V(OS ? *OS : NullStr);
3528 bool Broken = false;
3529 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
3530 if (!I->isDeclaration() && !I->isMaterializable())
3531 Broken |= !V.verify(*I);
3533 // Note that this function's return value is inverted from what you would
3534 // expect of a function called "verify".
3535 return !V.verify(M) || Broken;
3539 struct VerifierLegacyPass : public FunctionPass {
3545 VerifierLegacyPass() : FunctionPass(ID), V(dbgs()), FatalErrors(true) {
3546 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3548 explicit VerifierLegacyPass(bool FatalErrors)
3549 : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
3550 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3553 bool runOnFunction(Function &F) override {
3554 if (!V.verify(F) && FatalErrors)
3555 report_fatal_error("Broken function found, compilation aborted!");
3560 bool doFinalization(Module &M) override {
3561 if (!V.verify(M) && FatalErrors)
3562 report_fatal_error("Broken module found, compilation aborted!");
3567 void getAnalysisUsage(AnalysisUsage &AU) const override {
3568 AU.setPreservesAll();
3573 char VerifierLegacyPass::ID = 0;
3574 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
3576 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
3577 return new VerifierLegacyPass(FatalErrors);
3580 PreservedAnalyses VerifierPass::run(Module &M) {
3581 if (verifyModule(M, &dbgs()) && FatalErrors)
3582 report_fatal_error("Broken module found, compilation aborted!");
3584 return PreservedAnalyses::all();
3587 PreservedAnalyses VerifierPass::run(Function &F) {
3588 if (verifyFunction(F, &dbgs()) && FatalErrors)
3589 report_fatal_error("Broken function found, compilation aborted!");
3591 return PreservedAnalyses::all();