Add some basic checks of CallInst's.
[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 arithmetic and other things are only performed on first class
14 //    types.  No adding structures or arrays.
15 //  . All of the constants in a switch statement are of the correct type
16 //  . The code is in valid SSA form
17 //  . It should be illegal to put a label into any other type (like a structure)
18 //    or to return one. [except constant arrays!]
19 //  * Only phi nodes can be self referential: 'add int %0, %0 ; <int>:0' is bad
20 //  * PHI nodes must have an entry for each predecessor, with no extras.
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 //  . Verify that none of the Value getType()'s are null.
25 //  . Function's cannot take a void typed parameter
26 //  * Verify that a function's argument list agrees with it's declared type.
27 //  . Verify that arrays and structures have fixed elements: No unsized arrays.
28 //  * It is illegal to specify a name for a void value.
29 //  * It is illegal to have a internal function that is just a declaration
30 //  * It is illegal to have a ret instruction that returns a value that does not
31 //    agree with the function return value type.
32 //  . All other things that are tested by asserts spread about the code...
33 //
34 //===----------------------------------------------------------------------===//
35
36 #include "llvm/Analysis/Verifier.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Function.h"
39 #include "llvm/Module.h"
40 #include "llvm/BasicBlock.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/iPHINode.h"
43 #include "llvm/iTerminators.h"
44 #include "llvm/iOther.h"
45 #include "llvm/Argument.h"
46 #include "llvm/SymbolTable.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 MethodPass, InstVisitor<Verifier> {
55     bool Broken;
56
57     Verifier() : Broken(false) {}
58
59     bool doInitialization(Module *M) {
60       verifySymbolTable(M->getSymbolTable());
61       return false;
62     }
63
64     bool runOnMethod(Function *F) {
65       visit(F);
66       return false;
67     }
68
69     // Verification methods...
70     void verifySymbolTable(SymbolTable *ST);
71     void visitFunction(Function *F);
72     void visitBasicBlock(BasicBlock *BB);
73     void visitPHINode(PHINode *PN);
74     void visitBinaryOperator(BinaryOperator *B);
75     void visitCallInst(CallInst *CI);
76     void visitInstruction(Instruction *I);
77
78     // CheckFailed - A check failed, so print out the condition and the message
79     // that failed.  This provides a nice place to put a breakpoint if you want
80     // to see why something is not correct.
81     //
82     inline void CheckFailed(const char *Cond, const std::string &Message,
83                             const Value *V1 = 0, const Value *V2 = 0) {
84       std::cerr << Message << "\n";
85       if (V1) { std::cerr << V1 << "\n"; }
86       if (V2) { std::cerr << V2 << "\n"; }
87       Broken = true;
88     }
89   };
90 }
91
92 // Assert - We know that cond should be true, if not print an error message.
93 #define Assert(C, M) \
94   do { if (!(C)) { CheckFailed(#C, M); return; } } while (0)
95 #define Assert1(C, M, V1) \
96   do { if (!(C)) { CheckFailed(#C, M, V1); return; } } while (0)
97 #define Assert2(C, M, V1, V2) \
98   do { if (!(C)) { CheckFailed(#C, M, V1, V2); return; } } while (0)
99
100
101 // verifySymbolTable - Verify that a function or module symbol table is ok
102 //
103 void Verifier::verifySymbolTable(SymbolTable *ST) {
104   if (ST == 0) return;   // No symbol table to process
105
106   // Loop over all of the types in the symbol table...
107   for (SymbolTable::iterator TI = ST->begin(), TE = ST->end(); TI != TE; ++TI)
108     for (SymbolTable::type_iterator I = TI->second.begin(),
109            E = TI->second.end(); I != E; ++I) {
110       Value *V = I->second;
111
112       // Check that there are no void typed values in the symbol table.  Values
113       // with a void type cannot be put into symbol tables because they cannot
114       // have names!
115       Assert1(V->getType() != Type::VoidTy,
116               "Values with void type are not allowed to have names!\n", V);
117     }
118 }
119
120
121 // visitFunction - Verify that a function is ok.
122 //
123 void Verifier::visitFunction(Function *F) {
124   if (F->isExternal()) return;
125   verifySymbolTable(F->getSymbolTable());
126
127   // Check linkage of function...
128   Assert1(!F->isExternal() || F->hasExternalLinkage(),
129           "Function cannot be an 'internal' 'declare'ation!", F);
130
131   // Check function arguments...
132   const FunctionType *FT = F->getFunctionType();
133   const Function::ArgumentListType &ArgList = F->getArgumentList();
134
135   Assert2(!FT->isVarArg(), "Cannot define varargs functions in LLVM!", F, FT);
136   Assert2(FT->getParamTypes().size() == ArgList.size(),
137           "# formal arguments must match # of arguments for function type!",
138           F, FT);
139
140   // Check that the argument values match the function type for this function...
141   if (FT->getParamTypes().size() == ArgList.size()) {
142     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
143       Assert2(ArgList[i]->getType() == FT->getParamType(i),
144               "Argument value does not match function argument type!",
145               ArgList[i], FT->getParamType(i));
146   }
147
148   // Check the entry node
149   BasicBlock *Entry = F->getEntryNode();
150   Assert1(pred_begin(Entry) == pred_end(Entry),
151           "Entry block to function must not have predecessors!", Entry);
152 }
153
154
155 // verifyBasicBlock - Verify that a basic block is well formed...
156 //
157 void Verifier::visitBasicBlock(BasicBlock *BB) {
158   Assert1(BB->getTerminator(), "Basic Block does not have terminator!\n", BB);
159
160   // Check that the terminator is ok as well...
161   if (isa<ReturnInst>(BB->getTerminator())) {
162     Instruction *I = BB->getTerminator();
163     Function *F = I->getParent()->getParent();
164     if (I->getNumOperands() == 0)
165       Assert1(F->getReturnType() == Type::VoidTy,
166               "Function returns no value, but ret instruction found that does!",
167               I);
168     else
169       Assert2(F->getReturnType() == I->getOperand(0)->getType(),
170               "Function return type does not match operand "
171               "type of return inst!", I, F->getReturnType());
172   }
173 }
174
175
176 // visitPHINode - Ensure that a PHI node is well formed.
177 void Verifier::visitPHINode(PHINode *PN) {
178   std::vector<BasicBlock*> Preds(pred_begin(PN->getParent()),
179                                  pred_end(PN->getParent()));
180   // Loop over all of the incoming values, make sure that there are
181   // predecessors for each one...
182   //
183   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
184     // Make sure all of the incoming values are the right types...
185     Assert2(PN->getType() == PN->getIncomingValue(i)->getType(),
186             "PHI node argument type does not agree with PHI node type!",
187             PN, PN->getIncomingValue(i));
188
189     BasicBlock *BB = PN->getIncomingBlock(i);
190     std::vector<BasicBlock*>::iterator PI =
191       find(Preds.begin(), Preds.end(), BB);
192     Assert2(PI != Preds.end(), "PHI node has entry for basic block that"
193             " is not a predecessor!", PN, BB);
194     Preds.erase(PI);
195   }
196   
197   // There should be no entries left in the predecessor list...
198   for (std::vector<BasicBlock*>::iterator I = Preds.begin(),
199          E = Preds.end(); I != E; ++I)
200     Assert2(0, "PHI node does not have entry for a predecessor basic block!",
201             PN, *I);
202
203   visitInstruction(PN);
204 }
205
206 void Verifier::visitCallInst(CallInst *CI) {
207   Assert1(isa<PointerType>(CI->getOperand(0)->getType()),
208           "Called function must be a pointer!", CI);
209   PointerType *FPTy = cast<PointerType>(CI->getOperand(0)->getType());
210   Assert1(isa<FunctionType>(FPTy->getElementType()),
211           "Called function is not pointer to function type!", CI);
212 }
213
214 // visitBinaryOperator - Check that both arguments to the binary operator are
215 // of the same type!
216 //
217 void Verifier::visitBinaryOperator(BinaryOperator *B) {
218   Assert2(B->getOperand(0)->getType() == B->getOperand(1)->getType(),
219           "Both operands to a binary operator are not of the same type!",
220           B->getOperand(0), B->getOperand(1));
221
222   visitInstruction(B);
223 }
224
225
226 // verifyInstruction - Verify that a non-terminator instruction is well formed.
227 //
228 void Verifier::visitInstruction(Instruction *I) {
229   assert(I->getParent() && "Instruction not embedded in basic block!");
230
231   // Check that all uses of the instruction, if they are instructions
232   // themselves, actually have parent basic blocks.  If the use is not an
233   // instruction, it is an error!
234   //
235   for (User::use_iterator UI = I->use_begin(), UE = I->use_end();
236        UI != UE; ++UI) {
237     Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
238             *UI);
239     Instruction *Used = cast<Instruction>(*UI);
240     Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
241             " embeded in a basic block!", I, Used);
242   }
243
244   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
245     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
246          UI != UE; ++UI)
247       Assert1(*UI != (User*)I,
248               "Only PHI nodes may reference their own value!", I);
249   }
250
251   Assert1(I->getType() != Type::VoidTy || !I->hasName(),
252           "Instruction has a name, but provides a void value!", I);
253 }
254
255
256 //===----------------------------------------------------------------------===//
257 //  Implement the public interfaces to this file...
258 //===----------------------------------------------------------------------===//
259
260 Pass *createVerifierPass() {
261   return new Verifier();
262 }
263
264 bool verifyFunction(const Function *F) {
265   Verifier V;
266   V.visit((Function*)F);
267   return V.Broken;
268 }
269
270 // verifyModule - Check a module for errors, printing messages on stderr.
271 // Return true if the module is corrupt.
272 //
273 bool verifyModule(const Module *M) {
274   Verifier V;
275   V.run((Module*)M);
276   return V.Broken;
277 }