Use 'static const char' instead of 'static const int'.
[oota-llvm.git] / lib / VMCore / Verifier.cpp
1 //===-- Verifier.cpp - Implement the Module Verifier -------------*- C++ -*-==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the function verifier interface, that can be used for some
11 // sanity checking of input to the system.
12 //
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.
15 //
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...
39 //
40 //===----------------------------------------------------------------------===//
41
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/InlineAsm.h"
51 #include "llvm/Instructions.h"
52 #include "llvm/Intrinsics.h"
53 #include "llvm/PassManager.h"
54 #include "llvm/Analysis/Dominators.h"
55 #include "llvm/Support/CFG.h"
56 #include "llvm/Support/InstVisitor.h"
57 #include "llvm/Support/Streams.h"
58 #include "llvm/ADT/SmallPtrSet.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/StringExtras.h"
61 #include "llvm/ADT/STLExtras.h"
62 #include "llvm/Support/Compiler.h"
63 #include <algorithm>
64 #include <sstream>
65 #include <cstdarg>
66 using namespace llvm;
67
68 namespace {  // Anonymous namespace for class
69
70   struct VISIBILITY_HIDDEN
71      Verifier : public FunctionPass, InstVisitor<Verifier> {
72     static const char ID; // Pass ID, replacement for typeid
73     bool Broken;          // Is this module found to be broken?
74     bool RealPass;        // Are we not being run by a PassManager?
75     VerifierFailureAction action;
76                           // What to do if verification fails.
77     Module *Mod;          // Module we are verifying right now
78     ETForest *EF;     // ET-Forest, caution can be null!
79     std::stringstream msgs;  // A stringstream to collect messages
80
81     /// InstInThisBlock - when verifying a basic block, keep track of all of the
82     /// instructions we have seen so far.  This allows us to do efficient
83     /// dominance checks for the case when an instruction has an operand that is
84     /// an instruction in the same block.
85     SmallPtrSet<Instruction*, 16> InstsInThisBlock;
86
87     Verifier()
88       : FunctionPass((intptr_t)&ID), 
89       Broken(false), RealPass(true), action(AbortProcessAction),
90       EF(0), msgs( std::ios::app | std::ios::out ) {}
91     Verifier( VerifierFailureAction ctn )
92       : FunctionPass((intptr_t)&ID), 
93       Broken(false), RealPass(true), action(ctn), EF(0),
94       msgs( std::ios::app | std::ios::out ) {}
95     Verifier(bool AB )
96       : FunctionPass((intptr_t)&ID), 
97       Broken(false), RealPass(true),
98       action( AB ? AbortProcessAction : PrintMessageAction), EF(0),
99       msgs( std::ios::app | std::ios::out ) {}
100     Verifier(ETForest &ef)
101       : FunctionPass((intptr_t)&ID), 
102       Broken(false), RealPass(false), action(PrintMessageAction),
103       EF(&ef), msgs( std::ios::app | std::ios::out ) {}
104
105
106     bool doInitialization(Module &M) {
107       Mod = &M;
108       verifyTypeSymbolTable(M.getTypeSymbolTable());
109
110       // If this is a real pass, in a pass manager, we must abort before
111       // returning back to the pass manager, or else the pass manager may try to
112       // run other passes on the broken module.
113       if (RealPass)
114         return abortIfBroken();
115       return false;
116     }
117
118     bool runOnFunction(Function &F) {
119       // Get dominator information if we are being run by PassManager
120       if (RealPass) EF = &getAnalysis<ETForest>();
121
122       Mod = F.getParent();
123
124       visit(F);
125       InstsInThisBlock.clear();
126
127       // If this is a real pass, in a pass manager, we must abort before
128       // returning back to the pass manager, or else the pass manager may try to
129       // run other passes on the broken module.
130       if (RealPass)
131         return abortIfBroken();
132
133       return false;
134     }
135
136     bool doFinalization(Module &M) {
137       // Scan through, checking all of the external function's linkage now...
138       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
139         visitGlobalValue(*I);
140
141         // Check to make sure function prototypes are okay.
142         if (I->isDeclaration()) visitFunction(*I);
143       }
144
145       for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
146            I != E; ++I)
147         visitGlobalVariable(*I);
148
149       for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); 
150            I != E; ++I)
151         visitGlobalAlias(*I);
152
153       // If the module is broken, abort at this time.
154       return abortIfBroken();
155     }
156
157     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
158       AU.setPreservesAll();
159       if (RealPass)
160         AU.addRequired<ETForest>();
161     }
162
163     /// abortIfBroken - If the module is broken and we are supposed to abort on
164     /// this condition, do so.
165     ///
166     bool abortIfBroken() {
167       if (Broken) {
168         msgs << "Broken module found, ";
169         switch (action) {
170           case AbortProcessAction:
171             msgs << "compilation aborted!\n";
172             cerr << msgs.str();
173             abort();
174           case PrintMessageAction:
175             msgs << "verification continues.\n";
176             cerr << msgs.str();
177             return false;
178           case ReturnStatusAction:
179             msgs << "compilation terminated.\n";
180             return Broken;
181         }
182       }
183       return false;
184     }
185
186
187     // Verification methods...
188     void verifyTypeSymbolTable(TypeSymbolTable &ST);
189     void visitGlobalValue(GlobalValue &GV);
190     void visitGlobalVariable(GlobalVariable &GV);
191     void visitGlobalAlias(GlobalAlias &GA);
192     void visitFunction(Function &F);
193     void visitBasicBlock(BasicBlock &BB);
194     void visitTruncInst(TruncInst &I);
195     void visitZExtInst(ZExtInst &I);
196     void visitSExtInst(SExtInst &I);
197     void visitFPTruncInst(FPTruncInst &I);
198     void visitFPExtInst(FPExtInst &I);
199     void visitFPToUIInst(FPToUIInst &I);
200     void visitFPToSIInst(FPToSIInst &I);
201     void visitUIToFPInst(UIToFPInst &I);
202     void visitSIToFPInst(SIToFPInst &I);
203     void visitIntToPtrInst(IntToPtrInst &I);
204     void visitPtrToIntInst(PtrToIntInst &I);
205     void visitBitCastInst(BitCastInst &I);
206     void visitPHINode(PHINode &PN);
207     void visitBinaryOperator(BinaryOperator &B);
208     void visitICmpInst(ICmpInst &IC);
209     void visitFCmpInst(FCmpInst &FC);
210     void visitExtractElementInst(ExtractElementInst &EI);
211     void visitInsertElementInst(InsertElementInst &EI);
212     void visitShuffleVectorInst(ShuffleVectorInst &EI);
213     void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
214     void visitCallInst(CallInst &CI);
215     void visitGetElementPtrInst(GetElementPtrInst &GEP);
216     void visitLoadInst(LoadInst &LI);
217     void visitStoreInst(StoreInst &SI);
218     void visitInstruction(Instruction &I);
219     void visitTerminatorInst(TerminatorInst &I);
220     void visitReturnInst(ReturnInst &RI);
221     void visitSwitchInst(SwitchInst &SI);
222     void visitSelectInst(SelectInst &SI);
223     void visitUserOp1(Instruction &I);
224     void visitUserOp2(Instruction &I) { visitUserOp1(I); }
225     void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
226
227     void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F, ...);
228
229     void WriteValue(const Value *V) {
230       if (!V) return;
231       if (isa<Instruction>(V)) {
232         msgs << *V;
233       } else {
234         WriteAsOperand(msgs, V, true, Mod);
235         msgs << "\n";
236       }
237     }
238
239     void WriteType(const Type* T ) {
240       if ( !T ) return;
241       WriteTypeSymbolic(msgs, T, Mod );
242     }
243
244
245     // CheckFailed - A check failed, so print out the condition and the message
246     // that failed.  This provides a nice place to put a breakpoint if you want
247     // to see why something is not correct.
248     void CheckFailed(const std::string &Message,
249                      const Value *V1 = 0, const Value *V2 = 0,
250                      const Value *V3 = 0, const Value *V4 = 0) {
251       msgs << Message << "\n";
252       WriteValue(V1);
253       WriteValue(V2);
254       WriteValue(V3);
255       WriteValue(V4);
256       Broken = true;
257     }
258
259     void CheckFailed( const std::string& Message, const Value* V1,
260                       const Type* T2, const Value* V3 = 0 ) {
261       msgs << Message << "\n";
262       WriteValue(V1);
263       WriteType(T2);
264       WriteValue(V3);
265       Broken = true;
266     }
267   };
268
269   const char Verifier::ID = 0;
270   RegisterPass<Verifier> X("verify", "Module Verifier");
271 } // End anonymous namespace
272
273
274 // Assert - We know that cond should be true, if not print an error message.
275 #define Assert(C, M) \
276   do { if (!(C)) { CheckFailed(M); return; } } while (0)
277 #define Assert1(C, M, V1) \
278   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
279 #define Assert2(C, M, V1, V2) \
280   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
281 #define Assert3(C, M, V1, V2, V3) \
282   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
283 #define Assert4(C, M, V1, V2, V3, V4) \
284   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
285
286
287 void Verifier::visitGlobalValue(GlobalValue &GV) {
288   Assert1(!GV.isDeclaration() ||
289           GV.hasExternalLinkage() ||
290           GV.hasDLLImportLinkage() ||
291           GV.hasExternalWeakLinkage() ||
292           (isa<GlobalAlias>(GV) &&
293            (GV.hasInternalLinkage() || GV.hasWeakLinkage())),
294   "Global is external, but doesn't have external or dllimport or weak linkage!",
295           &GV);
296
297   Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
298           "Global is marked as dllimport, but not external", &GV);
299   
300   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
301           "Only global variables can have appending linkage!", &GV);
302
303   if (GV.hasAppendingLinkage()) {
304     GlobalVariable &GVar = cast<GlobalVariable>(GV);
305     Assert1(isa<ArrayType>(GVar.getType()->getElementType()),
306             "Only global arrays can have appending linkage!", &GV);
307   }
308 }
309
310 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
311   if (GV.hasInitializer())
312     Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
313             "Global variable initializer type does not match global "
314             "variable type!", &GV);
315
316   visitGlobalValue(GV);
317 }
318
319 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
320   Assert1(!GA.getName().empty(),
321           "Alias name cannot be empty!", &GA);
322   Assert1(GA.hasExternalLinkage() || GA.hasInternalLinkage() ||
323           GA.hasWeakLinkage(),
324           "Alias should have external or external weak linkage!", &GA);
325   Assert1(GA.getType() == GA.getAliasee()->getType(),
326           "Alias and aliasee types should match!", &GA);
327   
328   if (!isa<GlobalValue>(GA.getAliasee())) {
329     const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
330     Assert1(CE && CE->getOpcode() == Instruction::BitCast &&
331             isa<GlobalValue>(CE->getOperand(0)),
332             "Aliasee should be either GlobalValue or bitcast of GlobalValue",
333             &GA);
334   }
335   
336   visitGlobalValue(GA);
337 }
338
339 void Verifier::verifyTypeSymbolTable(TypeSymbolTable &ST) {
340 }
341
342 // visitFunction - Verify that a function is ok.
343 //
344 void Verifier::visitFunction(Function &F) {
345   // Check function arguments.
346   const FunctionType *FT = F.getFunctionType();
347   unsigned NumArgs = F.getArgumentList().size();
348
349   Assert2(FT->getNumParams() == NumArgs,
350           "# formal arguments must match # of arguments for function type!",
351           &F, FT);
352   Assert1(F.getReturnType()->isFirstClassType() ||
353           F.getReturnType() == Type::VoidTy,
354           "Functions cannot return aggregate values!", &F);
355
356   Assert1(!FT->isStructReturn() ||
357           (FT->getReturnType() == Type::VoidTy && 
358            FT->getNumParams() > 0 && isa<PointerType>(FT->getParamType(0))),
359           "Invalid struct-return function!", &F);
360
361   // Check that this function meets the restrictions on this calling convention.
362   switch (F.getCallingConv()) {
363   default:
364     break;
365   case CallingConv::C:
366     break;
367   case CallingConv::Fast:
368   case CallingConv::Cold:
369   case CallingConv::X86_FastCall:
370     Assert1(!F.isVarArg(),
371             "Varargs functions must have C calling conventions!", &F);
372     break;
373   }
374   
375   // Check that the argument values match the function type for this function...
376   unsigned i = 0;
377   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
378        I != E; ++I, ++i) {
379     Assert2(I->getType() == FT->getParamType(i),
380             "Argument value does not match function argument type!",
381             I, FT->getParamType(i));
382     // Make sure no aggregates are passed by value.
383     Assert1(I->getType()->isFirstClassType(),
384             "Functions cannot take aggregates as arguments by value!", I);
385    }
386
387   if (!F.isDeclaration()) {
388     // Verify that this function (which has a body) is not named "llvm.*".  It
389     // is not legal to define intrinsics.
390     if (F.getName().size() >= 5)
391       Assert1(F.getName().substr(0, 5) != "llvm.",
392               "llvm intrinsics cannot be defined!", &F);
393     
394     // Check the entry node
395     BasicBlock *Entry = &F.getEntryBlock();
396     Assert1(pred_begin(Entry) == pred_end(Entry),
397             "Entry block to function must not have predecessors!", Entry);
398   }
399 }
400
401
402 // verifyBasicBlock - Verify that a basic block is well formed...
403 //
404 void Verifier::visitBasicBlock(BasicBlock &BB) {
405   InstsInThisBlock.clear();
406
407   // Ensure that basic blocks have terminators!
408   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
409
410   // Check constraints that this basic block imposes on all of the PHI nodes in
411   // it.
412   if (isa<PHINode>(BB.front())) {
413     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
414     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
415     std::sort(Preds.begin(), Preds.end());
416     PHINode *PN;
417     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
418
419       // Ensure that PHI nodes have at least one entry!
420       Assert1(PN->getNumIncomingValues() != 0,
421               "PHI nodes must have at least one entry.  If the block is dead, "
422               "the PHI should be removed!", PN);
423       Assert1(PN->getNumIncomingValues() == Preds.size(),
424               "PHINode should have one entry for each predecessor of its "
425               "parent basic block!", PN);
426
427       // Get and sort all incoming values in the PHI node...
428       Values.clear();
429       Values.reserve(PN->getNumIncomingValues());
430       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
431         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
432                                         PN->getIncomingValue(i)));
433       std::sort(Values.begin(), Values.end());
434
435       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
436         // Check to make sure that if there is more than one entry for a
437         // particular basic block in this PHI node, that the incoming values are
438         // all identical.
439         //
440         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
441                 Values[i].second == Values[i-1].second,
442                 "PHI node has multiple entries for the same basic block with "
443                 "different incoming values!", PN, Values[i].first,
444                 Values[i].second, Values[i-1].second);
445
446         // Check to make sure that the predecessors and PHI node entries are
447         // matched up.
448         Assert3(Values[i].first == Preds[i],
449                 "PHI node entries do not match predecessors!", PN,
450                 Values[i].first, Preds[i]);
451       }
452     }
453   }
454 }
455
456 void Verifier::visitTerminatorInst(TerminatorInst &I) {
457   // Ensure that terminators only exist at the end of the basic block.
458   Assert1(&I == I.getParent()->getTerminator(),
459           "Terminator found in the middle of a basic block!", I.getParent());
460   visitInstruction(I);
461 }
462
463 void Verifier::visitReturnInst(ReturnInst &RI) {
464   Function *F = RI.getParent()->getParent();
465   if (RI.getNumOperands() == 0)
466     Assert2(F->getReturnType() == Type::VoidTy,
467             "Found return instr that returns void in Function of non-void "
468             "return type!", &RI, F->getReturnType());
469   else
470     Assert2(F->getReturnType() == RI.getOperand(0)->getType(),
471             "Function return type does not match operand "
472             "type of return inst!", &RI, F->getReturnType());
473
474   // Check to make sure that the return value has necessary properties for
475   // terminators...
476   visitTerminatorInst(RI);
477 }
478
479 void Verifier::visitSwitchInst(SwitchInst &SI) {
480   // Check to make sure that all of the constants in the switch instruction
481   // have the same type as the switched-on value.
482   const Type *SwitchTy = SI.getCondition()->getType();
483   for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i)
484     Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
485             "Switch constants must all be same type as switch value!", &SI);
486
487   visitTerminatorInst(SI);
488 }
489
490 void Verifier::visitSelectInst(SelectInst &SI) {
491   Assert1(SI.getCondition()->getType() == Type::Int1Ty,
492           "Select condition type must be bool!", &SI);
493   Assert1(SI.getTrueValue()->getType() == SI.getFalseValue()->getType(),
494           "Select values must have identical types!", &SI);
495   Assert1(SI.getTrueValue()->getType() == SI.getType(),
496           "Select values must have same type as select instruction!", &SI);
497   visitInstruction(SI);
498 }
499
500
501 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
502 /// a pass, if any exist, it's an error.
503 ///
504 void Verifier::visitUserOp1(Instruction &I) {
505   Assert1(0, "User-defined operators should not live outside of a pass!", &I);
506 }
507
508 void Verifier::visitTruncInst(TruncInst &I) {
509   // Get the source and destination types
510   const Type *SrcTy = I.getOperand(0)->getType();
511   const Type *DestTy = I.getType();
512
513   // Get the size of the types in bits, we'll need this later
514   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
515   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
516
517   Assert1(SrcTy->isInteger(), "Trunc only operates on integer", &I);
518   Assert1(DestTy->isInteger(), "Trunc only produces integer", &I);
519   Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
520
521   visitInstruction(I);
522 }
523
524 void Verifier::visitZExtInst(ZExtInst &I) {
525   // Get the source and destination types
526   const Type *SrcTy = I.getOperand(0)->getType();
527   const Type *DestTy = I.getType();
528
529   // Get the size of the types in bits, we'll need this later
530   Assert1(SrcTy->isInteger(), "ZExt only operates on integer", &I);
531   Assert1(DestTy->isInteger(), "ZExt only produces an integer", &I);
532   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
533   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
534
535   Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
536
537   visitInstruction(I);
538 }
539
540 void Verifier::visitSExtInst(SExtInst &I) {
541   // Get the source and destination types
542   const Type *SrcTy = I.getOperand(0)->getType();
543   const Type *DestTy = I.getType();
544
545   // Get the size of the types in bits, we'll need this later
546   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
547   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
548
549   Assert1(SrcTy->isInteger(), "SExt only operates on integer", &I);
550   Assert1(DestTy->isInteger(), "SExt only produces an integer", &I);
551   Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
552
553   visitInstruction(I);
554 }
555
556 void Verifier::visitFPTruncInst(FPTruncInst &I) {
557   // Get the source and destination types
558   const Type *SrcTy = I.getOperand(0)->getType();
559   const Type *DestTy = I.getType();
560   // Get the size of the types in bits, we'll need this later
561   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
562   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
563
564   Assert1(SrcTy->isFloatingPoint(),"FPTrunc only operates on FP", &I);
565   Assert1(DestTy->isFloatingPoint(),"FPTrunc only produces an FP", &I);
566   Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
567
568   visitInstruction(I);
569 }
570
571 void Verifier::visitFPExtInst(FPExtInst &I) {
572   // Get the source and destination types
573   const Type *SrcTy = I.getOperand(0)->getType();
574   const Type *DestTy = I.getType();
575
576   // Get the size of the types in bits, we'll need this later
577   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
578   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
579
580   Assert1(SrcTy->isFloatingPoint(),"FPExt only operates on FP", &I);
581   Assert1(DestTy->isFloatingPoint(),"FPExt only produces an FP", &I);
582   Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
583
584   visitInstruction(I);
585 }
586
587 void Verifier::visitUIToFPInst(UIToFPInst &I) {
588   // Get the source and destination types
589   const Type *SrcTy = I.getOperand(0)->getType();
590   const Type *DestTy = I.getType();
591
592   Assert1(SrcTy->isInteger(),"UInt2FP source must be integral", &I);
593   Assert1(DestTy->isFloatingPoint(),"UInt2FP result must be FP", &I);
594
595   visitInstruction(I);
596 }
597
598 void Verifier::visitSIToFPInst(SIToFPInst &I) {
599   // Get the source and destination types
600   const Type *SrcTy = I.getOperand(0)->getType();
601   const Type *DestTy = I.getType();
602
603   Assert1(SrcTy->isInteger(),"SInt2FP source must be integral", &I);
604   Assert1(DestTy->isFloatingPoint(),"SInt2FP result must be FP", &I);
605
606   visitInstruction(I);
607 }
608
609 void Verifier::visitFPToUIInst(FPToUIInst &I) {
610   // Get the source and destination types
611   const Type *SrcTy = I.getOperand(0)->getType();
612   const Type *DestTy = I.getType();
613
614   Assert1(SrcTy->isFloatingPoint(),"FP2UInt source must be FP", &I);
615   Assert1(DestTy->isInteger(),"FP2UInt result must be integral", &I);
616
617   visitInstruction(I);
618 }
619
620 void Verifier::visitFPToSIInst(FPToSIInst &I) {
621   // Get the source and destination types
622   const Type *SrcTy = I.getOperand(0)->getType();
623   const Type *DestTy = I.getType();
624
625   Assert1(SrcTy->isFloatingPoint(),"FPToSI source must be FP", &I);
626   Assert1(DestTy->isInteger(),"FP2ToI result must be integral", &I);
627
628   visitInstruction(I);
629 }
630
631 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
632   // Get the source and destination types
633   const Type *SrcTy = I.getOperand(0)->getType();
634   const Type *DestTy = I.getType();
635
636   Assert1(isa<PointerType>(SrcTy), "PtrToInt source must be pointer", &I);
637   Assert1(DestTy->isInteger(), "PtrToInt result must be integral", &I);
638
639   visitInstruction(I);
640 }
641
642 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
643   // Get the source and destination types
644   const Type *SrcTy = I.getOperand(0)->getType();
645   const Type *DestTy = I.getType();
646
647   Assert1(SrcTy->isInteger(), "IntToPtr source must be an integral", &I);
648   Assert1(isa<PointerType>(DestTy), "IntToPtr result must be a pointer",&I);
649
650   visitInstruction(I);
651 }
652
653 void Verifier::visitBitCastInst(BitCastInst &I) {
654   // Get the source and destination types
655   const Type *SrcTy = I.getOperand(0)->getType();
656   const Type *DestTy = I.getType();
657
658   // Get the size of the types in bits, we'll need this later
659   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
660   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
661
662   // BitCast implies a no-op cast of type only. No bits change.
663   // However, you can't cast pointers to anything but pointers.
664   Assert1(isa<PointerType>(DestTy) == isa<PointerType>(DestTy),
665           "Bitcast requires both operands to be pointer or neither", &I);
666   Assert1(SrcBitSize == DestBitSize, "Bitcast requies types of same width", &I);
667
668   visitInstruction(I);
669 }
670
671 /// visitPHINode - Ensure that a PHI node is well formed.
672 ///
673 void Verifier::visitPHINode(PHINode &PN) {
674   // Ensure that the PHI nodes are all grouped together at the top of the block.
675   // This can be tested by checking whether the instruction before this is
676   // either nonexistent (because this is begin()) or is a PHI node.  If not,
677   // then there is some other instruction before a PHI.
678   Assert2(&PN == &PN.getParent()->front() || 
679           isa<PHINode>(--BasicBlock::iterator(&PN)),
680           "PHI nodes not grouped at top of basic block!",
681           &PN, PN.getParent());
682
683   // Check that all of the operands of the PHI node have the same type as the
684   // result.
685   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
686     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
687             "PHI node operands are not the same type as the result!", &PN);
688
689   // All other PHI node constraints are checked in the visitBasicBlock method.
690
691   visitInstruction(PN);
692 }
693
694 void Verifier::visitCallInst(CallInst &CI) {
695   Assert1(isa<PointerType>(CI.getOperand(0)->getType()),
696           "Called function must be a pointer!", &CI);
697   const PointerType *FPTy = cast<PointerType>(CI.getOperand(0)->getType());
698   Assert1(isa<FunctionType>(FPTy->getElementType()),
699           "Called function is not pointer to function type!", &CI);
700
701   const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
702
703   // Verify that the correct number of arguments are being passed
704   if (FTy->isVarArg())
705     Assert1(CI.getNumOperands()-1 >= FTy->getNumParams(),
706             "Called function requires more parameters than were provided!",&CI);
707   else
708     Assert1(CI.getNumOperands()-1 == FTy->getNumParams(),
709             "Incorrect number of arguments passed to called function!", &CI);
710
711   // Verify that all arguments to the call match the function type...
712   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
713     Assert3(CI.getOperand(i+1)->getType() == FTy->getParamType(i),
714             "Call parameter type does not match function signature!",
715             CI.getOperand(i+1), FTy->getParamType(i), &CI);
716
717   if (Function *F = CI.getCalledFunction())
718     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
719       visitIntrinsicFunctionCall(ID, CI);
720
721   visitInstruction(CI);
722 }
723
724 /// visitBinaryOperator - Check that both arguments to the binary operator are
725 /// of the same type!
726 ///
727 void Verifier::visitBinaryOperator(BinaryOperator &B) {
728   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
729           "Both operands to a binary operator are not of the same type!", &B);
730
731   switch (B.getOpcode()) {
732   // Check that logical operators are only used with integral operands.
733   case Instruction::And:
734   case Instruction::Or:
735   case Instruction::Xor:
736     Assert1(B.getType()->isInteger() ||
737             (isa<VectorType>(B.getType()) && 
738              cast<VectorType>(B.getType())->getElementType()->isInteger()),
739             "Logical operators only work with integral types!", &B);
740     Assert1(B.getType() == B.getOperand(0)->getType(),
741             "Logical operators must have same type for operands and result!",
742             &B);
743     break;
744   case Instruction::Shl:
745   case Instruction::LShr:
746   case Instruction::AShr:
747     Assert1(B.getType()->isInteger(),
748             "Shift must return an integer result!", &B);
749     Assert1(B.getType() == B.getOperand(0)->getType(),
750             "Shift return type must be same as operands!", &B);
751     /* FALL THROUGH */
752   default:
753     // Arithmetic operators only work on integer or fp values
754     Assert1(B.getType() == B.getOperand(0)->getType(),
755             "Arithmetic operators must have same type for operands and result!",
756             &B);
757     Assert1(B.getType()->isInteger() || B.getType()->isFloatingPoint() ||
758             isa<VectorType>(B.getType()),
759             "Arithmetic operators must have integer, fp, or vector type!", &B);
760     break;
761   }
762
763   visitInstruction(B);
764 }
765
766 void Verifier::visitICmpInst(ICmpInst& IC) {
767   // Check that the operands are the same type
768   const Type* Op0Ty = IC.getOperand(0)->getType();
769   const Type* Op1Ty = IC.getOperand(1)->getType();
770   Assert1(Op0Ty == Op1Ty,
771           "Both operands to ICmp instruction are not of the same type!", &IC);
772   // Check that the operands are the right type
773   Assert1(Op0Ty->isInteger() || isa<PointerType>(Op0Ty),
774           "Invalid operand types for ICmp instruction", &IC);
775   visitInstruction(IC);
776 }
777
778 void Verifier::visitFCmpInst(FCmpInst& FC) {
779   // Check that the operands are the same type
780   const Type* Op0Ty = FC.getOperand(0)->getType();
781   const Type* Op1Ty = FC.getOperand(1)->getType();
782   Assert1(Op0Ty == Op1Ty,
783           "Both operands to FCmp instruction are not of the same type!", &FC);
784   // Check that the operands are the right type
785   Assert1(Op0Ty->isFloatingPoint(),
786           "Invalid operand types for FCmp instruction", &FC);
787   visitInstruction(FC);
788 }
789
790 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
791   Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
792                                               EI.getOperand(1)),
793           "Invalid extractelement operands!", &EI);
794   visitInstruction(EI);
795 }
796
797 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
798   Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
799                                              IE.getOperand(1),
800                                              IE.getOperand(2)),
801           "Invalid insertelement operands!", &IE);
802   visitInstruction(IE);
803 }
804
805 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
806   Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
807                                              SV.getOperand(2)),
808           "Invalid shufflevector operands!", &SV);
809   Assert1(SV.getType() == SV.getOperand(0)->getType(),
810           "Result of shufflevector must match first operand type!", &SV);
811   
812   // Check to see if Mask is valid.
813   if (const ConstantVector *MV = dyn_cast<ConstantVector>(SV.getOperand(2))) {
814     for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
815       Assert1(isa<ConstantInt>(MV->getOperand(i)) ||
816               isa<UndefValue>(MV->getOperand(i)),
817               "Invalid shufflevector shuffle mask!", &SV);
818     }
819   } else {
820     Assert1(isa<UndefValue>(SV.getOperand(2)) || 
821             isa<ConstantAggregateZero>(SV.getOperand(2)),
822             "Invalid shufflevector shuffle mask!", &SV);
823   }
824   
825   visitInstruction(SV);
826 }
827
828 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
829   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
830   const Type *ElTy =
831     GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
832                                       &Idxs[0], Idxs.size(), true);
833   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
834   Assert2(isa<PointerType>(GEP.getType()) &&
835           cast<PointerType>(GEP.getType())->getElementType() == ElTy,
836           "GEP is not of right type for indices!", &GEP, ElTy);
837   visitInstruction(GEP);
838 }
839
840 void Verifier::visitLoadInst(LoadInst &LI) {
841   const Type *ElTy =
842     cast<PointerType>(LI.getOperand(0)->getType())->getElementType();
843   Assert2(ElTy == LI.getType(),
844           "Load result type does not match pointer operand type!", &LI, ElTy);
845   visitInstruction(LI);
846 }
847
848 void Verifier::visitStoreInst(StoreInst &SI) {
849   const Type *ElTy =
850     cast<PointerType>(SI.getOperand(1)->getType())->getElementType();
851   Assert2(ElTy == SI.getOperand(0)->getType(),
852           "Stored value type does not match pointer operand type!", &SI, ElTy);
853   visitInstruction(SI);
854 }
855
856
857 /// verifyInstruction - Verify that an instruction is well formed.
858 ///
859 void Verifier::visitInstruction(Instruction &I) {
860   BasicBlock *BB = I.getParent();
861   Assert1(BB, "Instruction not embedded in basic block!", &I);
862
863   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
864     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
865          UI != UE; ++UI)
866       Assert1(*UI != (User*)&I ||
867               !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
868               "Only PHI nodes may reference their own value!", &I);
869   }
870
871   // Check that void typed values don't have names
872   Assert1(I.getType() != Type::VoidTy || !I.hasName(),
873           "Instruction has a name, but provides a void value!", &I);
874
875   // Check that the return value of the instruction is either void or a legal
876   // value type.
877   Assert1(I.getType() == Type::VoidTy || I.getType()->isFirstClassType(),
878           "Instruction returns a non-scalar type!", &I);
879
880   // Check that all uses of the instruction, if they are instructions
881   // themselves, actually have parent basic blocks.  If the use is not an
882   // instruction, it is an error!
883   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
884        UI != UE; ++UI) {
885     Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
886             *UI);
887     Instruction *Used = cast<Instruction>(*UI);
888     Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
889             " embeded in a basic block!", &I, Used);
890   }
891
892   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
893     Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
894
895     // Check to make sure that only first-class-values are operands to
896     // instructions.
897     Assert1(I.getOperand(i)->getType()->isFirstClassType(),
898             "Instruction operands must be first-class values!", &I);
899   
900     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
901       // Check to make sure that the "address of" an intrinsic function is never
902       // taken.
903       Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
904               "Cannot take the address of an intrinsic!", &I);
905       Assert1(F->getParent() == Mod, "Referencing function in another module!",
906               &I);
907     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
908       Assert1(OpBB->getParent() == BB->getParent(),
909               "Referring to a basic block in another function!", &I);
910     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
911       Assert1(OpArg->getParent() == BB->getParent(),
912               "Referring to an argument in another function!", &I);
913     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
914       Assert1(GV->getParent() == Mod, "Referencing global in another module!",
915               &I);
916     } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
917       BasicBlock *OpBlock = Op->getParent();
918
919       // Check that a definition dominates all of its uses.
920       if (!isa<PHINode>(I)) {
921         // Invoke results are only usable in the normal destination, not in the
922         // exceptional destination.
923         if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
924           OpBlock = II->getNormalDest();
925           
926           Assert2(OpBlock != II->getUnwindDest(),
927                   "No uses of invoke possible due to dominance structure!",
928                   Op, II);
929           
930           // If the normal successor of an invoke instruction has multiple
931           // predecessors, then the normal edge from the invoke is critical, so
932           // the invoke value can only be live if the destination block
933           // dominates all of it's predecessors (other than the invoke) or if
934           // the invoke value is only used by a phi in the successor.
935           if (!OpBlock->getSinglePredecessor() &&
936               EF->dominates(&BB->getParent()->getEntryBlock(), BB)) {
937             // The first case we allow is if the use is a PHI operand in the
938             // normal block, and if that PHI operand corresponds to the invoke's
939             // block.
940             bool Bad = true;
941             if (PHINode *PN = dyn_cast<PHINode>(&I))
942               if (PN->getParent() == OpBlock &&
943                   PN->getIncomingBlock(i/2) == Op->getParent())
944                 Bad = false;
945             
946             // If it is used by something non-phi, then the other case is that
947             // 'OpBlock' dominates all of its predecessors other than the
948             // invoke.  In this case, the invoke value can still be used.
949             if (Bad) {
950               Bad = false;
951               for (pred_iterator PI = pred_begin(OpBlock),
952                    E = pred_end(OpBlock); PI != E; ++PI) {
953                 if (*PI != II->getParent() && !EF->dominates(OpBlock, *PI)) {
954                   Bad = true;
955                   break;
956                 }
957               }
958             }
959             Assert2(!Bad,
960                     "Invoke value defined on critical edge but not dead!", &I,
961                     Op);
962           }
963         } else if (OpBlock == BB) {
964           // If they are in the same basic block, make sure that the definition
965           // comes before the use.
966           Assert2(InstsInThisBlock.count(Op) ||
967                   !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
968                   "Instruction does not dominate all uses!", Op, &I);
969         }
970
971         // Definition must dominate use unless use is unreachable!
972         Assert2(EF->dominates(OpBlock, BB) ||
973                 !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
974                 "Instruction does not dominate all uses!", Op, &I);
975       } else {
976         // PHI nodes are more difficult than other nodes because they actually
977         // "use" the value in the predecessor basic blocks they correspond to.
978         BasicBlock *PredBB = cast<BasicBlock>(I.getOperand(i+1));
979         Assert2(EF->dominates(OpBlock, PredBB) ||
980                 !EF->dominates(&BB->getParent()->getEntryBlock(), PredBB),
981                 "Instruction does not dominate all uses!", Op, &I);
982       }
983     } else if (isa<InlineAsm>(I.getOperand(i))) {
984       Assert1(i == 0 && isa<CallInst>(I),
985               "Cannot take the address of an inline asm!", &I);
986     }
987   }
988   InstsInThisBlock.insert(&I);
989 }
990
991 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
992 ///
993 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
994   Function *IF = CI.getCalledFunction();
995   Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
996           IF);
997   
998 #define GET_INTRINSIC_VERIFIER
999 #include "llvm/Intrinsics.gen"
1000 #undef GET_INTRINSIC_VERIFIER
1001 }
1002
1003 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
1004 /// Intrinsics.gen.  This implements a little state machine that verifies the
1005 /// prototype of intrinsics.
1006 void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F, ...) {
1007   va_list VA;
1008   va_start(VA, F);
1009   
1010   const FunctionType *FTy = F->getFunctionType();
1011   
1012   // For overloaded intrinsics, the Suffix of the function name must match the
1013   // types of the arguments. This variable keeps track of the expected
1014   // suffix, to be checked at the end.
1015   std::string Suffix;
1016
1017   // Note that "arg#0" is the return type.
1018   for (unsigned ArgNo = 0; 1; ++ArgNo) {
1019     int TypeID = va_arg(VA, int);
1020
1021     if (TypeID == -2) {
1022       break;
1023     }
1024
1025     if (TypeID == -1) {
1026       if (ArgNo != FTy->getNumParams()+1)
1027         CheckFailed("Intrinsic prototype has too many arguments!", F);
1028       break;
1029     }
1030
1031     if (ArgNo == FTy->getNumParams()+1) {
1032       CheckFailed("Intrinsic prototype has too few arguments!", F);
1033       break;
1034     }
1035     
1036     const Type *Ty;
1037     if (ArgNo == 0)
1038       Ty = FTy->getReturnType();
1039     else
1040       Ty = FTy->getParamType(ArgNo-1);
1041     
1042     if (TypeID != Ty->getTypeID()) {
1043       if (ArgNo == 0)
1044         CheckFailed("Intrinsic prototype has incorrect result type!", F);
1045       else
1046         CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is wrong!",F);
1047       break;
1048     }
1049
1050     if (TypeID == Type::IntegerTyID) {
1051       unsigned ExpectedBits = (unsigned) va_arg(VA, int);
1052       unsigned GotBits = cast<IntegerType>(Ty)->getBitWidth();
1053       if (ExpectedBits == 0) {
1054         Suffix += ".i" + utostr(GotBits);
1055       } else if (GotBits != ExpectedBits) {
1056         std::string bitmsg = " Expected " + utostr(ExpectedBits) + " but got "+
1057                              utostr(GotBits) + " bits.";
1058         if (ArgNo == 0)
1059           CheckFailed("Intrinsic prototype has incorrect integer result width!"
1060                       + bitmsg, F);
1061         else
1062           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " has "
1063                       "incorrect integer width!" + bitmsg, F);
1064         break;
1065       }
1066       // Check some constraints on various intrinsics.
1067       switch (ID) {
1068         default: break; // Not everything needs to be checked.
1069         case Intrinsic::bswap:
1070           if (GotBits < 16 || GotBits % 16 != 0)
1071             CheckFailed("Intrinsic requires even byte width argument", F);
1072           /* FALL THROUGH */
1073         case Intrinsic::part_set:
1074         case Intrinsic::part_select:
1075           if (ArgNo == 1) {
1076             unsigned ResultBits = 
1077               cast<IntegerType>(FTy->getReturnType())->getBitWidth();
1078             if (GotBits != ResultBits)
1079               CheckFailed("Intrinsic requires the bit widths of the first "
1080                           "parameter and the result to match", F);
1081           }
1082           break;
1083       }
1084     } else if (TypeID == Type::VectorTyID) {
1085       // If this is a packed argument, verify the number and type of elements.
1086       const VectorType *PTy = cast<VectorType>(Ty);
1087       int ElemTy = va_arg(VA, int);
1088       if (ElemTy != PTy->getElementType()->getTypeID()) {
1089         CheckFailed("Intrinsic prototype has incorrect vector element type!",
1090                     F);
1091         break;
1092       }
1093       if (ElemTy == Type::IntegerTyID) {
1094         unsigned NumBits = (unsigned)va_arg(VA, int);
1095         unsigned ExpectedBits = 
1096           cast<IntegerType>(PTy->getElementType())->getBitWidth();
1097         if (NumBits != ExpectedBits) {
1098           CheckFailed("Intrinsic prototype has incorrect vector element type!",
1099                       F);
1100           break;
1101         }
1102       }
1103       if ((unsigned)va_arg(VA, int) != PTy->getNumElements()) {
1104         CheckFailed("Intrinsic prototype has incorrect number of "
1105                     "vector elements!",F);
1106           break;
1107       }
1108     }
1109   }
1110
1111   va_end(VA);
1112
1113   // If we computed a Suffix then the intrinsic is overloaded and we need to 
1114   // make sure that the name of the function is correct. We add the suffix to
1115   // the name of the intrinsic and compare against the given function name. If
1116   // they are not the same, the function name is invalid. This ensures that
1117   // overloading of intrinsics uses a sane and consistent naming convention.
1118   if (!Suffix.empty()) {
1119     std::string Name(Intrinsic::getName(ID));
1120     if (Name + Suffix != F->getName())
1121       CheckFailed("Overloaded intrinsic has incorrect suffix: '" +
1122                   F->getName().substr(Name.length()) + "'. It should be '" +
1123                   Suffix + "'", F);
1124   }
1125 }
1126
1127
1128 //===----------------------------------------------------------------------===//
1129 //  Implement the public interfaces to this file...
1130 //===----------------------------------------------------------------------===//
1131
1132 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1133   return new Verifier(action);
1134 }
1135
1136
1137 // verifyFunction - Create
1138 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1139   Function &F = const_cast<Function&>(f);
1140   assert(!F.isDeclaration() && "Cannot verify external functions");
1141
1142   FunctionPassManager FPM(new ExistingModuleProvider(F.getParent()));
1143   Verifier *V = new Verifier(action);
1144   FPM.add(V);
1145   FPM.run(F);
1146   return V->Broken;
1147 }
1148
1149 /// verifyModule - Check a module for errors, printing messages on stderr.
1150 /// Return true if the module is corrupt.
1151 ///
1152 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
1153                         std::string *ErrorInfo) {
1154   PassManager PM;
1155   Verifier *V = new Verifier(action);
1156   PM.add(V);
1157   PM.run((Module&)M);
1158   
1159   if (ErrorInfo && V->Broken)
1160     *ErrorInfo = V->msgs.str();
1161   return V->Broken;
1162 }
1163
1164 // vim: sw=2