VMCore support for the insertelement operation.
[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/Instructions.h"
51 #include "llvm/Intrinsics.h"
52 #include "llvm/PassManager.h"
53 #include "llvm/SymbolTable.h"
54 #include "llvm/Analysis/Dominators.h"
55 #include "llvm/Support/CFG.h"
56 #include "llvm/Support/InstVisitor.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include <algorithm>
59 #include <iostream>
60 #include <sstream>
61 using namespace llvm;
62
63 namespace {  // Anonymous namespace for class
64
65   struct Verifier : public FunctionPass, InstVisitor<Verifier> {
66     bool Broken;          // Is this module found to be broken?
67     bool RealPass;        // Are we not being run by a PassManager?
68     VerifierFailureAction action;
69                           // What to do if verification fails.
70     Module *Mod;          // Module we are verifying right now
71     ETForest *EF;     // ET-Forest, caution can be null!
72     std::stringstream msgs;  // A stringstream to collect messages
73
74     /// InstInThisBlock - when verifying a basic block, keep track of all of the
75     /// instructions we have seen so far.  This allows us to do efficient
76     /// dominance checks for the case when an instruction has an operand that is
77     /// an instruction in the same block.
78     std::set<Instruction*> InstsInThisBlock;
79
80     Verifier()
81         : Broken(false), RealPass(true), action(AbortProcessAction),
82           EF(0), msgs( std::ios::app | std::ios::out ) {}
83     Verifier( VerifierFailureAction ctn )
84         : Broken(false), RealPass(true), action(ctn), EF(0),
85           msgs( std::ios::app | std::ios::out ) {}
86     Verifier(bool AB )
87         : Broken(false), RealPass(true),
88           action( AB ? AbortProcessAction : PrintMessageAction), EF(0),
89           msgs( std::ios::app | std::ios::out ) {}
90     Verifier(ETForest &ef)
91       : Broken(false), RealPass(false), action(PrintMessageAction),
92         EF(&ef), msgs( std::ios::app | std::ios::out ) {}
93
94
95     bool doInitialization(Module &M) {
96       Mod = &M;
97       verifySymbolTable(M.getSymbolTable());
98
99       // If this is a real pass, in a pass manager, we must abort before
100       // returning back to the pass manager, or else the pass manager may try to
101       // run other passes on the broken module.
102       if (RealPass)
103         abortIfBroken();
104       return false;
105     }
106
107     bool runOnFunction(Function &F) {
108       // Get dominator information if we are being run by PassManager
109       if (RealPass) EF = &getAnalysis<ETForest>();
110       visit(F);
111       InstsInThisBlock.clear();
112
113       // If this is a real pass, in a pass manager, we must abort before
114       // returning back to the pass manager, or else the pass manager may try to
115       // run other passes on the broken module.
116       if (RealPass)
117         abortIfBroken();
118
119       return false;
120     }
121
122     bool doFinalization(Module &M) {
123       // Scan through, checking all of the external function's linkage now...
124       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
125         visitGlobalValue(*I);
126
127         // Check to make sure function prototypes are okay.
128         if (I->isExternal()) visitFunction(*I);
129       }
130
131       for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
132            I != E; ++I)
133         visitGlobalVariable(*I);
134
135       // If the module is broken, abort at this time.
136       abortIfBroken();
137       return false;
138     }
139
140     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
141       AU.setPreservesAll();
142       if (RealPass)
143         AU.addRequired<ETForest>();
144     }
145
146     /// abortIfBroken - If the module is broken and we are supposed to abort on
147     /// this condition, do so.
148     ///
149     void abortIfBroken() {
150       if (Broken)
151       {
152         msgs << "Broken module found, ";
153         switch (action)
154         {
155           case AbortProcessAction:
156             msgs << "compilation aborted!\n";
157             std::cerr << msgs.str();
158             abort();
159           case ThrowExceptionAction:
160             msgs << "verification terminated.\n";
161             throw msgs.str();
162           case PrintMessageAction:
163             msgs << "verification continues.\n";
164             std::cerr << msgs.str();
165             break;
166           case ReturnStatusAction:
167             break;
168         }
169       }
170     }
171
172
173     // Verification methods...
174     void verifySymbolTable(SymbolTable &ST);
175     void visitGlobalValue(GlobalValue &GV);
176     void visitGlobalVariable(GlobalVariable &GV);
177     void visitFunction(Function &F);
178     void visitBasicBlock(BasicBlock &BB);
179     void visitPHINode(PHINode &PN);
180     void visitBinaryOperator(BinaryOperator &B);
181     void visitShiftInst(ShiftInst &SI);
182     void visitExtractElementInst(ExtractElementInst &EI);
183     void visitInsertElementInst(InsertElementInst &EI);
184     void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
185     void visitCallInst(CallInst &CI);
186     void visitGetElementPtrInst(GetElementPtrInst &GEP);
187     void visitLoadInst(LoadInst &LI);
188     void visitStoreInst(StoreInst &SI);
189     void visitInstruction(Instruction &I);
190     void visitTerminatorInst(TerminatorInst &I);
191     void visitReturnInst(ReturnInst &RI);
192     void visitSwitchInst(SwitchInst &SI);
193     void visitSelectInst(SelectInst &SI);
194     void visitUserOp1(Instruction &I);
195     void visitUserOp2(Instruction &I) { visitUserOp1(I); }
196     void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
197
198
199     void WriteValue(const Value *V) {
200       if (!V) return;
201       if (isa<Instruction>(V)) {
202         msgs << *V;
203       } else {
204         WriteAsOperand (msgs, V, true, true, Mod);
205         msgs << "\n";
206       }
207     }
208
209     void WriteType(const Type* T ) {
210       if ( !T ) return;
211       WriteTypeSymbolic(msgs, T, Mod );
212     }
213
214
215     // CheckFailed - A check failed, so print out the condition and the message
216     // that failed.  This provides a nice place to put a breakpoint if you want
217     // to see why something is not correct.
218     void CheckFailed(const std::string &Message,
219                      const Value *V1 = 0, const Value *V2 = 0,
220                      const Value *V3 = 0, const Value *V4 = 0) {
221       msgs << Message << "\n";
222       WriteValue(V1);
223       WriteValue(V2);
224       WriteValue(V3);
225       WriteValue(V4);
226       Broken = true;
227     }
228
229     void CheckFailed( const std::string& Message, const Value* V1,
230                       const Type* T2, const Value* V3 = 0 ) {
231       msgs << Message << "\n";
232       WriteValue(V1);
233       WriteType(T2);
234       WriteValue(V3);
235       Broken = true;
236     }
237   };
238
239   RegisterOpt<Verifier> X("verify", "Module Verifier");
240 } // End anonymous namespace
241
242
243 // Assert - We know that cond should be true, if not print an error message.
244 #define Assert(C, M) \
245   do { if (!(C)) { CheckFailed(M); return; } } while (0)
246 #define Assert1(C, M, V1) \
247   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
248 #define Assert2(C, M, V1, V2) \
249   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
250 #define Assert3(C, M, V1, V2, V3) \
251   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
252 #define Assert4(C, M, V1, V2, V3, V4) \
253   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
254
255
256 void Verifier::visitGlobalValue(GlobalValue &GV) {
257   Assert1(!GV.isExternal() || GV.hasExternalLinkage(),
258           "Global is external, but doesn't have external linkage!", &GV);
259   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
260           "Only global variables can have appending linkage!", &GV);
261
262   if (GV.hasAppendingLinkage()) {
263     GlobalVariable &GVar = cast<GlobalVariable>(GV);
264     Assert1(isa<ArrayType>(GVar.getType()->getElementType()),
265             "Only global arrays can have appending linkage!", &GV);
266   }
267 }
268
269 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
270   if (GV.hasInitializer())
271     Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
272             "Global variable initializer type does not match global "
273             "variable type!", &GV);
274
275   visitGlobalValue(GV);
276 }
277
278
279 // verifySymbolTable - Verify that a function or module symbol table is ok
280 //
281 void Verifier::verifySymbolTable(SymbolTable &ST) {
282
283   // Loop over all of the values in all type planes in the symbol table.
284   for (SymbolTable::plane_const_iterator PI = ST.plane_begin(),
285        PE = ST.plane_end(); PI != PE; ++PI)
286     for (SymbolTable::value_const_iterator VI = PI->second.begin(),
287          VE = PI->second.end(); VI != VE; ++VI) {
288       Value *V = VI->second;
289       // Check that there are no void typed values in the symbol table.  Values
290       // with a void type cannot be put into symbol tables because they cannot
291       // have names!
292       Assert1(V->getType() != Type::VoidTy,
293         "Values with void type are not allowed to have names!", V);
294     }
295 }
296
297 // visitFunction - Verify that a function is ok.
298 //
299 void Verifier::visitFunction(Function &F) {
300   Assert1(!F.isVarArg() || F.getCallingConv() == CallingConv::C,
301           "Varargs functions must have C calling conventions!", &F);
302
303   // Check function arguments.
304   const FunctionType *FT = F.getFunctionType();
305   unsigned NumArgs = F.getArgumentList().size();
306
307   Assert2(FT->getNumParams() == NumArgs,
308           "# formal arguments must match # of arguments for function type!",
309           &F, FT);
310   Assert1(F.getReturnType()->isFirstClassType() ||
311           F.getReturnType() == Type::VoidTy,
312           "Functions cannot return aggregate values!", &F);
313
314   // Check that the argument values match the function type for this function...
315   unsigned i = 0;
316   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I, ++i) {
317     Assert2(I->getType() == FT->getParamType(i),
318             "Argument value does not match function argument type!",
319             I, FT->getParamType(i));
320     // Make sure no aggregates are passed by value.
321     Assert1(I->getType()->isFirstClassType(),
322             "Functions cannot take aggregates as arguments by value!", I);
323    }
324
325   if (!F.isExternal()) {
326     verifySymbolTable(F.getSymbolTable());
327
328     // Check the entry node
329     BasicBlock *Entry = &F.getEntryBlock();
330     Assert1(pred_begin(Entry) == pred_end(Entry),
331             "Entry block to function must not have predecessors!", Entry);
332   }
333 }
334
335
336 // verifyBasicBlock - Verify that a basic block is well formed...
337 //
338 void Verifier::visitBasicBlock(BasicBlock &BB) {
339   InstsInThisBlock.clear();
340
341   // Ensure that basic blocks have terminators!
342   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
343
344   // Check constraints that this basic block imposes on all of the PHI nodes in
345   // it.
346   if (isa<PHINode>(BB.front())) {
347     std::vector<BasicBlock*> Preds(pred_begin(&BB), pred_end(&BB));
348     std::sort(Preds.begin(), Preds.end());
349     PHINode *PN;
350     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
351
352       // Ensure that PHI nodes have at least one entry!
353       Assert1(PN->getNumIncomingValues() != 0,
354               "PHI nodes must have at least one entry.  If the block is dead, "
355               "the PHI should be removed!", PN);
356       Assert1(PN->getNumIncomingValues() == Preds.size(),
357               "PHINode should have one entry for each predecessor of its "
358               "parent basic block!", PN);
359
360       // Get and sort all incoming values in the PHI node...
361       std::vector<std::pair<BasicBlock*, Value*> > Values;
362       Values.reserve(PN->getNumIncomingValues());
363       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
364         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
365                                         PN->getIncomingValue(i)));
366       std::sort(Values.begin(), Values.end());
367
368       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
369         // Check to make sure that if there is more than one entry for a
370         // particular basic block in this PHI node, that the incoming values are
371         // all identical.
372         //
373         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
374                 Values[i].second == Values[i-1].second,
375                 "PHI node has multiple entries for the same basic block with "
376                 "different incoming values!", PN, Values[i].first,
377                 Values[i].second, Values[i-1].second);
378
379         // Check to make sure that the predecessors and PHI node entries are
380         // matched up.
381         Assert3(Values[i].first == Preds[i],
382                 "PHI node entries do not match predecessors!", PN,
383                 Values[i].first, Preds[i]);
384       }
385     }
386   }
387 }
388
389 void Verifier::visitTerminatorInst(TerminatorInst &I) {
390   // Ensure that terminators only exist at the end of the basic block.
391   Assert1(&I == I.getParent()->getTerminator(),
392           "Terminator found in the middle of a basic block!", I.getParent());
393   visitInstruction(I);
394 }
395
396 void Verifier::visitReturnInst(ReturnInst &RI) {
397   Function *F = RI.getParent()->getParent();
398   if (RI.getNumOperands() == 0)
399     Assert2(F->getReturnType() == Type::VoidTy,
400             "Found return instr that returns void in Function of non-void "
401             "return type!", &RI, F->getReturnType());
402   else
403     Assert2(F->getReturnType() == RI.getOperand(0)->getType(),
404             "Function return type does not match operand "
405             "type of return inst!", &RI, F->getReturnType());
406
407   // Check to make sure that the return value has necessary properties for
408   // terminators...
409   visitTerminatorInst(RI);
410 }
411
412 void Verifier::visitSwitchInst(SwitchInst &SI) {
413   // Check to make sure that all of the constants in the switch instruction
414   // have the same type as the switched-on value.
415   const Type *SwitchTy = SI.getCondition()->getType();
416   for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i)
417     Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
418             "Switch constants must all be same type as switch value!", &SI);
419
420   visitTerminatorInst(SI);
421 }
422
423 void Verifier::visitSelectInst(SelectInst &SI) {
424   Assert1(SI.getCondition()->getType() == Type::BoolTy,
425           "Select condition type must be bool!", &SI);
426   Assert1(SI.getTrueValue()->getType() == SI.getFalseValue()->getType(),
427           "Select values must have identical types!", &SI);
428   Assert1(SI.getTrueValue()->getType() == SI.getType(),
429           "Select values must have same type as select instruction!", &SI);
430   visitInstruction(SI);
431 }
432
433
434 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
435 /// a pass, if any exist, it's an error.
436 ///
437 void Verifier::visitUserOp1(Instruction &I) {
438   Assert1(0, "User-defined operators should not live outside of a pass!",
439           &I);
440 }
441
442 /// visitPHINode - Ensure that a PHI node is well formed.
443 ///
444 void Verifier::visitPHINode(PHINode &PN) {
445   // Ensure that the PHI nodes are all grouped together at the top of the block.
446   // This can be tested by checking whether the instruction before this is
447   // either nonexistent (because this is begin()) or is a PHI node.  If not,
448   // then there is some other instruction before a PHI.
449   Assert2(&PN.getParent()->front() == &PN || isa<PHINode>(PN.getPrev()),
450           "PHI nodes not grouped at top of basic block!",
451           &PN, PN.getParent());
452
453   // Check that all of the operands of the PHI node have the same type as the
454   // result.
455   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
456     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
457             "PHI node operands are not the same type as the result!", &PN);
458
459   // All other PHI node constraints are checked in the visitBasicBlock method.
460
461   visitInstruction(PN);
462 }
463
464 void Verifier::visitCallInst(CallInst &CI) {
465   Assert1(isa<PointerType>(CI.getOperand(0)->getType()),
466           "Called function must be a pointer!", &CI);
467   const PointerType *FPTy = cast<PointerType>(CI.getOperand(0)->getType());
468   Assert1(isa<FunctionType>(FPTy->getElementType()),
469           "Called function is not pointer to function type!", &CI);
470
471   const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
472
473   // Verify that the correct number of arguments are being passed
474   if (FTy->isVarArg())
475     Assert1(CI.getNumOperands()-1 >= FTy->getNumParams(),
476             "Called function requires more parameters than were provided!",&CI);
477   else
478     Assert1(CI.getNumOperands()-1 == FTy->getNumParams(),
479             "Incorrect number of arguments passed to called function!", &CI);
480
481   // Verify that all arguments to the call match the function type...
482   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
483     Assert3(CI.getOperand(i+1)->getType() == FTy->getParamType(i),
484             "Call parameter type does not match function signature!",
485             CI.getOperand(i+1), FTy->getParamType(i), &CI);
486
487   if (Function *F = CI.getCalledFunction())
488     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
489       visitIntrinsicFunctionCall(ID, CI);
490
491   visitInstruction(CI);
492 }
493
494 /// visitBinaryOperator - Check that both arguments to the binary operator are
495 /// of the same type!
496 ///
497 void Verifier::visitBinaryOperator(BinaryOperator &B) {
498   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
499           "Both operands to a binary operator are not of the same type!", &B);
500
501   // Check that logical operators are only used with integral operands.
502   if (B.getOpcode() == Instruction::And || B.getOpcode() == Instruction::Or ||
503       B.getOpcode() == Instruction::Xor) {
504     Assert1(B.getType()->isIntegral() ||
505             (isa<PackedType>(B.getType()) && 
506              cast<PackedType>(B.getType())->getElementType()->isIntegral()),
507             "Logical operators only work with integral types!", &B);
508     Assert1(B.getType() == B.getOperand(0)->getType(),
509             "Logical operators must have same type for operands and result!",
510             &B);
511   } else if (isa<SetCondInst>(B)) {
512     // Check that setcc instructions return bool
513     Assert1(B.getType() == Type::BoolTy,
514             "setcc instructions must return boolean values!", &B);
515   } else {
516     // Arithmetic operators only work on integer or fp values
517     Assert1(B.getType() == B.getOperand(0)->getType(),
518             "Arithmetic operators must have same type for operands and result!",
519             &B);
520     Assert1(B.getType()->isInteger() || B.getType()->isFloatingPoint() ||
521             isa<PackedType>(B.getType()),
522             "Arithmetic operators must have integer, fp, or packed type!", &B);
523   }
524
525   visitInstruction(B);
526 }
527
528 void Verifier::visitShiftInst(ShiftInst &SI) {
529   Assert1(SI.getType()->isInteger(),
530           "Shift must return an integer result!", &SI);
531   Assert1(SI.getType() == SI.getOperand(0)->getType(),
532           "Shift return type must be same as first operand!", &SI);
533   Assert1(SI.getOperand(1)->getType() == Type::UByteTy,
534           "Second operand to shift must be ubyte type!", &SI);
535   visitInstruction(SI);
536 }
537
538 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
539   Assert1(isa<PackedType>(EI.getOperand(0)->getType()),
540           "First operand to extractelement must be packed type!", &EI);
541   Assert1(EI.getOperand(1)->getType() == Type::UIntTy,
542           "Second operand to extractelement must be uint type!", &EI);
543   Assert1(EI.getType() == 
544           cast<PackedType>(EI.getOperand(0)->getType())->getElementType(),
545           "Extractelement return type must match "
546           "first operand element type!", &EI);
547   visitInstruction(EI);
548 }
549
550 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
551   Assert1(isa<PackedType>(IE.getOperand(0)->getType()),
552           "First operand to insertelement must be packed type!", &IE);
553   Assert1(IE.getOperand(1)->getType() == 
554           cast<PackedType>(IE.getOperand(0)->getType())->getElementType(),
555           "Second operand to insertelement must match "
556           "first operand element type!", &IE);
557   Assert1(IE.getOperand(2)->getType() == Type::UIntTy,
558           "Third operand to insertelement must be uint type!", &IE);
559   visitInstruction(IE);
560 }
561
562 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
563   const Type *ElTy =
564     GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
565                    std::vector<Value*>(GEP.idx_begin(), GEP.idx_end()), true);
566   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
567   Assert2(PointerType::get(ElTy) == GEP.getType(),
568           "GEP is not of right type for indices!", &GEP, ElTy);
569   visitInstruction(GEP);
570 }
571
572 void Verifier::visitLoadInst(LoadInst &LI) {
573   const Type *ElTy =
574     cast<PointerType>(LI.getOperand(0)->getType())->getElementType();
575   Assert2(ElTy == LI.getType(),
576           "Load result type does not match pointer operand type!", &LI, ElTy);
577   visitInstruction(LI);
578 }
579
580 void Verifier::visitStoreInst(StoreInst &SI) {
581   const Type *ElTy =
582     cast<PointerType>(SI.getOperand(1)->getType())->getElementType();
583   Assert2(ElTy == SI.getOperand(0)->getType(),
584           "Stored value type does not match pointer operand type!", &SI, ElTy);
585   visitInstruction(SI);
586 }
587
588
589 /// verifyInstruction - Verify that an instruction is well formed.
590 ///
591 void Verifier::visitInstruction(Instruction &I) {
592   BasicBlock *BB = I.getParent();
593   Assert1(BB, "Instruction not embedded in basic block!", &I);
594
595   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
596     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
597          UI != UE; ++UI)
598       Assert1(*UI != (User*)&I ||
599               !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
600               "Only PHI nodes may reference their own value!", &I);
601   }
602
603   // Check that void typed values don't have names
604   Assert1(I.getType() != Type::VoidTy || !I.hasName(),
605           "Instruction has a name, but provides a void value!", &I);
606
607   // Check that the return value of the instruction is either void or a legal
608   // value type.
609   Assert1(I.getType() == Type::VoidTy || I.getType()->isFirstClassType(),
610           "Instruction returns a non-scalar type!", &I);
611
612   // Check that all uses of the instruction, if they are instructions
613   // themselves, actually have parent basic blocks.  If the use is not an
614   // instruction, it is an error!
615   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
616        UI != UE; ++UI) {
617     Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
618             *UI);
619     Instruction *Used = cast<Instruction>(*UI);
620     Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
621             " embeded in a basic block!", &I, Used);
622   }
623
624   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
625     // Check to make sure that the "address of" an intrinsic function is never
626     // taken.
627     Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
628     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
629       Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
630               "Cannot take the address of an intrinsic!", &I);
631     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
632       Assert1(OpBB->getParent() == BB->getParent(),
633               "Referring to a basic block in another function!", &I);
634     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
635       Assert1(OpArg->getParent() == BB->getParent(),
636               "Referring to an argument in another function!", &I);
637     } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
638       BasicBlock *OpBlock = Op->getParent();
639
640       // Check that a definition dominates all of its uses.
641       if (!isa<PHINode>(I)) {
642         // Invoke results are only usable in the normal destination, not in the
643         // exceptional destination.
644         if (InvokeInst *II = dyn_cast<InvokeInst>(Op))
645           OpBlock = II->getNormalDest();
646         else if (OpBlock == BB) {
647           // If they are in the same basic block, make sure that the definition
648           // comes before the use.
649           Assert2(InstsInThisBlock.count(Op) ||
650                   !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
651                   "Instruction does not dominate all uses!", Op, &I);
652         }
653
654         // Definition must dominate use unless use is unreachable!
655         Assert2(EF->dominates(OpBlock, BB) ||
656                 !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
657                 "Instruction does not dominate all uses!", Op, &I);
658       } else {
659         // PHI nodes are more difficult than other nodes because they actually
660         // "use" the value in the predecessor basic blocks they correspond to.
661         BasicBlock *PredBB = cast<BasicBlock>(I.getOperand(i+1));
662         Assert2(EF->dominates(OpBlock, PredBB) ||
663                 !EF->dominates(&BB->getParent()->getEntryBlock(), PredBB),
664                 "Instruction does not dominate all uses!", Op, &I);
665       }
666     }
667   }
668   InstsInThisBlock.insert(&I);
669 }
670
671 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
672 ///
673 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
674   Function *IF = CI.getCalledFunction();
675   const FunctionType *FT = IF->getFunctionType();
676   Assert1(IF->isExternal(), "Intrinsic functions should never be defined!", IF);
677   unsigned NumArgs = 0;
678
679   // FIXME: this should check the return type of each intrinsic as well, also
680   // arguments!
681   switch (ID) {
682   case Intrinsic::vastart:
683     Assert1(CI.getParent()->getParent()->getFunctionType()->isVarArg(),
684             "llvm.va_start intrinsic may only occur in function with variable"
685             " args!", &CI);
686     NumArgs = 1;
687     break;
688   case Intrinsic::vaend:          NumArgs = 1; break;
689   case Intrinsic::vacopy:         NumArgs = 2; break;
690
691   case Intrinsic::returnaddress:
692   case Intrinsic::frameaddress:
693     Assert1(isa<PointerType>(FT->getReturnType()),
694             "llvm.(frame|return)address must return pointers", IF);
695     Assert1(FT->getNumParams() == 1 && isa<ConstantInt>(CI.getOperand(1)),
696        "llvm.(frame|return)address require a single constant integer argument",
697             &CI);
698     NumArgs = 1;
699     break;
700
701   // Verify that read and write port have integral parameters of the correct
702   // signed-ness.
703   case Intrinsic::writeport:
704     Assert1(FT->getNumParams() == 2,
705             "Illegal # arguments for intrinsic function!", IF);
706     Assert1(FT->getParamType(0)->isIntegral(),
707             "First argument not unsigned int!", IF);
708     Assert1(FT->getParamType(1)->isUnsigned(),
709             "First argument not unsigned int!", IF);
710     NumArgs = 2;
711     break;
712
713   case Intrinsic::writeio:
714     Assert1(FT->getNumParams() == 2,
715             "Illegal # arguments for intrinsic function!", IF);
716     Assert1(FT->getParamType(0)->isFirstClassType(),
717             "First argument not a first class type!", IF);
718     Assert1(isa<PointerType>(FT->getParamType(1)),
719             "Second argument not a pointer!", IF);
720     NumArgs = 2;
721     break;
722
723   case Intrinsic::readport:
724     Assert1(FT->getNumParams() == 1,
725             "Illegal # arguments for intrinsic function!", IF);
726     Assert1(FT->getReturnType()->isFirstClassType(),
727             "Return type is not a first class type!", IF);
728     Assert1(FT->getParamType(0)->isUnsigned(),
729             "First argument not unsigned int!", IF);
730     NumArgs = 1;
731     break;
732
733   case Intrinsic::readio: {
734     const PointerType *ParamType = dyn_cast<PointerType>(FT->getParamType(0));
735     const Type *ReturnType = FT->getReturnType();
736
737     Assert1(FT->getNumParams() == 1,
738             "Illegal # arguments for intrinsic function!", IF);
739     Assert1(ParamType, "First argument not a pointer!", IF);
740     Assert1(ParamType->getElementType() == ReturnType,
741             "Pointer type doesn't match return type!", IF);
742     NumArgs = 1;
743     break;
744   }
745
746   case Intrinsic::isunordered_f32:
747     Assert1(FT->getNumParams() == 2,
748             "Illegal # arguments for intrinsic function!", IF);
749     Assert1(FT->getReturnType() == Type::BoolTy,
750             "Return type is not bool!", IF);
751     Assert1(FT->getParamType(0) == FT->getParamType(1),
752             "Arguments must be of the same type!", IF);
753     Assert1(FT->getParamType(0) == Type::FloatTy,
754             "Arguments must be a 32-bit floating point type!", IF);
755     NumArgs = 2;
756     break;
757
758   case Intrinsic::isunordered_f64:
759     Assert1(FT->getNumParams() == 2,
760             "Illegal # arguments for intrinsic function!", IF);
761     Assert1(FT->getReturnType() == Type::BoolTy,
762             "Return type is not bool!", IF);
763     Assert1(FT->getParamType(0) == FT->getParamType(1),
764             "Arguments must be of the same type!", IF);
765     Assert1(FT->getParamType(0) == Type::DoubleTy,
766             "Argument is not a 64-bit floating point type!", IF);
767     NumArgs = 2;
768     break;
769
770   case Intrinsic::readcyclecounter:
771     Assert1(FT->getNumParams() == 0,
772             "Illegal # arguments for intrinsic function!", IF);
773     Assert1(FT->getReturnType() == Type::ULongTy,
774             "Return type is not ulong!", IF);
775     NumArgs = 0;
776     break;
777
778   case Intrinsic::bswap_i16:
779     Assert1(FT->getNumParams() == 1,
780             "Illegal # arguments for intrinsic function!", IF);
781     Assert1(FT->getReturnType() == FT->getParamType(0),
782             "Return type does not match source type", IF);
783     Assert1(FT->getReturnType() == Type::UShortTy,
784             "Return type is not ushort!", IF);
785     NumArgs = 1;
786     break;    
787
788   case Intrinsic::bswap_i32:
789     Assert1(FT->getNumParams() == 1,
790             "Illegal # arguments for intrinsic function!", IF);
791     Assert1(FT->getReturnType() == FT->getParamType(0),
792             "Return type does not match source type", IF);
793     Assert1(FT->getReturnType() == Type::UIntTy,
794             "Return type is not uint!", IF);
795     NumArgs = 1;
796     break;    
797
798   case Intrinsic::bswap_i64:
799     Assert1(FT->getNumParams() == 1,
800             "Illegal # arguments for intrinsic function!", IF);
801     Assert1(FT->getReturnType() == FT->getParamType(0),
802             "Return type does not match source type", IF);
803     Assert1(FT->getReturnType() == Type::ULongTy,
804             "Return type is not ulong!", IF);
805     NumArgs = 1;
806     break;    
807     
808   case Intrinsic::ctpop_i8:
809     Assert1(FT->getNumParams() == 1,
810             "Illegal # arguments for intrinsic function!", IF);
811     Assert1(FT->getReturnType() == FT->getParamType(0),
812             "Return type does not match source type", IF);
813     Assert1(FT->getParamType(0) == Type::UByteTy 
814             || FT->getParamType(0) == Type::SByteTy,
815             "Argument must be a byte type!", IF);
816     NumArgs = 1;
817     break;
818
819   case Intrinsic::ctpop_i16:
820     Assert1(FT->getNumParams() == 1,
821             "Illegal # arguments for intrinsic function!", IF);
822     Assert1(FT->getReturnType() == FT->getParamType(0),
823             "Return type does not match source type", IF);
824     Assert1(FT->getParamType(0) == Type::UShortTy 
825             || FT->getParamType(0) == Type::ShortTy,
826             "Argument must be a short type!", IF);
827     NumArgs = 1;
828     break;
829
830   case Intrinsic::ctpop_i32:
831     Assert1(FT->getNumParams() == 1,
832             "Illegal # arguments for intrinsic function!", IF);
833     Assert1(FT->getReturnType() == FT->getParamType(0),
834             "Return type does not match source type", IF);
835     Assert1(FT->getParamType(0) == Type::UIntTy 
836             || FT->getParamType(0) == Type::IntTy,
837             "Argument must be an int type!", IF);
838     NumArgs = 1;
839     break;
840
841   case Intrinsic::ctpop_i64:
842     Assert1(FT->getNumParams() == 1,
843             "Illegal # arguments for intrinsic function!", IF);
844     Assert1(FT->getReturnType() == FT->getParamType(0),
845             "Return type does not match source type", IF);
846     Assert1(FT->getParamType(0) == Type::ULongTy 
847             || FT->getParamType(0) == Type::LongTy,
848             "Argument must be a long type!", IF);
849     NumArgs = 1;
850     break;
851
852   case Intrinsic::ctlz_i8:
853     Assert1(FT->getNumParams() == 1,
854             "Illegal # arguments for intrinsic function!", IF);
855     Assert1(FT->getReturnType() == FT->getParamType(0),
856             "Return type does not match source type", IF);
857     Assert1(FT->getParamType(0) == Type::UByteTy 
858             || FT->getParamType(0) == Type::SByteTy,
859             "Argument must be a byte type!", IF);
860     NumArgs = 1;
861     break;
862
863   case Intrinsic::ctlz_i16:
864     Assert1(FT->getNumParams() == 1,
865             "Illegal # arguments for intrinsic function!", IF);
866     Assert1(FT->getReturnType() == FT->getParamType(0),
867             "Return type does not match source type", IF);
868     Assert1(FT->getParamType(0) == Type::UShortTy 
869             || FT->getParamType(0) == Type::ShortTy,
870             "Argument must be a short type!", IF);
871     NumArgs = 1;
872     break;
873   case Intrinsic::ctlz_i32:
874     Assert1(FT->getNumParams() == 1,
875             "Illegal # arguments for intrinsic function!", IF);
876     Assert1(FT->getReturnType() == FT->getParamType(0),
877             "Return type does not match source type", IF);
878     Assert1(FT->getParamType(0) == Type::UIntTy 
879             || FT->getParamType(0) == Type::IntTy,
880             "Argument must be an int type!", IF);
881     NumArgs = 1;
882     break;
883   case Intrinsic::ctlz_i64:
884     Assert1(FT->getNumParams() == 1,
885             "Illegal # arguments for intrinsic function!", IF);
886     Assert1(FT->getReturnType() == FT->getParamType(0),
887             "Return type does not match source type", IF);
888     Assert1(FT->getParamType(0) == Type::ULongTy 
889             || FT->getParamType(0) == Type::LongTy,
890             "Argument must be a long type!", IF);
891     NumArgs = 1;
892     break;
893   case Intrinsic::cttz_i8:
894     Assert1(FT->getNumParams() == 1,
895             "Illegal # arguments for intrinsic function!", IF);
896     Assert1(FT->getReturnType() == FT->getParamType(0),
897             "Return type does not match source type", IF);
898     Assert1(FT->getParamType(0) == Type::UByteTy 
899             || FT->getParamType(0) == Type::SByteTy,
900             "Argument must be a byte type!", IF);
901     NumArgs = 1;
902     break;
903   case Intrinsic::cttz_i16:
904     Assert1(FT->getNumParams() == 1,
905             "Illegal # arguments for intrinsic function!", IF);
906     Assert1(FT->getReturnType() == FT->getParamType(0),
907             "Return type does not match source type", IF);
908     Assert1(FT->getParamType(0) == Type::UShortTy 
909             || FT->getParamType(0) == Type::ShortTy,
910             "Argument must be a short type!", IF);
911     NumArgs = 1;
912     break;
913   case Intrinsic::cttz_i32:
914     Assert1(FT->getNumParams() == 1,
915             "Illegal # arguments for intrinsic function!", IF);
916     Assert1(FT->getReturnType() == FT->getParamType(0),
917             "Return type does not match source type", IF);
918     Assert1(FT->getParamType(0) == Type::UIntTy 
919             || FT->getParamType(0) == Type::IntTy,
920             "Argument must be an int type!", IF);
921     NumArgs = 1;
922     break;
923   case Intrinsic::cttz_i64:
924     Assert1(FT->getNumParams() == 1,
925             "Illegal # arguments for intrinsic function!", IF);
926     Assert1(FT->getReturnType() == FT->getParamType(0),
927             "Return type does not match source type", IF);
928     Assert1(FT->getParamType(0) == Type::ULongTy 
929             || FT->getParamType(0) == Type::LongTy,
930             "Argument must be a long type!", IF);
931     NumArgs = 1;
932     break;
933
934   case Intrinsic::sqrt_f32:
935     Assert1(FT->getNumParams() == 1,
936             "Illegal # arguments for intrinsic function!", IF);
937     Assert1(FT->getParamType(0) == Type::FloatTy,
938             "Argument is not a 32-bit floating point type!", IF);
939     Assert1(FT->getReturnType() == FT->getParamType(0),
940             "Return type is not the same as argument type!", IF);
941     NumArgs = 1;
942     break;
943
944   case Intrinsic::sqrt_f64:
945     Assert1(FT->getNumParams() == 1,
946             "Illegal # arguments for intrinsic function!", IF);
947     Assert1(FT->getParamType(0) == Type::DoubleTy,
948             "Argument is not a 64-bit floating point type!", IF);
949     Assert1(FT->getReturnType() == FT->getParamType(0),
950             "Return type is not the same as argument type!", IF);
951     NumArgs = 1;
952     break;
953
954   case Intrinsic::setjmp:          NumArgs = 1; break;
955   case Intrinsic::longjmp:         NumArgs = 2; break;
956   case Intrinsic::sigsetjmp:       NumArgs = 2; break;
957   case Intrinsic::siglongjmp:      NumArgs = 2; break;
958
959   case Intrinsic::gcroot:
960     Assert1(FT->getNumParams() == 2,
961             "Illegal # arguments for intrinsic function!", IF);
962     Assert1(isa<Constant>(CI.getOperand(2)),
963             "Second argument to llvm.gcroot must be a constant!", &CI);
964     NumArgs = 2;
965     break;
966   case Intrinsic::gcread:          NumArgs = 2; break;
967   case Intrinsic::gcwrite:         NumArgs = 3; break;
968
969   case Intrinsic::dbg_stoppoint:   NumArgs = 4; break;
970   case Intrinsic::dbg_region_start:NumArgs = 1; break;
971   case Intrinsic::dbg_region_end:  NumArgs = 1; break;
972   case Intrinsic::dbg_func_start:  NumArgs = 1; break;
973   case Intrinsic::dbg_declare:     NumArgs = 1; break;
974
975   case Intrinsic::memcpy:          NumArgs = 4; break;
976   case Intrinsic::memmove:         NumArgs = 4; break;
977   case Intrinsic::memset:          NumArgs = 4; break;
978
979   case Intrinsic::stacksave:
980     NumArgs = 0;
981     Assert1(CI.getType() == PointerType::get(Type::SByteTy),
982             "llvm.stacksave must return an sbyte*", &CI);
983     break;
984   case Intrinsic::stackrestore:
985     NumArgs = 1;
986     Assert1(CI.getOperand(1)->getType() == PointerType::get(Type::SByteTy),
987             "llvm.stackrestore must take an sbyte*", &CI);
988     Assert1(CI.getType() == Type::VoidTy,
989             "llvm.stackrestore return void", &CI);
990     break;
991   case Intrinsic::prefetch:        NumArgs = 3; break;
992   case Intrinsic::pcmarker:
993     NumArgs = 1;
994     Assert1(isa<Constant>(CI.getOperand(1)),
995             "First argument to llvm.pcmarker must be a constant!", &CI);
996     break;
997
998   case Intrinsic::not_intrinsic:
999     assert(0 && "Invalid intrinsic!"); NumArgs = 0; break;
1000   }
1001
1002   Assert1(FT->getNumParams() == NumArgs || (FT->getNumParams() < NumArgs &&
1003                                              FT->isVarArg()),
1004           "Illegal # arguments for intrinsic function!", IF);
1005 }
1006
1007
1008 //===----------------------------------------------------------------------===//
1009 //  Implement the public interfaces to this file...
1010 //===----------------------------------------------------------------------===//
1011
1012 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1013   return new Verifier(action);
1014 }
1015
1016
1017 // verifyFunction - Create
1018 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1019   Function &F = const_cast<Function&>(f);
1020   assert(!F.isExternal() && "Cannot verify external functions");
1021
1022   FunctionPassManager FPM(new ExistingModuleProvider(F.getParent()));
1023   Verifier *V = new Verifier(action);
1024   FPM.add(V);
1025   FPM.run(F);
1026   return V->Broken;
1027 }
1028
1029 /// verifyModule - Check a module for errors, printing messages on stderr.
1030 /// Return true if the module is corrupt.
1031 ///
1032 bool llvm::verifyModule(const Module &M, VerifierFailureAction action) {
1033   PassManager PM;
1034   Verifier *V = new Verifier(action);
1035   PM.add(V);
1036   PM.run((Module&)M);
1037   return V->Broken;
1038 }
1039
1040 // vim: sw=2