0165e3b8cb055eb5280481ab4ab58c7ec1c6cfbd
[oota-llvm.git] / lib / VMCore / Verifier.cpp
1 //===-- Verifier.cpp - Implement the Module Verifier -------------*- C++ -*-==//
2 //
3 // This file defines the function verifier interface, that can be used for some
4 // sanity checking of input to the system.
5 //
6 // Note that this does not provide full 'java style' security and verifications,
7 // instead it just tries to ensure that code is well formed.
8 //
9 //  * Both of a binary operator's parameters are the same type
10 //  * Verify that the indices of mem access instructions match other operands
11 //  * Verify that arithmetic and other things are only performed on first class
12 //    types.  Verify that shifts & logicals only happen on integrals f.e.
13 //  . All of the constants in a switch statement are of the correct type
14 //  * The code is in valid SSA form
15 //  . It should be illegal to put a label into any other type (like a structure)
16 //    or to return one. [except constant arrays!]
17 //  * Only phi nodes can be self referential: 'add int %0, %0 ; <int>:0' is bad
18 //  * PHI nodes must have an entry for each predecessor, with no extras.
19 //  * PHI nodes must be the first thing in a basic block, all grouped together
20 //  * PHI nodes must have at least one entry
21 //  * All basic blocks should only end with terminator insts, not contain them
22 //  * The entry node to a function must not have predecessors
23 //  * All Instructions must be embeded into a basic block
24 //  . Function's cannot take a void typed parameter
25 //  * Verify that a function's argument list agrees with it's declared type.
26 //  * It is illegal to specify a name for a void value.
27 //  * It is illegal to have a internal global value with no intitalizer
28 //  * It is illegal to have a ret instruction that returns a value that does not
29 //    agree with the function return value type.
30 //  * Function call argument types match the function prototype
31 //  * All other things that are tested by asserts spread about the code...
32 //
33 //===----------------------------------------------------------------------===//
34
35 #include "llvm/Analysis/Verifier.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Module.h"
38 #include "llvm/DerivedTypes.h"
39 #include "llvm/iPHINode.h"
40 #include "llvm/iTerminators.h"
41 #include "llvm/iOther.h"
42 #include "llvm/iOperators.h"
43 #include "llvm/iMemory.h"
44 #include "llvm/SymbolTable.h"
45 #include "llvm/PassManager.h"
46 #include "llvm/Analysis/Dominators.h"
47 #include "llvm/Support/CFG.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "Support/STLExtras.h"
50 #include <algorithm>
51
52 namespace {  // Anonymous namespace for class
53
54   struct Verifier : public FunctionPass, InstVisitor<Verifier> {
55     bool Broken;          // Is this module found to be broken?
56     bool RealPass;        // Are we not being run by a PassManager?
57     bool AbortBroken;     // If broken, should it or should it not abort?
58     
59     DominatorSet *DS; // Dominator set, caution can be null!
60
61     Verifier() : Broken(false), RealPass(true), AbortBroken(true), DS(0) {}
62     Verifier(bool AB) : Broken(false), RealPass(true), AbortBroken(AB), DS(0) {}
63     Verifier(DominatorSet &ds) 
64       : Broken(false), RealPass(false), AbortBroken(false), DS(&ds) {}
65
66
67     bool doInitialization(Module &M) {
68       verifySymbolTable(M.getSymbolTable());
69
70       // If this is a real pass, in a pass manager, we must abort before
71       // returning back to the pass manager, or else the pass manager may try to
72       // run other passes on the broken module.
73       //
74       if (RealPass)
75         abortIfBroken();
76       return false;
77     }
78
79     bool runOnFunction(Function &F) {
80       // Get dominator information if we are being run by PassManager
81       if (RealPass) DS = &getAnalysis<DominatorSet>();
82       visit(F);
83
84       // If this is a real pass, in a pass manager, we must abort before
85       // returning back to the pass manager, or else the pass manager may try to
86       // run other passes on the broken module.
87       //
88       if (RealPass)
89         abortIfBroken();
90
91       return false;
92     }
93
94     bool doFinalization(Module &M) {
95       // Scan through, checking all of the external function's linkage now...
96       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
97         visitGlobalValue(*I);
98
99       for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
100         if (I->isExternal() && I->hasInternalLinkage())
101           CheckFailed("Global Variable is external with internal linkage!", I);
102
103       // If the module is broken, abort at this time.
104       abortIfBroken();
105       return false;
106     }
107
108     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
109       AU.setPreservesAll();
110       if (RealPass)
111         AU.addRequired<DominatorSet>();
112     }
113
114     // abortIfBroken - If the module is broken and we are supposed to abort on
115     // this condition, do so.
116     //
117     void abortIfBroken() const {
118       if (Broken && AbortBroken) {
119         std::cerr << "Broken module found, compilation aborted!\n";
120         abort();
121       }
122     }
123
124
125     // Verification methods...
126     void verifySymbolTable(SymbolTable &ST);
127     void visitGlobalValue(GlobalValue &GV);
128     void visitFunction(Function &F);
129     void visitBasicBlock(BasicBlock &BB);
130     void visitPHINode(PHINode &PN);
131     void visitBinaryOperator(BinaryOperator &B);
132     void visitShiftInst(ShiftInst &SI);
133     void visitCallInst(CallInst &CI);
134     void visitGetElementPtrInst(GetElementPtrInst &GEP);
135     void visitLoadInst(LoadInst &LI);
136     void visitStoreInst(StoreInst &SI);
137     void visitInstruction(Instruction &I);
138     void visitTerminatorInst(TerminatorInst &I);
139     void visitReturnInst(ReturnInst &RI);
140     void visitUserOp1(Instruction &I);
141     void visitUserOp2(Instruction &I) { visitUserOp1(I); }
142
143     // CheckFailed - A check failed, so print out the condition and the message
144     // that failed.  This provides a nice place to put a breakpoint if you want
145     // to see why something is not correct.
146     //
147     inline void CheckFailed(const std::string &Message,
148                             const Value *V1 = 0, const Value *V2 = 0,
149                             const Value *V3 = 0, const Value *V4 = 0) {
150       std::cerr << Message << "\n";
151       if (V1) std::cerr << *V1 << "\n";
152       if (V2) std::cerr << *V2 << "\n";
153       if (V3) std::cerr << *V3 << "\n";
154       if (V4) std::cerr << *V4 << "\n";
155       Broken = true;
156     }
157   };
158
159   RegisterPass<Verifier> X("verify", "Module Verifier");
160 }
161
162 // Assert - We know that cond should be true, if not print an error message.
163 #define Assert(C, M) \
164   do { if (!(C)) { CheckFailed(M); return; } } while (0)
165 #define Assert1(C, M, V1) \
166   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
167 #define Assert2(C, M, V1, V2) \
168   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
169 #define Assert3(C, M, V1, V2, V3) \
170   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
171 #define Assert4(C, M, V1, V2, V3, V4) \
172   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
173
174
175 void Verifier::visitGlobalValue(GlobalValue &GV) {
176   Assert1(!GV.isExternal() || GV.hasExternalLinkage(),
177           "Global value has Internal Linkage!", &GV);
178   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
179           "Only global variables can have appending linkage!", &GV);
180
181   if (GV.hasAppendingLinkage()) {
182     GlobalVariable &GVar = cast<GlobalVariable>(GV);
183     Assert1(isa<ArrayType>(GVar.getType()->getElementType()),
184             "Only global arrays can have appending linkage!", &GV);
185   }
186 }
187
188 // verifySymbolTable - Verify that a function or module symbol table is ok
189 //
190 void Verifier::verifySymbolTable(SymbolTable &ST) {
191   // Loop over all of the types in the symbol table...
192   for (SymbolTable::iterator TI = ST.begin(), TE = ST.end(); TI != TE; ++TI)
193     for (SymbolTable::type_iterator I = TI->second.begin(),
194            E = TI->second.end(); I != E; ++I) {
195       Value *V = I->second;
196
197       // Check that there are no void typed values in the symbol table.  Values
198       // with a void type cannot be put into symbol tables because they cannot
199       // have names!
200       Assert1(V->getType() != Type::VoidTy,
201               "Values with void type are not allowed to have names!", V);
202     }
203 }
204
205
206 // visitFunction - Verify that a function is ok.
207 //
208 void Verifier::visitFunction(Function &F) {
209   // Check function arguments...
210   const FunctionType *FT = F.getFunctionType();
211   unsigned NumArgs = F.getArgumentList().size();
212
213   Assert2(!FT->isVarArg(), "Cannot define varargs functions in LLVM!", &F, FT);
214   Assert2(FT->getNumParams() == NumArgs,
215           "# formal arguments must match # of arguments for function type!",
216           &F, FT);
217
218   // Check that the argument values match the function type for this function...
219   unsigned i = 0;
220   for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I, ++i)
221     Assert2(I->getType() == FT->getParamType(i),
222             "Argument value does not match function argument type!",
223             I, FT->getParamType(i));
224
225   if (!F.isExternal()) {
226     verifySymbolTable(F.getSymbolTable());
227
228     // Check the entry node
229     BasicBlock *Entry = &F.getEntryNode();
230     Assert1(pred_begin(Entry) == pred_end(Entry),
231             "Entry block to function must not have predecessors!", Entry);
232   }
233 }
234
235
236 // verifyBasicBlock - Verify that a basic block is well formed...
237 //
238 void Verifier::visitBasicBlock(BasicBlock &BB) {
239   // Ensure that basic blocks have terminators!
240   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
241 }
242
243 void Verifier::visitTerminatorInst(TerminatorInst &I) {
244   // Ensure that terminators only exist at the end of the basic block.
245   Assert1(&I == I.getParent()->getTerminator(),
246           "Terminator found in the middle of a basic block!", I.getParent());
247   visitInstruction(I);
248 }
249
250 void Verifier::visitReturnInst(ReturnInst &RI) {
251   Function *F = RI.getParent()->getParent();
252   if (RI.getNumOperands() == 0)
253     Assert1(F->getReturnType() == Type::VoidTy,
254             "Function returns no value, but ret instruction found that does!",
255             &RI);
256   else
257     Assert2(F->getReturnType() == RI.getOperand(0)->getType(),
258             "Function return type does not match operand "
259             "type of return inst!", &RI, F->getReturnType());
260
261   // Check to make sure that the return value has neccesary properties for
262   // terminators...
263   visitTerminatorInst(RI);
264 }
265
266 // visitUserOp1 - User defined operators shouldn't live beyond the lifetime of a
267 // pass, if any exist, it's an error.
268 //
269 void Verifier::visitUserOp1(Instruction &I) {
270   Assert1(0, "User-defined operators should not live outside of a pass!",
271           &I);
272 }
273
274 // visitPHINode - Ensure that a PHI node is well formed.
275 void Verifier::visitPHINode(PHINode &PN) {
276   // Ensure that the PHI nodes are all grouped together at the top of the block.
277   // This can be tested by checking whether the instruction before this is
278   // either nonexistant (because this is begin()) or is a PHI node.  If not,
279   // then there is some other instruction before a PHI.
280   Assert2(PN.getPrev() == 0 || isa<PHINode>(PN.getPrev()),
281           "PHI nodes not grouped at top of basic block!",
282           &PN, PN.getParent());
283
284   // Ensure that PHI nodes have at least one entry!
285   Assert1(PN.getNumIncomingValues() != 0,
286           "PHI nodes must have at least one entry.  If the block is dead, "
287           "the PHI should be removed!",
288           &PN);
289
290   std::vector<BasicBlock*> Preds(pred_begin(PN.getParent()),
291                                  pred_end(PN.getParent()));
292   // Loop over all of the incoming values, make sure that there are
293   // predecessors for each one...
294   //
295   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
296     // Make sure all of the incoming values are the right types...
297     Assert2(PN.getType() == PN.getIncomingValue(i)->getType(),
298             "PHI node argument type does not agree with PHI node type!",
299             &PN, PN.getIncomingValue(i));
300
301     BasicBlock *BB = PN.getIncomingBlock(i);
302     std::vector<BasicBlock*>::iterator PI =
303       find(Preds.begin(), Preds.end(), BB);
304     Assert2(PI != Preds.end(), "PHI node has entry for basic block that"
305             " is not a predecessor!", &PN, BB);
306     Preds.erase(PI);
307   }
308   
309   // There should be no entries left in the predecessor list...
310   for (std::vector<BasicBlock*>::iterator I = Preds.begin(),
311          E = Preds.end(); I != E; ++I)
312     Assert2(0, "PHI node does not have entry for a predecessor basic block!",
313             &PN, *I);
314
315   // Now we go through and check to make sure that if there is more than one
316   // entry for a particular basic block in this PHI node, that the incoming
317   // values are all identical.
318   //
319   std::vector<std::pair<BasicBlock*, Value*> > Values;
320   Values.reserve(PN.getNumIncomingValues());
321   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
322     Values.push_back(std::make_pair(PN.getIncomingBlock(i),
323                                     PN.getIncomingValue(i)));
324
325   // Sort the Values vector so that identical basic block entries are adjacent.
326   std::sort(Values.begin(), Values.end());
327
328   // Check for identical basic blocks with differing incoming values...
329   for (unsigned i = 1, e = PN.getNumIncomingValues(); i < e; ++i)
330     Assert4(Values[i].first  != Values[i-1].first ||
331             Values[i].second == Values[i-1].second,
332             "PHI node has multiple entries for the same basic block with "
333             "different incoming values!", &PN, Values[i].first,
334             Values[i].second, Values[i-1].second);
335
336   visitInstruction(PN);
337 }
338
339 void Verifier::visitCallInst(CallInst &CI) {
340   Assert1(isa<PointerType>(CI.getOperand(0)->getType()),
341           "Called function must be a pointer!", &CI);
342   const PointerType *FPTy = cast<PointerType>(CI.getOperand(0)->getType());
343   Assert1(isa<FunctionType>(FPTy->getElementType()),
344           "Called function is not pointer to function type!", &CI);
345
346   const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
347
348   // Verify that the correct number of arguments are being passed
349   if (FTy->isVarArg())
350     Assert1(CI.getNumOperands()-1 >= FTy->getNumParams(),
351             "Called function requires more parameters than were provided!",&CI);
352   else
353     Assert1(CI.getNumOperands()-1 == FTy->getNumParams(),
354             "Incorrect number of arguments passed to called function!", &CI);
355
356   // Verify that all arguments to the call match the function type...
357   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
358     Assert2(CI.getOperand(i+1)->getType() == FTy->getParamType(i),
359             "Call parameter type does not match function signature!",
360             CI.getOperand(i+1), FTy->getParamType(i));
361
362   visitInstruction(CI);
363 }
364
365 // visitBinaryOperator - Check that both arguments to the binary operator are
366 // of the same type!
367 //
368 void Verifier::visitBinaryOperator(BinaryOperator &B) {
369   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
370           "Both operands to a binary operator are not of the same type!", &B);
371
372   // Check that logical operators are only used with integral operands.
373   if (B.getOpcode() == Instruction::And || B.getOpcode() == Instruction::Or ||
374       B.getOpcode() == Instruction::Xor) {
375     Assert1(B.getType()->isIntegral(),
376             "Logical operators only work with integral types!", &B);
377     Assert1(B.getType() == B.getOperand(0)->getType(),
378             "Logical operators must have same type for operands and result!",
379             &B);
380   } else if (isa<SetCondInst>(B)) {
381     // Check that setcc instructions return bool
382     Assert1(B.getType() == Type::BoolTy,
383             "setcc instructions must return boolean values!", &B);
384   } else {
385     // Arithmetic operators only work on integer or fp values
386     Assert1(B.getType() == B.getOperand(0)->getType(),
387             "Arithmetic operators must have same type for operands and result!",
388             &B);
389     Assert1(B.getType()->isInteger() || B.getType()->isFloatingPoint(),
390             "Arithmetic operators must have integer or fp type!", &B);
391   }
392   
393   visitInstruction(B);
394 }
395
396 void Verifier::visitShiftInst(ShiftInst &SI) {
397   Assert1(SI.getType()->isInteger(),
398           "Shift must return an integer result!", &SI);
399   Assert1(SI.getType() == SI.getOperand(0)->getType(),
400           "Shift return type must be same as first operand!", &SI);
401   Assert1(SI.getOperand(1)->getType() == Type::UByteTy,
402           "Second operand to shift must be ubyte type!", &SI);
403   visitInstruction(SI);
404 }
405
406
407
408 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
409   const Type *ElTy =
410     GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
411                    std::vector<Value*>(GEP.idx_begin(), GEP.idx_end()), true);
412   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
413   Assert2(PointerType::get(ElTy) == GEP.getType(),
414           "GEP is not of right type for indices!", &GEP, ElTy);
415   visitInstruction(GEP);
416 }
417
418 void Verifier::visitLoadInst(LoadInst &LI) {
419   const Type *ElTy =
420     cast<PointerType>(LI.getOperand(0)->getType())->getElementType();
421   Assert2(ElTy == LI.getType(),
422           "Load is not of right type for indices!", &LI, ElTy);
423   visitInstruction(LI);
424 }
425
426 void Verifier::visitStoreInst(StoreInst &SI) {
427   const Type *ElTy =
428     cast<PointerType>(SI.getOperand(1)->getType())->getElementType();
429   Assert2(ElTy == SI.getOperand(0)->getType(),
430           "Stored value is not of right type for indices!", &SI, ElTy);
431   visitInstruction(SI);
432 }
433
434
435 // verifyInstruction - Verify that an instruction is well formed.
436 //
437 void Verifier::visitInstruction(Instruction &I) {
438   BasicBlock *BB = I.getParent();  
439   Assert1(BB, "Instruction not embedded in basic block!", &I);
440
441   // Check that all uses of the instruction, if they are instructions
442   // themselves, actually have parent basic blocks.  If the use is not an
443   // instruction, it is an error!
444   //
445   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
446        UI != UE; ++UI) {
447     Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
448             *UI);
449     Instruction *Used = cast<Instruction>(*UI);
450     Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
451             " embeded in a basic block!", &I, Used);
452   }
453
454   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
455     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
456          UI != UE; ++UI)
457       Assert1(*UI != (User*)&I,
458               "Only PHI nodes may reference their own value!", &I);
459   }
460
461   // Check that void typed values don't have names
462   Assert1(I.getType() != Type::VoidTy || !I.hasName(),
463           "Instruction has a name, but provides a void value!", &I);
464
465   // Check that a definition dominates all of its uses.
466   //
467   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
468        UI != UE; ++UI) {
469     Instruction *Use = cast<Instruction>(*UI);
470       
471     // PHI nodes are more difficult than other nodes because they actually
472     // "use" the value in the predecessor basic blocks they correspond to.
473     if (PHINode *PN = dyn_cast<PHINode>(Use)) {
474       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
475         if (&I == PN->getIncomingValue(i)) {
476           // Make sure that I dominates the end of pred(i)
477           BasicBlock *Pred = PN->getIncomingBlock(i);
478           
479           // Use must be dominated by by definition unless use is unreachable!
480           Assert2(DS->dominates(BB, Pred) ||
481                   !DS->dominates(&BB->getParent()->getEntryNode(), Pred),
482                   "Instruction does not dominate all uses!",
483                   &I, PN);
484         }
485
486     } else {
487       // Use must be dominated by by definition unless use is unreachable!
488       Assert2(DS->dominates(&I, Use) ||
489               !DS->dominates(&BB->getParent()->getEntryNode(),Use->getParent()),
490               "Instruction does not dominate all uses!", &I, Use);
491     }
492   }
493 }
494
495
496 //===----------------------------------------------------------------------===//
497 //  Implement the public interfaces to this file...
498 //===----------------------------------------------------------------------===//
499
500 Pass *createVerifierPass() {
501   return new Verifier();
502 }
503
504
505 // verifyFunction - Create 
506 bool verifyFunction(const Function &f) {
507   Function &F = (Function&)f;
508   assert(!F.isExternal() && "Cannot verify external functions");
509
510   DominatorSet DS;
511   DS.doInitialization(*F.getParent());
512   DS.runOnFunction(F);
513
514   Verifier V(DS);
515   V.runOnFunction(F);
516
517   DS.doFinalization(*F.getParent());
518
519   return V.Broken;
520 }
521
522 // verifyModule - Check a module for errors, printing messages on stderr.
523 // Return true if the module is corrupt.
524 //
525 bool verifyModule(const Module &M) {
526   PassManager PM;
527   Verifier *V = new Verifier();
528   PM.add(V);
529   PM.run((Module&)M);
530   return V->Broken;
531 }