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> VerifyDebugInfo("verify-debug-info", cl::init(false));
82 struct VerifierSupport {
86 /// \brief Track the brokenness of the module while recursively visiting.
89 explicit VerifierSupport(raw_ostream &OS)
90 : OS(OS), M(nullptr), Broken(false) {}
92 void WriteValue(const Value *V) {
95 if (isa<Instruction>(V)) {
98 V->printAsOperand(OS, true, M);
103 void WriteType(Type *T) {
109 // CheckFailed - A check failed, so print out the condition and the message
110 // that failed. This provides a nice place to put a breakpoint if you want
111 // to see why something is not correct.
112 void CheckFailed(const Twine &Message, const Value *V1 = nullptr,
113 const Value *V2 = nullptr, const Value *V3 = nullptr,
114 const Value *V4 = nullptr) {
115 OS << Message.str() << "\n";
123 void CheckFailed(const Twine &Message, const Value *V1, Type *T2,
124 const Value *V3 = nullptr) {
125 OS << Message.str() << "\n";
132 void CheckFailed(const Twine &Message, Type *T1, Type *T2 = nullptr,
133 Type *T3 = nullptr) {
134 OS << Message.str() << "\n";
141 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
142 friend class InstVisitor<Verifier>;
144 LLVMContext *Context;
145 const DataLayout *DL;
148 /// \brief When verifying a basic block, keep track of all of the
149 /// instructions we have seen so far.
151 /// This allows us to do efficient dominance checks for the case when an
152 /// instruction has an operand that is an instruction in the same block.
153 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
155 /// \brief Keep track of the metadata nodes that have been checked already.
156 SmallPtrSet<MDNode *, 32> MDNodes;
158 /// \brief The personality function referenced by the LandingPadInsts.
159 /// All LandingPadInsts within the same function must use the same
160 /// personality function.
161 const Value *PersonalityFn;
163 /// \brief Finder keeps track of all debug info MDNodes in a Module.
164 DebugInfoFinder Finder;
167 explicit Verifier(raw_ostream &OS = dbgs())
168 : VerifierSupport(OS), Context(nullptr), DL(nullptr),
169 PersonalityFn(nullptr) {}
171 bool verify(const Function &F) {
173 Context = &M->getContext();
175 // First ensure the function is well-enough formed to compute dominance
178 OS << "Function '" << F.getName()
179 << "' does not contain an entry block!\n";
182 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
183 if (I->empty() || !I->back().isTerminator()) {
184 OS << "Basic Block in function '" << F.getName()
185 << "' does not have terminator!\n";
186 I->printAsOperand(OS, true);
192 // Now directly compute a dominance tree. We don't rely on the pass
193 // manager to provide this as it isolates us from a potentially
194 // out-of-date dominator tree and makes it significantly more complex to
195 // run this code outside of a pass manager.
196 // FIXME: It's really gross that we have to cast away constness here.
197 DT.recalculate(const_cast<Function &>(F));
201 // FIXME: We strip const here because the inst visitor strips const.
202 visit(const_cast<Function &>(F));
203 InstsInThisBlock.clear();
204 PersonalityFn = nullptr;
207 // Verify Debug Info.
213 bool verify(const Module &M) {
215 Context = &M.getContext();
219 // Scan through, checking all of the external function's linkage now...
220 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
221 visitGlobalValue(*I);
223 // Check to make sure function prototypes are okay.
224 if (I->isDeclaration())
228 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
230 visitGlobalVariable(*I);
232 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
234 visitGlobalAlias(*I);
236 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
237 E = M.named_metadata_end();
239 visitNamedMDNode(*I);
242 visitModuleIdents(M);
244 if (VerifyDebugInfo) {
246 Finder.processModule(M);
247 // Verify Debug Info.
255 // Verification methods...
256 void visitGlobalValue(const GlobalValue &GV);
257 void visitGlobalVariable(const GlobalVariable &GV);
258 void visitGlobalAlias(const GlobalAlias &GA);
259 void visitNamedMDNode(const NamedMDNode &NMD);
260 void visitMDNode(MDNode &MD, Function *F);
261 void visitModuleIdents(const Module &M);
262 void visitModuleFlags(const Module &M);
263 void visitModuleFlag(const MDNode *Op,
264 DenseMap<const MDString *, const MDNode *> &SeenIDs,
265 SmallVectorImpl<const MDNode *> &Requirements);
266 void visitFunction(const Function &F);
267 void visitBasicBlock(BasicBlock &BB);
269 // InstVisitor overrides...
270 using InstVisitor<Verifier>::visit;
271 void visit(Instruction &I);
273 void visitTruncInst(TruncInst &I);
274 void visitZExtInst(ZExtInst &I);
275 void visitSExtInst(SExtInst &I);
276 void visitFPTruncInst(FPTruncInst &I);
277 void visitFPExtInst(FPExtInst &I);
278 void visitFPToUIInst(FPToUIInst &I);
279 void visitFPToSIInst(FPToSIInst &I);
280 void visitUIToFPInst(UIToFPInst &I);
281 void visitSIToFPInst(SIToFPInst &I);
282 void visitIntToPtrInst(IntToPtrInst &I);
283 void visitPtrToIntInst(PtrToIntInst &I);
284 void visitBitCastInst(BitCastInst &I);
285 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
286 void visitPHINode(PHINode &PN);
287 void visitBinaryOperator(BinaryOperator &B);
288 void visitICmpInst(ICmpInst &IC);
289 void visitFCmpInst(FCmpInst &FC);
290 void visitExtractElementInst(ExtractElementInst &EI);
291 void visitInsertElementInst(InsertElementInst &EI);
292 void visitShuffleVectorInst(ShuffleVectorInst &EI);
293 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
294 void visitCallInst(CallInst &CI);
295 void visitInvokeInst(InvokeInst &II);
296 void visitGetElementPtrInst(GetElementPtrInst &GEP);
297 void visitLoadInst(LoadInst &LI);
298 void visitStoreInst(StoreInst &SI);
299 void verifyDominatesUse(Instruction &I, unsigned i);
300 void visitInstruction(Instruction &I);
301 void visitTerminatorInst(TerminatorInst &I);
302 void visitBranchInst(BranchInst &BI);
303 void visitReturnInst(ReturnInst &RI);
304 void visitSwitchInst(SwitchInst &SI);
305 void visitIndirectBrInst(IndirectBrInst &BI);
306 void visitSelectInst(SelectInst &SI);
307 void visitUserOp1(Instruction &I);
308 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
309 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
310 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
311 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
312 void visitFenceInst(FenceInst &FI);
313 void visitAllocaInst(AllocaInst &AI);
314 void visitExtractValueInst(ExtractValueInst &EVI);
315 void visitInsertValueInst(InsertValueInst &IVI);
316 void visitLandingPadInst(LandingPadInst &LPI);
318 void VerifyCallSite(CallSite CS);
319 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
320 unsigned ArgNo, std::string &Suffix);
321 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
322 SmallVectorImpl<Type *> &ArgTys);
323 bool VerifyIntrinsicIsVarArg(bool isVarArg,
324 ArrayRef<Intrinsic::IITDescriptor> &Infos);
325 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
326 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
328 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
329 bool isReturnValue, const Value *V);
330 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
333 void VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy);
334 void VerifyConstantExprBitcastType(const ConstantExpr *CE);
336 void verifyDebugInfo();
338 } // End anonymous namespace
340 // Assert - We know that cond should be true, if not print an error message.
341 #define Assert(C, M) \
342 do { if (!(C)) { CheckFailed(M); return; } } while (0)
343 #define Assert1(C, M, V1) \
344 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
345 #define Assert2(C, M, V1, V2) \
346 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
347 #define Assert3(C, M, V1, V2, V3) \
348 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
349 #define Assert4(C, M, V1, V2, V3, V4) \
350 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
352 void Verifier::visit(Instruction &I) {
353 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
354 Assert1(I.getOperand(i) != nullptr, "Operand is null", &I);
355 InstVisitor<Verifier>::visit(I);
359 void Verifier::visitGlobalValue(const GlobalValue &GV) {
360 Assert1(!GV.isDeclaration() ||
361 GV.isMaterializable() ||
362 GV.hasExternalLinkage() ||
363 GV.hasExternalWeakLinkage() ||
364 (isa<GlobalAlias>(GV) &&
365 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
366 "Global is external, but doesn't have external or weak linkage!",
369 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
370 "Only global variables can have appending linkage!", &GV);
372 if (GV.hasAppendingLinkage()) {
373 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
374 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
375 "Only global arrays can have appending linkage!", GVar);
379 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
380 if (GV.hasInitializer()) {
381 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
382 "Global variable initializer type does not match global "
383 "variable type!", &GV);
385 // If the global has common linkage, it must have a zero initializer and
386 // cannot be constant.
387 if (GV.hasCommonLinkage()) {
388 Assert1(GV.getInitializer()->isNullValue(),
389 "'common' global must have a zero initializer!", &GV);
390 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
394 Assert1(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
395 "invalid linkage type for global declaration", &GV);
398 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
399 GV.getName() == "llvm.global_dtors")) {
400 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
401 "invalid linkage for intrinsic global variable", &GV);
402 // Don't worry about emitting an error for it not being an array,
403 // visitGlobalValue will complain on appending non-array.
404 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
405 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
406 PointerType *FuncPtrTy =
407 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
408 Assert1(STy && STy->getNumElements() == 2 &&
409 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
410 STy->getTypeAtIndex(1) == FuncPtrTy,
411 "wrong type for intrinsic global variable", &GV);
415 if (GV.hasName() && (GV.getName() == "llvm.used" ||
416 GV.getName() == "llvm.compiler.used")) {
417 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
418 "invalid linkage for intrinsic global variable", &GV);
419 Type *GVType = GV.getType()->getElementType();
420 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
421 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
422 Assert1(PTy, "wrong type for intrinsic global variable", &GV);
423 if (GV.hasInitializer()) {
424 const Constant *Init = GV.getInitializer();
425 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
426 Assert1(InitArray, "wrong initalizer for intrinsic global variable",
428 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
429 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
431 isa<GlobalVariable>(V) || isa<Function>(V) || isa<GlobalAlias>(V),
432 "invalid llvm.used member", V);
433 Assert1(V->hasName(), "members of llvm.used must be named", V);
439 Assert1(!GV.hasDLLImportStorageClass() ||
440 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
441 GV.hasAvailableExternallyLinkage(),
442 "Global is marked as dllimport, but not external", &GV);
444 if (!GV.hasInitializer()) {
445 visitGlobalValue(GV);
449 // Walk any aggregate initializers looking for bitcasts between address spaces
450 SmallPtrSet<const Value *, 4> Visited;
451 SmallVector<const Value *, 4> WorkStack;
452 WorkStack.push_back(cast<Value>(GV.getInitializer()));
454 while (!WorkStack.empty()) {
455 const Value *V = WorkStack.pop_back_val();
456 if (!Visited.insert(V))
459 if (const User *U = dyn_cast<User>(V)) {
460 for (unsigned I = 0, N = U->getNumOperands(); I != N; ++I)
461 WorkStack.push_back(U->getOperand(I));
464 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
465 VerifyConstantExprBitcastType(CE);
471 visitGlobalValue(GV);
474 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
475 Assert1(!GA.getName().empty(),
476 "Alias name cannot be empty!", &GA);
477 Assert1(GlobalAlias::isValidLinkage(GA.getLinkage()),
478 "Alias should have external or external weak linkage!", &GA);
479 Assert1(GA.getAliasee(),
480 "Aliasee cannot be NULL!", &GA);
481 Assert1(GA.getType() == GA.getAliasee()->getType(),
482 "Alias and aliasee types should match!", &GA);
483 Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
484 Assert1(!GA.hasSection(), "Alias cannot have a section!", &GA);
485 Assert1(!GA.getAlignment(), "Alias connot have an alignment", &GA);
487 const Constant *Aliasee = GA.getAliasee();
488 const GlobalValue *GV = dyn_cast<GlobalValue>(Aliasee);
491 const ConstantExpr *CE = dyn_cast<ConstantExpr>(Aliasee);
492 if (CE && (CE->getOpcode() == Instruction::BitCast ||
493 CE->getOpcode() == Instruction::AddrSpaceCast ||
494 CE->getOpcode() == Instruction::GetElementPtr))
495 GV = dyn_cast<GlobalValue>(CE->getOperand(0));
497 Assert1(GV, "Aliasee should be either GlobalValue, bitcast or "
498 "addrspacecast of GlobalValue",
501 if (CE->getOpcode() == Instruction::BitCast) {
502 unsigned SrcAS = GV->getType()->getPointerAddressSpace();
503 unsigned DstAS = CE->getType()->getPointerAddressSpace();
505 Assert1(SrcAS == DstAS,
506 "Alias bitcasts cannot be between different address spaces",
510 Assert1(!GV->isDeclaration(), "Alias must point to a definition", &GA);
511 if (const GlobalAlias *GAAliasee = dyn_cast<GlobalAlias>(GV)) {
512 Assert1(!GAAliasee->mayBeOverridden(), "Alias cannot point to a weak alias",
516 const GlobalValue *AG = GA.getAliasedGlobal();
517 Assert1(AG, "Aliasing chain should end with function or global variable",
520 visitGlobalValue(GA);
523 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
524 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
525 MDNode *MD = NMD.getOperand(i);
529 Assert1(!MD->isFunctionLocal(),
530 "Named metadata operand cannot be function local!", MD);
531 visitMDNode(*MD, nullptr);
535 void Verifier::visitMDNode(MDNode &MD, Function *F) {
536 // Only visit each node once. Metadata can be mutually recursive, so this
537 // avoids infinite recursion here, as well as being an optimization.
538 if (!MDNodes.insert(&MD))
541 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
542 Value *Op = MD.getOperand(i);
545 if (isa<Constant>(Op) || isa<MDString>(Op))
547 if (MDNode *N = dyn_cast<MDNode>(Op)) {
548 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
549 "Global metadata operand cannot be function local!", &MD, N);
553 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
555 // If this was an instruction, bb, or argument, verify that it is in the
556 // function that we expect.
557 Function *ActualF = nullptr;
558 if (Instruction *I = dyn_cast<Instruction>(Op))
559 ActualF = I->getParent()->getParent();
560 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
561 ActualF = BB->getParent();
562 else if (Argument *A = dyn_cast<Argument>(Op))
563 ActualF = A->getParent();
564 assert(ActualF && "Unimplemented function local metadata case!");
566 Assert2(ActualF == F, "function-local metadata used in wrong function",
571 void Verifier::visitModuleIdents(const Module &M) {
572 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
576 // llvm.ident takes a list of metadata entry. Each entry has only one string.
577 // Scan each llvm.ident entry and make sure that this requirement is met.
578 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
579 const MDNode *N = Idents->getOperand(i);
580 Assert1(N->getNumOperands() == 1,
581 "incorrect number of operands in llvm.ident metadata", N);
582 Assert1(isa<MDString>(N->getOperand(0)),
583 ("invalid value for llvm.ident metadata entry operand"
584 "(the operand should be a string)"),
589 void Verifier::visitModuleFlags(const Module &M) {
590 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
593 // Scan each flag, and track the flags and requirements.
594 DenseMap<const MDString*, const MDNode*> SeenIDs;
595 SmallVector<const MDNode*, 16> Requirements;
596 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
597 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
600 // Validate that the requirements in the module are valid.
601 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
602 const MDNode *Requirement = Requirements[I];
603 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
604 const Value *ReqValue = Requirement->getOperand(1);
606 const MDNode *Op = SeenIDs.lookup(Flag);
608 CheckFailed("invalid requirement on flag, flag is not present in module",
613 if (Op->getOperand(2) != ReqValue) {
614 CheckFailed(("invalid requirement on flag, "
615 "flag does not have the required value"),
623 Verifier::visitModuleFlag(const MDNode *Op,
624 DenseMap<const MDString *, const MDNode *> &SeenIDs,
625 SmallVectorImpl<const MDNode *> &Requirements) {
626 // Each module flag should have three arguments, the merge behavior (a
627 // constant int), the flag ID (an MDString), and the value.
628 Assert1(Op->getNumOperands() == 3,
629 "incorrect number of operands in module flag", Op);
630 ConstantInt *Behavior = dyn_cast<ConstantInt>(Op->getOperand(0));
631 MDString *ID = dyn_cast<MDString>(Op->getOperand(1));
633 "invalid behavior operand in module flag (expected constant integer)",
635 unsigned BehaviorValue = Behavior->getZExtValue();
637 "invalid ID operand in module flag (expected metadata string)",
640 // Sanity check the values for behaviors with additional requirements.
641 switch (BehaviorValue) {
644 "invalid behavior operand in module flag (unexpected constant)",
649 case Module::Warning:
650 case Module::Override:
651 // These behavior types accept any value.
654 case Module::Require: {
655 // The value should itself be an MDNode with two operands, a flag ID (an
656 // MDString), and a value.
657 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
658 Assert1(Value && Value->getNumOperands() == 2,
659 "invalid value for 'require' module flag (expected metadata pair)",
661 Assert1(isa<MDString>(Value->getOperand(0)),
662 ("invalid value for 'require' module flag "
663 "(first value operand should be a string)"),
664 Value->getOperand(0));
666 // Append it to the list of requirements, to check once all module flags are
668 Requirements.push_back(Value);
673 case Module::AppendUnique: {
674 // These behavior types require the operand be an MDNode.
675 Assert1(isa<MDNode>(Op->getOperand(2)),
676 "invalid value for 'append'-type module flag "
677 "(expected a metadata node)", Op->getOperand(2));
682 // Unless this is a "requires" flag, check the ID is unique.
683 if (BehaviorValue != Module::Require) {
684 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
686 "module flag identifiers must be unique (or of 'require' type)",
691 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
692 bool isFunction, const Value *V) {
694 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
695 if (Attrs.getSlotIndex(I) == Idx) {
700 assert(Slot != ~0U && "Attribute set inconsistency!");
702 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
704 if (I->isStringAttribute())
707 if (I->getKindAsEnum() == Attribute::NoReturn ||
708 I->getKindAsEnum() == Attribute::NoUnwind ||
709 I->getKindAsEnum() == Attribute::NoInline ||
710 I->getKindAsEnum() == Attribute::AlwaysInline ||
711 I->getKindAsEnum() == Attribute::OptimizeForSize ||
712 I->getKindAsEnum() == Attribute::StackProtect ||
713 I->getKindAsEnum() == Attribute::StackProtectReq ||
714 I->getKindAsEnum() == Attribute::StackProtectStrong ||
715 I->getKindAsEnum() == Attribute::NoRedZone ||
716 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
717 I->getKindAsEnum() == Attribute::Naked ||
718 I->getKindAsEnum() == Attribute::InlineHint ||
719 I->getKindAsEnum() == Attribute::StackAlignment ||
720 I->getKindAsEnum() == Attribute::UWTable ||
721 I->getKindAsEnum() == Attribute::NonLazyBind ||
722 I->getKindAsEnum() == Attribute::ReturnsTwice ||
723 I->getKindAsEnum() == Attribute::SanitizeAddress ||
724 I->getKindAsEnum() == Attribute::SanitizeThread ||
725 I->getKindAsEnum() == Attribute::SanitizeMemory ||
726 I->getKindAsEnum() == Attribute::MinSize ||
727 I->getKindAsEnum() == Attribute::NoDuplicate ||
728 I->getKindAsEnum() == Attribute::Builtin ||
729 I->getKindAsEnum() == Attribute::NoBuiltin ||
730 I->getKindAsEnum() == Attribute::Cold ||
731 I->getKindAsEnum() == Attribute::OptimizeNone) {
733 CheckFailed("Attribute '" + I->getAsString() +
734 "' only applies to functions!", V);
737 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
738 I->getKindAsEnum() == Attribute::ReadNone) {
740 CheckFailed("Attribute '" + I->getAsString() +
741 "' does not apply to function returns");
744 } else if (isFunction) {
745 CheckFailed("Attribute '" + I->getAsString() +
746 "' does not apply to functions!", V);
752 // VerifyParameterAttrs - Check the given attributes for an argument or return
753 // value of the specified type. The value V is printed in error messages.
754 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
755 bool isReturnValue, const Value *V) {
756 if (!Attrs.hasAttributes(Idx))
759 VerifyAttributeTypes(Attrs, Idx, false, V);
762 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
763 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
764 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
765 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
766 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
767 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
768 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
769 "'returned' do not apply to return values!", V);
771 // Check for mutually incompatible attributes. Only inreg is compatible with
773 unsigned AttrCount = 0;
774 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
775 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
776 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
777 Attrs.hasAttribute(Idx, Attribute::InReg);
778 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
779 Assert1(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
780 "and 'sret' are incompatible!", V);
782 Assert1(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
783 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
784 "'inalloca and readonly' are incompatible!", V);
786 Assert1(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
787 Attrs.hasAttribute(Idx, Attribute::Returned)), "Attributes "
788 "'sret and returned' are incompatible!", V);
790 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
791 Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes "
792 "'zeroext and signext' are incompatible!", V);
794 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
795 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
796 "'readnone and readonly' are incompatible!", V);
798 Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
799 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes "
800 "'noinline and alwaysinline' are incompatible!", V);
802 Assert1(!AttrBuilder(Attrs, Idx).
803 hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
804 "Wrong types for attribute: " +
805 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V);
807 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
808 if (!PTy->getElementType()->isSized()) {
809 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
810 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
811 "Attributes 'byval' and 'inalloca' do not support unsized types!",
815 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
816 "Attribute 'byval' only applies to parameters with pointer type!",
821 // VerifyFunctionAttrs - Check parameter attributes against a function type.
822 // The value V is printed in error messages.
823 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
828 bool SawNest = false;
829 bool SawReturned = false;
831 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
832 unsigned Idx = Attrs.getSlotIndex(i);
836 Ty = FT->getReturnType();
837 else if (Idx-1 < FT->getNumParams())
838 Ty = FT->getParamType(Idx-1);
840 break; // VarArgs attributes, verified elsewhere.
842 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
847 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
848 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
852 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
853 Assert1(!SawReturned, "More than one parameter has attribute returned!",
855 Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible "
856 "argument and return types for 'returned' attribute", V);
860 if (Attrs.hasAttribute(Idx, Attribute::StructRet))
861 Assert1(Idx == 1, "Attribute sret is not on first parameter!", V);
863 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
864 Assert1(Idx == FT->getNumParams(),
865 "inalloca isn't on the last parameter!", V);
869 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
872 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
874 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
875 Attribute::ReadNone) &&
876 Attrs.hasAttribute(AttributeSet::FunctionIndex,
877 Attribute::ReadOnly)),
878 "Attributes 'readnone and readonly' are incompatible!", V);
880 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
881 Attribute::NoInline) &&
882 Attrs.hasAttribute(AttributeSet::FunctionIndex,
883 Attribute::AlwaysInline)),
884 "Attributes 'noinline and alwaysinline' are incompatible!", V);
886 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
887 Attribute::OptimizeNone)) {
888 Assert1(Attrs.hasAttribute(AttributeSet::FunctionIndex,
889 Attribute::NoInline),
890 "Attribute 'optnone' requires 'noinline'!", V);
892 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
893 Attribute::OptimizeForSize),
894 "Attributes 'optsize and optnone' are incompatible!", V);
896 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
898 "Attributes 'minsize and optnone' are incompatible!", V);
902 void Verifier::VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy) {
903 // Get the size of the types in bits, we'll need this later
904 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
905 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
907 // BitCast implies a no-op cast of type only. No bits change.
908 // However, you can't cast pointers to anything but pointers.
909 Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
910 "Bitcast requires both operands to be pointer or neither", V);
911 Assert1(SrcBitSize == DestBitSize,
912 "Bitcast requires types of same width", V);
914 // Disallow aggregates.
915 Assert1(!SrcTy->isAggregateType(),
916 "Bitcast operand must not be aggregate", V);
917 Assert1(!DestTy->isAggregateType(),
918 "Bitcast type must not be aggregate", V);
920 // Without datalayout, assume all address spaces are the same size.
921 // Don't check if both types are not pointers.
922 // Skip casts between scalars and vectors.
924 !SrcTy->isPtrOrPtrVectorTy() ||
925 !DestTy->isPtrOrPtrVectorTy() ||
926 SrcTy->isVectorTy() != DestTy->isVectorTy()) {
930 unsigned SrcAS = SrcTy->getPointerAddressSpace();
931 unsigned DstAS = DestTy->getPointerAddressSpace();
933 Assert1(SrcAS == DstAS,
934 "Bitcasts between pointers of different address spaces is not legal."
935 "Use AddrSpaceCast instead.", V);
938 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
939 if (CE->getOpcode() == Instruction::BitCast) {
940 Type *SrcTy = CE->getOperand(0)->getType();
941 Type *DstTy = CE->getType();
942 VerifyBitcastType(CE, DstTy, SrcTy);
946 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
947 if (Attrs.getNumSlots() == 0)
950 unsigned LastSlot = Attrs.getNumSlots() - 1;
951 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
952 if (LastIndex <= Params
953 || (LastIndex == AttributeSet::FunctionIndex
954 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
960 // visitFunction - Verify that a function is ok.
962 void Verifier::visitFunction(const Function &F) {
963 // Check function arguments.
964 FunctionType *FT = F.getFunctionType();
965 unsigned NumArgs = F.arg_size();
967 Assert1(Context == &F.getContext(),
968 "Function context does not match Module context!", &F);
970 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
971 Assert2(FT->getNumParams() == NumArgs,
972 "# formal arguments must match # of arguments for function type!",
974 Assert1(F.getReturnType()->isFirstClassType() ||
975 F.getReturnType()->isVoidTy() ||
976 F.getReturnType()->isStructTy(),
977 "Functions cannot return aggregate values!", &F);
979 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
980 "Invalid struct return type!", &F);
982 AttributeSet Attrs = F.getAttributes();
984 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
985 "Attribute after last parameter!", &F);
987 // Check function attributes.
988 VerifyFunctionAttrs(FT, Attrs, &F);
990 // On function declarations/definitions, we do not support the builtin
991 // attribute. We do not check this in VerifyFunctionAttrs since that is
992 // checking for Attributes that can/can not ever be on functions.
993 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
995 "Attribute 'builtin' can only be applied to a callsite.", &F);
997 // Check that this function meets the restrictions on this calling convention.
998 switch (F.getCallingConv()) {
1001 case CallingConv::C:
1003 case CallingConv::Fast:
1004 case CallingConv::Cold:
1005 case CallingConv::X86_FastCall:
1006 case CallingConv::X86_ThisCall:
1007 case CallingConv::Intel_OCL_BI:
1008 case CallingConv::PTX_Kernel:
1009 case CallingConv::PTX_Device:
1010 Assert1(!F.isVarArg(),
1011 "Varargs functions must have C calling conventions!", &F);
1015 bool isLLVMdotName = F.getName().size() >= 5 &&
1016 F.getName().substr(0, 5) == "llvm.";
1018 // Check that the argument values match the function type for this function...
1020 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1022 Assert2(I->getType() == FT->getParamType(i),
1023 "Argument value does not match function argument type!",
1024 I, FT->getParamType(i));
1025 Assert1(I->getType()->isFirstClassType(),
1026 "Function arguments must have first-class types!", I);
1028 Assert2(!I->getType()->isMetadataTy(),
1029 "Function takes metadata but isn't an intrinsic", I, &F);
1032 if (F.isMaterializable()) {
1033 // Function has a body somewhere we can't see.
1034 } else if (F.isDeclaration()) {
1035 Assert1(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1036 "invalid linkage type for function declaration", &F);
1038 // Verify that this function (which has a body) is not named "llvm.*". It
1039 // is not legal to define intrinsics.
1040 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1042 // Check the entry node
1043 const BasicBlock *Entry = &F.getEntryBlock();
1044 Assert1(pred_begin(Entry) == pred_end(Entry),
1045 "Entry block to function must not have predecessors!", Entry);
1047 // The address of the entry block cannot be taken, unless it is dead.
1048 if (Entry->hasAddressTaken()) {
1049 Assert1(!BlockAddress::lookup(Entry)->isConstantUsed(),
1050 "blockaddress may not be used with the entry block!", Entry);
1054 // If this function is actually an intrinsic, verify that it is only used in
1055 // direct call/invokes, never having its "address taken".
1056 if (F.getIntrinsicID()) {
1058 if (F.hasAddressTaken(&U))
1059 Assert1(0, "Invalid user of intrinsic instruction!", U);
1062 Assert1(!F.hasDLLImportStorageClass() ||
1063 (F.isDeclaration() && F.hasExternalLinkage()) ||
1064 F.hasAvailableExternallyLinkage(),
1065 "Function is marked as dllimport, but not external.", &F);
1068 // verifyBasicBlock - Verify that a basic block is well formed...
1070 void Verifier::visitBasicBlock(BasicBlock &BB) {
1071 InstsInThisBlock.clear();
1073 // Ensure that basic blocks have terminators!
1074 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1076 // Check constraints that this basic block imposes on all of the PHI nodes in
1078 if (isa<PHINode>(BB.front())) {
1079 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1080 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1081 std::sort(Preds.begin(), Preds.end());
1083 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1084 // Ensure that PHI nodes have at least one entry!
1085 Assert1(PN->getNumIncomingValues() != 0,
1086 "PHI nodes must have at least one entry. If the block is dead, "
1087 "the PHI should be removed!", PN);
1088 Assert1(PN->getNumIncomingValues() == Preds.size(),
1089 "PHINode should have one entry for each predecessor of its "
1090 "parent basic block!", PN);
1092 // Get and sort all incoming values in the PHI node...
1094 Values.reserve(PN->getNumIncomingValues());
1095 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1096 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1097 PN->getIncomingValue(i)));
1098 std::sort(Values.begin(), Values.end());
1100 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1101 // Check to make sure that if there is more than one entry for a
1102 // particular basic block in this PHI node, that the incoming values are
1105 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
1106 Values[i].second == Values[i-1].second,
1107 "PHI node has multiple entries for the same basic block with "
1108 "different incoming values!", PN, Values[i].first,
1109 Values[i].second, Values[i-1].second);
1111 // Check to make sure that the predecessors and PHI node entries are
1113 Assert3(Values[i].first == Preds[i],
1114 "PHI node entries do not match predecessors!", PN,
1115 Values[i].first, Preds[i]);
1121 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1122 // Ensure that terminators only exist at the end of the basic block.
1123 Assert1(&I == I.getParent()->getTerminator(),
1124 "Terminator found in the middle of a basic block!", I.getParent());
1125 visitInstruction(I);
1128 void Verifier::visitBranchInst(BranchInst &BI) {
1129 if (BI.isConditional()) {
1130 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
1131 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1133 visitTerminatorInst(BI);
1136 void Verifier::visitReturnInst(ReturnInst &RI) {
1137 Function *F = RI.getParent()->getParent();
1138 unsigned N = RI.getNumOperands();
1139 if (F->getReturnType()->isVoidTy())
1141 "Found return instr that returns non-void in Function of void "
1142 "return type!", &RI, F->getReturnType());
1144 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1145 "Function return type does not match operand "
1146 "type of return inst!", &RI, F->getReturnType());
1148 // Check to make sure that the return value has necessary properties for
1150 visitTerminatorInst(RI);
1153 void Verifier::visitSwitchInst(SwitchInst &SI) {
1154 // Check to make sure that all of the constants in the switch instruction
1155 // have the same type as the switched-on value.
1156 Type *SwitchTy = SI.getCondition()->getType();
1157 SmallPtrSet<ConstantInt*, 32> Constants;
1158 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1159 Assert1(i.getCaseValue()->getType() == SwitchTy,
1160 "Switch constants must all be same type as switch value!", &SI);
1161 Assert2(Constants.insert(i.getCaseValue()),
1162 "Duplicate integer as switch case", &SI, i.getCaseValue());
1165 visitTerminatorInst(SI);
1168 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1169 Assert1(BI.getAddress()->getType()->isPointerTy(),
1170 "Indirectbr operand must have pointer type!", &BI);
1171 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1172 Assert1(BI.getDestination(i)->getType()->isLabelTy(),
1173 "Indirectbr destinations must all have pointer type!", &BI);
1175 visitTerminatorInst(BI);
1178 void Verifier::visitSelectInst(SelectInst &SI) {
1179 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1181 "Invalid operands for select instruction!", &SI);
1183 Assert1(SI.getTrueValue()->getType() == SI.getType(),
1184 "Select values must have same type as select instruction!", &SI);
1185 visitInstruction(SI);
1188 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1189 /// a pass, if any exist, it's an error.
1191 void Verifier::visitUserOp1(Instruction &I) {
1192 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
1195 void Verifier::visitTruncInst(TruncInst &I) {
1196 // Get the source and destination types
1197 Type *SrcTy = I.getOperand(0)->getType();
1198 Type *DestTy = I.getType();
1200 // Get the size of the types in bits, we'll need this later
1201 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1202 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1204 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1205 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1206 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1207 "trunc source and destination must both be a vector or neither", &I);
1208 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
1210 visitInstruction(I);
1213 void Verifier::visitZExtInst(ZExtInst &I) {
1214 // Get the source and destination types
1215 Type *SrcTy = I.getOperand(0)->getType();
1216 Type *DestTy = I.getType();
1218 // Get the size of the types in bits, we'll need this later
1219 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1220 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1221 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1222 "zext source and destination must both be a vector or neither", &I);
1223 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1224 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1226 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
1228 visitInstruction(I);
1231 void Verifier::visitSExtInst(SExtInst &I) {
1232 // Get the source and destination types
1233 Type *SrcTy = I.getOperand(0)->getType();
1234 Type *DestTy = I.getType();
1236 // Get the size of the types in bits, we'll need this later
1237 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1238 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1240 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1241 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1242 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1243 "sext source and destination must both be a vector or neither", &I);
1244 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
1246 visitInstruction(I);
1249 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1250 // Get the source and destination types
1251 Type *SrcTy = I.getOperand(0)->getType();
1252 Type *DestTy = I.getType();
1253 // Get the size of the types in bits, we'll need this later
1254 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1255 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1257 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
1258 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
1259 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1260 "fptrunc source and destination must both be a vector or neither",&I);
1261 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
1263 visitInstruction(I);
1266 void Verifier::visitFPExtInst(FPExtInst &I) {
1267 // Get the source and destination types
1268 Type *SrcTy = I.getOperand(0)->getType();
1269 Type *DestTy = I.getType();
1271 // Get the size of the types in bits, we'll need this later
1272 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1273 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1275 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
1276 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
1277 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1278 "fpext source and destination must both be a vector or neither", &I);
1279 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
1281 visitInstruction(I);
1284 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1285 // Get the source and destination types
1286 Type *SrcTy = I.getOperand(0)->getType();
1287 Type *DestTy = I.getType();
1289 bool SrcVec = SrcTy->isVectorTy();
1290 bool DstVec = DestTy->isVectorTy();
1292 Assert1(SrcVec == DstVec,
1293 "UIToFP source and dest must both be vector or scalar", &I);
1294 Assert1(SrcTy->isIntOrIntVectorTy(),
1295 "UIToFP source must be integer or integer vector", &I);
1296 Assert1(DestTy->isFPOrFPVectorTy(),
1297 "UIToFP result must be FP or FP vector", &I);
1299 if (SrcVec && DstVec)
1300 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1301 cast<VectorType>(DestTy)->getNumElements(),
1302 "UIToFP source and dest vector length mismatch", &I);
1304 visitInstruction(I);
1307 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1308 // Get the source and destination types
1309 Type *SrcTy = I.getOperand(0)->getType();
1310 Type *DestTy = I.getType();
1312 bool SrcVec = SrcTy->isVectorTy();
1313 bool DstVec = DestTy->isVectorTy();
1315 Assert1(SrcVec == DstVec,
1316 "SIToFP source and dest must both be vector or scalar", &I);
1317 Assert1(SrcTy->isIntOrIntVectorTy(),
1318 "SIToFP source must be integer or integer vector", &I);
1319 Assert1(DestTy->isFPOrFPVectorTy(),
1320 "SIToFP result must be FP or FP vector", &I);
1322 if (SrcVec && DstVec)
1323 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1324 cast<VectorType>(DestTy)->getNumElements(),
1325 "SIToFP source and dest vector length mismatch", &I);
1327 visitInstruction(I);
1330 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1331 // Get the source and destination types
1332 Type *SrcTy = I.getOperand(0)->getType();
1333 Type *DestTy = I.getType();
1335 bool SrcVec = SrcTy->isVectorTy();
1336 bool DstVec = DestTy->isVectorTy();
1338 Assert1(SrcVec == DstVec,
1339 "FPToUI source and dest must both be vector or scalar", &I);
1340 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1342 Assert1(DestTy->isIntOrIntVectorTy(),
1343 "FPToUI result must be integer or integer vector", &I);
1345 if (SrcVec && DstVec)
1346 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1347 cast<VectorType>(DestTy)->getNumElements(),
1348 "FPToUI source and dest vector length mismatch", &I);
1350 visitInstruction(I);
1353 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1354 // Get the source and destination types
1355 Type *SrcTy = I.getOperand(0)->getType();
1356 Type *DestTy = I.getType();
1358 bool SrcVec = SrcTy->isVectorTy();
1359 bool DstVec = DestTy->isVectorTy();
1361 Assert1(SrcVec == DstVec,
1362 "FPToSI source and dest must both be vector or scalar", &I);
1363 Assert1(SrcTy->isFPOrFPVectorTy(),
1364 "FPToSI source must be FP or FP vector", &I);
1365 Assert1(DestTy->isIntOrIntVectorTy(),
1366 "FPToSI result must be integer or integer vector", &I);
1368 if (SrcVec && DstVec)
1369 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1370 cast<VectorType>(DestTy)->getNumElements(),
1371 "FPToSI source and dest vector length mismatch", &I);
1373 visitInstruction(I);
1376 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1377 // Get the source and destination types
1378 Type *SrcTy = I.getOperand(0)->getType();
1379 Type *DestTy = I.getType();
1381 Assert1(SrcTy->getScalarType()->isPointerTy(),
1382 "PtrToInt source must be pointer", &I);
1383 Assert1(DestTy->getScalarType()->isIntegerTy(),
1384 "PtrToInt result must be integral", &I);
1385 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1386 "PtrToInt type mismatch", &I);
1388 if (SrcTy->isVectorTy()) {
1389 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1390 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1391 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1392 "PtrToInt Vector width mismatch", &I);
1395 visitInstruction(I);
1398 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1399 // Get the source and destination types
1400 Type *SrcTy = I.getOperand(0)->getType();
1401 Type *DestTy = I.getType();
1403 Assert1(SrcTy->getScalarType()->isIntegerTy(),
1404 "IntToPtr source must be an integral", &I);
1405 Assert1(DestTy->getScalarType()->isPointerTy(),
1406 "IntToPtr result must be a pointer",&I);
1407 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1408 "IntToPtr type mismatch", &I);
1409 if (SrcTy->isVectorTy()) {
1410 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1411 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1412 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1413 "IntToPtr Vector width mismatch", &I);
1415 visitInstruction(I);
1418 void Verifier::visitBitCastInst(BitCastInst &I) {
1419 Type *SrcTy = I.getOperand(0)->getType();
1420 Type *DestTy = I.getType();
1421 VerifyBitcastType(&I, DestTy, SrcTy);
1422 visitInstruction(I);
1425 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
1426 Type *SrcTy = I.getOperand(0)->getType();
1427 Type *DestTy = I.getType();
1429 Assert1(SrcTy->isPtrOrPtrVectorTy(),
1430 "AddrSpaceCast source must be a pointer", &I);
1431 Assert1(DestTy->isPtrOrPtrVectorTy(),
1432 "AddrSpaceCast result must be a pointer", &I);
1433 Assert1(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
1434 "AddrSpaceCast must be between different address spaces", &I);
1435 if (SrcTy->isVectorTy())
1436 Assert1(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
1437 "AddrSpaceCast vector pointer number of elements mismatch", &I);
1438 visitInstruction(I);
1441 /// visitPHINode - Ensure that a PHI node is well formed.
1443 void Verifier::visitPHINode(PHINode &PN) {
1444 // Ensure that the PHI nodes are all grouped together at the top of the block.
1445 // This can be tested by checking whether the instruction before this is
1446 // either nonexistent (because this is begin()) or is a PHI node. If not,
1447 // then there is some other instruction before a PHI.
1448 Assert2(&PN == &PN.getParent()->front() ||
1449 isa<PHINode>(--BasicBlock::iterator(&PN)),
1450 "PHI nodes not grouped at top of basic block!",
1451 &PN, PN.getParent());
1453 // Check that all of the values of the PHI node have the same type as the
1454 // result, and that the incoming blocks are really basic blocks.
1455 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1456 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1457 "PHI node operands are not the same type as the result!", &PN);
1460 // All other PHI node constraints are checked in the visitBasicBlock method.
1462 visitInstruction(PN);
1465 void Verifier::VerifyCallSite(CallSite CS) {
1466 Instruction *I = CS.getInstruction();
1468 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1469 "Called function must be a pointer!", I);
1470 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1472 Assert1(FPTy->getElementType()->isFunctionTy(),
1473 "Called function is not pointer to function type!", I);
1474 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1476 // Verify that the correct number of arguments are being passed
1477 if (FTy->isVarArg())
1478 Assert1(CS.arg_size() >= FTy->getNumParams(),
1479 "Called function requires more parameters than were provided!",I);
1481 Assert1(CS.arg_size() == FTy->getNumParams(),
1482 "Incorrect number of arguments passed to called function!", I);
1484 // Verify that all arguments to the call match the function type.
1485 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1486 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1487 "Call parameter type does not match function signature!",
1488 CS.getArgument(i), FTy->getParamType(i), I);
1490 AttributeSet Attrs = CS.getAttributes();
1492 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1493 "Attribute after last parameter!", I);
1495 // Verify call attributes.
1496 VerifyFunctionAttrs(FTy, Attrs, I);
1498 if (FTy->isVarArg()) {
1499 // FIXME? is 'nest' even legal here?
1500 bool SawNest = false;
1501 bool SawReturned = false;
1503 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1504 if (Attrs.hasAttribute(Idx, Attribute::Nest))
1506 if (Attrs.hasAttribute(Idx, Attribute::Returned))
1510 // Check attributes on the varargs part.
1511 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1512 Type *Ty = CS.getArgument(Idx-1)->getType();
1513 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1515 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1516 Assert1(!SawNest, "More than one parameter has attribute nest!", I);
1520 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1521 Assert1(!SawReturned, "More than one parameter has attribute returned!",
1523 Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1524 "Incompatible argument and return types for 'returned' "
1529 Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1530 "Attribute 'sret' cannot be used for vararg call arguments!", I);
1532 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
1533 Assert1(Idx == CS.arg_size(), "inalloca isn't on the last argument!",
1538 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1539 if (CS.getCalledFunction() == nullptr ||
1540 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1541 for (FunctionType::param_iterator PI = FTy->param_begin(),
1542 PE = FTy->param_end(); PI != PE; ++PI)
1543 Assert1(!(*PI)->isMetadataTy(),
1544 "Function has metadata parameter but isn't an intrinsic", I);
1547 visitInstruction(*I);
1550 void Verifier::visitCallInst(CallInst &CI) {
1551 VerifyCallSite(&CI);
1553 if (Function *F = CI.getCalledFunction())
1554 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1555 visitIntrinsicFunctionCall(ID, CI);
1558 void Verifier::visitInvokeInst(InvokeInst &II) {
1559 VerifyCallSite(&II);
1561 // Verify that there is a landingpad instruction as the first non-PHI
1562 // instruction of the 'unwind' destination.
1563 Assert1(II.getUnwindDest()->isLandingPad(),
1564 "The unwind destination does not have a landingpad instruction!",&II);
1566 visitTerminatorInst(II);
1569 /// visitBinaryOperator - Check that both arguments to the binary operator are
1570 /// of the same type!
1572 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1573 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1574 "Both operands to a binary operator are not of the same type!", &B);
1576 switch (B.getOpcode()) {
1577 // Check that integer arithmetic operators are only used with
1578 // integral operands.
1579 case Instruction::Add:
1580 case Instruction::Sub:
1581 case Instruction::Mul:
1582 case Instruction::SDiv:
1583 case Instruction::UDiv:
1584 case Instruction::SRem:
1585 case Instruction::URem:
1586 Assert1(B.getType()->isIntOrIntVectorTy(),
1587 "Integer arithmetic operators only work with integral types!", &B);
1588 Assert1(B.getType() == B.getOperand(0)->getType(),
1589 "Integer arithmetic operators must have same type "
1590 "for operands and result!", &B);
1592 // Check that floating-point arithmetic operators are only used with
1593 // floating-point operands.
1594 case Instruction::FAdd:
1595 case Instruction::FSub:
1596 case Instruction::FMul:
1597 case Instruction::FDiv:
1598 case Instruction::FRem:
1599 Assert1(B.getType()->isFPOrFPVectorTy(),
1600 "Floating-point arithmetic operators only work with "
1601 "floating-point types!", &B);
1602 Assert1(B.getType() == B.getOperand(0)->getType(),
1603 "Floating-point arithmetic operators must have same type "
1604 "for operands and result!", &B);
1606 // Check that logical operators are only used with integral operands.
1607 case Instruction::And:
1608 case Instruction::Or:
1609 case Instruction::Xor:
1610 Assert1(B.getType()->isIntOrIntVectorTy(),
1611 "Logical operators only work with integral types!", &B);
1612 Assert1(B.getType() == B.getOperand(0)->getType(),
1613 "Logical operators must have same type for operands and result!",
1616 case Instruction::Shl:
1617 case Instruction::LShr:
1618 case Instruction::AShr:
1619 Assert1(B.getType()->isIntOrIntVectorTy(),
1620 "Shifts only work with integral types!", &B);
1621 Assert1(B.getType() == B.getOperand(0)->getType(),
1622 "Shift return type must be same as operands!", &B);
1625 llvm_unreachable("Unknown BinaryOperator opcode!");
1628 visitInstruction(B);
1631 void Verifier::visitICmpInst(ICmpInst &IC) {
1632 // Check that the operands are the same type
1633 Type *Op0Ty = IC.getOperand(0)->getType();
1634 Type *Op1Ty = IC.getOperand(1)->getType();
1635 Assert1(Op0Ty == Op1Ty,
1636 "Both operands to ICmp instruction are not of the same type!", &IC);
1637 // Check that the operands are the right type
1638 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1639 "Invalid operand types for ICmp instruction", &IC);
1640 // Check that the predicate is valid.
1641 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1642 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1643 "Invalid predicate in ICmp instruction!", &IC);
1645 visitInstruction(IC);
1648 void Verifier::visitFCmpInst(FCmpInst &FC) {
1649 // Check that the operands are the same type
1650 Type *Op0Ty = FC.getOperand(0)->getType();
1651 Type *Op1Ty = FC.getOperand(1)->getType();
1652 Assert1(Op0Ty == Op1Ty,
1653 "Both operands to FCmp instruction are not of the same type!", &FC);
1654 // Check that the operands are the right type
1655 Assert1(Op0Ty->isFPOrFPVectorTy(),
1656 "Invalid operand types for FCmp instruction", &FC);
1657 // Check that the predicate is valid.
1658 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1659 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1660 "Invalid predicate in FCmp instruction!", &FC);
1662 visitInstruction(FC);
1665 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1666 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1668 "Invalid extractelement operands!", &EI);
1669 visitInstruction(EI);
1672 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1673 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1676 "Invalid insertelement operands!", &IE);
1677 visitInstruction(IE);
1680 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1681 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1683 "Invalid shufflevector operands!", &SV);
1684 visitInstruction(SV);
1687 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1688 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1690 Assert1(isa<PointerType>(TargetTy),
1691 "GEP base pointer is not a vector or a vector of pointers", &GEP);
1692 Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1693 "GEP into unsized type!", &GEP);
1694 Assert1(GEP.getPointerOperandType()->isVectorTy() ==
1695 GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
1698 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1700 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1701 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1703 Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
1704 cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
1705 == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
1707 if (GEP.getPointerOperandType()->isVectorTy()) {
1708 // Additional checks for vector GEPs.
1709 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
1710 Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
1711 "Vector GEP result width doesn't match operand's", &GEP);
1712 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1713 Type *IndexTy = Idxs[i]->getType();
1714 Assert1(IndexTy->isVectorTy(),
1715 "Vector GEP must have vector indices!", &GEP);
1716 unsigned IndexWidth = IndexTy->getVectorNumElements();
1717 Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1720 visitInstruction(GEP);
1723 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1724 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1727 void Verifier::visitLoadInst(LoadInst &LI) {
1728 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1729 Assert1(PTy, "Load operand must be a pointer.", &LI);
1730 Type *ElTy = PTy->getElementType();
1731 Assert2(ElTy == LI.getType(),
1732 "Load result type does not match pointer operand type!", &LI, ElTy);
1733 if (LI.isAtomic()) {
1734 Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1735 "Load cannot have Release ordering", &LI);
1736 Assert1(LI.getAlignment() != 0,
1737 "Atomic load must specify explicit alignment", &LI);
1738 if (!ElTy->isPointerTy()) {
1739 Assert2(ElTy->isIntegerTy(),
1740 "atomic load operand must have integer type!",
1742 unsigned Size = ElTy->getPrimitiveSizeInBits();
1743 Assert2(Size >= 8 && !(Size & (Size - 1)),
1744 "atomic load operand must be power-of-two byte-sized integer",
1748 Assert1(LI.getSynchScope() == CrossThread,
1749 "Non-atomic load cannot have SynchronizationScope specified", &LI);
1752 if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1753 unsigned NumOperands = Range->getNumOperands();
1754 Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1755 unsigned NumRanges = NumOperands / 2;
1756 Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1758 ConstantRange LastRange(1); // Dummy initial value
1759 for (unsigned i = 0; i < NumRanges; ++i) {
1760 ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1761 Assert1(Low, "The lower limit must be an integer!", Low);
1762 ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1763 Assert1(High, "The upper limit must be an integer!", High);
1764 Assert1(High->getType() == Low->getType() &&
1765 High->getType() == ElTy, "Range types must match load type!",
1768 APInt HighV = High->getValue();
1769 APInt LowV = Low->getValue();
1770 ConstantRange CurRange(LowV, HighV);
1771 Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1772 "Range must not be empty!", Range);
1774 Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1775 "Intervals are overlapping", Range);
1776 Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1778 Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1781 LastRange = ConstantRange(LowV, HighV);
1783 if (NumRanges > 2) {
1785 dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1787 dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1788 ConstantRange FirstRange(FirstLow, FirstHigh);
1789 Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1790 "Intervals are overlapping", Range);
1791 Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1798 visitInstruction(LI);
1801 void Verifier::visitStoreInst(StoreInst &SI) {
1802 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1803 Assert1(PTy, "Store operand must be a pointer.", &SI);
1804 Type *ElTy = PTy->getElementType();
1805 Assert2(ElTy == SI.getOperand(0)->getType(),
1806 "Stored value type does not match pointer operand type!",
1808 if (SI.isAtomic()) {
1809 Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1810 "Store cannot have Acquire ordering", &SI);
1811 Assert1(SI.getAlignment() != 0,
1812 "Atomic store must specify explicit alignment", &SI);
1813 if (!ElTy->isPointerTy()) {
1814 Assert2(ElTy->isIntegerTy(),
1815 "atomic store operand must have integer type!",
1817 unsigned Size = ElTy->getPrimitiveSizeInBits();
1818 Assert2(Size >= 8 && !(Size & (Size - 1)),
1819 "atomic store operand must be power-of-two byte-sized integer",
1823 Assert1(SI.getSynchScope() == CrossThread,
1824 "Non-atomic store cannot have SynchronizationScope specified", &SI);
1826 visitInstruction(SI);
1829 void Verifier::visitAllocaInst(AllocaInst &AI) {
1830 SmallPtrSet<const Type*, 4> Visited;
1831 PointerType *PTy = AI.getType();
1832 Assert1(PTy->getAddressSpace() == 0,
1833 "Allocation instruction pointer not in the generic address space!",
1835 Assert1(PTy->getElementType()->isSized(&Visited), "Cannot allocate unsized type",
1837 Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1838 "Alloca array size must have integer type", &AI);
1840 visitInstruction(AI);
1843 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1845 // FIXME: more conditions???
1846 Assert1(CXI.getSuccessOrdering() != NotAtomic,
1847 "cmpxchg instructions must be atomic.", &CXI);
1848 Assert1(CXI.getFailureOrdering() != NotAtomic,
1849 "cmpxchg instructions must be atomic.", &CXI);
1850 Assert1(CXI.getSuccessOrdering() != Unordered,
1851 "cmpxchg instructions cannot be unordered.", &CXI);
1852 Assert1(CXI.getFailureOrdering() != Unordered,
1853 "cmpxchg instructions cannot be unordered.", &CXI);
1854 Assert1(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
1855 "cmpxchg instructions be at least as constrained on success as fail",
1857 Assert1(CXI.getFailureOrdering() != Release &&
1858 CXI.getFailureOrdering() != AcquireRelease,
1859 "cmpxchg failure ordering cannot include release semantics", &CXI);
1861 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1862 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1863 Type *ElTy = PTy->getElementType();
1864 Assert2(ElTy->isIntegerTy(),
1865 "cmpxchg operand must have integer type!",
1867 unsigned Size = ElTy->getPrimitiveSizeInBits();
1868 Assert2(Size >= 8 && !(Size & (Size - 1)),
1869 "cmpxchg operand must be power-of-two byte-sized integer",
1871 Assert2(ElTy == CXI.getOperand(1)->getType(),
1872 "Expected value type does not match pointer operand type!",
1874 Assert2(ElTy == CXI.getOperand(2)->getType(),
1875 "Stored value type does not match pointer operand type!",
1877 visitInstruction(CXI);
1880 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1881 Assert1(RMWI.getOrdering() != NotAtomic,
1882 "atomicrmw instructions must be atomic.", &RMWI);
1883 Assert1(RMWI.getOrdering() != Unordered,
1884 "atomicrmw instructions cannot be unordered.", &RMWI);
1885 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1886 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1887 Type *ElTy = PTy->getElementType();
1888 Assert2(ElTy->isIntegerTy(),
1889 "atomicrmw operand must have integer type!",
1891 unsigned Size = ElTy->getPrimitiveSizeInBits();
1892 Assert2(Size >= 8 && !(Size & (Size - 1)),
1893 "atomicrmw operand must be power-of-two byte-sized integer",
1895 Assert2(ElTy == RMWI.getOperand(1)->getType(),
1896 "Argument value type does not match pointer operand type!",
1898 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1899 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1900 "Invalid binary operation!", &RMWI);
1901 visitInstruction(RMWI);
1904 void Verifier::visitFenceInst(FenceInst &FI) {
1905 const AtomicOrdering Ordering = FI.getOrdering();
1906 Assert1(Ordering == Acquire || Ordering == Release ||
1907 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1908 "fence instructions may only have "
1909 "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1910 visitInstruction(FI);
1913 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1914 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1915 EVI.getIndices()) ==
1917 "Invalid ExtractValueInst operands!", &EVI);
1919 visitInstruction(EVI);
1922 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1923 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1924 IVI.getIndices()) ==
1925 IVI.getOperand(1)->getType(),
1926 "Invalid InsertValueInst operands!", &IVI);
1928 visitInstruction(IVI);
1931 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1932 BasicBlock *BB = LPI.getParent();
1934 // The landingpad instruction is ill-formed if it doesn't have any clauses and
1936 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1937 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1939 // The landingpad instruction defines its parent as a landing pad block. The
1940 // landing pad block may be branched to only by the unwind edge of an invoke.
1941 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1942 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1943 Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
1944 "Block containing LandingPadInst must be jumped to "
1945 "only by the unwind edge of an invoke.", &LPI);
1948 // The landingpad instruction must be the first non-PHI instruction in the
1950 Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1951 "LandingPadInst not the first non-PHI instruction in the block.",
1954 // The personality functions for all landingpad instructions within the same
1955 // function should match.
1957 Assert1(LPI.getPersonalityFn() == PersonalityFn,
1958 "Personality function doesn't match others in function", &LPI);
1959 PersonalityFn = LPI.getPersonalityFn();
1961 // All operands must be constants.
1962 Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1964 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1965 Value *Clause = LPI.getClause(i);
1966 Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1967 if (LPI.isCatch(i)) {
1968 Assert1(isa<PointerType>(Clause->getType()),
1969 "Catch operand does not have pointer type!", &LPI);
1971 Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1972 Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1973 "Filter operand is not an array of constants!", &LPI);
1977 visitInstruction(LPI);
1980 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
1981 Instruction *Op = cast<Instruction>(I.getOperand(i));
1982 // If the we have an invalid invoke, don't try to compute the dominance.
1983 // We already reject it in the invoke specific checks and the dominance
1984 // computation doesn't handle multiple edges.
1985 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1986 if (II->getNormalDest() == II->getUnwindDest())
1990 const Use &U = I.getOperandUse(i);
1991 Assert2(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
1992 "Instruction does not dominate all uses!", Op, &I);
1995 /// verifyInstruction - Verify that an instruction is well formed.
1997 void Verifier::visitInstruction(Instruction &I) {
1998 BasicBlock *BB = I.getParent();
1999 Assert1(BB, "Instruction not embedded in basic block!", &I);
2001 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
2002 for (User *U : I.users()) {
2003 Assert1(U != (User*)&I || !DT.isReachableFromEntry(BB),
2004 "Only PHI nodes may reference their own value!", &I);
2008 // Check that void typed values don't have names
2009 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
2010 "Instruction has a name, but provides a void value!", &I);
2012 // Check that the return value of the instruction is either void or a legal
2014 Assert1(I.getType()->isVoidTy() ||
2015 I.getType()->isFirstClassType(),
2016 "Instruction returns a non-scalar type!", &I);
2018 // Check that the instruction doesn't produce metadata. Calls are already
2019 // checked against the callee type.
2020 Assert1(!I.getType()->isMetadataTy() ||
2021 isa<CallInst>(I) || isa<InvokeInst>(I),
2022 "Invalid use of metadata!", &I);
2024 // Check that all uses of the instruction, if they are instructions
2025 // themselves, actually have parent basic blocks. If the use is not an
2026 // instruction, it is an error!
2027 for (Use &U : I.uses()) {
2028 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
2029 Assert2(Used->getParent() != nullptr, "Instruction referencing"
2030 " instruction not embedded in a basic block!", &I, Used);
2032 CheckFailed("Use of instruction is not an instruction!", U);
2037 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2038 Assert1(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
2040 // Check to make sure that only first-class-values are operands to
2042 if (!I.getOperand(i)->getType()->isFirstClassType()) {
2043 Assert1(0, "Instruction operands must be first-class values!", &I);
2046 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2047 // Check to make sure that the "address of" an intrinsic function is never
2049 Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
2050 "Cannot take the address of an intrinsic!", &I);
2051 Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
2052 F->getIntrinsicID() == Intrinsic::donothing,
2053 "Cannot invoke an intrinsinc other than donothing", &I);
2054 Assert1(F->getParent() == M, "Referencing function in another module!",
2056 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2057 Assert1(OpBB->getParent() == BB->getParent(),
2058 "Referring to a basic block in another function!", &I);
2059 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2060 Assert1(OpArg->getParent() == BB->getParent(),
2061 "Referring to an argument in another function!", &I);
2062 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2063 Assert1(GV->getParent() == M, "Referencing global in another module!",
2065 } else if (isa<Instruction>(I.getOperand(i))) {
2066 verifyDominatesUse(I, i);
2067 } else if (isa<InlineAsm>(I.getOperand(i))) {
2068 Assert1((i + 1 == e && isa<CallInst>(I)) ||
2069 (i + 3 == e && isa<InvokeInst>(I)),
2070 "Cannot take the address of an inline asm!", &I);
2071 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2072 if (CE->getType()->isPtrOrPtrVectorTy()) {
2073 // If we have a ConstantExpr pointer, we need to see if it came from an
2074 // illegal bitcast (inttoptr <constant int> )
2075 SmallVector<const ConstantExpr *, 4> Stack;
2076 SmallPtrSet<const ConstantExpr *, 4> Visited;
2077 Stack.push_back(CE);
2079 while (!Stack.empty()) {
2080 const ConstantExpr *V = Stack.pop_back_val();
2081 if (!Visited.insert(V))
2084 VerifyConstantExprBitcastType(V);
2086 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2087 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2088 Stack.push_back(Op);
2095 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2096 Assert1(I.getType()->isFPOrFPVectorTy(),
2097 "fpmath requires a floating point result!", &I);
2098 Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2099 Value *Op0 = MD->getOperand(0);
2100 if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
2101 APFloat Accuracy = CFP0->getValueAPF();
2102 Assert1(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2103 "fpmath accuracy not a positive number!", &I);
2105 Assert1(false, "invalid fpmath accuracy!", &I);
2109 MDNode *MD = I.getMetadata(LLVMContext::MD_range);
2110 Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
2112 if (VerifyDebugInfo) {
2113 MD = I.getMetadata(LLVMContext::MD_dbg);
2114 Finder.processLocation(*M, DILocation(MD));
2117 InstsInThisBlock.insert(&I);
2120 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2121 /// intrinsic argument or return value) matches the type constraints specified
2122 /// by the .td file (e.g. an "any integer" argument really is an integer).
2124 /// This return true on error but does not print a message.
2125 bool Verifier::VerifyIntrinsicType(Type *Ty,
2126 ArrayRef<Intrinsic::IITDescriptor> &Infos,
2127 SmallVectorImpl<Type*> &ArgTys) {
2128 using namespace Intrinsic;
2130 // If we ran out of descriptors, there are too many arguments.
2131 if (Infos.empty()) return true;
2132 IITDescriptor D = Infos.front();
2133 Infos = Infos.slice(1);
2136 case IITDescriptor::Void: return !Ty->isVoidTy();
2137 case IITDescriptor::VarArg: return true;
2138 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
2139 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2140 case IITDescriptor::Half: return !Ty->isHalfTy();
2141 case IITDescriptor::Float: return !Ty->isFloatTy();
2142 case IITDescriptor::Double: return !Ty->isDoubleTy();
2143 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2144 case IITDescriptor::Vector: {
2145 VectorType *VT = dyn_cast<VectorType>(Ty);
2146 return !VT || VT->getNumElements() != D.Vector_Width ||
2147 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2149 case IITDescriptor::Pointer: {
2150 PointerType *PT = dyn_cast<PointerType>(Ty);
2151 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2152 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2155 case IITDescriptor::Struct: {
2156 StructType *ST = dyn_cast<StructType>(Ty);
2157 if (!ST || ST->getNumElements() != D.Struct_NumElements)
2160 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2161 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2166 case IITDescriptor::Argument:
2167 // Two cases here - If this is the second occurrence of an argument, verify
2168 // that the later instance matches the previous instance.
2169 if (D.getArgumentNumber() < ArgTys.size())
2170 return Ty != ArgTys[D.getArgumentNumber()];
2172 // Otherwise, if this is the first instance of an argument, record it and
2173 // verify the "Any" kind.
2174 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2175 ArgTys.push_back(Ty);
2177 switch (D.getArgumentKind()) {
2178 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2179 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
2180 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
2181 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2183 llvm_unreachable("all argument kinds not covered");
2185 case IITDescriptor::ExtendArgument: {
2186 // This may only be used when referring to a previous vector argument.
2187 if (D.getArgumentNumber() >= ArgTys.size())
2190 Type *NewTy = ArgTys[D.getArgumentNumber()];
2191 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2192 NewTy = VectorType::getExtendedElementVectorType(VTy);
2193 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2194 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
2200 case IITDescriptor::TruncArgument: {
2201 // This may only be used when referring to a previous vector argument.
2202 if (D.getArgumentNumber() >= ArgTys.size())
2205 Type *NewTy = ArgTys[D.getArgumentNumber()];
2206 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2207 NewTy = VectorType::getTruncatedElementVectorType(VTy);
2208 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2209 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
2215 case IITDescriptor::HalfVecArgument:
2216 // This may only be used when referring to a previous vector argument.
2217 return D.getArgumentNumber() >= ArgTys.size() ||
2218 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2219 VectorType::getHalfElementsVectorType(
2220 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2222 llvm_unreachable("unhandled");
2225 /// \brief Verify if the intrinsic has variable arguments.
2226 /// This method is intended to be called after all the fixed arguments have been
2229 /// This method returns true on error and does not print an error message.
2231 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
2232 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
2233 using namespace Intrinsic;
2235 // If there are no descriptors left, then it can't be a vararg.
2237 return isVarArg ? true : false;
2239 // There should be only one descriptor remaining at this point.
2240 if (Infos.size() != 1)
2243 // Check and verify the descriptor.
2244 IITDescriptor D = Infos.front();
2245 Infos = Infos.slice(1);
2246 if (D.Kind == IITDescriptor::VarArg)
2247 return isVarArg ? false : true;
2252 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2254 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2255 Function *IF = CI.getCalledFunction();
2256 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2259 // Verify that the intrinsic prototype lines up with what the .td files
2261 FunctionType *IFTy = IF->getFunctionType();
2262 bool IsVarArg = IFTy->isVarArg();
2264 SmallVector<Intrinsic::IITDescriptor, 8> Table;
2265 getIntrinsicInfoTableEntries(ID, Table);
2266 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2268 SmallVector<Type *, 4> ArgTys;
2269 Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2270 "Intrinsic has incorrect return type!", IF);
2271 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2272 Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2273 "Intrinsic has incorrect argument type!", IF);
2275 // Verify if the intrinsic call matches the vararg property.
2277 Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2278 "Intrinsic was not defined with variable arguments!", IF);
2280 Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2281 "Callsite was not defined with variable arguments!", IF);
2283 // All descriptors should be absorbed by now.
2284 Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2286 // Now that we have the intrinsic ID and the actual argument types (and we
2287 // know they are legal for the intrinsic!) get the intrinsic name through the
2288 // usual means. This allows us to verify the mangling of argument types into
2290 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
2291 Assert1(ExpectedName == IF->getName(),
2292 "Intrinsic name not mangled correctly for type arguments! "
2293 "Should be: " + ExpectedName, IF);
2295 // If the intrinsic takes MDNode arguments, verify that they are either global
2296 // or are local to *this* function.
2297 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2298 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
2299 visitMDNode(*MD, CI.getParent()->getParent());
2304 case Intrinsic::ctlz: // llvm.ctlz
2305 case Intrinsic::cttz: // llvm.cttz
2306 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2307 "is_zero_undef argument of bit counting intrinsics must be a "
2308 "constant int", &CI);
2310 case Intrinsic::dbg_declare: { // llvm.dbg.declare
2311 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2312 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2313 MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
2314 Assert1(MD->getNumOperands() == 1,
2315 "invalid llvm.dbg.declare intrinsic call 2", &CI);
2316 if (VerifyDebugInfo)
2317 Finder.processDeclare(*M, cast<DbgDeclareInst>(&CI));
2319 case Intrinsic::dbg_value: { //llvm.dbg.value
2320 if (VerifyDebugInfo) {
2321 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2322 "invalid llvm.dbg.value intrinsic call 1", &CI);
2323 Finder.processValue(*M, cast<DbgValueInst>(&CI));
2327 case Intrinsic::memcpy:
2328 case Intrinsic::memmove:
2329 case Intrinsic::memset:
2330 Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
2331 "alignment argument of memory intrinsics must be a constant int",
2333 Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
2334 "isvolatile argument of memory intrinsics must be a constant int",
2337 case Intrinsic::gcroot:
2338 case Intrinsic::gcwrite:
2339 case Intrinsic::gcread:
2340 if (ID == Intrinsic::gcroot) {
2342 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2343 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2344 Assert1(isa<Constant>(CI.getArgOperand(1)),
2345 "llvm.gcroot parameter #2 must be a constant.", &CI);
2346 if (!AI->getType()->getElementType()->isPointerTy()) {
2347 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2348 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2349 "or argument #2 must be a non-null constant.", &CI);
2353 Assert1(CI.getParent()->getParent()->hasGC(),
2354 "Enclosing function does not use GC.", &CI);
2356 case Intrinsic::init_trampoline:
2357 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2358 "llvm.init_trampoline parameter #2 must resolve to a function.",
2361 case Intrinsic::prefetch:
2362 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
2363 isa<ConstantInt>(CI.getArgOperand(2)) &&
2364 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2365 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2366 "invalid arguments to llvm.prefetch",
2369 case Intrinsic::stackprotector:
2370 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2371 "llvm.stackprotector parameter #2 must resolve to an alloca.",
2374 case Intrinsic::lifetime_start:
2375 case Intrinsic::lifetime_end:
2376 case Intrinsic::invariant_start:
2377 Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
2378 "size argument of memory use markers must be a constant integer",
2381 case Intrinsic::invariant_end:
2382 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2383 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2388 void Verifier::verifyDebugInfo() {
2389 // Verify Debug Info.
2390 if (VerifyDebugInfo) {
2391 for (DICompileUnit CU : Finder.compile_units()) {
2392 Assert1(CU.Verify(), "DICompileUnit does not Verify!", CU);
2394 for (DISubprogram S : Finder.subprograms()) {
2395 Assert1(S.Verify(), "DISubprogram does not Verify!", S);
2397 for (DIGlobalVariable GV : Finder.global_variables()) {
2398 Assert1(GV.Verify(), "DIGlobalVariable does not Verify!", GV);
2400 for (DIType T : Finder.types()) {
2401 Assert1(T.Verify(), "DIType does not Verify!", T);
2403 for (DIScope S : Finder.scopes()) {
2404 Assert1(S.Verify(), "DIScope does not Verify!", S);
2409 //===----------------------------------------------------------------------===//
2410 // Implement the public interfaces to this file...
2411 //===----------------------------------------------------------------------===//
2413 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
2414 Function &F = const_cast<Function &>(f);
2415 assert(!F.isDeclaration() && "Cannot verify external functions");
2417 raw_null_ostream NullStr;
2418 Verifier V(OS ? *OS : NullStr);
2420 // Note that this function's return value is inverted from what you would
2421 // expect of a function called "verify".
2422 return !V.verify(F);
2425 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
2426 raw_null_ostream NullStr;
2427 Verifier V(OS ? *OS : NullStr);
2429 bool Broken = false;
2430 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
2431 if (!I->isDeclaration())
2432 Broken |= !V.verify(*I);
2434 // Note that this function's return value is inverted from what you would
2435 // expect of a function called "verify".
2436 return !V.verify(M) || Broken;
2440 struct VerifierLegacyPass : public FunctionPass {
2446 VerifierLegacyPass() : FunctionPass(ID), FatalErrors(true) {
2447 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
2449 explicit VerifierLegacyPass(bool FatalErrors)
2450 : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
2451 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
2454 bool runOnFunction(Function &F) override {
2455 if (!V.verify(F) && FatalErrors)
2456 report_fatal_error("Broken function found, compilation aborted!");
2461 bool doFinalization(Module &M) override {
2462 if (!V.verify(M) && FatalErrors)
2463 report_fatal_error("Broken module found, compilation aborted!");
2468 void getAnalysisUsage(AnalysisUsage &AU) const override {
2469 AU.setPreservesAll();
2474 char VerifierLegacyPass::ID = 0;
2475 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
2477 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
2478 return new VerifierLegacyPass(FatalErrors);
2481 PreservedAnalyses VerifierPass::run(Module *M) {
2482 if (verifyModule(*M, &dbgs()) && FatalErrors)
2483 report_fatal_error("Broken module found, compilation aborted!");
2485 return PreservedAnalyses::all();
2488 PreservedAnalyses VerifierPass::run(Function *F) {
2489 if (verifyFunction(*F, &dbgs()) && FatalErrors)
2490 report_fatal_error("Broken function found, compilation aborted!");
2492 return PreservedAnalyses::all();