* Update to work with Megapatch
[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 //  . There are no duplicated names in a symbol table... ie there !exist a val
10 //    with the same name as something in the symbol table, but with a different
11 //    address as what is in the symbol table...
12 //  * Both of a binary operator's parameters are the same type
13 //  * Verify that the indices of mem access instructions match other operands
14 //  . Verify that arithmetic and other things are only performed on first class
15 //    types.  No adding structures or arrays.
16 //  . All of the constants in a switch statement are of the correct type
17 //  . The code is in valid SSA form
18 //  . It should be illegal to put a label into any other type (like a structure)
19 //    or to return one. [except constant arrays!]
20 //  * Only phi nodes can be self referential: 'add int %0, %0 ; <int>:0' is bad
21 //  * PHI nodes must have an entry for each predecessor, with no extras.
22 //  * PHI nodes must be the first thing in a basic block, all grouped together
23 //  * All basic blocks should only end with terminator insts, not contain them
24 //  * The entry node to a function must not have predecessors
25 //  * All Instructions must be embeded into a basic block
26 //  . Verify that none of the Value getType()'s are null.
27 //  . Function's cannot take a void typed parameter
28 //  * Verify that a function's argument list agrees with it's declared type.
29 //  . Verify that arrays and structures have fixed elements: No unsized arrays.
30 //  * It is illegal to specify a name for a void value.
31 //  * It is illegal to have a internal function that is just a declaration
32 //  * It is illegal to have a ret instruction that returns a value that does not
33 //    agree with the function return value type.
34 //  * Function call argument types match the function prototype
35 //  * All other things that are tested by asserts spread about the code...
36 //
37 //===----------------------------------------------------------------------===//
38
39 #include "llvm/Analysis/Verifier.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Module.h"
42 #include "llvm/DerivedTypes.h"
43 #include "llvm/iPHINode.h"
44 #include "llvm/iTerminators.h"
45 #include "llvm/iOther.h"
46 #include "llvm/iMemory.h"
47 #include "llvm/SymbolTable.h"
48 #include "llvm/Support/CFG.h"
49 #include "llvm/Support/InstVisitor.h"
50 #include "Support/STLExtras.h"
51 #include <algorithm>
52
53 namespace {  // Anonymous namespace for class
54
55   struct Verifier : public FunctionPass, InstVisitor<Verifier> {
56     bool Broken;
57
58     Verifier() : Broken(false) {}
59
60     virtual const char *getPassName() const { return "Module Verifier"; }
61
62     bool doInitialization(Module &M) {
63       verifySymbolTable(M.getSymbolTable());
64       return false;
65     }
66
67     bool runOnFunction(Function &F) {
68       visit(F);
69       return false;
70     }
71
72     bool doFinalization(Module &M) {
73       // Scan through, checking all of the external function's linkage now...
74       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
75         if (I->isExternal() && I->hasInternalLinkage())
76           CheckFailed("Function Declaration has Internal Linkage!", I);
77
78       if (Broken) {
79         cerr << "Broken module found, compilation aborted!\n";
80         abort();
81       }
82       return false;
83     }
84
85     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
86       AU.setPreservesAll();
87     }
88
89     // Verification methods...
90     void verifySymbolTable(SymbolTable *ST);
91     void visitFunction(Function &F);
92     void visitBasicBlock(BasicBlock &BB);
93     void visitPHINode(PHINode &PN);
94     void visitBinaryOperator(BinaryOperator &B);
95     void visitCallInst(CallInst &CI);
96     void visitGetElementPtrInst(GetElementPtrInst &GEP);
97     void visitLoadInst(LoadInst &LI);
98     void visitStoreInst(StoreInst &SI);
99     void visitInstruction(Instruction &I);
100     void visitTerminatorInst(TerminatorInst &I);
101     void visitReturnInst(ReturnInst &RI);
102
103     // CheckFailed - A check failed, so print out the condition and the message
104     // that failed.  This provides a nice place to put a breakpoint if you want
105     // to see why something is not correct.
106     //
107     inline void CheckFailed(const std::string &Message,
108                             const Value *V1 = 0, const Value *V2 = 0,
109                             const Value *V3 = 0, const Value *V4 = 0) {
110       std::cerr << Message << "\n";
111       if (V1) std::cerr << *V1 << "\n";
112       if (V2) std::cerr << *V2 << "\n";
113       if (V3) std::cerr << *V3 << "\n";
114       if (V4) std::cerr << *V4 << "\n";
115       Broken = true;
116     }
117   };
118 }
119
120 // Assert - We know that cond should be true, if not print an error message.
121 #define Assert(C, M) \
122   do { if (!(C)) { CheckFailed(M); return; } } while (0)
123 #define Assert1(C, M, V1) \
124   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
125 #define Assert2(C, M, V1, V2) \
126   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
127 #define Assert3(C, M, V1, V2, V3) \
128   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
129 #define Assert4(C, M, V1, V2, V3, V4) \
130   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
131
132
133 // verifySymbolTable - Verify that a function or module symbol table is ok
134 //
135 void Verifier::verifySymbolTable(SymbolTable *ST) {
136   if (ST == 0) return;   // No symbol table to process
137
138   // Loop over all of the types in the symbol table...
139   for (SymbolTable::iterator TI = ST->begin(), TE = ST->end(); TI != TE; ++TI)
140     for (SymbolTable::type_iterator I = TI->second.begin(),
141            E = TI->second.end(); I != E; ++I) {
142       Value *V = I->second;
143
144       // Check that there are no void typed values in the symbol table.  Values
145       // with a void type cannot be put into symbol tables because they cannot
146       // have names!
147       Assert1(V->getType() != Type::VoidTy,
148               "Values with void type are not allowed to have names!", V);
149     }
150 }
151
152
153 // visitFunction - Verify that a function is ok.
154 //
155 void Verifier::visitFunction(Function &F) {
156   if (F.isExternal()) return;
157
158   verifySymbolTable(F.getSymbolTable());
159
160   // Check function arguments...
161   const FunctionType *FT = F.getFunctionType();
162   unsigned NumArgs = F.getArgumentList().size();
163
164   Assert2(!FT->isVarArg(), "Cannot define varargs functions in LLVM!", &F, FT);
165   Assert2(FT->getParamTypes().size() == NumArgs,
166           "# formal arguments must match # of arguments for function type!",
167           &F, FT);
168
169   // Check that the argument values match the function type for this function...
170   if (FT->getParamTypes().size() == NumArgs) {
171     unsigned i = 0;
172     for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I, ++i)
173       Assert2(I->getType() == FT->getParamType(i),
174               "Argument value does not match function argument type!",
175               I, FT->getParamType(i));
176   }
177
178   // Check the entry node
179   BasicBlock *Entry = &F.getEntryNode();
180   Assert1(pred_begin(Entry) == pred_end(Entry),
181           "Entry block to function must not have predecessors!", Entry);
182 }
183
184
185 // verifyBasicBlock - Verify that a basic block is well formed...
186 //
187 void Verifier::visitBasicBlock(BasicBlock &BB) {
188   // Ensure that basic blocks have terminators!
189   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
190 }
191
192 void Verifier::visitTerminatorInst(TerminatorInst &I) {
193   // Ensure that terminators only exist at the end of the basic block.
194   Assert1(&I == I.getParent()->getTerminator(),
195           "Terminator found in the middle of a basic block!", I.getParent());
196 }
197
198 void Verifier::visitReturnInst(ReturnInst &RI) {
199   Function *F = RI.getParent()->getParent();
200   if (RI.getNumOperands() == 0)
201     Assert1(F->getReturnType() == Type::VoidTy,
202             "Function returns no value, but ret instruction found that does!",
203             &RI);
204   else
205     Assert2(F->getReturnType() == RI.getOperand(0)->getType(),
206             "Function return type does not match operand "
207             "type of return inst!", &RI, F->getReturnType());
208
209   // Check to make sure that the return value has neccesary properties for
210   // terminators...
211   visitTerminatorInst(RI);
212 }
213
214
215 // visitPHINode - Ensure that a PHI node is well formed.
216 void Verifier::visitPHINode(PHINode &PN) {
217   // Ensure that the PHI nodes are all grouped together at the top of the block.
218   // This can be tested by checking whether the instruction before this is
219   // either nonexistant (because this is begin()) or is a PHI node.  If not,
220   // then there is some other instruction before a PHI.
221   Assert2(PN.getPrev() == 0 || isa<PHINode>(PN.getPrev()),
222           "PHI nodes not grouped at top of basic block!",
223           &PN, PN.getParent());
224
225   std::vector<BasicBlock*> Preds(pred_begin(PN.getParent()),
226                                  pred_end(PN.getParent()));
227   // Loop over all of the incoming values, make sure that there are
228   // predecessors for each one...
229   //
230   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
231     // Make sure all of the incoming values are the right types...
232     Assert2(PN.getType() == PN.getIncomingValue(i)->getType(),
233             "PHI node argument type does not agree with PHI node type!",
234             &PN, PN.getIncomingValue(i));
235
236     BasicBlock *BB = PN.getIncomingBlock(i);
237     std::vector<BasicBlock*>::iterator PI =
238       find(Preds.begin(), Preds.end(), BB);
239     Assert2(PI != Preds.end(), "PHI node has entry for basic block that"
240             " is not a predecessor!", &PN, BB);
241     Preds.erase(PI);
242   }
243   
244   // There should be no entries left in the predecessor list...
245   for (std::vector<BasicBlock*>::iterator I = Preds.begin(),
246          E = Preds.end(); I != E; ++I)
247     Assert2(0, "PHI node does not have entry for a predecessor basic block!",
248             &PN, *I);
249
250   // Now we go through and check to make sure that if there is more than one
251   // entry for a particular basic block in this PHI node, that the incoming
252   // values are all identical.
253   //
254   std::vector<std::pair<BasicBlock*, Value*> > Values;
255   Values.reserve(PN.getNumIncomingValues());
256   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
257     Values.push_back(std::make_pair(PN.getIncomingBlock(i),
258                                     PN.getIncomingValue(i)));
259
260   // Sort the Values vector so that identical basic block entries are adjacent.
261   std::sort(Values.begin(), Values.end());
262
263   // Check for identical basic blocks with differing incoming values...
264   for (unsigned i = 1, e = PN.getNumIncomingValues(); i < e; ++i)
265     Assert4(Values[i].first  != Values[i-1].first ||
266             Values[i].second == Values[i-1].second,
267             "PHI node has multiple entries for the same basic block with "
268             "different incoming values!", &PN, Values[i].first,
269             Values[i].second, Values[i-1].second);
270
271   visitInstruction(PN);
272 }
273
274 void Verifier::visitCallInst(CallInst &CI) {
275   Assert1(isa<PointerType>(CI.getOperand(0)->getType()),
276           "Called function must be a pointer!", &CI);
277   const PointerType *FPTy = cast<PointerType>(CI.getOperand(0)->getType());
278   Assert1(isa<FunctionType>(FPTy->getElementType()),
279           "Called function is not pointer to function type!", &CI);
280
281   const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
282
283   // Verify that the correct number of arguments are being passed
284   if (FTy->isVarArg())
285     Assert1(CI.getNumOperands()-1 >= FTy->getNumParams(),
286             "Called function requires more parameters than were provided!",&CI);
287   else
288     Assert1(CI.getNumOperands()-1 == FTy->getNumParams(),
289             "Incorrect number of arguments passed to called function!", &CI);
290
291   // Verify that all arguments to the call match the function type...
292   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
293     Assert2(CI.getOperand(i+1)->getType() == FTy->getParamType(i),
294             "Call parameter type does not match function signature!",
295             CI.getOperand(i+1), FTy->getParamType(i));
296 }
297
298 // visitBinaryOperator - Check that both arguments to the binary operator are
299 // of the same type!
300 //
301 void Verifier::visitBinaryOperator(BinaryOperator &B) {
302   Assert2(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
303           "Both operands to a binary operator are not of the same type!",
304           B.getOperand(0), B.getOperand(1));
305
306   visitInstruction(B);
307 }
308
309 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
310   const Type *ElTy = MemAccessInst::getIndexedType(GEP.getOperand(0)->getType(),
311                                                    GEP.copyIndices(), true);
312   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
313   Assert2(PointerType::get(ElTy) == GEP.getType(),
314           "GEP is not of right type for indices!", &GEP, ElTy);
315   visitInstruction(GEP);
316 }
317
318 void Verifier::visitLoadInst(LoadInst &LI) {
319   const Type *ElTy = LoadInst::getIndexedType(LI.getOperand(0)->getType(),
320                                               LI.copyIndices());
321   Assert1(ElTy, "Invalid indices for load pointer type!", &LI);
322   Assert2(ElTy == LI.getType(),
323           "Load is not of right type for indices!", &LI, ElTy);
324   visitInstruction(LI);
325 }
326
327 void Verifier::visitStoreInst(StoreInst &SI) {
328   const Type *ElTy = StoreInst::getIndexedType(SI.getOperand(1)->getType(),
329                                                SI.copyIndices());
330   Assert1(ElTy, "Invalid indices for store pointer type!", &SI);
331   Assert2(ElTy == SI.getOperand(0)->getType(),
332           "Stored value is not of right type for indices!", &SI, ElTy);
333   visitInstruction(SI);
334 }
335
336
337 // verifyInstruction - Verify that a non-terminator instruction is well formed.
338 //
339 void Verifier::visitInstruction(Instruction &I) {
340   Assert1(I.getParent(), "Instruction not embedded in basic block!", &I);
341
342   // Check that all uses of the instruction, if they are instructions
343   // themselves, actually have parent basic blocks.  If the use is not an
344   // instruction, it is an error!
345   //
346   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
347        UI != UE; ++UI) {
348     Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
349             *UI);
350     Instruction *Used = cast<Instruction>(*UI);
351     Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
352             " embeded in a basic block!", &I, Used);
353   }
354
355   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
356     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
357          UI != UE; ++UI)
358       Assert1(*UI != (User*)&I,
359               "Only PHI nodes may reference their own value!", &I);
360   }
361
362   Assert1(I.getType() != Type::VoidTy || !I.hasName(),
363           "Instruction has a name, but provides a void value!", &I);
364 }
365
366
367 //===----------------------------------------------------------------------===//
368 //  Implement the public interfaces to this file...
369 //===----------------------------------------------------------------------===//
370
371 Pass *createVerifierPass() {
372   return new Verifier();
373 }
374
375 bool verifyFunction(const Function &F) {
376   Verifier V;
377   V.visit((Function&)F);
378   return V.Broken;
379 }
380
381 // verifyModule - Check a module for errors, printing messages on stderr.
382 // Return true if the module is corrupt.
383 //
384 bool verifyModule(const Module &M) {
385   Verifier V;
386   V.run((Module&)M);
387   return V.Broken;
388 }