Handle the removal of the debug chain.
[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/SymbolTable.h"
55 #include "llvm/Analysis/Dominators.h"
56 #include "llvm/Support/CFG.h"
57 #include "llvm/Support/InstVisitor.h"
58 #include "llvm/ADT/STLExtras.h"
59 #include <algorithm>
60 #include <iostream>
61 #include <sstream>
62 using namespace llvm;
63
64 namespace {  // Anonymous namespace for class
65
66   struct Verifier : public FunctionPass, InstVisitor<Verifier> {
67     bool Broken;          // Is this module found to be broken?
68     bool RealPass;        // Are we not being run by a PassManager?
69     VerifierFailureAction action;
70                           // What to do if verification fails.
71     Module *Mod;          // Module we are verifying right now
72     ETForest *EF;     // ET-Forest, caution can be null!
73     std::stringstream msgs;  // A stringstream to collect messages
74
75     /// InstInThisBlock - when verifying a basic block, keep track of all of the
76     /// instructions we have seen so far.  This allows us to do efficient
77     /// dominance checks for the case when an instruction has an operand that is
78     /// an instruction in the same block.
79     std::set<Instruction*> InstsInThisBlock;
80
81     Verifier()
82         : Broken(false), RealPass(true), action(AbortProcessAction),
83           EF(0), msgs( std::ios::app | std::ios::out ) {}
84     Verifier( VerifierFailureAction ctn )
85         : Broken(false), RealPass(true), action(ctn), EF(0),
86           msgs( std::ios::app | std::ios::out ) {}
87     Verifier(bool AB )
88         : Broken(false), RealPass(true),
89           action( AB ? AbortProcessAction : PrintMessageAction), EF(0),
90           msgs( std::ios::app | std::ios::out ) {}
91     Verifier(ETForest &ef)
92       : Broken(false), RealPass(false), action(PrintMessageAction),
93         EF(&ef), msgs( std::ios::app | std::ios::out ) {}
94
95
96     bool doInitialization(Module &M) {
97       Mod = &M;
98       verifySymbolTable(M.getSymbolTable());
99
100       // If this is a real pass, in a pass manager, we must abort before
101       // returning back to the pass manager, or else the pass manager may try to
102       // run other passes on the broken module.
103       if (RealPass)
104         abortIfBroken();
105       return false;
106     }
107
108     bool runOnFunction(Function &F) {
109       // Get dominator information if we are being run by PassManager
110       if (RealPass) EF = &getAnalysis<ETForest>();
111       visit(F);
112       InstsInThisBlock.clear();
113
114       // If this is a real pass, in a pass manager, we must abort before
115       // returning back to the pass manager, or else the pass manager may try to
116       // run other passes on the broken module.
117       if (RealPass)
118         abortIfBroken();
119
120       return false;
121     }
122
123     bool doFinalization(Module &M) {
124       // Scan through, checking all of the external function's linkage now...
125       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
126         visitGlobalValue(*I);
127
128         // Check to make sure function prototypes are okay.
129         if (I->isExternal()) visitFunction(*I);
130       }
131
132       for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
133            I != E; ++I)
134         visitGlobalVariable(*I);
135
136       // If the module is broken, abort at this time.
137       abortIfBroken();
138       return false;
139     }
140
141     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
142       AU.setPreservesAll();
143       if (RealPass)
144         AU.addRequired<ETForest>();
145     }
146
147     /// abortIfBroken - If the module is broken and we are supposed to abort on
148     /// this condition, do so.
149     ///
150     void abortIfBroken() {
151       if (Broken)
152       {
153         msgs << "Broken module found, ";
154         switch (action)
155         {
156           case AbortProcessAction:
157             msgs << "compilation aborted!\n";
158             std::cerr << msgs.str();
159             abort();
160           case ThrowExceptionAction:
161             msgs << "verification terminated.\n";
162             throw msgs.str();
163           case PrintMessageAction:
164             msgs << "verification continues.\n";
165             std::cerr << msgs.str();
166             break;
167           case ReturnStatusAction:
168             break;
169         }
170       }
171     }
172
173
174     // Verification methods...
175     void verifySymbolTable(SymbolTable &ST);
176     void visitGlobalValue(GlobalValue &GV);
177     void visitGlobalVariable(GlobalVariable &GV);
178     void visitFunction(Function &F);
179     void visitBasicBlock(BasicBlock &BB);
180     void visitPHINode(PHINode &PN);
181     void visitBinaryOperator(BinaryOperator &B);
182     void visitShiftInst(ShiftInst &SI);
183     void visitExtractElementInst(ExtractElementInst &EI);
184     void visitInsertElementInst(InsertElementInst &EI);
185     void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
186     void visitCallInst(CallInst &CI);
187     void visitGetElementPtrInst(GetElementPtrInst &GEP);
188     void visitLoadInst(LoadInst &LI);
189     void visitStoreInst(StoreInst &SI);
190     void visitInstruction(Instruction &I);
191     void visitTerminatorInst(TerminatorInst &I);
192     void visitReturnInst(ReturnInst &RI);
193     void visitSwitchInst(SwitchInst &SI);
194     void visitSelectInst(SelectInst &SI);
195     void visitUserOp1(Instruction &I);
196     void visitUserOp2(Instruction &I) { visitUserOp1(I); }
197     void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
198
199
200     void WriteValue(const Value *V) {
201       if (!V) return;
202       if (isa<Instruction>(V)) {
203         msgs << *V;
204       } else {
205         WriteAsOperand (msgs, V, true, true, Mod);
206         msgs << "\n";
207       }
208     }
209
210     void WriteType(const Type* T ) {
211       if ( !T ) return;
212       WriteTypeSymbolic(msgs, T, Mod );
213     }
214
215
216     // CheckFailed - A check failed, so print out the condition and the message
217     // that failed.  This provides a nice place to put a breakpoint if you want
218     // to see why something is not correct.
219     void CheckFailed(const std::string &Message,
220                      const Value *V1 = 0, const Value *V2 = 0,
221                      const Value *V3 = 0, const Value *V4 = 0) {
222       msgs << Message << "\n";
223       WriteValue(V1);
224       WriteValue(V2);
225       WriteValue(V3);
226       WriteValue(V4);
227       Broken = true;
228     }
229
230     void CheckFailed( const std::string& Message, const Value* V1,
231                       const Type* T2, const Value* V3 = 0 ) {
232       msgs << Message << "\n";
233       WriteValue(V1);
234       WriteType(T2);
235       WriteValue(V3);
236       Broken = true;
237     }
238   };
239
240   RegisterOpt<Verifier> X("verify", "Module Verifier");
241 } // End anonymous namespace
242
243
244 // Assert - We know that cond should be true, if not print an error message.
245 #define Assert(C, M) \
246   do { if (!(C)) { CheckFailed(M); return; } } while (0)
247 #define Assert1(C, M, V1) \
248   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
249 #define Assert2(C, M, V1, V2) \
250   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
251 #define Assert3(C, M, V1, V2, V3) \
252   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
253 #define Assert4(C, M, V1, V2, V3, V4) \
254   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
255
256
257 void Verifier::visitGlobalValue(GlobalValue &GV) {
258   Assert1(!GV.isExternal() || GV.hasExternalLinkage(),
259           "Global is external, but doesn't have external linkage!", &GV);
260   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
261           "Only global variables can have appending linkage!", &GV);
262
263   if (GV.hasAppendingLinkage()) {
264     GlobalVariable &GVar = cast<GlobalVariable>(GV);
265     Assert1(isa<ArrayType>(GVar.getType()->getElementType()),
266             "Only global arrays can have appending linkage!", &GV);
267   }
268 }
269
270 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
271   if (GV.hasInitializer())
272     Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
273             "Global variable initializer type does not match global "
274             "variable type!", &GV);
275
276   visitGlobalValue(GV);
277 }
278
279
280 // verifySymbolTable - Verify that a function or module symbol table is ok
281 //
282 void Verifier::verifySymbolTable(SymbolTable &ST) {
283
284   // Loop over all of the values in all type planes in the symbol table.
285   for (SymbolTable::plane_const_iterator PI = ST.plane_begin(),
286        PE = ST.plane_end(); PI != PE; ++PI)
287     for (SymbolTable::value_const_iterator VI = PI->second.begin(),
288          VE = PI->second.end(); VI != VE; ++VI) {
289       Value *V = VI->second;
290       // Check that there are no void typed values in the symbol table.  Values
291       // with a void type cannot be put into symbol tables because they cannot
292       // have names!
293       Assert1(V->getType() != Type::VoidTy,
294         "Values with void type are not allowed to have names!", V);
295     }
296 }
297
298 // visitFunction - Verify that a function is ok.
299 //
300 void Verifier::visitFunction(Function &F) {
301   Assert1(!F.isVarArg() || F.getCallingConv() == CallingConv::C,
302           "Varargs functions must have C calling conventions!", &F);
303
304   // Check function arguments.
305   const FunctionType *FT = F.getFunctionType();
306   unsigned NumArgs = F.getArgumentList().size();
307
308   Assert2(FT->getNumParams() == NumArgs,
309           "# formal arguments must match # of arguments for function type!",
310           &F, FT);
311   Assert1(F.getReturnType()->isFirstClassType() ||
312           F.getReturnType() == Type::VoidTy,
313           "Functions cannot return aggregate values!", &F);
314
315   // Check that the argument values match the function type for this function...
316   unsigned i = 0;
317   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I, ++i) {
318     Assert2(I->getType() == FT->getParamType(i),
319             "Argument value does not match function argument type!",
320             I, FT->getParamType(i));
321     // Make sure no aggregates are passed by value.
322     Assert1(I->getType()->isFirstClassType(),
323             "Functions cannot take aggregates as arguments by value!", I);
324    }
325
326   if (!F.isExternal()) {
327     verifySymbolTable(F.getSymbolTable());
328
329     // Check the entry node
330     BasicBlock *Entry = &F.getEntryBlock();
331     Assert1(pred_begin(Entry) == pred_end(Entry),
332             "Entry block to function must not have predecessors!", Entry);
333   }
334 }
335
336
337 // verifyBasicBlock - Verify that a basic block is well formed...
338 //
339 void Verifier::visitBasicBlock(BasicBlock &BB) {
340   InstsInThisBlock.clear();
341
342   // Ensure that basic blocks have terminators!
343   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
344
345   // Check constraints that this basic block imposes on all of the PHI nodes in
346   // it.
347   if (isa<PHINode>(BB.front())) {
348     std::vector<BasicBlock*> Preds(pred_begin(&BB), pred_end(&BB));
349     std::sort(Preds.begin(), Preds.end());
350     PHINode *PN;
351     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
352
353       // Ensure that PHI nodes have at least one entry!
354       Assert1(PN->getNumIncomingValues() != 0,
355               "PHI nodes must have at least one entry.  If the block is dead, "
356               "the PHI should be removed!", PN);
357       Assert1(PN->getNumIncomingValues() == Preds.size(),
358               "PHINode should have one entry for each predecessor of its "
359               "parent basic block!", PN);
360
361       // Get and sort all incoming values in the PHI node...
362       std::vector<std::pair<BasicBlock*, Value*> > Values;
363       Values.reserve(PN->getNumIncomingValues());
364       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
365         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
366                                         PN->getIncomingValue(i)));
367       std::sort(Values.begin(), Values.end());
368
369       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
370         // Check to make sure that if there is more than one entry for a
371         // particular basic block in this PHI node, that the incoming values are
372         // all identical.
373         //
374         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
375                 Values[i].second == Values[i-1].second,
376                 "PHI node has multiple entries for the same basic block with "
377                 "different incoming values!", PN, Values[i].first,
378                 Values[i].second, Values[i-1].second);
379
380         // Check to make sure that the predecessors and PHI node entries are
381         // matched up.
382         Assert3(Values[i].first == Preds[i],
383                 "PHI node entries do not match predecessors!", PN,
384                 Values[i].first, Preds[i]);
385       }
386     }
387   }
388 }
389
390 void Verifier::visitTerminatorInst(TerminatorInst &I) {
391   // Ensure that terminators only exist at the end of the basic block.
392   Assert1(&I == I.getParent()->getTerminator(),
393           "Terminator found in the middle of a basic block!", I.getParent());
394   visitInstruction(I);
395 }
396
397 void Verifier::visitReturnInst(ReturnInst &RI) {
398   Function *F = RI.getParent()->getParent();
399   if (RI.getNumOperands() == 0)
400     Assert2(F->getReturnType() == Type::VoidTy,
401             "Found return instr that returns void in Function of non-void "
402             "return type!", &RI, F->getReturnType());
403   else
404     Assert2(F->getReturnType() == RI.getOperand(0)->getType(),
405             "Function return type does not match operand "
406             "type of return inst!", &RI, F->getReturnType());
407
408   // Check to make sure that the return value has necessary properties for
409   // terminators...
410   visitTerminatorInst(RI);
411 }
412
413 void Verifier::visitSwitchInst(SwitchInst &SI) {
414   // Check to make sure that all of the constants in the switch instruction
415   // have the same type as the switched-on value.
416   const Type *SwitchTy = SI.getCondition()->getType();
417   for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i)
418     Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
419             "Switch constants must all be same type as switch value!", &SI);
420
421   visitTerminatorInst(SI);
422 }
423
424 void Verifier::visitSelectInst(SelectInst &SI) {
425   Assert1(SI.getCondition()->getType() == Type::BoolTy,
426           "Select condition type must be bool!", &SI);
427   Assert1(SI.getTrueValue()->getType() == SI.getFalseValue()->getType(),
428           "Select values must have identical types!", &SI);
429   Assert1(SI.getTrueValue()->getType() == SI.getType(),
430           "Select values must have same type as select instruction!", &SI);
431   visitInstruction(SI);
432 }
433
434
435 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
436 /// a pass, if any exist, it's an error.
437 ///
438 void Verifier::visitUserOp1(Instruction &I) {
439   Assert1(0, "User-defined operators should not live outside of a pass!",
440           &I);
441 }
442
443 /// visitPHINode - Ensure that a PHI node is well formed.
444 ///
445 void Verifier::visitPHINode(PHINode &PN) {
446   // Ensure that the PHI nodes are all grouped together at the top of the block.
447   // This can be tested by checking whether the instruction before this is
448   // either nonexistent (because this is begin()) or is a PHI node.  If not,
449   // then there is some other instruction before a PHI.
450   Assert2(&PN.getParent()->front() == &PN || isa<PHINode>(PN.getPrev()),
451           "PHI nodes not grouped at top of basic block!",
452           &PN, PN.getParent());
453
454   // Check that all of the operands of the PHI node have the same type as the
455   // result.
456   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
457     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
458             "PHI node operands are not the same type as the result!", &PN);
459
460   // All other PHI node constraints are checked in the visitBasicBlock method.
461
462   visitInstruction(PN);
463 }
464
465 void Verifier::visitCallInst(CallInst &CI) {
466   Assert1(isa<PointerType>(CI.getOperand(0)->getType()),
467           "Called function must be a pointer!", &CI);
468   const PointerType *FPTy = cast<PointerType>(CI.getOperand(0)->getType());
469   Assert1(isa<FunctionType>(FPTy->getElementType()),
470           "Called function is not pointer to function type!", &CI);
471
472   const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
473
474   // Verify that the correct number of arguments are being passed
475   if (FTy->isVarArg())
476     Assert1(CI.getNumOperands()-1 >= FTy->getNumParams(),
477             "Called function requires more parameters than were provided!",&CI);
478   else
479     Assert1(CI.getNumOperands()-1 == FTy->getNumParams(),
480             "Incorrect number of arguments passed to called function!", &CI);
481
482   // Verify that all arguments to the call match the function type...
483   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
484     Assert3(CI.getOperand(i+1)->getType() == FTy->getParamType(i),
485             "Call parameter type does not match function signature!",
486             CI.getOperand(i+1), FTy->getParamType(i), &CI);
487
488   if (Function *F = CI.getCalledFunction())
489     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
490       visitIntrinsicFunctionCall(ID, CI);
491
492   visitInstruction(CI);
493 }
494
495 /// visitBinaryOperator - Check that both arguments to the binary operator are
496 /// of the same type!
497 ///
498 void Verifier::visitBinaryOperator(BinaryOperator &B) {
499   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
500           "Both operands to a binary operator are not of the same type!", &B);
501
502   // Check that logical operators are only used with integral operands.
503   if (B.getOpcode() == Instruction::And || B.getOpcode() == Instruction::Or ||
504       B.getOpcode() == Instruction::Xor) {
505     Assert1(B.getType()->isIntegral() ||
506             (isa<PackedType>(B.getType()) && 
507              cast<PackedType>(B.getType())->getElementType()->isIntegral()),
508             "Logical operators only work with integral types!", &B);
509     Assert1(B.getType() == B.getOperand(0)->getType(),
510             "Logical operators must have same type for operands and result!",
511             &B);
512   } else if (isa<SetCondInst>(B)) {
513     // Check that setcc instructions return bool
514     Assert1(B.getType() == Type::BoolTy,
515             "setcc instructions must return boolean values!", &B);
516   } else {
517     // Arithmetic operators only work on integer or fp values
518     Assert1(B.getType() == B.getOperand(0)->getType(),
519             "Arithmetic operators must have same type for operands and result!",
520             &B);
521     Assert1(B.getType()->isInteger() || B.getType()->isFloatingPoint() ||
522             isa<PackedType>(B.getType()),
523             "Arithmetic operators must have integer, fp, or packed type!", &B);
524   }
525
526   visitInstruction(B);
527 }
528
529 void Verifier::visitShiftInst(ShiftInst &SI) {
530   Assert1(SI.getType()->isInteger(),
531           "Shift must return an integer result!", &SI);
532   Assert1(SI.getType() == SI.getOperand(0)->getType(),
533           "Shift return type must be same as first operand!", &SI);
534   Assert1(SI.getOperand(1)->getType() == Type::UByteTy,
535           "Second operand to shift must be ubyte type!", &SI);
536   visitInstruction(SI);
537 }
538
539 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
540   Assert1(isa<PackedType>(EI.getOperand(0)->getType()),
541           "First operand to extractelement must be packed type!", &EI);
542   Assert1(EI.getOperand(1)->getType() == Type::UIntTy,
543           "Second operand to extractelement must be uint type!", &EI);
544   Assert1(EI.getType() == 
545           cast<PackedType>(EI.getOperand(0)->getType())->getElementType(),
546           "Extractelement return type must match "
547           "first operand element type!", &EI);
548   visitInstruction(EI);
549 }
550
551 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
552   Assert1(isa<PackedType>(IE.getOperand(0)->getType()),
553           "First operand to insertelement must be packed type!", &IE);
554   Assert1(IE.getOperand(1)->getType() == 
555           cast<PackedType>(IE.getOperand(0)->getType())->getElementType(),
556           "Second operand to insertelement must match "
557           "first operand element type!", &IE);
558   Assert1(IE.getOperand(2)->getType() == Type::UIntTy,
559           "Third operand to insertelement must be uint type!", &IE);
560   visitInstruction(IE);
561 }
562
563 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
564   const Type *ElTy =
565     GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
566                    std::vector<Value*>(GEP.idx_begin(), GEP.idx_end()), true);
567   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
568   Assert2(PointerType::get(ElTy) == GEP.getType(),
569           "GEP is not of right type for indices!", &GEP, ElTy);
570   visitInstruction(GEP);
571 }
572
573 void Verifier::visitLoadInst(LoadInst &LI) {
574   const Type *ElTy =
575     cast<PointerType>(LI.getOperand(0)->getType())->getElementType();
576   Assert2(ElTy == LI.getType(),
577           "Load result type does not match pointer operand type!", &LI, ElTy);
578   visitInstruction(LI);
579 }
580
581 void Verifier::visitStoreInst(StoreInst &SI) {
582   const Type *ElTy =
583     cast<PointerType>(SI.getOperand(1)->getType())->getElementType();
584   Assert2(ElTy == SI.getOperand(0)->getType(),
585           "Stored value type does not match pointer operand type!", &SI, ElTy);
586   visitInstruction(SI);
587 }
588
589
590 /// verifyInstruction - Verify that an instruction is well formed.
591 ///
592 void Verifier::visitInstruction(Instruction &I) {
593   BasicBlock *BB = I.getParent();
594   Assert1(BB, "Instruction not embedded in basic block!", &I);
595
596   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
597     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
598          UI != UE; ++UI)
599       Assert1(*UI != (User*)&I ||
600               !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
601               "Only PHI nodes may reference their own value!", &I);
602   }
603
604   // Check that void typed values don't have names
605   Assert1(I.getType() != Type::VoidTy || !I.hasName(),
606           "Instruction has a name, but provides a void value!", &I);
607
608   // Check that the return value of the instruction is either void or a legal
609   // value type.
610   Assert1(I.getType() == Type::VoidTy || I.getType()->isFirstClassType(),
611           "Instruction returns a non-scalar type!", &I);
612
613   // Check that all uses of the instruction, if they are instructions
614   // themselves, actually have parent basic blocks.  If the use is not an
615   // instruction, it is an error!
616   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
617        UI != UE; ++UI) {
618     Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
619             *UI);
620     Instruction *Used = cast<Instruction>(*UI);
621     Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
622             " embeded in a basic block!", &I, Used);
623   }
624
625   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
626     // Check to make sure that the "address of" an intrinsic function is never
627     // taken.
628     Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
629     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
630       Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
631               "Cannot take the address of an intrinsic!", &I);
632     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
633       Assert1(OpBB->getParent() == BB->getParent(),
634               "Referring to a basic block in another function!", &I);
635     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
636       Assert1(OpArg->getParent() == BB->getParent(),
637               "Referring to an argument in another function!", &I);
638     } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
639       BasicBlock *OpBlock = Op->getParent();
640
641       // Check that a definition dominates all of its uses.
642       if (!isa<PHINode>(I)) {
643         // Invoke results are only usable in the normal destination, not in the
644         // exceptional destination.
645         if (InvokeInst *II = dyn_cast<InvokeInst>(Op))
646           OpBlock = II->getNormalDest();
647         else if (OpBlock == BB) {
648           // If they are in the same basic block, make sure that the definition
649           // comes before the use.
650           Assert2(InstsInThisBlock.count(Op) ||
651                   !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
652                   "Instruction does not dominate all uses!", Op, &I);
653         }
654
655         // Definition must dominate use unless use is unreachable!
656         Assert2(EF->dominates(OpBlock, BB) ||
657                 !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
658                 "Instruction does not dominate all uses!", Op, &I);
659       } else {
660         // PHI nodes are more difficult than other nodes because they actually
661         // "use" the value in the predecessor basic blocks they correspond to.
662         BasicBlock *PredBB = cast<BasicBlock>(I.getOperand(i+1));
663         Assert2(EF->dominates(OpBlock, PredBB) ||
664                 !EF->dominates(&BB->getParent()->getEntryBlock(), PredBB),
665                 "Instruction does not dominate all uses!", Op, &I);
666       }
667     } else if (isa<InlineAsm>(I.getOperand(i))) {
668       Assert1(i == 0 && isa<CallInst>(I),
669               "Cannot take the address of an inline asm!", &I);
670     }
671   }
672   InstsInThisBlock.insert(&I);
673 }
674
675 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
676 ///
677 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
678   Function *IF = CI.getCalledFunction();
679   const FunctionType *FTy = IF->getFunctionType();
680   Assert1(IF->isExternal(), "Intrinsic functions should never be defined!", IF);
681   
682 #define GET_INTRINSIC_VERIFIER
683 #include "llvm/Intrinsics.gen"
684 #undef GET_INTRINSIC_VERIFIER
685 }
686
687
688 //===----------------------------------------------------------------------===//
689 //  Implement the public interfaces to this file...
690 //===----------------------------------------------------------------------===//
691
692 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
693   return new Verifier(action);
694 }
695
696
697 // verifyFunction - Create
698 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
699   Function &F = const_cast<Function&>(f);
700   assert(!F.isExternal() && "Cannot verify external functions");
701
702   FunctionPassManager FPM(new ExistingModuleProvider(F.getParent()));
703   Verifier *V = new Verifier(action);
704   FPM.add(V);
705   FPM.run(F);
706   return V->Broken;
707 }
708
709 /// verifyModule - Check a module for errors, printing messages on stderr.
710 /// Return true if the module is corrupt.
711 ///
712 bool llvm::verifyModule(const Module &M, VerifierFailureAction action) {
713   PassManager PM;
714   Verifier *V = new Verifier(action);
715   PM.add(V);
716   PM.run((Module&)M);
717   return V->Broken;
718 }
719
720 // vim: sw=2