1 //===-- Verifier.cpp - Implement the Module Verifier -------------*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 int %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 // * All other things that are tested by asserts spread about the code...
40 //===----------------------------------------------------------------------===//
42 #include "llvm/Analysis/Verifier.h"
43 #include "llvm/Assembly/Writer.h"
44 #include "llvm/CallingConv.h"
45 #include "llvm/Constants.h"
46 #include "llvm/Pass.h"
47 #include "llvm/Module.h"
48 #include "llvm/ModuleProvider.h"
49 #include "llvm/DerivedTypes.h"
50 #include "llvm/Instructions.h"
51 #include "llvm/Intrinsics.h"
52 #include "llvm/PassManager.h"
53 #include "llvm/SymbolTable.h"
54 #include "llvm/Analysis/Dominators.h"
55 #include "llvm/Support/CFG.h"
56 #include "llvm/Support/InstVisitor.h"
57 #include "llvm/ADT/STLExtras.h"
63 namespace { // Anonymous namespace for class
65 struct Verifier : public FunctionPass, InstVisitor<Verifier> {
66 bool Broken; // Is this module found to be broken?
67 bool RealPass; // Are we not being run by a PassManager?
68 VerifierFailureAction action;
69 // What to do if verification fails.
70 Module *Mod; // Module we are verifying right now
71 ETForest *EF; // ET-Forest, caution can be null!
72 std::stringstream msgs; // A stringstream to collect messages
74 /// InstInThisBlock - when verifying a basic block, keep track of all of the
75 /// instructions we have seen so far. This allows us to do efficient
76 /// dominance checks for the case when an instruction has an operand that is
77 /// an instruction in the same block.
78 std::set<Instruction*> InstsInThisBlock;
81 : Broken(false), RealPass(true), action(AbortProcessAction),
82 EF(0), msgs( std::ios::app | std::ios::out ) {}
83 Verifier( VerifierFailureAction ctn )
84 : Broken(false), RealPass(true), action(ctn), EF(0),
85 msgs( std::ios::app | std::ios::out ) {}
87 : Broken(false), RealPass(true),
88 action( AB ? AbortProcessAction : PrintMessageAction), EF(0),
89 msgs( std::ios::app | std::ios::out ) {}
90 Verifier(ETForest &ef)
91 : Broken(false), RealPass(false), action(PrintMessageAction),
92 EF(&ef), msgs( std::ios::app | std::ios::out ) {}
95 bool doInitialization(Module &M) {
97 verifySymbolTable(M.getSymbolTable());
99 // If this is a real pass, in a pass manager, we must abort before
100 // returning back to the pass manager, or else the pass manager may try to
101 // run other passes on the broken module.
107 bool runOnFunction(Function &F) {
108 // Get dominator information if we are being run by PassManager
109 if (RealPass) EF = &getAnalysis<ETForest>();
111 InstsInThisBlock.clear();
113 // If this is a real pass, in a pass manager, we must abort before
114 // returning back to the pass manager, or else the pass manager may try to
115 // run other passes on the broken module.
122 bool doFinalization(Module &M) {
123 // Scan through, checking all of the external function's linkage now...
124 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
125 visitGlobalValue(*I);
127 // Check to make sure function prototypes are okay.
128 if (I->isExternal()) visitFunction(*I);
131 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
133 visitGlobalVariable(*I);
135 // If the module is broken, abort at this time.
140 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
141 AU.setPreservesAll();
143 AU.addRequired<ETForest>();
146 /// abortIfBroken - If the module is broken and we are supposed to abort on
147 /// this condition, do so.
149 void abortIfBroken() {
152 msgs << "Broken module found, ";
155 case AbortProcessAction:
156 msgs << "compilation aborted!\n";
157 std::cerr << msgs.str();
159 case ThrowExceptionAction:
160 msgs << "verification terminated.\n";
162 case PrintMessageAction:
163 msgs << "verification continues.\n";
164 std::cerr << msgs.str();
166 case ReturnStatusAction:
173 // Verification methods...
174 void verifySymbolTable(SymbolTable &ST);
175 void visitGlobalValue(GlobalValue &GV);
176 void visitGlobalVariable(GlobalVariable &GV);
177 void visitFunction(Function &F);
178 void visitBasicBlock(BasicBlock &BB);
179 void visitPHINode(PHINode &PN);
180 void visitBinaryOperator(BinaryOperator &B);
181 void visitShiftInst(ShiftInst &SI);
182 void visitExtractElementInst(ExtractElementInst &EI);
183 void visitInsertElementInst(InsertElementInst &EI);
184 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
185 void visitCallInst(CallInst &CI);
186 void visitGetElementPtrInst(GetElementPtrInst &GEP);
187 void visitLoadInst(LoadInst &LI);
188 void visitStoreInst(StoreInst &SI);
189 void visitInstruction(Instruction &I);
190 void visitTerminatorInst(TerminatorInst &I);
191 void visitReturnInst(ReturnInst &RI);
192 void visitSwitchInst(SwitchInst &SI);
193 void visitSelectInst(SelectInst &SI);
194 void visitUserOp1(Instruction &I);
195 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
196 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
199 void WriteValue(const Value *V) {
201 if (isa<Instruction>(V)) {
204 WriteAsOperand (msgs, V, true, true, Mod);
209 void WriteType(const Type* T ) {
211 WriteTypeSymbolic(msgs, T, Mod );
215 // CheckFailed - A check failed, so print out the condition and the message
216 // that failed. This provides a nice place to put a breakpoint if you want
217 // to see why something is not correct.
218 void CheckFailed(const std::string &Message,
219 const Value *V1 = 0, const Value *V2 = 0,
220 const Value *V3 = 0, const Value *V4 = 0) {
221 msgs << Message << "\n";
229 void CheckFailed( const std::string& Message, const Value* V1,
230 const Type* T2, const Value* V3 = 0 ) {
231 msgs << Message << "\n";
239 RegisterOpt<Verifier> X("verify", "Module Verifier");
240 } // End anonymous namespace
243 // Assert - We know that cond should be true, if not print an error message.
244 #define Assert(C, M) \
245 do { if (!(C)) { CheckFailed(M); return; } } while (0)
246 #define Assert1(C, M, V1) \
247 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
248 #define Assert2(C, M, V1, V2) \
249 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
250 #define Assert3(C, M, V1, V2, V3) \
251 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
252 #define Assert4(C, M, V1, V2, V3, V4) \
253 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
256 void Verifier::visitGlobalValue(GlobalValue &GV) {
257 Assert1(!GV.isExternal() || GV.hasExternalLinkage(),
258 "Global is external, but doesn't have external linkage!", &GV);
259 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
260 "Only global variables can have appending linkage!", &GV);
262 if (GV.hasAppendingLinkage()) {
263 GlobalVariable &GVar = cast<GlobalVariable>(GV);
264 Assert1(isa<ArrayType>(GVar.getType()->getElementType()),
265 "Only global arrays can have appending linkage!", &GV);
269 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
270 if (GV.hasInitializer())
271 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
272 "Global variable initializer type does not match global "
273 "variable type!", &GV);
275 visitGlobalValue(GV);
279 // verifySymbolTable - Verify that a function or module symbol table is ok
281 void Verifier::verifySymbolTable(SymbolTable &ST) {
283 // Loop over all of the values in all type planes in the symbol table.
284 for (SymbolTable::plane_const_iterator PI = ST.plane_begin(),
285 PE = ST.plane_end(); PI != PE; ++PI)
286 for (SymbolTable::value_const_iterator VI = PI->second.begin(),
287 VE = PI->second.end(); VI != VE; ++VI) {
288 Value *V = VI->second;
289 // Check that there are no void typed values in the symbol table. Values
290 // with a void type cannot be put into symbol tables because they cannot
292 Assert1(V->getType() != Type::VoidTy,
293 "Values with void type are not allowed to have names!", V);
297 // visitFunction - Verify that a function is ok.
299 void Verifier::visitFunction(Function &F) {
300 Assert1(!F.isVarArg() || F.getCallingConv() == CallingConv::C,
301 "Varargs functions must have C calling conventions!", &F);
303 // Check function arguments.
304 const FunctionType *FT = F.getFunctionType();
305 unsigned NumArgs = F.getArgumentList().size();
307 Assert2(FT->getNumParams() == NumArgs,
308 "# formal arguments must match # of arguments for function type!",
310 Assert1(F.getReturnType()->isFirstClassType() ||
311 F.getReturnType() == Type::VoidTy,
312 "Functions cannot return aggregate values!", &F);
314 // Check that the argument values match the function type for this function...
316 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I, ++i) {
317 Assert2(I->getType() == FT->getParamType(i),
318 "Argument value does not match function argument type!",
319 I, FT->getParamType(i));
320 // Make sure no aggregates are passed by value.
321 Assert1(I->getType()->isFirstClassType(),
322 "Functions cannot take aggregates as arguments by value!", I);
325 if (!F.isExternal()) {
326 verifySymbolTable(F.getSymbolTable());
328 // Check the entry node
329 BasicBlock *Entry = &F.getEntryBlock();
330 Assert1(pred_begin(Entry) == pred_end(Entry),
331 "Entry block to function must not have predecessors!", Entry);
336 // verifyBasicBlock - Verify that a basic block is well formed...
338 void Verifier::visitBasicBlock(BasicBlock &BB) {
339 InstsInThisBlock.clear();
341 // Ensure that basic blocks have terminators!
342 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
344 // Check constraints that this basic block imposes on all of the PHI nodes in
346 if (isa<PHINode>(BB.front())) {
347 std::vector<BasicBlock*> Preds(pred_begin(&BB), pred_end(&BB));
348 std::sort(Preds.begin(), Preds.end());
350 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
352 // Ensure that PHI nodes have at least one entry!
353 Assert1(PN->getNumIncomingValues() != 0,
354 "PHI nodes must have at least one entry. If the block is dead, "
355 "the PHI should be removed!", PN);
356 Assert1(PN->getNumIncomingValues() == Preds.size(),
357 "PHINode should have one entry for each predecessor of its "
358 "parent basic block!", PN);
360 // Get and sort all incoming values in the PHI node...
361 std::vector<std::pair<BasicBlock*, Value*> > Values;
362 Values.reserve(PN->getNumIncomingValues());
363 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
364 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
365 PN->getIncomingValue(i)));
366 std::sort(Values.begin(), Values.end());
368 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
369 // Check to make sure that if there is more than one entry for a
370 // particular basic block in this PHI node, that the incoming values are
373 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
374 Values[i].second == Values[i-1].second,
375 "PHI node has multiple entries for the same basic block with "
376 "different incoming values!", PN, Values[i].first,
377 Values[i].second, Values[i-1].second);
379 // Check to make sure that the predecessors and PHI node entries are
381 Assert3(Values[i].first == Preds[i],
382 "PHI node entries do not match predecessors!", PN,
383 Values[i].first, Preds[i]);
389 void Verifier::visitTerminatorInst(TerminatorInst &I) {
390 // Ensure that terminators only exist at the end of the basic block.
391 Assert1(&I == I.getParent()->getTerminator(),
392 "Terminator found in the middle of a basic block!", I.getParent());
396 void Verifier::visitReturnInst(ReturnInst &RI) {
397 Function *F = RI.getParent()->getParent();
398 if (RI.getNumOperands() == 0)
399 Assert2(F->getReturnType() == Type::VoidTy,
400 "Found return instr that returns void in Function of non-void "
401 "return type!", &RI, F->getReturnType());
403 Assert2(F->getReturnType() == RI.getOperand(0)->getType(),
404 "Function return type does not match operand "
405 "type of return inst!", &RI, F->getReturnType());
407 // Check to make sure that the return value has necessary properties for
409 visitTerminatorInst(RI);
412 void Verifier::visitSwitchInst(SwitchInst &SI) {
413 // Check to make sure that all of the constants in the switch instruction
414 // have the same type as the switched-on value.
415 const Type *SwitchTy = SI.getCondition()->getType();
416 for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i)
417 Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
418 "Switch constants must all be same type as switch value!", &SI);
420 visitTerminatorInst(SI);
423 void Verifier::visitSelectInst(SelectInst &SI) {
424 Assert1(SI.getCondition()->getType() == Type::BoolTy,
425 "Select condition type must be bool!", &SI);
426 Assert1(SI.getTrueValue()->getType() == SI.getFalseValue()->getType(),
427 "Select values must have identical types!", &SI);
428 Assert1(SI.getTrueValue()->getType() == SI.getType(),
429 "Select values must have same type as select instruction!", &SI);
430 visitInstruction(SI);
434 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
435 /// a pass, if any exist, it's an error.
437 void Verifier::visitUserOp1(Instruction &I) {
438 Assert1(0, "User-defined operators should not live outside of a pass!",
442 /// visitPHINode - Ensure that a PHI node is well formed.
444 void Verifier::visitPHINode(PHINode &PN) {
445 // Ensure that the PHI nodes are all grouped together at the top of the block.
446 // This can be tested by checking whether the instruction before this is
447 // either nonexistent (because this is begin()) or is a PHI node. If not,
448 // then there is some other instruction before a PHI.
449 Assert2(&PN.getParent()->front() == &PN || isa<PHINode>(PN.getPrev()),
450 "PHI nodes not grouped at top of basic block!",
451 &PN, PN.getParent());
453 // Check that all of the operands of the PHI node have the same type as the
455 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
456 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
457 "PHI node operands are not the same type as the result!", &PN);
459 // All other PHI node constraints are checked in the visitBasicBlock method.
461 visitInstruction(PN);
464 void Verifier::visitCallInst(CallInst &CI) {
465 Assert1(isa<PointerType>(CI.getOperand(0)->getType()),
466 "Called function must be a pointer!", &CI);
467 const PointerType *FPTy = cast<PointerType>(CI.getOperand(0)->getType());
468 Assert1(isa<FunctionType>(FPTy->getElementType()),
469 "Called function is not pointer to function type!", &CI);
471 const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
473 // Verify that the correct number of arguments are being passed
475 Assert1(CI.getNumOperands()-1 >= FTy->getNumParams(),
476 "Called function requires more parameters than were provided!",&CI);
478 Assert1(CI.getNumOperands()-1 == FTy->getNumParams(),
479 "Incorrect number of arguments passed to called function!", &CI);
481 // Verify that all arguments to the call match the function type...
482 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
483 Assert3(CI.getOperand(i+1)->getType() == FTy->getParamType(i),
484 "Call parameter type does not match function signature!",
485 CI.getOperand(i+1), FTy->getParamType(i), &CI);
487 if (Function *F = CI.getCalledFunction())
488 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
489 visitIntrinsicFunctionCall(ID, CI);
491 visitInstruction(CI);
494 /// visitBinaryOperator - Check that both arguments to the binary operator are
495 /// of the same type!
497 void Verifier::visitBinaryOperator(BinaryOperator &B) {
498 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
499 "Both operands to a binary operator are not of the same type!", &B);
501 // Check that logical operators are only used with integral operands.
502 if (B.getOpcode() == Instruction::And || B.getOpcode() == Instruction::Or ||
503 B.getOpcode() == Instruction::Xor) {
504 Assert1(B.getType()->isIntegral() ||
505 (isa<PackedType>(B.getType()) &&
506 cast<PackedType>(B.getType())->getElementType()->isIntegral()),
507 "Logical operators only work with integral types!", &B);
508 Assert1(B.getType() == B.getOperand(0)->getType(),
509 "Logical operators must have same type for operands and result!",
511 } else if (isa<SetCondInst>(B)) {
512 // Check that setcc instructions return bool
513 Assert1(B.getType() == Type::BoolTy,
514 "setcc instructions must return boolean values!", &B);
516 // Arithmetic operators only work on integer or fp values
517 Assert1(B.getType() == B.getOperand(0)->getType(),
518 "Arithmetic operators must have same type for operands and result!",
520 Assert1(B.getType()->isInteger() || B.getType()->isFloatingPoint() ||
521 isa<PackedType>(B.getType()),
522 "Arithmetic operators must have integer, fp, or packed type!", &B);
528 void Verifier::visitShiftInst(ShiftInst &SI) {
529 Assert1(SI.getType()->isInteger(),
530 "Shift must return an integer result!", &SI);
531 Assert1(SI.getType() == SI.getOperand(0)->getType(),
532 "Shift return type must be same as first operand!", &SI);
533 Assert1(SI.getOperand(1)->getType() == Type::UByteTy,
534 "Second operand to shift must be ubyte type!", &SI);
535 visitInstruction(SI);
538 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
539 Assert1(isa<PackedType>(EI.getOperand(0)->getType()),
540 "First operand to extractelement must be packed type!", &EI);
541 Assert1(EI.getOperand(1)->getType() == Type::UIntTy,
542 "Second operand to extractelement must be uint type!", &EI);
543 Assert1(EI.getType() ==
544 cast<PackedType>(EI.getOperand(0)->getType())->getElementType(),
545 "Extractelement return type must match "
546 "first operand element type!", &EI);
547 visitInstruction(EI);
550 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
551 Assert1(isa<PackedType>(IE.getOperand(0)->getType()),
552 "First operand to insertelement must be packed type!", &IE);
553 Assert1(IE.getOperand(1)->getType() ==
554 cast<PackedType>(IE.getOperand(0)->getType())->getElementType(),
555 "Second operand to insertelement must match "
556 "first operand element type!", &IE);
557 Assert1(IE.getOperand(2)->getType() == Type::UIntTy,
558 "Third operand to insertelement must be uint type!", &IE);
559 visitInstruction(IE);
562 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
564 GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
565 std::vector<Value*>(GEP.idx_begin(), GEP.idx_end()), true);
566 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
567 Assert2(PointerType::get(ElTy) == GEP.getType(),
568 "GEP is not of right type for indices!", &GEP, ElTy);
569 visitInstruction(GEP);
572 void Verifier::visitLoadInst(LoadInst &LI) {
574 cast<PointerType>(LI.getOperand(0)->getType())->getElementType();
575 Assert2(ElTy == LI.getType(),
576 "Load result type does not match pointer operand type!", &LI, ElTy);
577 visitInstruction(LI);
580 void Verifier::visitStoreInst(StoreInst &SI) {
582 cast<PointerType>(SI.getOperand(1)->getType())->getElementType();
583 Assert2(ElTy == SI.getOperand(0)->getType(),
584 "Stored value type does not match pointer operand type!", &SI, ElTy);
585 visitInstruction(SI);
589 /// verifyInstruction - Verify that an instruction is well formed.
591 void Verifier::visitInstruction(Instruction &I) {
592 BasicBlock *BB = I.getParent();
593 Assert1(BB, "Instruction not embedded in basic block!", &I);
595 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
596 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
598 Assert1(*UI != (User*)&I ||
599 !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
600 "Only PHI nodes may reference their own value!", &I);
603 // Check that void typed values don't have names
604 Assert1(I.getType() != Type::VoidTy || !I.hasName(),
605 "Instruction has a name, but provides a void value!", &I);
607 // Check that the return value of the instruction is either void or a legal
609 Assert1(I.getType() == Type::VoidTy || I.getType()->isFirstClassType(),
610 "Instruction returns a non-scalar type!", &I);
612 // Check that all uses of the instruction, if they are instructions
613 // themselves, actually have parent basic blocks. If the use is not an
614 // instruction, it is an error!
615 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
617 Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
619 Instruction *Used = cast<Instruction>(*UI);
620 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
621 " embeded in a basic block!", &I, Used);
624 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
625 // Check to make sure that the "address of" an intrinsic function is never
627 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
628 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
629 Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
630 "Cannot take the address of an intrinsic!", &I);
631 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
632 Assert1(OpBB->getParent() == BB->getParent(),
633 "Referring to a basic block in another function!", &I);
634 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
635 Assert1(OpArg->getParent() == BB->getParent(),
636 "Referring to an argument in another function!", &I);
637 } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
638 BasicBlock *OpBlock = Op->getParent();
640 // Check that a definition dominates all of its uses.
641 if (!isa<PHINode>(I)) {
642 // Invoke results are only usable in the normal destination, not in the
643 // exceptional destination.
644 if (InvokeInst *II = dyn_cast<InvokeInst>(Op))
645 OpBlock = II->getNormalDest();
646 else if (OpBlock == BB) {
647 // If they are in the same basic block, make sure that the definition
648 // comes before the use.
649 Assert2(InstsInThisBlock.count(Op) ||
650 !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
651 "Instruction does not dominate all uses!", Op, &I);
654 // Definition must dominate use unless use is unreachable!
655 Assert2(EF->dominates(OpBlock, BB) ||
656 !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
657 "Instruction does not dominate all uses!", Op, &I);
659 // PHI nodes are more difficult than other nodes because they actually
660 // "use" the value in the predecessor basic blocks they correspond to.
661 BasicBlock *PredBB = cast<BasicBlock>(I.getOperand(i+1));
662 Assert2(EF->dominates(OpBlock, PredBB) ||
663 !EF->dominates(&BB->getParent()->getEntryBlock(), PredBB),
664 "Instruction does not dominate all uses!", Op, &I);
668 InstsInThisBlock.insert(&I);
671 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
673 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
674 Function *IF = CI.getCalledFunction();
675 const FunctionType *FT = IF->getFunctionType();
676 Assert1(IF->isExternal(), "Intrinsic functions should never be defined!", IF);
677 unsigned NumArgs = 0;
679 // FIXME: this should check the return type of each intrinsic as well, also
682 case Intrinsic::vastart:
683 Assert1(CI.getParent()->getParent()->getFunctionType()->isVarArg(),
684 "llvm.va_start intrinsic may only occur in function with variable"
688 case Intrinsic::vaend: NumArgs = 1; break;
689 case Intrinsic::vacopy: NumArgs = 2; break;
691 case Intrinsic::returnaddress:
692 case Intrinsic::frameaddress:
693 Assert1(isa<PointerType>(FT->getReturnType()),
694 "llvm.(frame|return)address must return pointers", IF);
695 Assert1(FT->getNumParams() == 1 && isa<ConstantInt>(CI.getOperand(1)),
696 "llvm.(frame|return)address require a single constant integer argument",
701 // Verify that read and write port have integral parameters of the correct
703 case Intrinsic::writeport:
704 Assert1(FT->getNumParams() == 2,
705 "Illegal # arguments for intrinsic function!", IF);
706 Assert1(FT->getParamType(0)->isIntegral(),
707 "First argument not unsigned int!", IF);
708 Assert1(FT->getParamType(1)->isUnsigned(),
709 "First argument not unsigned int!", IF);
713 case Intrinsic::writeio:
714 Assert1(FT->getNumParams() == 2,
715 "Illegal # arguments for intrinsic function!", IF);
716 Assert1(FT->getParamType(0)->isFirstClassType(),
717 "First argument not a first class type!", IF);
718 Assert1(isa<PointerType>(FT->getParamType(1)),
719 "Second argument not a pointer!", IF);
723 case Intrinsic::readport:
724 Assert1(FT->getNumParams() == 1,
725 "Illegal # arguments for intrinsic function!", IF);
726 Assert1(FT->getReturnType()->isFirstClassType(),
727 "Return type is not a first class type!", IF);
728 Assert1(FT->getParamType(0)->isUnsigned(),
729 "First argument not unsigned int!", IF);
733 case Intrinsic::readio: {
734 const PointerType *ParamType = dyn_cast<PointerType>(FT->getParamType(0));
735 const Type *ReturnType = FT->getReturnType();
737 Assert1(FT->getNumParams() == 1,
738 "Illegal # arguments for intrinsic function!", IF);
739 Assert1(ParamType, "First argument not a pointer!", IF);
740 Assert1(ParamType->getElementType() == ReturnType,
741 "Pointer type doesn't match return type!", IF);
746 case Intrinsic::isunordered_f32:
747 Assert1(FT->getNumParams() == 2,
748 "Illegal # arguments for intrinsic function!", IF);
749 Assert1(FT->getReturnType() == Type::BoolTy,
750 "Return type is not bool!", IF);
751 Assert1(FT->getParamType(0) == FT->getParamType(1),
752 "Arguments must be of the same type!", IF);
753 Assert1(FT->getParamType(0) == Type::FloatTy,
754 "Arguments must be a 32-bit floating point type!", IF);
758 case Intrinsic::isunordered_f64:
759 Assert1(FT->getNumParams() == 2,
760 "Illegal # arguments for intrinsic function!", IF);
761 Assert1(FT->getReturnType() == Type::BoolTy,
762 "Return type is not bool!", IF);
763 Assert1(FT->getParamType(0) == FT->getParamType(1),
764 "Arguments must be of the same type!", IF);
765 Assert1(FT->getParamType(0) == Type::DoubleTy,
766 "Argument is not a 64-bit floating point type!", IF);
770 case Intrinsic::readcyclecounter:
771 Assert1(FT->getNumParams() == 0,
772 "Illegal # arguments for intrinsic function!", IF);
773 Assert1(FT->getReturnType() == Type::ULongTy,
774 "Return type is not ulong!", IF);
778 case Intrinsic::bswap_i16:
779 Assert1(FT->getNumParams() == 1,
780 "Illegal # arguments for intrinsic function!", IF);
781 Assert1(FT->getReturnType() == FT->getParamType(0),
782 "Return type does not match source type", IF);
783 Assert1(FT->getReturnType() == Type::UShortTy,
784 "Return type is not ushort!", IF);
788 case Intrinsic::bswap_i32:
789 Assert1(FT->getNumParams() == 1,
790 "Illegal # arguments for intrinsic function!", IF);
791 Assert1(FT->getReturnType() == FT->getParamType(0),
792 "Return type does not match source type", IF);
793 Assert1(FT->getReturnType() == Type::UIntTy,
794 "Return type is not uint!", IF);
798 case Intrinsic::bswap_i64:
799 Assert1(FT->getNumParams() == 1,
800 "Illegal # arguments for intrinsic function!", IF);
801 Assert1(FT->getReturnType() == FT->getParamType(0),
802 "Return type does not match source type", IF);
803 Assert1(FT->getReturnType() == Type::ULongTy,
804 "Return type is not ulong!", IF);
808 case Intrinsic::ctpop_i8:
809 Assert1(FT->getNumParams() == 1,
810 "Illegal # arguments for intrinsic function!", IF);
811 Assert1(FT->getReturnType() == FT->getParamType(0),
812 "Return type does not match source type", IF);
813 Assert1(FT->getParamType(0) == Type::UByteTy,
814 "Argument is not ubyte!", IF);
818 case Intrinsic::ctpop_i16:
819 Assert1(FT->getNumParams() == 1,
820 "Illegal # arguments for intrinsic function!", IF);
821 Assert1(FT->getReturnType() == FT->getParamType(0),
822 "Return type does not match source type", IF);
823 Assert1(FT->getParamType(0) == Type::UShortTy,
824 "Argument is not ushort!", IF);
828 case Intrinsic::ctpop_i32:
829 Assert1(FT->getNumParams() == 1,
830 "Illegal # arguments for intrinsic function!", IF);
831 Assert1(FT->getReturnType() == FT->getParamType(0),
832 "Return type does not match source type", IF);
833 Assert1(FT->getParamType(0) == Type::UIntTy, "Argument is not uint!", IF);
837 case Intrinsic::ctpop_i64:
838 Assert1(FT->getNumParams() == 1,
839 "Illegal # arguments for intrinsic function!", IF);
840 Assert1(FT->getReturnType() == FT->getParamType(0),
841 "Return type does not match source type", IF);
842 Assert1(FT->getParamType(0) == Type::ULongTy, "Argument is not ulong!", IF);
846 case Intrinsic::ctlz_i8:
847 Assert1(FT->getNumParams() == 1,
848 "Illegal # arguments for intrinsic function!", IF);
849 Assert1(FT->getReturnType() == FT->getParamType(0),
850 "Return type does not match source type", IF);
851 Assert1(FT->getParamType(0) == Type::UByteTy, "Argument is not ubyte!", IF);
855 case Intrinsic::ctlz_i16:
856 Assert1(FT->getNumParams() == 1,
857 "Illegal # arguments for intrinsic function!", IF);
858 Assert1(FT->getReturnType() == FT->getParamType(0),
859 "Return type does not match source type", IF);
860 Assert1(FT->getParamType(0) == Type::UShortTy,
861 "Argument is not ushort!", IF);
864 case Intrinsic::ctlz_i32:
865 Assert1(FT->getNumParams() == 1,
866 "Illegal # arguments for intrinsic function!", IF);
867 Assert1(FT->getReturnType() == FT->getParamType(0),
868 "Return type does not match source type", IF);
869 Assert1(FT->getParamType(0) == Type::UIntTy, "Argument is not uint!", IF);
872 case Intrinsic::ctlz_i64:
873 Assert1(FT->getNumParams() == 1,
874 "Illegal # arguments for intrinsic function!", IF);
875 Assert1(FT->getReturnType() == FT->getParamType(0),
876 "Return type does not match source type", IF);
877 Assert1(FT->getParamType(0) == Type::ULongTy, "Argument is not ulong!", IF);
880 case Intrinsic::cttz_i8:
881 Assert1(FT->getNumParams() == 1,
882 "Illegal # arguments for intrinsic function!", IF);
883 Assert1(FT->getReturnType() == FT->getParamType(0),
884 "Return type does not match source type", IF);
885 Assert1(FT->getParamType(0) == Type::UByteTy, "Argument is not ubyte!", IF);
888 case Intrinsic::cttz_i16:
889 Assert1(FT->getNumParams() == 1,
890 "Illegal # arguments for intrinsic function!", IF);
891 Assert1(FT->getReturnType() == FT->getParamType(0),
892 "Return type does not match source type", IF);
893 Assert1(FT->getParamType(0) == Type::UShortTy,
894 "Argument is not ushort!", IF);
897 case Intrinsic::cttz_i32:
898 Assert1(FT->getNumParams() == 1,
899 "Illegal # arguments for intrinsic function!", IF);
900 Assert1(FT->getReturnType() == FT->getParamType(0),
901 "Return type does not match source type", IF);
902 Assert1(FT->getParamType(0) == Type::UIntTy, "Argument is not uint!", IF);
905 case Intrinsic::cttz_i64:
906 Assert1(FT->getNumParams() == 1,
907 "Illegal # arguments for intrinsic function!", IF);
908 Assert1(FT->getReturnType() == FT->getParamType(0),
909 "Return type does not match source type", IF);
910 Assert1(FT->getParamType(0) == Type::ULongTy, "Argument Is not ulong!", IF);
914 case Intrinsic::sqrt_f32:
915 Assert1(FT->getNumParams() == 1,
916 "Illegal # arguments for intrinsic function!", IF);
917 Assert1(FT->getParamType(0) == Type::FloatTy,
918 "Argument is not a 32-bit floating point type!", IF);
919 Assert1(FT->getReturnType() == FT->getParamType(0),
920 "Return type is not the same as argument type!", IF);
924 case Intrinsic::sqrt_f64:
925 Assert1(FT->getNumParams() == 1,
926 "Illegal # arguments for intrinsic function!", IF);
927 Assert1(FT->getParamType(0) == Type::DoubleTy,
928 "Argument is not a 64-bit floating point type!", IF);
929 Assert1(FT->getReturnType() == FT->getParamType(0),
930 "Return type is not the same as argument type!", IF);
934 case Intrinsic::setjmp: NumArgs = 1; break;
935 case Intrinsic::longjmp: NumArgs = 2; break;
936 case Intrinsic::sigsetjmp: NumArgs = 2; break;
937 case Intrinsic::siglongjmp: NumArgs = 2; break;
939 case Intrinsic::gcroot:
940 Assert1(FT->getNumParams() == 2,
941 "Illegal # arguments for intrinsic function!", IF);
942 Assert1(isa<Constant>(CI.getOperand(2)),
943 "Second argument to llvm.gcroot must be a constant!", &CI);
946 case Intrinsic::gcread: NumArgs = 2; break;
947 case Intrinsic::gcwrite: NumArgs = 3; break;
949 case Intrinsic::dbg_stoppoint: NumArgs = 4; break;
950 case Intrinsic::dbg_region_start:NumArgs = 1; break;
951 case Intrinsic::dbg_region_end: NumArgs = 1; break;
952 case Intrinsic::dbg_func_start: NumArgs = 1; break;
953 case Intrinsic::dbg_declare: NumArgs = 1; break;
955 case Intrinsic::memcpy: NumArgs = 4; break;
956 case Intrinsic::memmove: NumArgs = 4; break;
957 case Intrinsic::memset: NumArgs = 4; break;
959 case Intrinsic::stacksave:
961 Assert1(CI.getType() == PointerType::get(Type::SByteTy),
962 "llvm.stacksave must return an sbyte*", &CI);
964 case Intrinsic::stackrestore:
966 Assert1(CI.getOperand(1)->getType() == PointerType::get(Type::SByteTy),
967 "llvm.stackrestore must take an sbyte*", &CI);
968 Assert1(CI.getType() == Type::VoidTy,
969 "llvm.stackrestore return void", &CI);
971 case Intrinsic::prefetch: NumArgs = 3; break;
972 case Intrinsic::pcmarker:
974 Assert1(isa<Constant>(CI.getOperand(1)),
975 "First argument to llvm.pcmarker must be a constant!", &CI);
978 case Intrinsic::not_intrinsic:
979 assert(0 && "Invalid intrinsic!"); NumArgs = 0; break;
982 Assert1(FT->getNumParams() == NumArgs || (FT->getNumParams() < NumArgs &&
984 "Illegal # arguments for intrinsic function!", IF);
988 //===----------------------------------------------------------------------===//
989 // Implement the public interfaces to this file...
990 //===----------------------------------------------------------------------===//
992 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
993 return new Verifier(action);
997 // verifyFunction - Create
998 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
999 Function &F = const_cast<Function&>(f);
1000 assert(!F.isExternal() && "Cannot verify external functions");
1002 FunctionPassManager FPM(new ExistingModuleProvider(F.getParent()));
1003 Verifier *V = new Verifier(action);
1009 /// verifyModule - Check a module for errors, printing messages on stderr.
1010 /// Return true if the module is corrupt.
1012 bool llvm::verifyModule(const Module &M, VerifierFailureAction action) {
1014 Verifier *V = new Verifier(action);