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