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/InstVisitor.h"
65 #include "llvm/IR/IntrinsicInst.h"
66 #include "llvm/IR/LLVMContext.h"
67 #include "llvm/IR/Metadata.h"
68 #include "llvm/IR/Module.h"
69 #include "llvm/IR/PassManager.h"
70 #include "llvm/Pass.h"
71 #include "llvm/Support/CommandLine.h"
72 #include "llvm/Support/Debug.h"
73 #include "llvm/Support/ErrorHandling.h"
74 #include "llvm/Support/raw_ostream.h"
79 static cl::opt<bool> DisableDebugInfoVerifier("disable-debug-info-verifier",
83 class Verifier : public InstVisitor<Verifier> {
84 friend class InstVisitor<Verifier>;
92 /// \brief When verifying a basic block, keep track of all of the
93 /// instructions we have seen so far.
95 /// This allows us to do efficient dominance checks for the case when an
96 /// instruction has an operand that is an instruction in the same block.
97 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
99 /// \brief Keep track of the metadata nodes that have been checked already.
100 SmallPtrSet<MDNode *, 32> MDNodes;
102 /// \brief The personality function referenced by the LandingPadInsts.
103 /// All LandingPadInsts within the same function must use the same
104 /// personality function.
105 const Value *PersonalityFn;
107 /// \brief Finder keeps track of all debug info MDNodes in a Module.
108 DebugInfoFinder Finder;
110 /// \brief Track the brokenness of the module while recursively visiting.
114 explicit Verifier(raw_ostream &OS = dbgs())
115 : OS(OS), M(0), Context(0), DL(0), PersonalityFn(0), Broken(false) {}
117 bool verify(const Function &F) {
119 Context = &M->getContext();
121 // First ensure the function is well-enough formed to compute dominance
124 OS << "Function '" << F.getName()
125 << "' does not contain an entry block!\n";
128 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
129 if (I->empty() || !I->back().isTerminator()) {
130 OS << "Basic Block in function '" << F.getName()
131 << "' does not have terminator!\n";
132 I->printAsOperand(OS, true);
138 // Now directly compute a dominance tree. We don't rely on the pass
139 // manager to provide this as it isolates us from a potentially
140 // out-of-date dominator tree and makes it significantly more complex to
141 // run this code outside of a pass manager.
142 // FIXME: It's really gross that we have to cast away constness here.
143 DT.recalculate(const_cast<Function &>(F));
147 // FIXME: We strip const here because the inst visitor strips const.
148 visit(const_cast<Function &>(F));
149 InstsInThisBlock.clear();
152 if (!DisableDebugInfoVerifier)
153 // Verify Debug Info.
159 bool verify(const Module &M) {
161 Context = &M.getContext();
165 // Scan through, checking all of the external function's linkage now...
166 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
167 visitGlobalValue(*I);
169 // Check to make sure function prototypes are okay.
170 if (I->isDeclaration())
174 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
176 visitGlobalVariable(*I);
178 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
180 visitGlobalAlias(*I);
182 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
183 E = M.named_metadata_end();
185 visitNamedMDNode(*I);
188 visitModuleIdents(M);
190 if (!DisableDebugInfoVerifier) {
192 Finder.processModule(M);
193 // Verify Debug Info.
201 // Verification methods...
202 void visitGlobalValue(const GlobalValue &GV);
203 void visitGlobalVariable(const GlobalVariable &GV);
204 void visitGlobalAlias(const GlobalAlias &GA);
205 void visitNamedMDNode(const NamedMDNode &NMD);
206 void visitMDNode(MDNode &MD, Function *F);
207 void visitModuleIdents(const Module &M);
208 void visitModuleFlags(const Module &M);
209 void visitModuleFlag(const MDNode *Op,
210 DenseMap<const MDString *, const MDNode *> &SeenIDs,
211 SmallVectorImpl<const MDNode *> &Requirements);
212 void visitFunction(const Function &F);
213 void visitBasicBlock(BasicBlock &BB);
215 // InstVisitor overrides...
216 using InstVisitor<Verifier>::visit;
217 void visit(Instruction &I);
219 void visitTruncInst(TruncInst &I);
220 void visitZExtInst(ZExtInst &I);
221 void visitSExtInst(SExtInst &I);
222 void visitFPTruncInst(FPTruncInst &I);
223 void visitFPExtInst(FPExtInst &I);
224 void visitFPToUIInst(FPToUIInst &I);
225 void visitFPToSIInst(FPToSIInst &I);
226 void visitUIToFPInst(UIToFPInst &I);
227 void visitSIToFPInst(SIToFPInst &I);
228 void visitIntToPtrInst(IntToPtrInst &I);
229 void visitPtrToIntInst(PtrToIntInst &I);
230 void visitBitCastInst(BitCastInst &I);
231 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
232 void visitPHINode(PHINode &PN);
233 void visitBinaryOperator(BinaryOperator &B);
234 void visitICmpInst(ICmpInst &IC);
235 void visitFCmpInst(FCmpInst &FC);
236 void visitExtractElementInst(ExtractElementInst &EI);
237 void visitInsertElementInst(InsertElementInst &EI);
238 void visitShuffleVectorInst(ShuffleVectorInst &EI);
239 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
240 void visitCallInst(CallInst &CI);
241 void visitInvokeInst(InvokeInst &II);
242 void visitGetElementPtrInst(GetElementPtrInst &GEP);
243 void visitLoadInst(LoadInst &LI);
244 void visitStoreInst(StoreInst &SI);
245 void verifyDominatesUse(Instruction &I, unsigned i);
246 void visitInstruction(Instruction &I);
247 void visitTerminatorInst(TerminatorInst &I);
248 void visitBranchInst(BranchInst &BI);
249 void visitReturnInst(ReturnInst &RI);
250 void visitSwitchInst(SwitchInst &SI);
251 void visitIndirectBrInst(IndirectBrInst &BI);
252 void visitSelectInst(SelectInst &SI);
253 void visitUserOp1(Instruction &I);
254 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
255 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
256 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
257 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
258 void visitFenceInst(FenceInst &FI);
259 void visitAllocaInst(AllocaInst &AI);
260 void visitExtractValueInst(ExtractValueInst &EVI);
261 void visitInsertValueInst(InsertValueInst &IVI);
262 void visitLandingPadInst(LandingPadInst &LPI);
264 void VerifyCallSite(CallSite CS);
265 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
266 unsigned ArgNo, std::string &Suffix);
267 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
268 SmallVectorImpl<Type *> &ArgTys);
269 bool VerifyIntrinsicIsVarArg(bool isVarArg,
270 ArrayRef<Intrinsic::IITDescriptor> &Infos);
271 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
272 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
274 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
275 bool isReturnValue, const Value *V);
276 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
279 void VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy);
280 void VerifyConstantExprBitcastType(const ConstantExpr *CE);
282 void verifyDebugInfo();
284 void WriteValue(const Value *V) {
287 if (isa<Instruction>(V)) {
290 V->printAsOperand(OS, true, M);
295 void WriteType(Type *T) {
301 // CheckFailed - A check failed, so print out the condition and the message
302 // that failed. This provides a nice place to put a breakpoint if you want
303 // to see why something is not correct.
304 void CheckFailed(const Twine &Message, const Value *V1 = 0,
305 const Value *V2 = 0, const Value *V3 = 0,
306 const Value *V4 = 0) {
307 OS << Message.str() << "\n";
315 void CheckFailed(const Twine &Message, const Value *V1, Type *T2,
316 const Value *V3 = 0) {
317 OS << Message.str() << "\n";
324 void CheckFailed(const Twine &Message, Type *T1, Type *T2 = 0, Type *T3 = 0) {
325 OS << Message.str() << "\n";
332 } // End anonymous namespace
334 // Assert - We know that cond should be true, if not print an error message.
335 #define Assert(C, M) \
336 do { if (!(C)) { CheckFailed(M); return; } } while (0)
337 #define Assert1(C, M, V1) \
338 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
339 #define Assert2(C, M, V1, V2) \
340 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
341 #define Assert3(C, M, V1, V2, V3) \
342 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
343 #define Assert4(C, M, V1, V2, V3, V4) \
344 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
346 void Verifier::visit(Instruction &I) {
347 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
348 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
349 InstVisitor<Verifier>::visit(I);
353 void Verifier::visitGlobalValue(const GlobalValue &GV) {
354 Assert1(!GV.isDeclaration() ||
355 GV.isMaterializable() ||
356 GV.hasExternalLinkage() ||
357 GV.hasExternalWeakLinkage() ||
358 (isa<GlobalAlias>(GV) &&
359 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
360 "Global is external, but doesn't have external or weak linkage!",
363 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
364 "Only global variables can have appending linkage!", &GV);
366 if (GV.hasAppendingLinkage()) {
367 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
368 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
369 "Only global arrays can have appending linkage!", GVar);
373 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
374 if (GV.hasInitializer()) {
375 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
376 "Global variable initializer type does not match global "
377 "variable type!", &GV);
379 // If the global has common linkage, it must have a zero initializer and
380 // cannot be constant.
381 if (GV.hasCommonLinkage()) {
382 Assert1(GV.getInitializer()->isNullValue(),
383 "'common' global must have a zero initializer!", &GV);
384 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
388 Assert1(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
389 "invalid linkage type for global declaration", &GV);
392 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
393 GV.getName() == "llvm.global_dtors")) {
394 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
395 "invalid linkage for intrinsic global variable", &GV);
396 // Don't worry about emitting an error for it not being an array,
397 // visitGlobalValue will complain on appending non-array.
398 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
399 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
400 PointerType *FuncPtrTy =
401 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
402 Assert1(STy && STy->getNumElements() == 2 &&
403 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
404 STy->getTypeAtIndex(1) == FuncPtrTy,
405 "wrong type for intrinsic global variable", &GV);
409 if (GV.hasName() && (GV.getName() == "llvm.used" ||
410 GV.getName() == "llvm.compiler.used")) {
411 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
412 "invalid linkage for intrinsic global variable", &GV);
413 Type *GVType = GV.getType()->getElementType();
414 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
415 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
416 Assert1(PTy, "wrong type for intrinsic global variable", &GV);
417 if (GV.hasInitializer()) {
418 const Constant *Init = GV.getInitializer();
419 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
420 Assert1(InitArray, "wrong initalizer for intrinsic global variable",
422 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
423 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
425 isa<GlobalVariable>(V) || isa<Function>(V) || isa<GlobalAlias>(V),
426 "invalid llvm.used member", V);
427 Assert1(V->hasName(), "members of llvm.used must be named", V);
433 Assert1(!GV.hasDLLImportStorageClass() ||
434 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
435 GV.hasAvailableExternallyLinkage(),
436 "Global is marked as dllimport, but not external", &GV);
438 if (!GV.hasInitializer()) {
439 visitGlobalValue(GV);
443 // Walk any aggregate initializers looking for bitcasts between address spaces
444 SmallPtrSet<const Value *, 4> Visited;
445 SmallVector<const Value *, 4> WorkStack;
446 WorkStack.push_back(cast<Value>(GV.getInitializer()));
448 while (!WorkStack.empty()) {
449 const Value *V = WorkStack.pop_back_val();
450 if (!Visited.insert(V))
453 if (const User *U = dyn_cast<User>(V)) {
454 for (unsigned I = 0, N = U->getNumOperands(); I != N; ++I)
455 WorkStack.push_back(U->getOperand(I));
458 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
459 VerifyConstantExprBitcastType(CE);
465 visitGlobalValue(GV);
468 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
469 Assert1(!GA.getName().empty(),
470 "Alias name cannot be empty!", &GA);
471 Assert1(GlobalAlias::isValidLinkage(GA.getLinkage()),
472 "Alias should have external or external weak linkage!", &GA);
473 Assert1(GA.getAliasee(),
474 "Aliasee cannot be NULL!", &GA);
475 Assert1(GA.getType() == GA.getAliasee()->getType(),
476 "Alias and aliasee types should match!", &GA);
477 Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
478 Assert1(!GA.hasSection(), "Alias cannot have a section!", &GA);
479 Assert1(!GA.getAlignment(), "Alias connot have an alignment", &GA);
481 const Constant *Aliasee = GA.getAliasee();
482 const GlobalValue *GV = dyn_cast<GlobalValue>(Aliasee);
485 const ConstantExpr *CE = dyn_cast<ConstantExpr>(Aliasee);
486 if (CE && (CE->getOpcode() == Instruction::BitCast ||
487 CE->getOpcode() == Instruction::AddrSpaceCast ||
488 CE->getOpcode() == Instruction::GetElementPtr))
489 GV = dyn_cast<GlobalValue>(CE->getOperand(0));
491 Assert1(GV, "Aliasee should be either GlobalValue, bitcast or "
492 "addrspacecast of GlobalValue",
495 if (CE->getOpcode() == Instruction::BitCast) {
496 unsigned SrcAS = GV->getType()->getPointerAddressSpace();
497 unsigned DstAS = CE->getType()->getPointerAddressSpace();
499 Assert1(SrcAS == DstAS,
500 "Alias bitcasts cannot be between different address spaces",
505 const GlobalValue* Resolved = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
507 "Aliasing chain should end with function or global variable", &GA);
509 visitGlobalValue(GA);
512 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
513 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
514 MDNode *MD = NMD.getOperand(i);
518 Assert1(!MD->isFunctionLocal(),
519 "Named metadata operand cannot be function local!", MD);
524 void Verifier::visitMDNode(MDNode &MD, Function *F) {
525 // Only visit each node once. Metadata can be mutually recursive, so this
526 // avoids infinite recursion here, as well as being an optimization.
527 if (!MDNodes.insert(&MD))
530 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
531 Value *Op = MD.getOperand(i);
534 if (isa<Constant>(Op) || isa<MDString>(Op))
536 if (MDNode *N = dyn_cast<MDNode>(Op)) {
537 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
538 "Global metadata operand cannot be function local!", &MD, N);
542 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
544 // If this was an instruction, bb, or argument, verify that it is in the
545 // function that we expect.
546 Function *ActualF = 0;
547 if (Instruction *I = dyn_cast<Instruction>(Op))
548 ActualF = I->getParent()->getParent();
549 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
550 ActualF = BB->getParent();
551 else if (Argument *A = dyn_cast<Argument>(Op))
552 ActualF = A->getParent();
553 assert(ActualF && "Unimplemented function local metadata case!");
555 Assert2(ActualF == F, "function-local metadata used in wrong function",
560 void Verifier::visitModuleIdents(const Module &M) {
561 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
565 // llvm.ident takes a list of metadata entry. Each entry has only one string.
566 // Scan each llvm.ident entry and make sure that this requirement is met.
567 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
568 const MDNode *N = Idents->getOperand(i);
569 Assert1(N->getNumOperands() == 1,
570 "incorrect number of operands in llvm.ident metadata", N);
571 Assert1(isa<MDString>(N->getOperand(0)),
572 ("invalid value for llvm.ident metadata entry operand"
573 "(the operand should be a string)"),
578 void Verifier::visitModuleFlags(const Module &M) {
579 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
582 // Scan each flag, and track the flags and requirements.
583 DenseMap<const MDString*, const MDNode*> SeenIDs;
584 SmallVector<const MDNode*, 16> Requirements;
585 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
586 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
589 // Validate that the requirements in the module are valid.
590 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
591 const MDNode *Requirement = Requirements[I];
592 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
593 const Value *ReqValue = Requirement->getOperand(1);
595 const MDNode *Op = SeenIDs.lookup(Flag);
597 CheckFailed("invalid requirement on flag, flag is not present in module",
602 if (Op->getOperand(2) != ReqValue) {
603 CheckFailed(("invalid requirement on flag, "
604 "flag does not have the required value"),
612 Verifier::visitModuleFlag(const MDNode *Op,
613 DenseMap<const MDString *, const MDNode *> &SeenIDs,
614 SmallVectorImpl<const MDNode *> &Requirements) {
615 // Each module flag should have three arguments, the merge behavior (a
616 // constant int), the flag ID (an MDString), and the value.
617 Assert1(Op->getNumOperands() == 3,
618 "incorrect number of operands in module flag", Op);
619 ConstantInt *Behavior = dyn_cast<ConstantInt>(Op->getOperand(0));
620 MDString *ID = dyn_cast<MDString>(Op->getOperand(1));
622 "invalid behavior operand in module flag (expected constant integer)",
624 unsigned BehaviorValue = Behavior->getZExtValue();
626 "invalid ID operand in module flag (expected metadata string)",
629 // Sanity check the values for behaviors with additional requirements.
630 switch (BehaviorValue) {
633 "invalid behavior operand in module flag (unexpected constant)",
638 case Module::Warning:
639 case Module::Override:
640 // These behavior types accept any value.
643 case Module::Require: {
644 // The value should itself be an MDNode with two operands, a flag ID (an
645 // MDString), and a value.
646 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
647 Assert1(Value && Value->getNumOperands() == 2,
648 "invalid value for 'require' module flag (expected metadata pair)",
650 Assert1(isa<MDString>(Value->getOperand(0)),
651 ("invalid value for 'require' module flag "
652 "(first value operand should be a string)"),
653 Value->getOperand(0));
655 // Append it to the list of requirements, to check once all module flags are
657 Requirements.push_back(Value);
662 case Module::AppendUnique: {
663 // These behavior types require the operand be an MDNode.
664 Assert1(isa<MDNode>(Op->getOperand(2)),
665 "invalid value for 'append'-type module flag "
666 "(expected a metadata node)", Op->getOperand(2));
671 // Unless this is a "requires" flag, check the ID is unique.
672 if (BehaviorValue != Module::Require) {
673 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
675 "module flag identifiers must be unique (or of 'require' type)",
680 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
681 bool isFunction, const Value *V) {
683 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
684 if (Attrs.getSlotIndex(I) == Idx) {
689 assert(Slot != ~0U && "Attribute set inconsistency!");
691 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
693 if (I->isStringAttribute())
696 if (I->getKindAsEnum() == Attribute::NoReturn ||
697 I->getKindAsEnum() == Attribute::NoUnwind ||
698 I->getKindAsEnum() == Attribute::NoInline ||
699 I->getKindAsEnum() == Attribute::AlwaysInline ||
700 I->getKindAsEnum() == Attribute::OptimizeForSize ||
701 I->getKindAsEnum() == Attribute::StackProtect ||
702 I->getKindAsEnum() == Attribute::StackProtectReq ||
703 I->getKindAsEnum() == Attribute::StackProtectStrong ||
704 I->getKindAsEnum() == Attribute::NoRedZone ||
705 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
706 I->getKindAsEnum() == Attribute::Naked ||
707 I->getKindAsEnum() == Attribute::InlineHint ||
708 I->getKindAsEnum() == Attribute::StackAlignment ||
709 I->getKindAsEnum() == Attribute::UWTable ||
710 I->getKindAsEnum() == Attribute::NonLazyBind ||
711 I->getKindAsEnum() == Attribute::ReturnsTwice ||
712 I->getKindAsEnum() == Attribute::SanitizeAddress ||
713 I->getKindAsEnum() == Attribute::SanitizeThread ||
714 I->getKindAsEnum() == Attribute::SanitizeMemory ||
715 I->getKindAsEnum() == Attribute::MinSize ||
716 I->getKindAsEnum() == Attribute::NoDuplicate ||
717 I->getKindAsEnum() == Attribute::Builtin ||
718 I->getKindAsEnum() == Attribute::NoBuiltin ||
719 I->getKindAsEnum() == Attribute::Cold ||
720 I->getKindAsEnum() == Attribute::OptimizeNone) {
722 CheckFailed("Attribute '" + I->getAsString() +
723 "' only applies to functions!", V);
726 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
727 I->getKindAsEnum() == Attribute::ReadNone) {
729 CheckFailed("Attribute '" + I->getAsString() +
730 "' does not apply to function returns");
733 } else if (isFunction) {
734 CheckFailed("Attribute '" + I->getAsString() +
735 "' does not apply to functions!", V);
741 // VerifyParameterAttrs - Check the given attributes for an argument or return
742 // value of the specified type. The value V is printed in error messages.
743 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
744 bool isReturnValue, const Value *V) {
745 if (!Attrs.hasAttributes(Idx))
748 VerifyAttributeTypes(Attrs, Idx, false, V);
751 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
752 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
753 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
754 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
755 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
756 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
757 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
758 "'returned' do not apply to return values!", V);
760 // Check for mutually incompatible attributes. Only inreg is compatible with
762 unsigned AttrCount = 0;
763 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
764 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
765 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
766 Attrs.hasAttribute(Idx, Attribute::InReg);
767 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
768 Assert1(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
769 "and 'sret' are incompatible!", V);
771 Assert1(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
772 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
773 "'inalloca and readonly' are incompatible!", V);
775 Assert1(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
776 Attrs.hasAttribute(Idx, Attribute::Returned)), "Attributes "
777 "'sret and returned' are incompatible!", V);
779 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
780 Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes "
781 "'zeroext and signext' are incompatible!", V);
783 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
784 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
785 "'readnone and readonly' are incompatible!", V);
787 Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
788 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes "
789 "'noinline and alwaysinline' are incompatible!", V);
791 Assert1(!AttrBuilder(Attrs, Idx).
792 hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
793 "Wrong types for attribute: " +
794 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V);
796 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
797 if (!PTy->getElementType()->isSized()) {
798 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
799 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
800 "Attributes 'byval' and 'inalloca' do not support unsized types!",
804 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
805 "Attribute 'byval' only applies to parameters with pointer type!",
810 // VerifyFunctionAttrs - Check parameter attributes against a function type.
811 // The value V is printed in error messages.
812 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
817 bool SawNest = false;
818 bool SawReturned = false;
820 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
821 unsigned Idx = Attrs.getSlotIndex(i);
825 Ty = FT->getReturnType();
826 else if (Idx-1 < FT->getNumParams())
827 Ty = FT->getParamType(Idx-1);
829 break; // VarArgs attributes, verified elsewhere.
831 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
836 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
837 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
841 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
842 Assert1(!SawReturned, "More than one parameter has attribute returned!",
844 Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible "
845 "argument and return types for 'returned' attribute", V);
849 if (Attrs.hasAttribute(Idx, Attribute::StructRet))
850 Assert1(Idx == 1, "Attribute sret is not on first parameter!", V);
852 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
853 Assert1(Idx == FT->getNumParams(),
854 "inalloca isn't on the last parameter!", V);
858 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
861 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
863 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
864 Attribute::ReadNone) &&
865 Attrs.hasAttribute(AttributeSet::FunctionIndex,
866 Attribute::ReadOnly)),
867 "Attributes 'readnone and readonly' are incompatible!", V);
869 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
870 Attribute::NoInline) &&
871 Attrs.hasAttribute(AttributeSet::FunctionIndex,
872 Attribute::AlwaysInline)),
873 "Attributes 'noinline and alwaysinline' are incompatible!", V);
875 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
876 Attribute::OptimizeNone)) {
877 Assert1(Attrs.hasAttribute(AttributeSet::FunctionIndex,
878 Attribute::NoInline),
879 "Attribute 'optnone' requires 'noinline'!", V);
881 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
882 Attribute::OptimizeForSize),
883 "Attributes 'optsize and optnone' are incompatible!", V);
885 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
887 "Attributes 'minsize and optnone' are incompatible!", V);
891 void Verifier::VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy) {
892 // Get the size of the types in bits, we'll need this later
893 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
894 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
896 // BitCast implies a no-op cast of type only. No bits change.
897 // However, you can't cast pointers to anything but pointers.
898 Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
899 "Bitcast requires both operands to be pointer or neither", V);
900 Assert1(SrcBitSize == DestBitSize,
901 "Bitcast requires types of same width", V);
903 // Disallow aggregates.
904 Assert1(!SrcTy->isAggregateType(),
905 "Bitcast operand must not be aggregate", V);
906 Assert1(!DestTy->isAggregateType(),
907 "Bitcast type must not be aggregate", V);
909 // Without datalayout, assume all address spaces are the same size.
910 // Don't check if both types are not pointers.
911 // Skip casts between scalars and vectors.
913 !SrcTy->isPtrOrPtrVectorTy() ||
914 !DestTy->isPtrOrPtrVectorTy() ||
915 SrcTy->isVectorTy() != DestTy->isVectorTy()) {
919 unsigned SrcAS = SrcTy->getPointerAddressSpace();
920 unsigned DstAS = DestTy->getPointerAddressSpace();
922 Assert1(SrcAS == DstAS,
923 "Bitcasts between pointers of different address spaces is not legal."
924 "Use AddrSpaceCast instead.", V);
927 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
928 if (CE->getOpcode() == Instruction::BitCast) {
929 Type *SrcTy = CE->getOperand(0)->getType();
930 Type *DstTy = CE->getType();
931 VerifyBitcastType(CE, DstTy, SrcTy);
935 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
936 if (Attrs.getNumSlots() == 0)
939 unsigned LastSlot = Attrs.getNumSlots() - 1;
940 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
941 if (LastIndex <= Params
942 || (LastIndex == AttributeSet::FunctionIndex
943 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
949 // visitFunction - Verify that a function is ok.
951 void Verifier::visitFunction(const Function &F) {
952 // Check function arguments.
953 FunctionType *FT = F.getFunctionType();
954 unsigned NumArgs = F.arg_size();
956 Assert1(Context == &F.getContext(),
957 "Function context does not match Module context!", &F);
959 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
960 Assert2(FT->getNumParams() == NumArgs,
961 "# formal arguments must match # of arguments for function type!",
963 Assert1(F.getReturnType()->isFirstClassType() ||
964 F.getReturnType()->isVoidTy() ||
965 F.getReturnType()->isStructTy(),
966 "Functions cannot return aggregate values!", &F);
968 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
969 "Invalid struct return type!", &F);
971 AttributeSet Attrs = F.getAttributes();
973 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
974 "Attribute after last parameter!", &F);
976 // Check function attributes.
977 VerifyFunctionAttrs(FT, Attrs, &F);
979 // On function declarations/definitions, we do not support the builtin
980 // attribute. We do not check this in VerifyFunctionAttrs since that is
981 // checking for Attributes that can/can not ever be on functions.
982 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
984 "Attribute 'builtin' can only be applied to a callsite.", &F);
986 // Check that this function meets the restrictions on this calling convention.
987 switch (F.getCallingConv()) {
992 case CallingConv::Fast:
993 case CallingConv::Cold:
994 case CallingConv::X86_FastCall:
995 case CallingConv::X86_ThisCall:
996 case CallingConv::Intel_OCL_BI:
997 case CallingConv::PTX_Kernel:
998 case CallingConv::PTX_Device:
999 Assert1(!F.isVarArg(),
1000 "Varargs functions must have C calling conventions!", &F);
1004 bool isLLVMdotName = F.getName().size() >= 5 &&
1005 F.getName().substr(0, 5) == "llvm.";
1007 // Check that the argument values match the function type for this function...
1009 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1011 Assert2(I->getType() == FT->getParamType(i),
1012 "Argument value does not match function argument type!",
1013 I, FT->getParamType(i));
1014 Assert1(I->getType()->isFirstClassType(),
1015 "Function arguments must have first-class types!", I);
1017 Assert2(!I->getType()->isMetadataTy(),
1018 "Function takes metadata but isn't an intrinsic", I, &F);
1021 if (F.isMaterializable()) {
1022 // Function has a body somewhere we can't see.
1023 } else if (F.isDeclaration()) {
1024 Assert1(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1025 "invalid linkage type for function declaration", &F);
1027 // Verify that this function (which has a body) is not named "llvm.*". It
1028 // is not legal to define intrinsics.
1029 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1031 // Check the entry node
1032 const BasicBlock *Entry = &F.getEntryBlock();
1033 Assert1(pred_begin(Entry) == pred_end(Entry),
1034 "Entry block to function must not have predecessors!", Entry);
1036 // The address of the entry block cannot be taken, unless it is dead.
1037 if (Entry->hasAddressTaken()) {
1038 Assert1(!BlockAddress::lookup(Entry)->isConstantUsed(),
1039 "blockaddress may not be used with the entry block!", Entry);
1043 // If this function is actually an intrinsic, verify that it is only used in
1044 // direct call/invokes, never having its "address taken".
1045 if (F.getIntrinsicID()) {
1047 if (F.hasAddressTaken(&U))
1048 Assert1(0, "Invalid user of intrinsic instruction!", U);
1051 Assert1(!F.hasDLLImportStorageClass() ||
1052 (F.isDeclaration() && F.hasExternalLinkage()) ||
1053 F.hasAvailableExternallyLinkage(),
1054 "Function is marked as dllimport, but not external.", &F);
1057 // verifyBasicBlock - Verify that a basic block is well formed...
1059 void Verifier::visitBasicBlock(BasicBlock &BB) {
1060 InstsInThisBlock.clear();
1062 // Ensure that basic blocks have terminators!
1063 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1065 // Check constraints that this basic block imposes on all of the PHI nodes in
1067 if (isa<PHINode>(BB.front())) {
1068 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1069 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1070 std::sort(Preds.begin(), Preds.end());
1072 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1073 // Ensure that PHI nodes have at least one entry!
1074 Assert1(PN->getNumIncomingValues() != 0,
1075 "PHI nodes must have at least one entry. If the block is dead, "
1076 "the PHI should be removed!", PN);
1077 Assert1(PN->getNumIncomingValues() == Preds.size(),
1078 "PHINode should have one entry for each predecessor of its "
1079 "parent basic block!", PN);
1081 // Get and sort all incoming values in the PHI node...
1083 Values.reserve(PN->getNumIncomingValues());
1084 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1085 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1086 PN->getIncomingValue(i)));
1087 std::sort(Values.begin(), Values.end());
1089 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1090 // Check to make sure that if there is more than one entry for a
1091 // particular basic block in this PHI node, that the incoming values are
1094 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
1095 Values[i].second == Values[i-1].second,
1096 "PHI node has multiple entries for the same basic block with "
1097 "different incoming values!", PN, Values[i].first,
1098 Values[i].second, Values[i-1].second);
1100 // Check to make sure that the predecessors and PHI node entries are
1102 Assert3(Values[i].first == Preds[i],
1103 "PHI node entries do not match predecessors!", PN,
1104 Values[i].first, Preds[i]);
1110 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1111 // Ensure that terminators only exist at the end of the basic block.
1112 Assert1(&I == I.getParent()->getTerminator(),
1113 "Terminator found in the middle of a basic block!", I.getParent());
1114 visitInstruction(I);
1117 void Verifier::visitBranchInst(BranchInst &BI) {
1118 if (BI.isConditional()) {
1119 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
1120 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1122 visitTerminatorInst(BI);
1125 void Verifier::visitReturnInst(ReturnInst &RI) {
1126 Function *F = RI.getParent()->getParent();
1127 unsigned N = RI.getNumOperands();
1128 if (F->getReturnType()->isVoidTy())
1130 "Found return instr that returns non-void in Function of void "
1131 "return type!", &RI, F->getReturnType());
1133 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1134 "Function return type does not match operand "
1135 "type of return inst!", &RI, F->getReturnType());
1137 // Check to make sure that the return value has necessary properties for
1139 visitTerminatorInst(RI);
1142 void Verifier::visitSwitchInst(SwitchInst &SI) {
1143 // Check to make sure that all of the constants in the switch instruction
1144 // have the same type as the switched-on value.
1145 Type *SwitchTy = SI.getCondition()->getType();
1146 SmallPtrSet<ConstantInt*, 32> Constants;
1147 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1148 Assert1(i.getCaseValue()->getType() == SwitchTy,
1149 "Switch constants must all be same type as switch value!", &SI);
1150 Assert2(Constants.insert(i.getCaseValue()),
1151 "Duplicate integer as switch case", &SI, i.getCaseValue());
1154 visitTerminatorInst(SI);
1157 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1158 Assert1(BI.getAddress()->getType()->isPointerTy(),
1159 "Indirectbr operand must have pointer type!", &BI);
1160 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1161 Assert1(BI.getDestination(i)->getType()->isLabelTy(),
1162 "Indirectbr destinations must all have pointer type!", &BI);
1164 visitTerminatorInst(BI);
1167 void Verifier::visitSelectInst(SelectInst &SI) {
1168 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1170 "Invalid operands for select instruction!", &SI);
1172 Assert1(SI.getTrueValue()->getType() == SI.getType(),
1173 "Select values must have same type as select instruction!", &SI);
1174 visitInstruction(SI);
1177 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1178 /// a pass, if any exist, it's an error.
1180 void Verifier::visitUserOp1(Instruction &I) {
1181 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
1184 void Verifier::visitTruncInst(TruncInst &I) {
1185 // Get the source and destination types
1186 Type *SrcTy = I.getOperand(0)->getType();
1187 Type *DestTy = I.getType();
1189 // Get the size of the types in bits, we'll need this later
1190 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1191 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1193 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1194 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1195 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1196 "trunc source and destination must both be a vector or neither", &I);
1197 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
1199 visitInstruction(I);
1202 void Verifier::visitZExtInst(ZExtInst &I) {
1203 // Get the source and destination types
1204 Type *SrcTy = I.getOperand(0)->getType();
1205 Type *DestTy = I.getType();
1207 // Get the size of the types in bits, we'll need this later
1208 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1209 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1210 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1211 "zext source and destination must both be a vector or neither", &I);
1212 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1213 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1215 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
1217 visitInstruction(I);
1220 void Verifier::visitSExtInst(SExtInst &I) {
1221 // Get the source and destination types
1222 Type *SrcTy = I.getOperand(0)->getType();
1223 Type *DestTy = I.getType();
1225 // Get the size of the types in bits, we'll need this later
1226 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1227 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1229 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1230 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1231 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1232 "sext source and destination must both be a vector or neither", &I);
1233 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
1235 visitInstruction(I);
1238 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1239 // Get the source and destination types
1240 Type *SrcTy = I.getOperand(0)->getType();
1241 Type *DestTy = I.getType();
1242 // Get the size of the types in bits, we'll need this later
1243 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1244 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1246 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
1247 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
1248 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1249 "fptrunc source and destination must both be a vector or neither",&I);
1250 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
1252 visitInstruction(I);
1255 void Verifier::visitFPExtInst(FPExtInst &I) {
1256 // Get the source and destination types
1257 Type *SrcTy = I.getOperand(0)->getType();
1258 Type *DestTy = I.getType();
1260 // Get the size of the types in bits, we'll need this later
1261 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1262 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1264 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
1265 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
1266 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1267 "fpext source and destination must both be a vector or neither", &I);
1268 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
1270 visitInstruction(I);
1273 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1274 // Get the source and destination types
1275 Type *SrcTy = I.getOperand(0)->getType();
1276 Type *DestTy = I.getType();
1278 bool SrcVec = SrcTy->isVectorTy();
1279 bool DstVec = DestTy->isVectorTy();
1281 Assert1(SrcVec == DstVec,
1282 "UIToFP source and dest must both be vector or scalar", &I);
1283 Assert1(SrcTy->isIntOrIntVectorTy(),
1284 "UIToFP source must be integer or integer vector", &I);
1285 Assert1(DestTy->isFPOrFPVectorTy(),
1286 "UIToFP result must be FP or FP vector", &I);
1288 if (SrcVec && DstVec)
1289 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1290 cast<VectorType>(DestTy)->getNumElements(),
1291 "UIToFP source and dest vector length mismatch", &I);
1293 visitInstruction(I);
1296 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1297 // Get the source and destination types
1298 Type *SrcTy = I.getOperand(0)->getType();
1299 Type *DestTy = I.getType();
1301 bool SrcVec = SrcTy->isVectorTy();
1302 bool DstVec = DestTy->isVectorTy();
1304 Assert1(SrcVec == DstVec,
1305 "SIToFP source and dest must both be vector or scalar", &I);
1306 Assert1(SrcTy->isIntOrIntVectorTy(),
1307 "SIToFP source must be integer or integer vector", &I);
1308 Assert1(DestTy->isFPOrFPVectorTy(),
1309 "SIToFP result must be FP or FP vector", &I);
1311 if (SrcVec && DstVec)
1312 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1313 cast<VectorType>(DestTy)->getNumElements(),
1314 "SIToFP source and dest vector length mismatch", &I);
1316 visitInstruction(I);
1319 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1320 // Get the source and destination types
1321 Type *SrcTy = I.getOperand(0)->getType();
1322 Type *DestTy = I.getType();
1324 bool SrcVec = SrcTy->isVectorTy();
1325 bool DstVec = DestTy->isVectorTy();
1327 Assert1(SrcVec == DstVec,
1328 "FPToUI source and dest must both be vector or scalar", &I);
1329 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1331 Assert1(DestTy->isIntOrIntVectorTy(),
1332 "FPToUI result must be integer or integer vector", &I);
1334 if (SrcVec && DstVec)
1335 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1336 cast<VectorType>(DestTy)->getNumElements(),
1337 "FPToUI source and dest vector length mismatch", &I);
1339 visitInstruction(I);
1342 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1343 // Get the source and destination types
1344 Type *SrcTy = I.getOperand(0)->getType();
1345 Type *DestTy = I.getType();
1347 bool SrcVec = SrcTy->isVectorTy();
1348 bool DstVec = DestTy->isVectorTy();
1350 Assert1(SrcVec == DstVec,
1351 "FPToSI source and dest must both be vector or scalar", &I);
1352 Assert1(SrcTy->isFPOrFPVectorTy(),
1353 "FPToSI source must be FP or FP vector", &I);
1354 Assert1(DestTy->isIntOrIntVectorTy(),
1355 "FPToSI result must be integer or integer vector", &I);
1357 if (SrcVec && DstVec)
1358 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1359 cast<VectorType>(DestTy)->getNumElements(),
1360 "FPToSI source and dest vector length mismatch", &I);
1362 visitInstruction(I);
1365 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1366 // Get the source and destination types
1367 Type *SrcTy = I.getOperand(0)->getType();
1368 Type *DestTy = I.getType();
1370 Assert1(SrcTy->getScalarType()->isPointerTy(),
1371 "PtrToInt source must be pointer", &I);
1372 Assert1(DestTy->getScalarType()->isIntegerTy(),
1373 "PtrToInt result must be integral", &I);
1374 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1375 "PtrToInt type mismatch", &I);
1377 if (SrcTy->isVectorTy()) {
1378 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1379 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1380 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1381 "PtrToInt Vector width mismatch", &I);
1384 visitInstruction(I);
1387 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1388 // Get the source and destination types
1389 Type *SrcTy = I.getOperand(0)->getType();
1390 Type *DestTy = I.getType();
1392 Assert1(SrcTy->getScalarType()->isIntegerTy(),
1393 "IntToPtr source must be an integral", &I);
1394 Assert1(DestTy->getScalarType()->isPointerTy(),
1395 "IntToPtr result must be a pointer",&I);
1396 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1397 "IntToPtr type mismatch", &I);
1398 if (SrcTy->isVectorTy()) {
1399 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1400 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1401 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1402 "IntToPtr Vector width mismatch", &I);
1404 visitInstruction(I);
1407 void Verifier::visitBitCastInst(BitCastInst &I) {
1408 Type *SrcTy = I.getOperand(0)->getType();
1409 Type *DestTy = I.getType();
1410 VerifyBitcastType(&I, DestTy, SrcTy);
1411 visitInstruction(I);
1414 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
1415 Type *SrcTy = I.getOperand(0)->getType();
1416 Type *DestTy = I.getType();
1418 Assert1(SrcTy->isPtrOrPtrVectorTy(),
1419 "AddrSpaceCast source must be a pointer", &I);
1420 Assert1(DestTy->isPtrOrPtrVectorTy(),
1421 "AddrSpaceCast result must be a pointer", &I);
1422 Assert1(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
1423 "AddrSpaceCast must be between different address spaces", &I);
1424 if (SrcTy->isVectorTy())
1425 Assert1(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
1426 "AddrSpaceCast vector pointer number of elements mismatch", &I);
1427 visitInstruction(I);
1430 /// visitPHINode - Ensure that a PHI node is well formed.
1432 void Verifier::visitPHINode(PHINode &PN) {
1433 // Ensure that the PHI nodes are all grouped together at the top of the block.
1434 // This can be tested by checking whether the instruction before this is
1435 // either nonexistent (because this is begin()) or is a PHI node. If not,
1436 // then there is some other instruction before a PHI.
1437 Assert2(&PN == &PN.getParent()->front() ||
1438 isa<PHINode>(--BasicBlock::iterator(&PN)),
1439 "PHI nodes not grouped at top of basic block!",
1440 &PN, PN.getParent());
1442 // Check that all of the values of the PHI node have the same type as the
1443 // result, and that the incoming blocks are really basic blocks.
1444 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1445 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1446 "PHI node operands are not the same type as the result!", &PN);
1449 // All other PHI node constraints are checked in the visitBasicBlock method.
1451 visitInstruction(PN);
1454 void Verifier::VerifyCallSite(CallSite CS) {
1455 Instruction *I = CS.getInstruction();
1457 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1458 "Called function must be a pointer!", I);
1459 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1461 Assert1(FPTy->getElementType()->isFunctionTy(),
1462 "Called function is not pointer to function type!", I);
1463 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1465 // Verify that the correct number of arguments are being passed
1466 if (FTy->isVarArg())
1467 Assert1(CS.arg_size() >= FTy->getNumParams(),
1468 "Called function requires more parameters than were provided!",I);
1470 Assert1(CS.arg_size() == FTy->getNumParams(),
1471 "Incorrect number of arguments passed to called function!", I);
1473 // Verify that all arguments to the call match the function type.
1474 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1475 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1476 "Call parameter type does not match function signature!",
1477 CS.getArgument(i), FTy->getParamType(i), I);
1479 AttributeSet Attrs = CS.getAttributes();
1481 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1482 "Attribute after last parameter!", I);
1484 // Verify call attributes.
1485 VerifyFunctionAttrs(FTy, Attrs, I);
1487 if (FTy->isVarArg()) {
1488 // FIXME? is 'nest' even legal here?
1489 bool SawNest = false;
1490 bool SawReturned = false;
1492 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1493 if (Attrs.hasAttribute(Idx, Attribute::Nest))
1495 if (Attrs.hasAttribute(Idx, Attribute::Returned))
1499 // Check attributes on the varargs part.
1500 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1501 Type *Ty = CS.getArgument(Idx-1)->getType();
1502 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1504 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1505 Assert1(!SawNest, "More than one parameter has attribute nest!", I);
1509 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1510 Assert1(!SawReturned, "More than one parameter has attribute returned!",
1512 Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1513 "Incompatible argument and return types for 'returned' "
1518 Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1519 "Attribute 'sret' cannot be used for vararg call arguments!", I);
1521 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
1522 Assert1(Idx == CS.arg_size(), "inalloca isn't on the last argument!",
1527 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1528 if (CS.getCalledFunction() == 0 ||
1529 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1530 for (FunctionType::param_iterator PI = FTy->param_begin(),
1531 PE = FTy->param_end(); PI != PE; ++PI)
1532 Assert1(!(*PI)->isMetadataTy(),
1533 "Function has metadata parameter but isn't an intrinsic", I);
1536 visitInstruction(*I);
1539 void Verifier::visitCallInst(CallInst &CI) {
1540 VerifyCallSite(&CI);
1542 if (Function *F = CI.getCalledFunction())
1543 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1544 visitIntrinsicFunctionCall(ID, CI);
1547 void Verifier::visitInvokeInst(InvokeInst &II) {
1548 VerifyCallSite(&II);
1550 // Verify that there is a landingpad instruction as the first non-PHI
1551 // instruction of the 'unwind' destination.
1552 Assert1(II.getUnwindDest()->isLandingPad(),
1553 "The unwind destination does not have a landingpad instruction!",&II);
1555 visitTerminatorInst(II);
1558 /// visitBinaryOperator - Check that both arguments to the binary operator are
1559 /// of the same type!
1561 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1562 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1563 "Both operands to a binary operator are not of the same type!", &B);
1565 switch (B.getOpcode()) {
1566 // Check that integer arithmetic operators are only used with
1567 // integral operands.
1568 case Instruction::Add:
1569 case Instruction::Sub:
1570 case Instruction::Mul:
1571 case Instruction::SDiv:
1572 case Instruction::UDiv:
1573 case Instruction::SRem:
1574 case Instruction::URem:
1575 Assert1(B.getType()->isIntOrIntVectorTy(),
1576 "Integer arithmetic operators only work with integral types!", &B);
1577 Assert1(B.getType() == B.getOperand(0)->getType(),
1578 "Integer arithmetic operators must have same type "
1579 "for operands and result!", &B);
1581 // Check that floating-point arithmetic operators are only used with
1582 // floating-point operands.
1583 case Instruction::FAdd:
1584 case Instruction::FSub:
1585 case Instruction::FMul:
1586 case Instruction::FDiv:
1587 case Instruction::FRem:
1588 Assert1(B.getType()->isFPOrFPVectorTy(),
1589 "Floating-point arithmetic operators only work with "
1590 "floating-point types!", &B);
1591 Assert1(B.getType() == B.getOperand(0)->getType(),
1592 "Floating-point arithmetic operators must have same type "
1593 "for operands and result!", &B);
1595 // Check that logical operators are only used with integral operands.
1596 case Instruction::And:
1597 case Instruction::Or:
1598 case Instruction::Xor:
1599 Assert1(B.getType()->isIntOrIntVectorTy(),
1600 "Logical operators only work with integral types!", &B);
1601 Assert1(B.getType() == B.getOperand(0)->getType(),
1602 "Logical operators must have same type for operands and result!",
1605 case Instruction::Shl:
1606 case Instruction::LShr:
1607 case Instruction::AShr:
1608 Assert1(B.getType()->isIntOrIntVectorTy(),
1609 "Shifts only work with integral types!", &B);
1610 Assert1(B.getType() == B.getOperand(0)->getType(),
1611 "Shift return type must be same as operands!", &B);
1614 llvm_unreachable("Unknown BinaryOperator opcode!");
1617 visitInstruction(B);
1620 void Verifier::visitICmpInst(ICmpInst &IC) {
1621 // Check that the operands are the same type
1622 Type *Op0Ty = IC.getOperand(0)->getType();
1623 Type *Op1Ty = IC.getOperand(1)->getType();
1624 Assert1(Op0Ty == Op1Ty,
1625 "Both operands to ICmp instruction are not of the same type!", &IC);
1626 // Check that the operands are the right type
1627 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1628 "Invalid operand types for ICmp instruction", &IC);
1629 // Check that the predicate is valid.
1630 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1631 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1632 "Invalid predicate in ICmp instruction!", &IC);
1634 visitInstruction(IC);
1637 void Verifier::visitFCmpInst(FCmpInst &FC) {
1638 // Check that the operands are the same type
1639 Type *Op0Ty = FC.getOperand(0)->getType();
1640 Type *Op1Ty = FC.getOperand(1)->getType();
1641 Assert1(Op0Ty == Op1Ty,
1642 "Both operands to FCmp instruction are not of the same type!", &FC);
1643 // Check that the operands are the right type
1644 Assert1(Op0Ty->isFPOrFPVectorTy(),
1645 "Invalid operand types for FCmp instruction", &FC);
1646 // Check that the predicate is valid.
1647 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1648 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1649 "Invalid predicate in FCmp instruction!", &FC);
1651 visitInstruction(FC);
1654 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1655 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1657 "Invalid extractelement operands!", &EI);
1658 visitInstruction(EI);
1661 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1662 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1665 "Invalid insertelement operands!", &IE);
1666 visitInstruction(IE);
1669 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1670 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1672 "Invalid shufflevector operands!", &SV);
1673 visitInstruction(SV);
1676 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1677 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1679 Assert1(isa<PointerType>(TargetTy),
1680 "GEP base pointer is not a vector or a vector of pointers", &GEP);
1681 Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1682 "GEP into unsized type!", &GEP);
1683 Assert1(GEP.getPointerOperandType()->isVectorTy() ==
1684 GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
1687 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1689 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1690 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1692 Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
1693 cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
1694 == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
1696 if (GEP.getPointerOperandType()->isVectorTy()) {
1697 // Additional checks for vector GEPs.
1698 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
1699 Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
1700 "Vector GEP result width doesn't match operand's", &GEP);
1701 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1702 Type *IndexTy = Idxs[i]->getType();
1703 Assert1(IndexTy->isVectorTy(),
1704 "Vector GEP must have vector indices!", &GEP);
1705 unsigned IndexWidth = IndexTy->getVectorNumElements();
1706 Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1709 visitInstruction(GEP);
1712 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1713 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1716 void Verifier::visitLoadInst(LoadInst &LI) {
1717 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1718 Assert1(PTy, "Load operand must be a pointer.", &LI);
1719 Type *ElTy = PTy->getElementType();
1720 Assert2(ElTy == LI.getType(),
1721 "Load result type does not match pointer operand type!", &LI, ElTy);
1722 if (LI.isAtomic()) {
1723 Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1724 "Load cannot have Release ordering", &LI);
1725 Assert1(LI.getAlignment() != 0,
1726 "Atomic load must specify explicit alignment", &LI);
1727 if (!ElTy->isPointerTy()) {
1728 Assert2(ElTy->isIntegerTy(),
1729 "atomic store operand must have integer type!",
1731 unsigned Size = ElTy->getPrimitiveSizeInBits();
1732 Assert2(Size >= 8 && !(Size & (Size - 1)),
1733 "atomic store operand must be power-of-two byte-sized integer",
1737 Assert1(LI.getSynchScope() == CrossThread,
1738 "Non-atomic load cannot have SynchronizationScope specified", &LI);
1741 if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1742 unsigned NumOperands = Range->getNumOperands();
1743 Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1744 unsigned NumRanges = NumOperands / 2;
1745 Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1747 ConstantRange LastRange(1); // Dummy initial value
1748 for (unsigned i = 0; i < NumRanges; ++i) {
1749 ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1750 Assert1(Low, "The lower limit must be an integer!", Low);
1751 ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1752 Assert1(High, "The upper limit must be an integer!", High);
1753 Assert1(High->getType() == Low->getType() &&
1754 High->getType() == ElTy, "Range types must match load type!",
1757 APInt HighV = High->getValue();
1758 APInt LowV = Low->getValue();
1759 ConstantRange CurRange(LowV, HighV);
1760 Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1761 "Range must not be empty!", Range);
1763 Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1764 "Intervals are overlapping", Range);
1765 Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1767 Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1770 LastRange = ConstantRange(LowV, HighV);
1772 if (NumRanges > 2) {
1774 dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1776 dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1777 ConstantRange FirstRange(FirstLow, FirstHigh);
1778 Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1779 "Intervals are overlapping", Range);
1780 Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1787 visitInstruction(LI);
1790 void Verifier::visitStoreInst(StoreInst &SI) {
1791 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1792 Assert1(PTy, "Store operand must be a pointer.", &SI);
1793 Type *ElTy = PTy->getElementType();
1794 Assert2(ElTy == SI.getOperand(0)->getType(),
1795 "Stored value type does not match pointer operand type!",
1797 if (SI.isAtomic()) {
1798 Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1799 "Store cannot have Acquire ordering", &SI);
1800 Assert1(SI.getAlignment() != 0,
1801 "Atomic store must specify explicit alignment", &SI);
1802 if (!ElTy->isPointerTy()) {
1803 Assert2(ElTy->isIntegerTy(),
1804 "atomic store operand must have integer type!",
1806 unsigned Size = ElTy->getPrimitiveSizeInBits();
1807 Assert2(Size >= 8 && !(Size & (Size - 1)),
1808 "atomic store operand must be power-of-two byte-sized integer",
1812 Assert1(SI.getSynchScope() == CrossThread,
1813 "Non-atomic store cannot have SynchronizationScope specified", &SI);
1815 visitInstruction(SI);
1818 void Verifier::visitAllocaInst(AllocaInst &AI) {
1819 SmallPtrSet<const Type*, 4> Visited;
1820 PointerType *PTy = AI.getType();
1821 Assert1(PTy->getAddressSpace() == 0,
1822 "Allocation instruction pointer not in the generic address space!",
1824 Assert1(PTy->getElementType()->isSized(&Visited), "Cannot allocate unsized type",
1826 Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1827 "Alloca array size must have integer type", &AI);
1829 visitInstruction(AI);
1832 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1834 // FIXME: more conditions???
1835 Assert1(CXI.getSuccessOrdering() != NotAtomic,
1836 "cmpxchg instructions must be atomic.", &CXI);
1837 Assert1(CXI.getFailureOrdering() != NotAtomic,
1838 "cmpxchg instructions must be atomic.", &CXI);
1839 Assert1(CXI.getSuccessOrdering() != Unordered,
1840 "cmpxchg instructions cannot be unordered.", &CXI);
1841 Assert1(CXI.getFailureOrdering() != Unordered,
1842 "cmpxchg instructions cannot be unordered.", &CXI);
1843 Assert1(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
1844 "cmpxchg instructions be at least as constrained on success as fail",
1846 Assert1(CXI.getFailureOrdering() != Release &&
1847 CXI.getFailureOrdering() != AcquireRelease,
1848 "cmpxchg failure ordering cannot include release semantics", &CXI);
1850 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1851 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1852 Type *ElTy = PTy->getElementType();
1853 Assert2(ElTy->isIntegerTy(),
1854 "cmpxchg operand must have integer type!",
1856 unsigned Size = ElTy->getPrimitiveSizeInBits();
1857 Assert2(Size >= 8 && !(Size & (Size - 1)),
1858 "cmpxchg operand must be power-of-two byte-sized integer",
1860 Assert2(ElTy == CXI.getOperand(1)->getType(),
1861 "Expected value type does not match pointer operand type!",
1863 Assert2(ElTy == CXI.getOperand(2)->getType(),
1864 "Stored value type does not match pointer operand type!",
1866 visitInstruction(CXI);
1869 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1870 Assert1(RMWI.getOrdering() != NotAtomic,
1871 "atomicrmw instructions must be atomic.", &RMWI);
1872 Assert1(RMWI.getOrdering() != Unordered,
1873 "atomicrmw instructions cannot be unordered.", &RMWI);
1874 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1875 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1876 Type *ElTy = PTy->getElementType();
1877 Assert2(ElTy->isIntegerTy(),
1878 "atomicrmw operand must have integer type!",
1880 unsigned Size = ElTy->getPrimitiveSizeInBits();
1881 Assert2(Size >= 8 && !(Size & (Size - 1)),
1882 "atomicrmw operand must be power-of-two byte-sized integer",
1884 Assert2(ElTy == RMWI.getOperand(1)->getType(),
1885 "Argument value type does not match pointer operand type!",
1887 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1888 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1889 "Invalid binary operation!", &RMWI);
1890 visitInstruction(RMWI);
1893 void Verifier::visitFenceInst(FenceInst &FI) {
1894 const AtomicOrdering Ordering = FI.getOrdering();
1895 Assert1(Ordering == Acquire || Ordering == Release ||
1896 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1897 "fence instructions may only have "
1898 "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1899 visitInstruction(FI);
1902 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1903 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1904 EVI.getIndices()) ==
1906 "Invalid ExtractValueInst operands!", &EVI);
1908 visitInstruction(EVI);
1911 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1912 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1913 IVI.getIndices()) ==
1914 IVI.getOperand(1)->getType(),
1915 "Invalid InsertValueInst operands!", &IVI);
1917 visitInstruction(IVI);
1920 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1921 BasicBlock *BB = LPI.getParent();
1923 // The landingpad instruction is ill-formed if it doesn't have any clauses and
1925 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1926 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1928 // The landingpad instruction defines its parent as a landing pad block. The
1929 // landing pad block may be branched to only by the unwind edge of an invoke.
1930 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1931 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1932 Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
1933 "Block containing LandingPadInst must be jumped to "
1934 "only by the unwind edge of an invoke.", &LPI);
1937 // The landingpad instruction must be the first non-PHI instruction in the
1939 Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1940 "LandingPadInst not the first non-PHI instruction in the block.",
1943 // The personality functions for all landingpad instructions within the same
1944 // function should match.
1946 Assert1(LPI.getPersonalityFn() == PersonalityFn,
1947 "Personality function doesn't match others in function", &LPI);
1948 PersonalityFn = LPI.getPersonalityFn();
1950 // All operands must be constants.
1951 Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1953 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1954 Value *Clause = LPI.getClause(i);
1955 Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1956 if (LPI.isCatch(i)) {
1957 Assert1(isa<PointerType>(Clause->getType()),
1958 "Catch operand does not have pointer type!", &LPI);
1960 Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1961 Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1962 "Filter operand is not an array of constants!", &LPI);
1966 visitInstruction(LPI);
1969 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
1970 Instruction *Op = cast<Instruction>(I.getOperand(i));
1971 // If the we have an invalid invoke, don't try to compute the dominance.
1972 // We already reject it in the invoke specific checks and the dominance
1973 // computation doesn't handle multiple edges.
1974 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1975 if (II->getNormalDest() == II->getUnwindDest())
1979 const Use &U = I.getOperandUse(i);
1980 Assert2(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
1981 "Instruction does not dominate all uses!", Op, &I);
1984 /// verifyInstruction - Verify that an instruction is well formed.
1986 void Verifier::visitInstruction(Instruction &I) {
1987 BasicBlock *BB = I.getParent();
1988 Assert1(BB, "Instruction not embedded in basic block!", &I);
1990 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1991 for (User *U : I.users()) {
1992 Assert1(U != (User*)&I || !DT.isReachableFromEntry(BB),
1993 "Only PHI nodes may reference their own value!", &I);
1997 // Check that void typed values don't have names
1998 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1999 "Instruction has a name, but provides a void value!", &I);
2001 // Check that the return value of the instruction is either void or a legal
2003 Assert1(I.getType()->isVoidTy() ||
2004 I.getType()->isFirstClassType(),
2005 "Instruction returns a non-scalar type!", &I);
2007 // Check that the instruction doesn't produce metadata. Calls are already
2008 // checked against the callee type.
2009 Assert1(!I.getType()->isMetadataTy() ||
2010 isa<CallInst>(I) || isa<InvokeInst>(I),
2011 "Invalid use of metadata!", &I);
2013 // Check that all uses of the instruction, if they are instructions
2014 // themselves, actually have parent basic blocks. If the use is not an
2015 // instruction, it is an error!
2016 for (Use &U : I.uses()) {
2017 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
2018 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
2019 " embedded in a basic block!", &I, Used);
2021 CheckFailed("Use of instruction is not an instruction!", U);
2026 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2027 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
2029 // Check to make sure that only first-class-values are operands to
2031 if (!I.getOperand(i)->getType()->isFirstClassType()) {
2032 Assert1(0, "Instruction operands must be first-class values!", &I);
2035 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2036 // Check to make sure that the "address of" an intrinsic function is never
2038 Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
2039 "Cannot take the address of an intrinsic!", &I);
2040 Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
2041 F->getIntrinsicID() == Intrinsic::donothing,
2042 "Cannot invoke an intrinsinc other than donothing", &I);
2043 Assert1(F->getParent() == M, "Referencing function in another module!",
2045 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2046 Assert1(OpBB->getParent() == BB->getParent(),
2047 "Referring to a basic block in another function!", &I);
2048 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2049 Assert1(OpArg->getParent() == BB->getParent(),
2050 "Referring to an argument in another function!", &I);
2051 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2052 Assert1(GV->getParent() == M, "Referencing global in another module!",
2054 } else if (isa<Instruction>(I.getOperand(i))) {
2055 verifyDominatesUse(I, i);
2056 } else if (isa<InlineAsm>(I.getOperand(i))) {
2057 Assert1((i + 1 == e && isa<CallInst>(I)) ||
2058 (i + 3 == e && isa<InvokeInst>(I)),
2059 "Cannot take the address of an inline asm!", &I);
2060 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2061 if (CE->getType()->isPtrOrPtrVectorTy()) {
2062 // If we have a ConstantExpr pointer, we need to see if it came from an
2063 // illegal bitcast (inttoptr <constant int> )
2064 SmallVector<const ConstantExpr *, 4> Stack;
2065 SmallPtrSet<const ConstantExpr *, 4> Visited;
2066 Stack.push_back(CE);
2068 while (!Stack.empty()) {
2069 const ConstantExpr *V = Stack.pop_back_val();
2070 if (!Visited.insert(V))
2073 VerifyConstantExprBitcastType(V);
2075 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2076 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2077 Stack.push_back(Op);
2084 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2085 Assert1(I.getType()->isFPOrFPVectorTy(),
2086 "fpmath requires a floating point result!", &I);
2087 Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2088 Value *Op0 = MD->getOperand(0);
2089 if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
2090 APFloat Accuracy = CFP0->getValueAPF();
2091 Assert1(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2092 "fpmath accuracy not a positive number!", &I);
2094 Assert1(false, "invalid fpmath accuracy!", &I);
2098 MDNode *MD = I.getMetadata(LLVMContext::MD_range);
2099 Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
2101 if (!DisableDebugInfoVerifier) {
2102 MD = I.getMetadata(LLVMContext::MD_dbg);
2103 Finder.processLocation(*M, DILocation(MD));
2106 InstsInThisBlock.insert(&I);
2109 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2110 /// intrinsic argument or return value) matches the type constraints specified
2111 /// by the .td file (e.g. an "any integer" argument really is an integer).
2113 /// This return true on error but does not print a message.
2114 bool Verifier::VerifyIntrinsicType(Type *Ty,
2115 ArrayRef<Intrinsic::IITDescriptor> &Infos,
2116 SmallVectorImpl<Type*> &ArgTys) {
2117 using namespace Intrinsic;
2119 // If we ran out of descriptors, there are too many arguments.
2120 if (Infos.empty()) return true;
2121 IITDescriptor D = Infos.front();
2122 Infos = Infos.slice(1);
2125 case IITDescriptor::Void: return !Ty->isVoidTy();
2126 case IITDescriptor::VarArg: return true;
2127 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
2128 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2129 case IITDescriptor::Half: return !Ty->isHalfTy();
2130 case IITDescriptor::Float: return !Ty->isFloatTy();
2131 case IITDescriptor::Double: return !Ty->isDoubleTy();
2132 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2133 case IITDescriptor::Vector: {
2134 VectorType *VT = dyn_cast<VectorType>(Ty);
2135 return VT == 0 || VT->getNumElements() != D.Vector_Width ||
2136 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2138 case IITDescriptor::Pointer: {
2139 PointerType *PT = dyn_cast<PointerType>(Ty);
2140 return PT == 0 || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2141 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2144 case IITDescriptor::Struct: {
2145 StructType *ST = dyn_cast<StructType>(Ty);
2146 if (ST == 0 || ST->getNumElements() != D.Struct_NumElements)
2149 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2150 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2155 case IITDescriptor::Argument:
2156 // Two cases here - If this is the second occurrence of an argument, verify
2157 // that the later instance matches the previous instance.
2158 if (D.getArgumentNumber() < ArgTys.size())
2159 return Ty != ArgTys[D.getArgumentNumber()];
2161 // Otherwise, if this is the first instance of an argument, record it and
2162 // verify the "Any" kind.
2163 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2164 ArgTys.push_back(Ty);
2166 switch (D.getArgumentKind()) {
2167 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2168 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
2169 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
2170 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2172 llvm_unreachable("all argument kinds not covered");
2174 case IITDescriptor::ExtendVecArgument:
2175 // This may only be used when referring to a previous vector argument.
2176 return D.getArgumentNumber() >= ArgTys.size() ||
2177 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2178 VectorType::getExtendedElementVectorType(
2179 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2181 case IITDescriptor::TruncVecArgument:
2182 // This may only be used when referring to a previous vector argument.
2183 return D.getArgumentNumber() >= ArgTys.size() ||
2184 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2185 VectorType::getTruncatedElementVectorType(
2186 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2188 llvm_unreachable("unhandled");
2191 /// \brief Verify if the intrinsic has variable arguments.
2192 /// This method is intended to be called after all the fixed arguments have been
2195 /// This method returns true on error and does not print an error message.
2197 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
2198 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
2199 using namespace Intrinsic;
2201 // If there are no descriptors left, then it can't be a vararg.
2203 return isVarArg ? true : false;
2205 // There should be only one descriptor remaining at this point.
2206 if (Infos.size() != 1)
2209 // Check and verify the descriptor.
2210 IITDescriptor D = Infos.front();
2211 Infos = Infos.slice(1);
2212 if (D.Kind == IITDescriptor::VarArg)
2213 return isVarArg ? false : true;
2218 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2220 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2221 Function *IF = CI.getCalledFunction();
2222 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2225 // Verify that the intrinsic prototype lines up with what the .td files
2227 FunctionType *IFTy = IF->getFunctionType();
2228 bool IsVarArg = IFTy->isVarArg();
2230 SmallVector<Intrinsic::IITDescriptor, 8> Table;
2231 getIntrinsicInfoTableEntries(ID, Table);
2232 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2234 SmallVector<Type *, 4> ArgTys;
2235 Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2236 "Intrinsic has incorrect return type!", IF);
2237 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2238 Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2239 "Intrinsic has incorrect argument type!", IF);
2241 // Verify if the intrinsic call matches the vararg property.
2243 Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2244 "Intrinsic was not defined with variable arguments!", IF);
2246 Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2247 "Callsite was not defined with variable arguments!", IF);
2249 // All descriptors should be absorbed by now.
2250 Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2252 // Now that we have the intrinsic ID and the actual argument types (and we
2253 // know they are legal for the intrinsic!) get the intrinsic name through the
2254 // usual means. This allows us to verify the mangling of argument types into
2256 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
2257 Assert1(ExpectedName == IF->getName(),
2258 "Intrinsic name not mangled correctly for type arguments! "
2259 "Should be: " + ExpectedName, IF);
2261 // If the intrinsic takes MDNode arguments, verify that they are either global
2262 // or are local to *this* function.
2263 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2264 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
2265 visitMDNode(*MD, CI.getParent()->getParent());
2270 case Intrinsic::ctlz: // llvm.ctlz
2271 case Intrinsic::cttz: // llvm.cttz
2272 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2273 "is_zero_undef argument of bit counting intrinsics must be a "
2274 "constant int", &CI);
2276 case Intrinsic::dbg_declare: { // llvm.dbg.declare
2277 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2278 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2279 MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
2280 Assert1(MD->getNumOperands() == 1,
2281 "invalid llvm.dbg.declare intrinsic call 2", &CI);
2282 if (!DisableDebugInfoVerifier)
2283 Finder.processDeclare(*M, cast<DbgDeclareInst>(&CI));
2285 case Intrinsic::dbg_value: { //llvm.dbg.value
2286 if (!DisableDebugInfoVerifier) {
2287 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2288 "invalid llvm.dbg.value intrinsic call 1", &CI);
2289 Finder.processValue(*M, cast<DbgValueInst>(&CI));
2293 case Intrinsic::memcpy:
2294 case Intrinsic::memmove:
2295 case Intrinsic::memset:
2296 Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
2297 "alignment argument of memory intrinsics must be a constant int",
2299 Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
2300 "isvolatile argument of memory intrinsics must be a constant int",
2303 case Intrinsic::gcroot:
2304 case Intrinsic::gcwrite:
2305 case Intrinsic::gcread:
2306 if (ID == Intrinsic::gcroot) {
2308 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2309 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2310 Assert1(isa<Constant>(CI.getArgOperand(1)),
2311 "llvm.gcroot parameter #2 must be a constant.", &CI);
2312 if (!AI->getType()->getElementType()->isPointerTy()) {
2313 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2314 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2315 "or argument #2 must be a non-null constant.", &CI);
2319 Assert1(CI.getParent()->getParent()->hasGC(),
2320 "Enclosing function does not use GC.", &CI);
2322 case Intrinsic::init_trampoline:
2323 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2324 "llvm.init_trampoline parameter #2 must resolve to a function.",
2327 case Intrinsic::prefetch:
2328 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
2329 isa<ConstantInt>(CI.getArgOperand(2)) &&
2330 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2331 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2332 "invalid arguments to llvm.prefetch",
2335 case Intrinsic::stackprotector:
2336 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2337 "llvm.stackprotector parameter #2 must resolve to an alloca.",
2340 case Intrinsic::lifetime_start:
2341 case Intrinsic::lifetime_end:
2342 case Intrinsic::invariant_start:
2343 Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
2344 "size argument of memory use markers must be a constant integer",
2347 case Intrinsic::invariant_end:
2348 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2349 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2354 void Verifier::verifyDebugInfo() {
2355 // Verify Debug Info.
2356 if (!DisableDebugInfoVerifier) {
2357 for (DebugInfoFinder::iterator I = Finder.compile_unit_begin(),
2358 E = Finder.compile_unit_end(); I != E; ++I)
2359 Assert1(DICompileUnit(*I).Verify(), "DICompileUnit does not Verify!", *I);
2360 for (DebugInfoFinder::iterator I = Finder.subprogram_begin(),
2361 E = Finder.subprogram_end(); I != E; ++I)
2362 Assert1(DISubprogram(*I).Verify(), "DISubprogram does not Verify!", *I);
2363 for (DebugInfoFinder::iterator I = Finder.global_variable_begin(),
2364 E = Finder.global_variable_end(); I != E; ++I)
2365 Assert1(DIGlobalVariable(*I).Verify(),
2366 "DIGlobalVariable does not Verify!", *I);
2367 for (DebugInfoFinder::iterator I = Finder.type_begin(),
2368 E = Finder.type_end(); I != E; ++I)
2369 Assert1(DIType(*I).Verify(), "DIType does not Verify!", *I);
2370 for (DebugInfoFinder::iterator I = Finder.scope_begin(),
2371 E = Finder.scope_end(); I != E; ++I)
2372 Assert1(DIScope(*I).Verify(), "DIScope does not Verify!", *I);
2376 //===----------------------------------------------------------------------===//
2377 // Implement the public interfaces to this file...
2378 //===----------------------------------------------------------------------===//
2380 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
2381 Function &F = const_cast<Function &>(f);
2382 assert(!F.isDeclaration() && "Cannot verify external functions");
2384 raw_null_ostream NullStr;
2385 Verifier V(OS ? *OS : NullStr);
2387 // Note that this function's return value is inverted from what you would
2388 // expect of a function called "verify".
2389 return !V.verify(F);
2392 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
2393 raw_null_ostream NullStr;
2394 Verifier V(OS ? *OS : NullStr);
2396 bool Broken = false;
2397 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
2398 if (!I->isDeclaration())
2399 Broken |= !V.verify(*I);
2401 // Note that this function's return value is inverted from what you would
2402 // expect of a function called "verify".
2403 return !V.verify(M) || Broken;
2407 struct VerifierLegacyPass : public FunctionPass {
2413 VerifierLegacyPass() : FunctionPass(ID), FatalErrors(true) {
2414 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
2416 explicit VerifierLegacyPass(bool FatalErrors)
2417 : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
2418 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
2421 bool runOnFunction(Function &F) override {
2422 if (!V.verify(F) && FatalErrors)
2423 report_fatal_error("Broken function found, compilation aborted!");
2428 bool doFinalization(Module &M) override {
2429 if (!V.verify(M) && FatalErrors)
2430 report_fatal_error("Broken module found, compilation aborted!");
2435 void getAnalysisUsage(AnalysisUsage &AU) const override {
2436 AU.setPreservesAll();
2441 char VerifierLegacyPass::ID = 0;
2442 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
2444 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
2445 return new VerifierLegacyPass(FatalErrors);
2448 PreservedAnalyses VerifierPass::run(Module *M) {
2449 if (verifyModule(*M, &dbgs()) && FatalErrors)
2450 report_fatal_error("Broken module found, compilation aborted!");
2452 return PreservedAnalyses::all();
2455 PreservedAnalyses VerifierPass::run(Function *F) {
2456 if (verifyFunction(*F, &dbgs()) && FatalErrors)
2457 report_fatal_error("Broken function found, compilation aborted!");
2459 return PreservedAnalyses::all();