[C++11] More 'nullptr' conversion or in some cases just using a boolean check instead...
[oota-llvm.git] / lib / IR / Verifier.cpp
1 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 i32 %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 //  * A landing pad is defined by a landingpad instruction, and can be jumped to
39 //    only by the unwind edge of an invoke instruction.
40 //  * A landingpad instruction must be the first non-PHI instruction in the
41 //    block.
42 //  * All landingpad instructions must use the same personality function with
43 //    the same function.
44 //  * All other things that are tested by asserts spread about the code...
45 //
46 //===----------------------------------------------------------------------===//
47
48 #include "llvm/IR/Verifier.h"
49 #include "llvm/ADT/STLExtras.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallVector.h"
53 #include "llvm/ADT/StringExtras.h"
54 #include "llvm/IR/CFG.h"
55 #include "llvm/IR/CallSite.h"
56 #include "llvm/IR/CallingConv.h"
57 #include "llvm/IR/ConstantRange.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugInfo.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/Dominators.h"
63 #include "llvm/IR/InlineAsm.h"
64 #include "llvm/IR/InstVisitor.h"
65 #include "llvm/IR/IntrinsicInst.h"
66 #include "llvm/IR/LLVMContext.h"
67 #include "llvm/IR/Metadata.h"
68 #include "llvm/IR/Module.h"
69 #include "llvm/IR/PassManager.h"
70 #include "llvm/Pass.h"
71 #include "llvm/Support/CommandLine.h"
72 #include "llvm/Support/Debug.h"
73 #include "llvm/Support/ErrorHandling.h"
74 #include "llvm/Support/raw_ostream.h"
75 #include <algorithm>
76 #include <cstdarg>
77 using namespace llvm;
78
79 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(false));
80
81 namespace {
82 class Verifier : public InstVisitor<Verifier> {
83   friend class InstVisitor<Verifier>;
84
85   raw_ostream &OS;
86   const Module *M;
87   LLVMContext *Context;
88   const DataLayout *DL;
89   DominatorTree DT;
90
91   /// \brief When verifying a basic block, keep track of all of the
92   /// instructions we have seen so far.
93   ///
94   /// This allows us to do efficient dominance checks for the case when an
95   /// instruction has an operand that is an instruction in the same block.
96   SmallPtrSet<Instruction *, 16> InstsInThisBlock;
97
98   /// \brief Keep track of the metadata nodes that have been checked already.
99   SmallPtrSet<MDNode *, 32> MDNodes;
100
101   /// \brief The personality function referenced by the LandingPadInsts.
102   /// All LandingPadInsts within the same function must use the same
103   /// personality function.
104   const Value *PersonalityFn;
105
106   /// \brief Finder keeps track of all debug info MDNodes in a Module.
107   DebugInfoFinder Finder;
108
109   /// \brief Track the brokenness of the module while recursively visiting.
110   bool Broken;
111
112 public:
113   explicit Verifier(raw_ostream &OS = dbgs())
114       : OS(OS), M(nullptr), Context(nullptr), DL(nullptr),
115         PersonalityFn(nullptr), Broken(false) {}
116
117   bool verify(const Function &F) {
118     M = F.getParent();
119     Context = &M->getContext();
120
121     // First ensure the function is well-enough formed to compute dominance
122     // information.
123     if (F.empty()) {
124       OS << "Function '" << F.getName()
125          << "' does not contain an entry block!\n";
126       return false;
127     }
128     for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
129       if (I->empty() || !I->back().isTerminator()) {
130         OS << "Basic Block in function '" << F.getName()
131            << "' does not have terminator!\n";
132         I->printAsOperand(OS, true);
133         OS << "\n";
134         return false;
135       }
136     }
137
138     // Now directly compute a dominance tree. We don't rely on the pass
139     // manager to provide this as it isolates us from a potentially
140     // out-of-date dominator tree and makes it significantly more complex to
141     // run this code outside of a pass manager.
142     // FIXME: It's really gross that we have to cast away constness here.
143     DT.recalculate(const_cast<Function &>(F));
144
145     Finder.reset();
146     Broken = false;
147     // FIXME: We strip const here because the inst visitor strips const.
148     visit(const_cast<Function &>(F));
149     InstsInThisBlock.clear();
150     PersonalityFn = nullptr;
151
152     if (VerifyDebugInfo)
153       // Verify Debug Info.
154       verifyDebugInfo();
155
156     return !Broken;
157   }
158
159   bool verify(const Module &M) {
160     this->M = &M;
161     Context = &M.getContext();
162     Finder.reset();
163     Broken = false;
164
165     // Scan through, checking all of the external function's linkage now...
166     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
167       visitGlobalValue(*I);
168
169       // Check to make sure function prototypes are okay.
170       if (I->isDeclaration())
171         visitFunction(*I);
172     }
173
174     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
175          I != E; ++I)
176       visitGlobalVariable(*I);
177
178     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
179          I != E; ++I)
180       visitGlobalAlias(*I);
181
182     for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
183                                                E = M.named_metadata_end();
184          I != E; ++I)
185       visitNamedMDNode(*I);
186
187     visitModuleFlags(M);
188     visitModuleIdents(M);
189
190     if (VerifyDebugInfo) {
191       Finder.reset();
192       Finder.processModule(M);
193       // Verify Debug Info.
194       verifyDebugInfo();
195     }
196
197     return !Broken;
198   }
199
200 private:
201   // Verification methods...
202   void visitGlobalValue(const GlobalValue &GV);
203   void visitGlobalVariable(const GlobalVariable &GV);
204   void visitGlobalAlias(const GlobalAlias &GA);
205   void visitNamedMDNode(const NamedMDNode &NMD);
206   void visitMDNode(MDNode &MD, Function *F);
207   void visitModuleIdents(const Module &M);
208   void visitModuleFlags(const Module &M);
209   void visitModuleFlag(const MDNode *Op,
210                        DenseMap<const MDString *, const MDNode *> &SeenIDs,
211                        SmallVectorImpl<const MDNode *> &Requirements);
212   void visitFunction(const Function &F);
213   void visitBasicBlock(BasicBlock &BB);
214
215   // InstVisitor overrides...
216   using InstVisitor<Verifier>::visit;
217   void visit(Instruction &I);
218
219   void visitTruncInst(TruncInst &I);
220   void visitZExtInst(ZExtInst &I);
221   void visitSExtInst(SExtInst &I);
222   void visitFPTruncInst(FPTruncInst &I);
223   void visitFPExtInst(FPExtInst &I);
224   void visitFPToUIInst(FPToUIInst &I);
225   void visitFPToSIInst(FPToSIInst &I);
226   void visitUIToFPInst(UIToFPInst &I);
227   void visitSIToFPInst(SIToFPInst &I);
228   void visitIntToPtrInst(IntToPtrInst &I);
229   void visitPtrToIntInst(PtrToIntInst &I);
230   void visitBitCastInst(BitCastInst &I);
231   void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
232   void visitPHINode(PHINode &PN);
233   void visitBinaryOperator(BinaryOperator &B);
234   void visitICmpInst(ICmpInst &IC);
235   void visitFCmpInst(FCmpInst &FC);
236   void visitExtractElementInst(ExtractElementInst &EI);
237   void visitInsertElementInst(InsertElementInst &EI);
238   void visitShuffleVectorInst(ShuffleVectorInst &EI);
239   void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
240   void visitCallInst(CallInst &CI);
241   void visitInvokeInst(InvokeInst &II);
242   void visitGetElementPtrInst(GetElementPtrInst &GEP);
243   void visitLoadInst(LoadInst &LI);
244   void visitStoreInst(StoreInst &SI);
245   void verifyDominatesUse(Instruction &I, unsigned i);
246   void visitInstruction(Instruction &I);
247   void visitTerminatorInst(TerminatorInst &I);
248   void visitBranchInst(BranchInst &BI);
249   void visitReturnInst(ReturnInst &RI);
250   void visitSwitchInst(SwitchInst &SI);
251   void visitIndirectBrInst(IndirectBrInst &BI);
252   void visitSelectInst(SelectInst &SI);
253   void visitUserOp1(Instruction &I);
254   void visitUserOp2(Instruction &I) { visitUserOp1(I); }
255   void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
256   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
257   void visitAtomicRMWInst(AtomicRMWInst &RMWI);
258   void visitFenceInst(FenceInst &FI);
259   void visitAllocaInst(AllocaInst &AI);
260   void visitExtractValueInst(ExtractValueInst &EVI);
261   void visitInsertValueInst(InsertValueInst &IVI);
262   void visitLandingPadInst(LandingPadInst &LPI);
263
264   void VerifyCallSite(CallSite CS);
265   bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
266                         unsigned ArgNo, std::string &Suffix);
267   bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
268                            SmallVectorImpl<Type *> &ArgTys);
269   bool VerifyIntrinsicIsVarArg(bool isVarArg,
270                                ArrayRef<Intrinsic::IITDescriptor> &Infos);
271   bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
272   void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
273                             const Value *V);
274   void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
275                             bool isReturnValue, const Value *V);
276   void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
277                            const Value *V);
278
279   void VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy);
280   void VerifyConstantExprBitcastType(const ConstantExpr *CE);
281
282   void verifyDebugInfo();
283
284   void WriteValue(const Value *V) {
285     if (!V)
286       return;
287     if (isa<Instruction>(V)) {
288       OS << *V << '\n';
289     } else {
290       V->printAsOperand(OS, true, M);
291       OS << '\n';
292     }
293   }
294
295   void WriteType(Type *T) {
296     if (!T)
297       return;
298     OS << ' ' << *T;
299   }
300
301   // CheckFailed - A check failed, so print out the condition and the message
302   // that failed.  This provides a nice place to put a breakpoint if you want
303   // to see why something is not correct.
304   void CheckFailed(const Twine &Message, const Value *V1 = nullptr,
305                    const Value *V2 = nullptr, const Value *V3 = nullptr,
306                    const Value *V4 = nullptr) {
307     OS << Message.str() << "\n";
308     WriteValue(V1);
309     WriteValue(V2);
310     WriteValue(V3);
311     WriteValue(V4);
312     Broken = true;
313   }
314
315   void CheckFailed(const Twine &Message, const Value *V1, Type *T2,
316                    const Value *V3 = nullptr) {
317     OS << Message.str() << "\n";
318     WriteValue(V1);
319     WriteType(T2);
320     WriteValue(V3);
321     Broken = true;
322   }
323
324   void CheckFailed(const Twine &Message, Type *T1, Type *T2 = nullptr,
325                    Type *T3 = nullptr) {
326     OS << Message.str() << "\n";
327     WriteType(T1);
328     WriteType(T2);
329     WriteType(T3);
330     Broken = true;
331   }
332 };
333 } // End anonymous namespace
334
335 // Assert - We know that cond should be true, if not print an error message.
336 #define Assert(C, M) \
337   do { if (!(C)) { CheckFailed(M); return; } } while (0)
338 #define Assert1(C, M, V1) \
339   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
340 #define Assert2(C, M, V1, V2) \
341   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
342 #define Assert3(C, M, V1, V2, V3) \
343   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
344 #define Assert4(C, M, V1, V2, V3, V4) \
345   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
346
347 void Verifier::visit(Instruction &I) {
348   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
349     Assert1(I.getOperand(i) != nullptr, "Operand is null", &I);
350   InstVisitor<Verifier>::visit(I);
351 }
352
353
354 void Verifier::visitGlobalValue(const GlobalValue &GV) {
355   Assert1(!GV.isDeclaration() ||
356           GV.isMaterializable() ||
357           GV.hasExternalLinkage() ||
358           GV.hasExternalWeakLinkage() ||
359           (isa<GlobalAlias>(GV) &&
360            (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
361           "Global is external, but doesn't have external or weak linkage!",
362           &GV);
363
364   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
365           "Only global variables can have appending linkage!", &GV);
366
367   if (GV.hasAppendingLinkage()) {
368     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
369     Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
370             "Only global arrays can have appending linkage!", GVar);
371   }
372 }
373
374 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
375   if (GV.hasInitializer()) {
376     Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
377             "Global variable initializer type does not match global "
378             "variable type!", &GV);
379
380     // If the global has common linkage, it must have a zero initializer and
381     // cannot be constant.
382     if (GV.hasCommonLinkage()) {
383       Assert1(GV.getInitializer()->isNullValue(),
384               "'common' global must have a zero initializer!", &GV);
385       Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
386               &GV);
387     }
388   } else {
389     Assert1(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
390             "invalid linkage type for global declaration", &GV);
391   }
392
393   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
394                        GV.getName() == "llvm.global_dtors")) {
395     Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
396             "invalid linkage for intrinsic global variable", &GV);
397     // Don't worry about emitting an error for it not being an array,
398     // visitGlobalValue will complain on appending non-array.
399     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
400       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
401       PointerType *FuncPtrTy =
402           FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
403       Assert1(STy && STy->getNumElements() == 2 &&
404               STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
405               STy->getTypeAtIndex(1) == FuncPtrTy,
406               "wrong type for intrinsic global variable", &GV);
407     }
408   }
409
410   if (GV.hasName() && (GV.getName() == "llvm.used" ||
411                        GV.getName() == "llvm.compiler.used")) {
412     Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
413             "invalid linkage for intrinsic global variable", &GV);
414     Type *GVType = GV.getType()->getElementType();
415     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
416       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
417       Assert1(PTy, "wrong type for intrinsic global variable", &GV);
418       if (GV.hasInitializer()) {
419         const Constant *Init = GV.getInitializer();
420         const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
421         Assert1(InitArray, "wrong initalizer for intrinsic global variable",
422                 Init);
423         for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
424           Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
425           Assert1(
426               isa<GlobalVariable>(V) || isa<Function>(V) || isa<GlobalAlias>(V),
427               "invalid llvm.used member", V);
428           Assert1(V->hasName(), "members of llvm.used must be named", V);
429         }
430       }
431     }
432   }
433
434   Assert1(!GV.hasDLLImportStorageClass() ||
435           (GV.isDeclaration() && GV.hasExternalLinkage()) ||
436           GV.hasAvailableExternallyLinkage(),
437           "Global is marked as dllimport, but not external", &GV);
438
439   if (!GV.hasInitializer()) {
440     visitGlobalValue(GV);
441     return;
442   }
443
444   // Walk any aggregate initializers looking for bitcasts between address spaces
445   SmallPtrSet<const Value *, 4> Visited;
446   SmallVector<const Value *, 4> WorkStack;
447   WorkStack.push_back(cast<Value>(GV.getInitializer()));
448
449   while (!WorkStack.empty()) {
450     const Value *V = WorkStack.pop_back_val();
451     if (!Visited.insert(V))
452       continue;
453
454     if (const User *U = dyn_cast<User>(V)) {
455       for (unsigned I = 0, N = U->getNumOperands(); I != N; ++I)
456         WorkStack.push_back(U->getOperand(I));
457     }
458
459     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
460       VerifyConstantExprBitcastType(CE);
461       if (Broken)
462         return;
463     }
464   }
465
466   visitGlobalValue(GV);
467 }
468
469 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
470   Assert1(!GA.getName().empty(),
471           "Alias name cannot be empty!", &GA);
472   Assert1(GlobalAlias::isValidLinkage(GA.getLinkage()),
473           "Alias should have external or external weak linkage!", &GA);
474   Assert1(GA.getAliasee(),
475           "Aliasee cannot be NULL!", &GA);
476   Assert1(GA.getType() == GA.getAliasee()->getType(),
477           "Alias and aliasee types should match!", &GA);
478   Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
479   Assert1(!GA.hasSection(), "Alias cannot have a section!", &GA);
480   Assert1(!GA.getAlignment(), "Alias connot have an alignment", &GA);
481
482   const Constant *Aliasee = GA.getAliasee();
483   const GlobalValue *GV = dyn_cast<GlobalValue>(Aliasee);
484
485   if (!GV) {
486     const ConstantExpr *CE = dyn_cast<ConstantExpr>(Aliasee);
487     if (CE && (CE->getOpcode() == Instruction::BitCast ||
488                CE->getOpcode() == Instruction::AddrSpaceCast ||
489                CE->getOpcode() == Instruction::GetElementPtr))
490       GV = dyn_cast<GlobalValue>(CE->getOperand(0));
491
492     Assert1(GV, "Aliasee should be either GlobalValue, bitcast or "
493                 "addrspacecast of GlobalValue",
494             &GA);
495
496     if (CE->getOpcode() == Instruction::BitCast) {
497       unsigned SrcAS = GV->getType()->getPointerAddressSpace();
498       unsigned DstAS = CE->getType()->getPointerAddressSpace();
499
500       Assert1(SrcAS == DstAS,
501               "Alias bitcasts cannot be between different address spaces",
502               &GA);
503     }
504   }
505   Assert1(!GV->isDeclaration(), "Alias must point to a definition", &GA);
506   if (const GlobalAlias *GAAliasee = dyn_cast<GlobalAlias>(GV)) {
507     Assert1(!GAAliasee->mayBeOverridden(), "Alias cannot point to a weak alias",
508             &GA);
509   }
510
511   const GlobalValue *AG = GA.getAliasedGlobal();
512   Assert1(AG, "Aliasing chain should end with function or global variable",
513           &GA);
514
515   visitGlobalValue(GA);
516 }
517
518 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
519   for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
520     MDNode *MD = NMD.getOperand(i);
521     if (!MD)
522       continue;
523
524     Assert1(!MD->isFunctionLocal(),
525             "Named metadata operand cannot be function local!", MD);
526     visitMDNode(*MD, nullptr);
527   }
528 }
529
530 void Verifier::visitMDNode(MDNode &MD, Function *F) {
531   // Only visit each node once.  Metadata can be mutually recursive, so this
532   // avoids infinite recursion here, as well as being an optimization.
533   if (!MDNodes.insert(&MD))
534     return;
535
536   for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
537     Value *Op = MD.getOperand(i);
538     if (!Op)
539       continue;
540     if (isa<Constant>(Op) || isa<MDString>(Op))
541       continue;
542     if (MDNode *N = dyn_cast<MDNode>(Op)) {
543       Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
544               "Global metadata operand cannot be function local!", &MD, N);
545       visitMDNode(*N, F);
546       continue;
547     }
548     Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
549
550     // If this was an instruction, bb, or argument, verify that it is in the
551     // function that we expect.
552     Function *ActualF = nullptr;
553     if (Instruction *I = dyn_cast<Instruction>(Op))
554       ActualF = I->getParent()->getParent();
555     else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
556       ActualF = BB->getParent();
557     else if (Argument *A = dyn_cast<Argument>(Op))
558       ActualF = A->getParent();
559     assert(ActualF && "Unimplemented function local metadata case!");
560
561     Assert2(ActualF == F, "function-local metadata used in wrong function",
562             &MD, Op);
563   }
564 }
565
566 void Verifier::visitModuleIdents(const Module &M) {
567   const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
568   if (!Idents) 
569     return;
570   
571   // llvm.ident takes a list of metadata entry. Each entry has only one string.
572   // Scan each llvm.ident entry and make sure that this requirement is met.
573   for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
574     const MDNode *N = Idents->getOperand(i);
575     Assert1(N->getNumOperands() == 1,
576             "incorrect number of operands in llvm.ident metadata", N);
577     Assert1(isa<MDString>(N->getOperand(0)),
578             ("invalid value for llvm.ident metadata entry operand"
579              "(the operand should be a string)"),
580             N->getOperand(0));
581   } 
582 }
583
584 void Verifier::visitModuleFlags(const Module &M) {
585   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
586   if (!Flags) return;
587
588   // Scan each flag, and track the flags and requirements.
589   DenseMap<const MDString*, const MDNode*> SeenIDs;
590   SmallVector<const MDNode*, 16> Requirements;
591   for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
592     visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
593   }
594
595   // Validate that the requirements in the module are valid.
596   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
597     const MDNode *Requirement = Requirements[I];
598     const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
599     const Value *ReqValue = Requirement->getOperand(1);
600
601     const MDNode *Op = SeenIDs.lookup(Flag);
602     if (!Op) {
603       CheckFailed("invalid requirement on flag, flag is not present in module",
604                   Flag);
605       continue;
606     }
607
608     if (Op->getOperand(2) != ReqValue) {
609       CheckFailed(("invalid requirement on flag, "
610                    "flag does not have the required value"),
611                   Flag);
612       continue;
613     }
614   }
615 }
616
617 void
618 Verifier::visitModuleFlag(const MDNode *Op,
619                           DenseMap<const MDString *, const MDNode *> &SeenIDs,
620                           SmallVectorImpl<const MDNode *> &Requirements) {
621   // Each module flag should have three arguments, the merge behavior (a
622   // constant int), the flag ID (an MDString), and the value.
623   Assert1(Op->getNumOperands() == 3,
624           "incorrect number of operands in module flag", Op);
625   ConstantInt *Behavior = dyn_cast<ConstantInt>(Op->getOperand(0));
626   MDString *ID = dyn_cast<MDString>(Op->getOperand(1));
627   Assert1(Behavior,
628           "invalid behavior operand in module flag (expected constant integer)",
629           Op->getOperand(0));
630   unsigned BehaviorValue = Behavior->getZExtValue();
631   Assert1(ID,
632           "invalid ID operand in module flag (expected metadata string)",
633           Op->getOperand(1));
634
635   // Sanity check the values for behaviors with additional requirements.
636   switch (BehaviorValue) {
637   default:
638     Assert1(false,
639             "invalid behavior operand in module flag (unexpected constant)",
640             Op->getOperand(0));
641     break;
642
643   case Module::Error:
644   case Module::Warning:
645   case Module::Override:
646     // These behavior types accept any value.
647     break;
648
649   case Module::Require: {
650     // The value should itself be an MDNode with two operands, a flag ID (an
651     // MDString), and a value.
652     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
653     Assert1(Value && Value->getNumOperands() == 2,
654             "invalid value for 'require' module flag (expected metadata pair)",
655             Op->getOperand(2));
656     Assert1(isa<MDString>(Value->getOperand(0)),
657             ("invalid value for 'require' module flag "
658              "(first value operand should be a string)"),
659             Value->getOperand(0));
660
661     // Append it to the list of requirements, to check once all module flags are
662     // scanned.
663     Requirements.push_back(Value);
664     break;
665   }
666
667   case Module::Append:
668   case Module::AppendUnique: {
669     // These behavior types require the operand be an MDNode.
670     Assert1(isa<MDNode>(Op->getOperand(2)),
671             "invalid value for 'append'-type module flag "
672             "(expected a metadata node)", Op->getOperand(2));
673     break;
674   }
675   }
676
677   // Unless this is a "requires" flag, check the ID is unique.
678   if (BehaviorValue != Module::Require) {
679     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
680     Assert1(Inserted,
681             "module flag identifiers must be unique (or of 'require' type)",
682             ID);
683   }
684 }
685
686 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
687                                     bool isFunction, const Value *V) {
688   unsigned Slot = ~0U;
689   for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
690     if (Attrs.getSlotIndex(I) == Idx) {
691       Slot = I;
692       break;
693     }
694
695   assert(Slot != ~0U && "Attribute set inconsistency!");
696
697   for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
698          I != E; ++I) {
699     if (I->isStringAttribute())
700       continue;
701
702     if (I->getKindAsEnum() == Attribute::NoReturn ||
703         I->getKindAsEnum() == Attribute::NoUnwind ||
704         I->getKindAsEnum() == Attribute::NoInline ||
705         I->getKindAsEnum() == Attribute::AlwaysInline ||
706         I->getKindAsEnum() == Attribute::OptimizeForSize ||
707         I->getKindAsEnum() == Attribute::StackProtect ||
708         I->getKindAsEnum() == Attribute::StackProtectReq ||
709         I->getKindAsEnum() == Attribute::StackProtectStrong ||
710         I->getKindAsEnum() == Attribute::NoRedZone ||
711         I->getKindAsEnum() == Attribute::NoImplicitFloat ||
712         I->getKindAsEnum() == Attribute::Naked ||
713         I->getKindAsEnum() == Attribute::InlineHint ||
714         I->getKindAsEnum() == Attribute::StackAlignment ||
715         I->getKindAsEnum() == Attribute::UWTable ||
716         I->getKindAsEnum() == Attribute::NonLazyBind ||
717         I->getKindAsEnum() == Attribute::ReturnsTwice ||
718         I->getKindAsEnum() == Attribute::SanitizeAddress ||
719         I->getKindAsEnum() == Attribute::SanitizeThread ||
720         I->getKindAsEnum() == Attribute::SanitizeMemory ||
721         I->getKindAsEnum() == Attribute::MinSize ||
722         I->getKindAsEnum() == Attribute::NoDuplicate ||
723         I->getKindAsEnum() == Attribute::Builtin ||
724         I->getKindAsEnum() == Attribute::NoBuiltin ||
725         I->getKindAsEnum() == Attribute::Cold ||
726         I->getKindAsEnum() == Attribute::OptimizeNone) {
727       if (!isFunction) {
728         CheckFailed("Attribute '" + I->getAsString() +
729                     "' only applies to functions!", V);
730         return;
731       }
732     } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
733                I->getKindAsEnum() == Attribute::ReadNone) {
734       if (Idx == 0) {
735         CheckFailed("Attribute '" + I->getAsString() +
736                     "' does not apply to function returns");
737         return;
738       }
739     } else if (isFunction) {
740       CheckFailed("Attribute '" + I->getAsString() +
741                   "' does not apply to functions!", V);
742       return;
743     }
744   }
745 }
746
747 // VerifyParameterAttrs - Check the given attributes for an argument or return
748 // value of the specified type.  The value V is printed in error messages.
749 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
750                                     bool isReturnValue, const Value *V) {
751   if (!Attrs.hasAttributes(Idx))
752     return;
753
754   VerifyAttributeTypes(Attrs, Idx, false, V);
755
756   if (isReturnValue)
757     Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
758             !Attrs.hasAttribute(Idx, Attribute::Nest) &&
759             !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
760             !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
761             !Attrs.hasAttribute(Idx, Attribute::Returned) &&
762             !Attrs.hasAttribute(Idx, Attribute::InAlloca),
763             "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
764             "'returned' do not apply to return values!", V);
765
766   // Check for mutually incompatible attributes.  Only inreg is compatible with
767   // sret.
768   unsigned AttrCount = 0;
769   AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
770   AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
771   AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
772                Attrs.hasAttribute(Idx, Attribute::InReg);
773   AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
774   Assert1(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
775                           "and 'sret' are incompatible!", V);
776
777   Assert1(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
778             Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
779           "'inalloca and readonly' are incompatible!", V);
780
781   Assert1(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
782             Attrs.hasAttribute(Idx, Attribute::Returned)), "Attributes "
783           "'sret and returned' are incompatible!", V);
784
785   Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
786             Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes "
787           "'zeroext and signext' are incompatible!", V);
788
789   Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
790             Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
791           "'readnone and readonly' are incompatible!", V);
792
793   Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
794             Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes "
795           "'noinline and alwaysinline' are incompatible!", V);
796
797   Assert1(!AttrBuilder(Attrs, Idx).
798             hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
799           "Wrong types for attribute: " +
800           AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V);
801
802   if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
803     if (!PTy->getElementType()->isSized()) {
804       Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
805               !Attrs.hasAttribute(Idx, Attribute::InAlloca),
806               "Attributes 'byval' and 'inalloca' do not support unsized types!",
807               V);
808     }
809   } else {
810     Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
811             "Attribute 'byval' only applies to parameters with pointer type!",
812             V);
813   }
814 }
815
816 // VerifyFunctionAttrs - Check parameter attributes against a function type.
817 // The value V is printed in error messages.
818 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
819                                    const Value *V) {
820   if (Attrs.isEmpty())
821     return;
822
823   bool SawNest = false;
824   bool SawReturned = false;
825
826   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
827     unsigned Idx = Attrs.getSlotIndex(i);
828
829     Type *Ty;
830     if (Idx == 0)
831       Ty = FT->getReturnType();
832     else if (Idx-1 < FT->getNumParams())
833       Ty = FT->getParamType(Idx-1);
834     else
835       break;  // VarArgs attributes, verified elsewhere.
836
837     VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
838
839     if (Idx == 0)
840       continue;
841
842     if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
843       Assert1(!SawNest, "More than one parameter has attribute nest!", V);
844       SawNest = true;
845     }
846
847     if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
848       Assert1(!SawReturned, "More than one parameter has attribute returned!",
849               V);
850       Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible "
851               "argument and return types for 'returned' attribute", V);
852       SawReturned = true;
853     }
854
855     if (Attrs.hasAttribute(Idx, Attribute::StructRet))
856       Assert1(Idx == 1, "Attribute sret is not on first parameter!", V);
857
858     if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
859       Assert1(Idx == FT->getNumParams(),
860               "inalloca isn't on the last parameter!", V);
861     }
862   }
863
864   if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
865     return;
866
867   VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
868
869   Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
870                                Attribute::ReadNone) &&
871             Attrs.hasAttribute(AttributeSet::FunctionIndex,
872                                Attribute::ReadOnly)),
873           "Attributes 'readnone and readonly' are incompatible!", V);
874
875   Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
876                                Attribute::NoInline) &&
877             Attrs.hasAttribute(AttributeSet::FunctionIndex,
878                                Attribute::AlwaysInline)),
879           "Attributes 'noinline and alwaysinline' are incompatible!", V);
880
881   if (Attrs.hasAttribute(AttributeSet::FunctionIndex, 
882                          Attribute::OptimizeNone)) {
883     Assert1(Attrs.hasAttribute(AttributeSet::FunctionIndex,
884                                Attribute::NoInline),
885             "Attribute 'optnone' requires 'noinline'!", V);
886
887     Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
888                                 Attribute::OptimizeForSize),
889             "Attributes 'optsize and optnone' are incompatible!", V);
890
891     Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
892                                 Attribute::MinSize),
893             "Attributes 'minsize and optnone' are incompatible!", V);
894   }
895 }
896
897 void Verifier::VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy) {
898   // Get the size of the types in bits, we'll need this later
899   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
900   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
901
902   // BitCast implies a no-op cast of type only. No bits change.
903   // However, you can't cast pointers to anything but pointers.
904   Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
905           "Bitcast requires both operands to be pointer or neither", V);
906   Assert1(SrcBitSize == DestBitSize,
907           "Bitcast requires types of same width", V);
908
909   // Disallow aggregates.
910   Assert1(!SrcTy->isAggregateType(),
911           "Bitcast operand must not be aggregate", V);
912   Assert1(!DestTy->isAggregateType(),
913           "Bitcast type must not be aggregate", V);
914
915   // Without datalayout, assume all address spaces are the same size.
916   // Don't check if both types are not pointers.
917   // Skip casts between scalars and vectors.
918   if (!DL ||
919       !SrcTy->isPtrOrPtrVectorTy() ||
920       !DestTy->isPtrOrPtrVectorTy() ||
921       SrcTy->isVectorTy() != DestTy->isVectorTy()) {
922     return;
923   }
924
925   unsigned SrcAS = SrcTy->getPointerAddressSpace();
926   unsigned DstAS = DestTy->getPointerAddressSpace();
927
928   Assert1(SrcAS == DstAS,
929           "Bitcasts between pointers of different address spaces is not legal."
930           "Use AddrSpaceCast instead.", V);
931 }
932
933 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
934   if (CE->getOpcode() == Instruction::BitCast) {
935     Type *SrcTy = CE->getOperand(0)->getType();
936     Type *DstTy = CE->getType();
937     VerifyBitcastType(CE, DstTy, SrcTy);
938   }
939 }
940
941 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
942   if (Attrs.getNumSlots() == 0)
943     return true;
944
945   unsigned LastSlot = Attrs.getNumSlots() - 1;
946   unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
947   if (LastIndex <= Params
948       || (LastIndex == AttributeSet::FunctionIndex
949           && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
950     return true;
951
952   return false;
953 }
954
955 // visitFunction - Verify that a function is ok.
956 //
957 void Verifier::visitFunction(const Function &F) {
958   // Check function arguments.
959   FunctionType *FT = F.getFunctionType();
960   unsigned NumArgs = F.arg_size();
961
962   Assert1(Context == &F.getContext(),
963           "Function context does not match Module context!", &F);
964
965   Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
966   Assert2(FT->getNumParams() == NumArgs,
967           "# formal arguments must match # of arguments for function type!",
968           &F, FT);
969   Assert1(F.getReturnType()->isFirstClassType() ||
970           F.getReturnType()->isVoidTy() ||
971           F.getReturnType()->isStructTy(),
972           "Functions cannot return aggregate values!", &F);
973
974   Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
975           "Invalid struct return type!", &F);
976
977   AttributeSet Attrs = F.getAttributes();
978
979   Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
980           "Attribute after last parameter!", &F);
981
982   // Check function attributes.
983   VerifyFunctionAttrs(FT, Attrs, &F);
984
985   // On function declarations/definitions, we do not support the builtin
986   // attribute. We do not check this in VerifyFunctionAttrs since that is
987   // checking for Attributes that can/can not ever be on functions.
988   Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
989                               Attribute::Builtin),
990           "Attribute 'builtin' can only be applied to a callsite.", &F);
991
992   // Check that this function meets the restrictions on this calling convention.
993   switch (F.getCallingConv()) {
994   default:
995     break;
996   case CallingConv::C:
997     break;
998   case CallingConv::Fast:
999   case CallingConv::Cold:
1000   case CallingConv::X86_FastCall:
1001   case CallingConv::X86_ThisCall:
1002   case CallingConv::Intel_OCL_BI:
1003   case CallingConv::PTX_Kernel:
1004   case CallingConv::PTX_Device:
1005     Assert1(!F.isVarArg(),
1006             "Varargs functions must have C calling conventions!", &F);
1007     break;
1008   }
1009
1010   bool isLLVMdotName = F.getName().size() >= 5 &&
1011                        F.getName().substr(0, 5) == "llvm.";
1012
1013   // Check that the argument values match the function type for this function...
1014   unsigned i = 0;
1015   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1016        ++I, ++i) {
1017     Assert2(I->getType() == FT->getParamType(i),
1018             "Argument value does not match function argument type!",
1019             I, FT->getParamType(i));
1020     Assert1(I->getType()->isFirstClassType(),
1021             "Function arguments must have first-class types!", I);
1022     if (!isLLVMdotName)
1023       Assert2(!I->getType()->isMetadataTy(),
1024               "Function takes metadata but isn't an intrinsic", I, &F);
1025   }
1026
1027   if (F.isMaterializable()) {
1028     // Function has a body somewhere we can't see.
1029   } else if (F.isDeclaration()) {
1030     Assert1(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1031             "invalid linkage type for function declaration", &F);
1032   } else {
1033     // Verify that this function (which has a body) is not named "llvm.*".  It
1034     // is not legal to define intrinsics.
1035     Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1036
1037     // Check the entry node
1038     const BasicBlock *Entry = &F.getEntryBlock();
1039     Assert1(pred_begin(Entry) == pred_end(Entry),
1040             "Entry block to function must not have predecessors!", Entry);
1041
1042     // The address of the entry block cannot be taken, unless it is dead.
1043     if (Entry->hasAddressTaken()) {
1044       Assert1(!BlockAddress::lookup(Entry)->isConstantUsed(),
1045               "blockaddress may not be used with the entry block!", Entry);
1046     }
1047   }
1048
1049   // If this function is actually an intrinsic, verify that it is only used in
1050   // direct call/invokes, never having its "address taken".
1051   if (F.getIntrinsicID()) {
1052     const User *U;
1053     if (F.hasAddressTaken(&U))
1054       Assert1(0, "Invalid user of intrinsic instruction!", U);
1055   }
1056
1057   Assert1(!F.hasDLLImportStorageClass() ||
1058           (F.isDeclaration() && F.hasExternalLinkage()) ||
1059           F.hasAvailableExternallyLinkage(),
1060           "Function is marked as dllimport, but not external.", &F);
1061 }
1062
1063 // verifyBasicBlock - Verify that a basic block is well formed...
1064 //
1065 void Verifier::visitBasicBlock(BasicBlock &BB) {
1066   InstsInThisBlock.clear();
1067
1068   // Ensure that basic blocks have terminators!
1069   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1070
1071   // Check constraints that this basic block imposes on all of the PHI nodes in
1072   // it.
1073   if (isa<PHINode>(BB.front())) {
1074     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1075     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1076     std::sort(Preds.begin(), Preds.end());
1077     PHINode *PN;
1078     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1079       // Ensure that PHI nodes have at least one entry!
1080       Assert1(PN->getNumIncomingValues() != 0,
1081               "PHI nodes must have at least one entry.  If the block is dead, "
1082               "the PHI should be removed!", PN);
1083       Assert1(PN->getNumIncomingValues() == Preds.size(),
1084               "PHINode should have one entry for each predecessor of its "
1085               "parent basic block!", PN);
1086
1087       // Get and sort all incoming values in the PHI node...
1088       Values.clear();
1089       Values.reserve(PN->getNumIncomingValues());
1090       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1091         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1092                                         PN->getIncomingValue(i)));
1093       std::sort(Values.begin(), Values.end());
1094
1095       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1096         // Check to make sure that if there is more than one entry for a
1097         // particular basic block in this PHI node, that the incoming values are
1098         // all identical.
1099         //
1100         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
1101                 Values[i].second == Values[i-1].second,
1102                 "PHI node has multiple entries for the same basic block with "
1103                 "different incoming values!", PN, Values[i].first,
1104                 Values[i].second, Values[i-1].second);
1105
1106         // Check to make sure that the predecessors and PHI node entries are
1107         // matched up.
1108         Assert3(Values[i].first == Preds[i],
1109                 "PHI node entries do not match predecessors!", PN,
1110                 Values[i].first, Preds[i]);
1111       }
1112     }
1113   }
1114 }
1115
1116 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1117   // Ensure that terminators only exist at the end of the basic block.
1118   Assert1(&I == I.getParent()->getTerminator(),
1119           "Terminator found in the middle of a basic block!", I.getParent());
1120   visitInstruction(I);
1121 }
1122
1123 void Verifier::visitBranchInst(BranchInst &BI) {
1124   if (BI.isConditional()) {
1125     Assert2(BI.getCondition()->getType()->isIntegerTy(1),
1126             "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1127   }
1128   visitTerminatorInst(BI);
1129 }
1130
1131 void Verifier::visitReturnInst(ReturnInst &RI) {
1132   Function *F = RI.getParent()->getParent();
1133   unsigned N = RI.getNumOperands();
1134   if (F->getReturnType()->isVoidTy())
1135     Assert2(N == 0,
1136             "Found return instr that returns non-void in Function of void "
1137             "return type!", &RI, F->getReturnType());
1138   else
1139     Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1140             "Function return type does not match operand "
1141             "type of return inst!", &RI, F->getReturnType());
1142
1143   // Check to make sure that the return value has necessary properties for
1144   // terminators...
1145   visitTerminatorInst(RI);
1146 }
1147
1148 void Verifier::visitSwitchInst(SwitchInst &SI) {
1149   // Check to make sure that all of the constants in the switch instruction
1150   // have the same type as the switched-on value.
1151   Type *SwitchTy = SI.getCondition()->getType();
1152   SmallPtrSet<ConstantInt*, 32> Constants;
1153   for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1154     Assert1(i.getCaseValue()->getType() == SwitchTy,
1155             "Switch constants must all be same type as switch value!", &SI);
1156     Assert2(Constants.insert(i.getCaseValue()),
1157             "Duplicate integer as switch case", &SI, i.getCaseValue());
1158   }
1159
1160   visitTerminatorInst(SI);
1161 }
1162
1163 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1164   Assert1(BI.getAddress()->getType()->isPointerTy(),
1165           "Indirectbr operand must have pointer type!", &BI);
1166   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1167     Assert1(BI.getDestination(i)->getType()->isLabelTy(),
1168             "Indirectbr destinations must all have pointer type!", &BI);
1169
1170   visitTerminatorInst(BI);
1171 }
1172
1173 void Verifier::visitSelectInst(SelectInst &SI) {
1174   Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1175                                           SI.getOperand(2)),
1176           "Invalid operands for select instruction!", &SI);
1177
1178   Assert1(SI.getTrueValue()->getType() == SI.getType(),
1179           "Select values must have same type as select instruction!", &SI);
1180   visitInstruction(SI);
1181 }
1182
1183 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1184 /// a pass, if any exist, it's an error.
1185 ///
1186 void Verifier::visitUserOp1(Instruction &I) {
1187   Assert1(0, "User-defined operators should not live outside of a pass!", &I);
1188 }
1189
1190 void Verifier::visitTruncInst(TruncInst &I) {
1191   // Get the source and destination types
1192   Type *SrcTy = I.getOperand(0)->getType();
1193   Type *DestTy = I.getType();
1194
1195   // Get the size of the types in bits, we'll need this later
1196   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1197   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1198
1199   Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1200   Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1201   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1202           "trunc source and destination must both be a vector or neither", &I);
1203   Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
1204
1205   visitInstruction(I);
1206 }
1207
1208 void Verifier::visitZExtInst(ZExtInst &I) {
1209   // Get the source and destination types
1210   Type *SrcTy = I.getOperand(0)->getType();
1211   Type *DestTy = I.getType();
1212
1213   // Get the size of the types in bits, we'll need this later
1214   Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1215   Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1216   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1217           "zext source and destination must both be a vector or neither", &I);
1218   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1219   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1220
1221   Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
1222
1223   visitInstruction(I);
1224 }
1225
1226 void Verifier::visitSExtInst(SExtInst &I) {
1227   // Get the source and destination types
1228   Type *SrcTy = I.getOperand(0)->getType();
1229   Type *DestTy = I.getType();
1230
1231   // Get the size of the types in bits, we'll need this later
1232   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1233   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1234
1235   Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1236   Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1237   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1238           "sext source and destination must both be a vector or neither", &I);
1239   Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
1240
1241   visitInstruction(I);
1242 }
1243
1244 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1245   // Get the source and destination types
1246   Type *SrcTy = I.getOperand(0)->getType();
1247   Type *DestTy = I.getType();
1248   // Get the size of the types in bits, we'll need this later
1249   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1250   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1251
1252   Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
1253   Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
1254   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1255           "fptrunc source and destination must both be a vector or neither",&I);
1256   Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
1257
1258   visitInstruction(I);
1259 }
1260
1261 void Verifier::visitFPExtInst(FPExtInst &I) {
1262   // Get the source and destination types
1263   Type *SrcTy = I.getOperand(0)->getType();
1264   Type *DestTy = I.getType();
1265
1266   // Get the size of the types in bits, we'll need this later
1267   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1268   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1269
1270   Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
1271   Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
1272   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1273           "fpext source and destination must both be a vector or neither", &I);
1274   Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
1275
1276   visitInstruction(I);
1277 }
1278
1279 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1280   // Get the source and destination types
1281   Type *SrcTy = I.getOperand(0)->getType();
1282   Type *DestTy = I.getType();
1283
1284   bool SrcVec = SrcTy->isVectorTy();
1285   bool DstVec = DestTy->isVectorTy();
1286
1287   Assert1(SrcVec == DstVec,
1288           "UIToFP source and dest must both be vector or scalar", &I);
1289   Assert1(SrcTy->isIntOrIntVectorTy(),
1290           "UIToFP source must be integer or integer vector", &I);
1291   Assert1(DestTy->isFPOrFPVectorTy(),
1292           "UIToFP result must be FP or FP vector", &I);
1293
1294   if (SrcVec && DstVec)
1295     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1296             cast<VectorType>(DestTy)->getNumElements(),
1297             "UIToFP source and dest vector length mismatch", &I);
1298
1299   visitInstruction(I);
1300 }
1301
1302 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1303   // Get the source and destination types
1304   Type *SrcTy = I.getOperand(0)->getType();
1305   Type *DestTy = I.getType();
1306
1307   bool SrcVec = SrcTy->isVectorTy();
1308   bool DstVec = DestTy->isVectorTy();
1309
1310   Assert1(SrcVec == DstVec,
1311           "SIToFP source and dest must both be vector or scalar", &I);
1312   Assert1(SrcTy->isIntOrIntVectorTy(),
1313           "SIToFP source must be integer or integer vector", &I);
1314   Assert1(DestTy->isFPOrFPVectorTy(),
1315           "SIToFP result must be FP or FP vector", &I);
1316
1317   if (SrcVec && DstVec)
1318     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1319             cast<VectorType>(DestTy)->getNumElements(),
1320             "SIToFP source and dest vector length mismatch", &I);
1321
1322   visitInstruction(I);
1323 }
1324
1325 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1326   // Get the source and destination types
1327   Type *SrcTy = I.getOperand(0)->getType();
1328   Type *DestTy = I.getType();
1329
1330   bool SrcVec = SrcTy->isVectorTy();
1331   bool DstVec = DestTy->isVectorTy();
1332
1333   Assert1(SrcVec == DstVec,
1334           "FPToUI source and dest must both be vector or scalar", &I);
1335   Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1336           &I);
1337   Assert1(DestTy->isIntOrIntVectorTy(),
1338           "FPToUI result must be integer or integer vector", &I);
1339
1340   if (SrcVec && DstVec)
1341     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1342             cast<VectorType>(DestTy)->getNumElements(),
1343             "FPToUI source and dest vector length mismatch", &I);
1344
1345   visitInstruction(I);
1346 }
1347
1348 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1349   // Get the source and destination types
1350   Type *SrcTy = I.getOperand(0)->getType();
1351   Type *DestTy = I.getType();
1352
1353   bool SrcVec = SrcTy->isVectorTy();
1354   bool DstVec = DestTy->isVectorTy();
1355
1356   Assert1(SrcVec == DstVec,
1357           "FPToSI source and dest must both be vector or scalar", &I);
1358   Assert1(SrcTy->isFPOrFPVectorTy(),
1359           "FPToSI source must be FP or FP vector", &I);
1360   Assert1(DestTy->isIntOrIntVectorTy(),
1361           "FPToSI result must be integer or integer vector", &I);
1362
1363   if (SrcVec && DstVec)
1364     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1365             cast<VectorType>(DestTy)->getNumElements(),
1366             "FPToSI source and dest vector length mismatch", &I);
1367
1368   visitInstruction(I);
1369 }
1370
1371 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1372   // Get the source and destination types
1373   Type *SrcTy = I.getOperand(0)->getType();
1374   Type *DestTy = I.getType();
1375
1376   Assert1(SrcTy->getScalarType()->isPointerTy(),
1377           "PtrToInt source must be pointer", &I);
1378   Assert1(DestTy->getScalarType()->isIntegerTy(),
1379           "PtrToInt result must be integral", &I);
1380   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1381           "PtrToInt type mismatch", &I);
1382
1383   if (SrcTy->isVectorTy()) {
1384     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1385     VectorType *VDest = dyn_cast<VectorType>(DestTy);
1386     Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1387           "PtrToInt Vector width mismatch", &I);
1388   }
1389
1390   visitInstruction(I);
1391 }
1392
1393 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1394   // Get the source and destination types
1395   Type *SrcTy = I.getOperand(0)->getType();
1396   Type *DestTy = I.getType();
1397
1398   Assert1(SrcTy->getScalarType()->isIntegerTy(),
1399           "IntToPtr source must be an integral", &I);
1400   Assert1(DestTy->getScalarType()->isPointerTy(),
1401           "IntToPtr result must be a pointer",&I);
1402   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1403           "IntToPtr type mismatch", &I);
1404   if (SrcTy->isVectorTy()) {
1405     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1406     VectorType *VDest = dyn_cast<VectorType>(DestTy);
1407     Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1408           "IntToPtr Vector width mismatch", &I);
1409   }
1410   visitInstruction(I);
1411 }
1412
1413 void Verifier::visitBitCastInst(BitCastInst &I) {
1414   Type *SrcTy = I.getOperand(0)->getType();
1415   Type *DestTy = I.getType();
1416   VerifyBitcastType(&I, DestTy, SrcTy);
1417   visitInstruction(I);
1418 }
1419
1420 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
1421   Type *SrcTy = I.getOperand(0)->getType();
1422   Type *DestTy = I.getType();
1423
1424   Assert1(SrcTy->isPtrOrPtrVectorTy(),
1425           "AddrSpaceCast source must be a pointer", &I);
1426   Assert1(DestTy->isPtrOrPtrVectorTy(),
1427           "AddrSpaceCast result must be a pointer", &I);
1428   Assert1(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
1429           "AddrSpaceCast must be between different address spaces", &I);
1430   if (SrcTy->isVectorTy())
1431     Assert1(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
1432             "AddrSpaceCast vector pointer number of elements mismatch", &I);
1433   visitInstruction(I);
1434 }
1435
1436 /// visitPHINode - Ensure that a PHI node is well formed.
1437 ///
1438 void Verifier::visitPHINode(PHINode &PN) {
1439   // Ensure that the PHI nodes are all grouped together at the top of the block.
1440   // This can be tested by checking whether the instruction before this is
1441   // either nonexistent (because this is begin()) or is a PHI node.  If not,
1442   // then there is some other instruction before a PHI.
1443   Assert2(&PN == &PN.getParent()->front() ||
1444           isa<PHINode>(--BasicBlock::iterator(&PN)),
1445           "PHI nodes not grouped at top of basic block!",
1446           &PN, PN.getParent());
1447
1448   // Check that all of the values of the PHI node have the same type as the
1449   // result, and that the incoming blocks are really basic blocks.
1450   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1451     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1452             "PHI node operands are not the same type as the result!", &PN);
1453   }
1454
1455   // All other PHI node constraints are checked in the visitBasicBlock method.
1456
1457   visitInstruction(PN);
1458 }
1459
1460 void Verifier::VerifyCallSite(CallSite CS) {
1461   Instruction *I = CS.getInstruction();
1462
1463   Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1464           "Called function must be a pointer!", I);
1465   PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1466
1467   Assert1(FPTy->getElementType()->isFunctionTy(),
1468           "Called function is not pointer to function type!", I);
1469   FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1470
1471   // Verify that the correct number of arguments are being passed
1472   if (FTy->isVarArg())
1473     Assert1(CS.arg_size() >= FTy->getNumParams(),
1474             "Called function requires more parameters than were provided!",I);
1475   else
1476     Assert1(CS.arg_size() == FTy->getNumParams(),
1477             "Incorrect number of arguments passed to called function!", I);
1478
1479   // Verify that all arguments to the call match the function type.
1480   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1481     Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1482             "Call parameter type does not match function signature!",
1483             CS.getArgument(i), FTy->getParamType(i), I);
1484
1485   AttributeSet Attrs = CS.getAttributes();
1486
1487   Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1488           "Attribute after last parameter!", I);
1489
1490   // Verify call attributes.
1491   VerifyFunctionAttrs(FTy, Attrs, I);
1492
1493   if (FTy->isVarArg()) {
1494     // FIXME? is 'nest' even legal here?
1495     bool SawNest = false;
1496     bool SawReturned = false;
1497
1498     for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1499       if (Attrs.hasAttribute(Idx, Attribute::Nest))
1500         SawNest = true;
1501       if (Attrs.hasAttribute(Idx, Attribute::Returned))
1502         SawReturned = true;
1503     }
1504
1505     // Check attributes on the varargs part.
1506     for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1507       Type *Ty = CS.getArgument(Idx-1)->getType();
1508       VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1509
1510       if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1511         Assert1(!SawNest, "More than one parameter has attribute nest!", I);
1512         SawNest = true;
1513       }
1514
1515       if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1516         Assert1(!SawReturned, "More than one parameter has attribute returned!",
1517                 I);
1518         Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1519                 "Incompatible argument and return types for 'returned' "
1520                 "attribute", I);
1521         SawReturned = true;
1522       }
1523
1524       Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1525               "Attribute 'sret' cannot be used for vararg call arguments!", I);
1526
1527       if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
1528         Assert1(Idx == CS.arg_size(), "inalloca isn't on the last argument!",
1529                 I);
1530     }
1531   }
1532
1533   // Verify that there's no metadata unless it's a direct call to an intrinsic.
1534   if (CS.getCalledFunction() == nullptr ||
1535       !CS.getCalledFunction()->getName().startswith("llvm.")) {
1536     for (FunctionType::param_iterator PI = FTy->param_begin(),
1537            PE = FTy->param_end(); PI != PE; ++PI)
1538       Assert1(!(*PI)->isMetadataTy(),
1539               "Function has metadata parameter but isn't an intrinsic", I);
1540   }
1541
1542   visitInstruction(*I);
1543 }
1544
1545 void Verifier::visitCallInst(CallInst &CI) {
1546   VerifyCallSite(&CI);
1547
1548   if (Function *F = CI.getCalledFunction())
1549     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1550       visitIntrinsicFunctionCall(ID, CI);
1551 }
1552
1553 void Verifier::visitInvokeInst(InvokeInst &II) {
1554   VerifyCallSite(&II);
1555
1556   // Verify that there is a landingpad instruction as the first non-PHI
1557   // instruction of the 'unwind' destination.
1558   Assert1(II.getUnwindDest()->isLandingPad(),
1559           "The unwind destination does not have a landingpad instruction!",&II);
1560
1561   visitTerminatorInst(II);
1562 }
1563
1564 /// visitBinaryOperator - Check that both arguments to the binary operator are
1565 /// of the same type!
1566 ///
1567 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1568   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1569           "Both operands to a binary operator are not of the same type!", &B);
1570
1571   switch (B.getOpcode()) {
1572   // Check that integer arithmetic operators are only used with
1573   // integral operands.
1574   case Instruction::Add:
1575   case Instruction::Sub:
1576   case Instruction::Mul:
1577   case Instruction::SDiv:
1578   case Instruction::UDiv:
1579   case Instruction::SRem:
1580   case Instruction::URem:
1581     Assert1(B.getType()->isIntOrIntVectorTy(),
1582             "Integer arithmetic operators only work with integral types!", &B);
1583     Assert1(B.getType() == B.getOperand(0)->getType(),
1584             "Integer arithmetic operators must have same type "
1585             "for operands and result!", &B);
1586     break;
1587   // Check that floating-point arithmetic operators are only used with
1588   // floating-point operands.
1589   case Instruction::FAdd:
1590   case Instruction::FSub:
1591   case Instruction::FMul:
1592   case Instruction::FDiv:
1593   case Instruction::FRem:
1594     Assert1(B.getType()->isFPOrFPVectorTy(),
1595             "Floating-point arithmetic operators only work with "
1596             "floating-point types!", &B);
1597     Assert1(B.getType() == B.getOperand(0)->getType(),
1598             "Floating-point arithmetic operators must have same type "
1599             "for operands and result!", &B);
1600     break;
1601   // Check that logical operators are only used with integral operands.
1602   case Instruction::And:
1603   case Instruction::Or:
1604   case Instruction::Xor:
1605     Assert1(B.getType()->isIntOrIntVectorTy(),
1606             "Logical operators only work with integral types!", &B);
1607     Assert1(B.getType() == B.getOperand(0)->getType(),
1608             "Logical operators must have same type for operands and result!",
1609             &B);
1610     break;
1611   case Instruction::Shl:
1612   case Instruction::LShr:
1613   case Instruction::AShr:
1614     Assert1(B.getType()->isIntOrIntVectorTy(),
1615             "Shifts only work with integral types!", &B);
1616     Assert1(B.getType() == B.getOperand(0)->getType(),
1617             "Shift return type must be same as operands!", &B);
1618     break;
1619   default:
1620     llvm_unreachable("Unknown BinaryOperator opcode!");
1621   }
1622
1623   visitInstruction(B);
1624 }
1625
1626 void Verifier::visitICmpInst(ICmpInst &IC) {
1627   // Check that the operands are the same type
1628   Type *Op0Ty = IC.getOperand(0)->getType();
1629   Type *Op1Ty = IC.getOperand(1)->getType();
1630   Assert1(Op0Ty == Op1Ty,
1631           "Both operands to ICmp instruction are not of the same type!", &IC);
1632   // Check that the operands are the right type
1633   Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1634           "Invalid operand types for ICmp instruction", &IC);
1635   // Check that the predicate is valid.
1636   Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1637           IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1638           "Invalid predicate in ICmp instruction!", &IC);
1639
1640   visitInstruction(IC);
1641 }
1642
1643 void Verifier::visitFCmpInst(FCmpInst &FC) {
1644   // Check that the operands are the same type
1645   Type *Op0Ty = FC.getOperand(0)->getType();
1646   Type *Op1Ty = FC.getOperand(1)->getType();
1647   Assert1(Op0Ty == Op1Ty,
1648           "Both operands to FCmp instruction are not of the same type!", &FC);
1649   // Check that the operands are the right type
1650   Assert1(Op0Ty->isFPOrFPVectorTy(),
1651           "Invalid operand types for FCmp instruction", &FC);
1652   // Check that the predicate is valid.
1653   Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1654           FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1655           "Invalid predicate in FCmp instruction!", &FC);
1656
1657   visitInstruction(FC);
1658 }
1659
1660 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1661   Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1662                                               EI.getOperand(1)),
1663           "Invalid extractelement operands!", &EI);
1664   visitInstruction(EI);
1665 }
1666
1667 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1668   Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1669                                              IE.getOperand(1),
1670                                              IE.getOperand(2)),
1671           "Invalid insertelement operands!", &IE);
1672   visitInstruction(IE);
1673 }
1674
1675 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1676   Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1677                                              SV.getOperand(2)),
1678           "Invalid shufflevector operands!", &SV);
1679   visitInstruction(SV);
1680 }
1681
1682 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1683   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1684
1685   Assert1(isa<PointerType>(TargetTy),
1686     "GEP base pointer is not a vector or a vector of pointers", &GEP);
1687   Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1688           "GEP into unsized type!", &GEP);
1689   Assert1(GEP.getPointerOperandType()->isVectorTy() ==
1690           GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
1691           &GEP);
1692
1693   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1694   Type *ElTy =
1695     GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1696   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1697
1698   Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
1699           cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
1700           == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
1701
1702   if (GEP.getPointerOperandType()->isVectorTy()) {
1703     // Additional checks for vector GEPs.
1704     unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
1705     Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
1706             "Vector GEP result width doesn't match operand's", &GEP);
1707     for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1708       Type *IndexTy = Idxs[i]->getType();
1709       Assert1(IndexTy->isVectorTy(),
1710               "Vector GEP must have vector indices!", &GEP);
1711       unsigned IndexWidth = IndexTy->getVectorNumElements();
1712       Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1713     }
1714   }
1715   visitInstruction(GEP);
1716 }
1717
1718 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1719   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1720 }
1721
1722 void Verifier::visitLoadInst(LoadInst &LI) {
1723   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1724   Assert1(PTy, "Load operand must be a pointer.", &LI);
1725   Type *ElTy = PTy->getElementType();
1726   Assert2(ElTy == LI.getType(),
1727           "Load result type does not match pointer operand type!", &LI, ElTy);
1728   if (LI.isAtomic()) {
1729     Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1730             "Load cannot have Release ordering", &LI);
1731     Assert1(LI.getAlignment() != 0,
1732             "Atomic load must specify explicit alignment", &LI);
1733     if (!ElTy->isPointerTy()) {
1734       Assert2(ElTy->isIntegerTy(),
1735               "atomic load operand must have integer type!",
1736               &LI, ElTy);
1737       unsigned Size = ElTy->getPrimitiveSizeInBits();
1738       Assert2(Size >= 8 && !(Size & (Size - 1)),
1739               "atomic load operand must be power-of-two byte-sized integer",
1740               &LI, ElTy);
1741     }
1742   } else {
1743     Assert1(LI.getSynchScope() == CrossThread,
1744             "Non-atomic load cannot have SynchronizationScope specified", &LI);
1745   }
1746
1747   if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1748     unsigned NumOperands = Range->getNumOperands();
1749     Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1750     unsigned NumRanges = NumOperands / 2;
1751     Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1752
1753     ConstantRange LastRange(1); // Dummy initial value
1754     for (unsigned i = 0; i < NumRanges; ++i) {
1755       ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1756       Assert1(Low, "The lower limit must be an integer!", Low);
1757       ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1758       Assert1(High, "The upper limit must be an integer!", High);
1759       Assert1(High->getType() == Low->getType() &&
1760               High->getType() == ElTy, "Range types must match load type!",
1761               &LI);
1762
1763       APInt HighV = High->getValue();
1764       APInt LowV = Low->getValue();
1765       ConstantRange CurRange(LowV, HighV);
1766       Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1767               "Range must not be empty!", Range);
1768       if (i != 0) {
1769         Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1770                 "Intervals are overlapping", Range);
1771         Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1772                 Range);
1773         Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1774                 Range);
1775       }
1776       LastRange = ConstantRange(LowV, HighV);
1777     }
1778     if (NumRanges > 2) {
1779       APInt FirstLow =
1780         dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1781       APInt FirstHigh =
1782         dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1783       ConstantRange FirstRange(FirstLow, FirstHigh);
1784       Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1785               "Intervals are overlapping", Range);
1786       Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1787               Range);
1788     }
1789
1790
1791   }
1792
1793   visitInstruction(LI);
1794 }
1795
1796 void Verifier::visitStoreInst(StoreInst &SI) {
1797   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1798   Assert1(PTy, "Store operand must be a pointer.", &SI);
1799   Type *ElTy = PTy->getElementType();
1800   Assert2(ElTy == SI.getOperand(0)->getType(),
1801           "Stored value type does not match pointer operand type!",
1802           &SI, ElTy);
1803   if (SI.isAtomic()) {
1804     Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1805             "Store cannot have Acquire ordering", &SI);
1806     Assert1(SI.getAlignment() != 0,
1807             "Atomic store must specify explicit alignment", &SI);
1808     if (!ElTy->isPointerTy()) {
1809       Assert2(ElTy->isIntegerTy(),
1810               "atomic store operand must have integer type!",
1811               &SI, ElTy);
1812       unsigned Size = ElTy->getPrimitiveSizeInBits();
1813       Assert2(Size >= 8 && !(Size & (Size - 1)),
1814               "atomic store operand must be power-of-two byte-sized integer",
1815               &SI, ElTy);
1816     }
1817   } else {
1818     Assert1(SI.getSynchScope() == CrossThread,
1819             "Non-atomic store cannot have SynchronizationScope specified", &SI);
1820   }
1821   visitInstruction(SI);
1822 }
1823
1824 void Verifier::visitAllocaInst(AllocaInst &AI) {
1825   SmallPtrSet<const Type*, 4> Visited;
1826   PointerType *PTy = AI.getType();
1827   Assert1(PTy->getAddressSpace() == 0,
1828           "Allocation instruction pointer not in the generic address space!",
1829           &AI);
1830   Assert1(PTy->getElementType()->isSized(&Visited), "Cannot allocate unsized type",
1831           &AI);
1832   Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1833           "Alloca array size must have integer type", &AI);
1834
1835   visitInstruction(AI);
1836 }
1837
1838 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1839
1840   // FIXME: more conditions???
1841   Assert1(CXI.getSuccessOrdering() != NotAtomic,
1842           "cmpxchg instructions must be atomic.", &CXI);
1843   Assert1(CXI.getFailureOrdering() != NotAtomic,
1844           "cmpxchg instructions must be atomic.", &CXI);
1845   Assert1(CXI.getSuccessOrdering() != Unordered,
1846           "cmpxchg instructions cannot be unordered.", &CXI);
1847   Assert1(CXI.getFailureOrdering() != Unordered,
1848           "cmpxchg instructions cannot be unordered.", &CXI);
1849   Assert1(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
1850           "cmpxchg instructions be at least as constrained on success as fail",
1851           &CXI);
1852   Assert1(CXI.getFailureOrdering() != Release &&
1853               CXI.getFailureOrdering() != AcquireRelease,
1854           "cmpxchg failure ordering cannot include release semantics", &CXI);
1855
1856   PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1857   Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1858   Type *ElTy = PTy->getElementType();
1859   Assert2(ElTy->isIntegerTy(),
1860           "cmpxchg operand must have integer type!",
1861           &CXI, ElTy);
1862   unsigned Size = ElTy->getPrimitiveSizeInBits();
1863   Assert2(Size >= 8 && !(Size & (Size - 1)),
1864           "cmpxchg operand must be power-of-two byte-sized integer",
1865           &CXI, ElTy);
1866   Assert2(ElTy == CXI.getOperand(1)->getType(),
1867           "Expected value type does not match pointer operand type!",
1868           &CXI, ElTy);
1869   Assert2(ElTy == CXI.getOperand(2)->getType(),
1870           "Stored value type does not match pointer operand type!",
1871           &CXI, ElTy);
1872   visitInstruction(CXI);
1873 }
1874
1875 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1876   Assert1(RMWI.getOrdering() != NotAtomic,
1877           "atomicrmw instructions must be atomic.", &RMWI);
1878   Assert1(RMWI.getOrdering() != Unordered,
1879           "atomicrmw instructions cannot be unordered.", &RMWI);
1880   PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1881   Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1882   Type *ElTy = PTy->getElementType();
1883   Assert2(ElTy->isIntegerTy(),
1884           "atomicrmw operand must have integer type!",
1885           &RMWI, ElTy);
1886   unsigned Size = ElTy->getPrimitiveSizeInBits();
1887   Assert2(Size >= 8 && !(Size & (Size - 1)),
1888           "atomicrmw operand must be power-of-two byte-sized integer",
1889           &RMWI, ElTy);
1890   Assert2(ElTy == RMWI.getOperand(1)->getType(),
1891           "Argument value type does not match pointer operand type!",
1892           &RMWI, ElTy);
1893   Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1894           RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1895           "Invalid binary operation!", &RMWI);
1896   visitInstruction(RMWI);
1897 }
1898
1899 void Verifier::visitFenceInst(FenceInst &FI) {
1900   const AtomicOrdering Ordering = FI.getOrdering();
1901   Assert1(Ordering == Acquire || Ordering == Release ||
1902           Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1903           "fence instructions may only have "
1904           "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1905   visitInstruction(FI);
1906 }
1907
1908 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1909   Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1910                                            EVI.getIndices()) ==
1911           EVI.getType(),
1912           "Invalid ExtractValueInst operands!", &EVI);
1913
1914   visitInstruction(EVI);
1915 }
1916
1917 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1918   Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1919                                            IVI.getIndices()) ==
1920           IVI.getOperand(1)->getType(),
1921           "Invalid InsertValueInst operands!", &IVI);
1922
1923   visitInstruction(IVI);
1924 }
1925
1926 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1927   BasicBlock *BB = LPI.getParent();
1928
1929   // The landingpad instruction is ill-formed if it doesn't have any clauses and
1930   // isn't a cleanup.
1931   Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1932           "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1933
1934   // The landingpad instruction defines its parent as a landing pad block. The
1935   // landing pad block may be branched to only by the unwind edge of an invoke.
1936   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1937     const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1938     Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
1939             "Block containing LandingPadInst must be jumped to "
1940             "only by the unwind edge of an invoke.", &LPI);
1941   }
1942
1943   // The landingpad instruction must be the first non-PHI instruction in the
1944   // block.
1945   Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1946           "LandingPadInst not the first non-PHI instruction in the block.",
1947           &LPI);
1948
1949   // The personality functions for all landingpad instructions within the same
1950   // function should match.
1951   if (PersonalityFn)
1952     Assert1(LPI.getPersonalityFn() == PersonalityFn,
1953             "Personality function doesn't match others in function", &LPI);
1954   PersonalityFn = LPI.getPersonalityFn();
1955
1956   // All operands must be constants.
1957   Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1958           &LPI);
1959   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1960     Value *Clause = LPI.getClause(i);
1961     Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1962     if (LPI.isCatch(i)) {
1963       Assert1(isa<PointerType>(Clause->getType()),
1964               "Catch operand does not have pointer type!", &LPI);
1965     } else {
1966       Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1967       Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1968               "Filter operand is not an array of constants!", &LPI);
1969     }
1970   }
1971
1972   visitInstruction(LPI);
1973 }
1974
1975 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
1976   Instruction *Op = cast<Instruction>(I.getOperand(i));
1977   // If the we have an invalid invoke, don't try to compute the dominance.
1978   // We already reject it in the invoke specific checks and the dominance
1979   // computation doesn't handle multiple edges.
1980   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1981     if (II->getNormalDest() == II->getUnwindDest())
1982       return;
1983   }
1984
1985   const Use &U = I.getOperandUse(i);
1986   Assert2(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
1987           "Instruction does not dominate all uses!", Op, &I);
1988 }
1989
1990 /// verifyInstruction - Verify that an instruction is well formed.
1991 ///
1992 void Verifier::visitInstruction(Instruction &I) {
1993   BasicBlock *BB = I.getParent();
1994   Assert1(BB, "Instruction not embedded in basic block!", &I);
1995
1996   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
1997     for (User *U : I.users()) {
1998       Assert1(U != (User*)&I || !DT.isReachableFromEntry(BB),
1999               "Only PHI nodes may reference their own value!", &I);
2000     }
2001   }
2002
2003   // Check that void typed values don't have names
2004   Assert1(!I.getType()->isVoidTy() || !I.hasName(),
2005           "Instruction has a name, but provides a void value!", &I);
2006
2007   // Check that the return value of the instruction is either void or a legal
2008   // value type.
2009   Assert1(I.getType()->isVoidTy() ||
2010           I.getType()->isFirstClassType(),
2011           "Instruction returns a non-scalar type!", &I);
2012
2013   // Check that the instruction doesn't produce metadata. Calls are already
2014   // checked against the callee type.
2015   Assert1(!I.getType()->isMetadataTy() ||
2016           isa<CallInst>(I) || isa<InvokeInst>(I),
2017           "Invalid use of metadata!", &I);
2018
2019   // Check that all uses of the instruction, if they are instructions
2020   // themselves, actually have parent basic blocks.  If the use is not an
2021   // instruction, it is an error!
2022   for (Use &U : I.uses()) {
2023     if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
2024       Assert2(Used->getParent() != nullptr, "Instruction referencing"
2025               " instruction not embedded in a basic block!", &I, Used);
2026     else {
2027       CheckFailed("Use of instruction is not an instruction!", U);
2028       return;
2029     }
2030   }
2031
2032   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2033     Assert1(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
2034
2035     // Check to make sure that only first-class-values are operands to
2036     // instructions.
2037     if (!I.getOperand(i)->getType()->isFirstClassType()) {
2038       Assert1(0, "Instruction operands must be first-class values!", &I);
2039     }
2040
2041     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2042       // Check to make sure that the "address of" an intrinsic function is never
2043       // taken.
2044       Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
2045               "Cannot take the address of an intrinsic!", &I);
2046       Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
2047               F->getIntrinsicID() == Intrinsic::donothing,
2048               "Cannot invoke an intrinsinc other than donothing", &I);
2049       Assert1(F->getParent() == M, "Referencing function in another module!",
2050               &I);
2051     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2052       Assert1(OpBB->getParent() == BB->getParent(),
2053               "Referring to a basic block in another function!", &I);
2054     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2055       Assert1(OpArg->getParent() == BB->getParent(),
2056               "Referring to an argument in another function!", &I);
2057     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2058       Assert1(GV->getParent() == M, "Referencing global in another module!",
2059               &I);
2060     } else if (isa<Instruction>(I.getOperand(i))) {
2061       verifyDominatesUse(I, i);
2062     } else if (isa<InlineAsm>(I.getOperand(i))) {
2063       Assert1((i + 1 == e && isa<CallInst>(I)) ||
2064               (i + 3 == e && isa<InvokeInst>(I)),
2065               "Cannot take the address of an inline asm!", &I);
2066     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2067       if (CE->getType()->isPtrOrPtrVectorTy()) {
2068         // If we have a ConstantExpr pointer, we need to see if it came from an
2069         // illegal bitcast (inttoptr <constant int> )
2070         SmallVector<const ConstantExpr *, 4> Stack;
2071         SmallPtrSet<const ConstantExpr *, 4> Visited;
2072         Stack.push_back(CE);
2073
2074         while (!Stack.empty()) {
2075           const ConstantExpr *V = Stack.pop_back_val();
2076           if (!Visited.insert(V))
2077             continue;
2078
2079           VerifyConstantExprBitcastType(V);
2080
2081           for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2082             if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2083               Stack.push_back(Op);
2084           }
2085         }
2086       }
2087     }
2088   }
2089
2090   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2091     Assert1(I.getType()->isFPOrFPVectorTy(),
2092             "fpmath requires a floating point result!", &I);
2093     Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2094     Value *Op0 = MD->getOperand(0);
2095     if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
2096       APFloat Accuracy = CFP0->getValueAPF();
2097       Assert1(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2098               "fpmath accuracy not a positive number!", &I);
2099     } else {
2100       Assert1(false, "invalid fpmath accuracy!", &I);
2101     }
2102   }
2103
2104   MDNode *MD = I.getMetadata(LLVMContext::MD_range);
2105   Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
2106
2107   if (VerifyDebugInfo) {
2108     MD = I.getMetadata(LLVMContext::MD_dbg);
2109     Finder.processLocation(*M, DILocation(MD));
2110   }
2111
2112   InstsInThisBlock.insert(&I);
2113 }
2114
2115 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2116 /// intrinsic argument or return value) matches the type constraints specified
2117 /// by the .td file (e.g. an "any integer" argument really is an integer).
2118 ///
2119 /// This return true on error but does not print a message.
2120 bool Verifier::VerifyIntrinsicType(Type *Ty,
2121                                    ArrayRef<Intrinsic::IITDescriptor> &Infos,
2122                                    SmallVectorImpl<Type*> &ArgTys) {
2123   using namespace Intrinsic;
2124
2125   // If we ran out of descriptors, there are too many arguments.
2126   if (Infos.empty()) return true;
2127   IITDescriptor D = Infos.front();
2128   Infos = Infos.slice(1);
2129
2130   switch (D.Kind) {
2131   case IITDescriptor::Void: return !Ty->isVoidTy();
2132   case IITDescriptor::VarArg: return true;
2133   case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
2134   case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2135   case IITDescriptor::Half: return !Ty->isHalfTy();
2136   case IITDescriptor::Float: return !Ty->isFloatTy();
2137   case IITDescriptor::Double: return !Ty->isDoubleTy();
2138   case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2139   case IITDescriptor::Vector: {
2140     VectorType *VT = dyn_cast<VectorType>(Ty);
2141     return !VT || VT->getNumElements() != D.Vector_Width ||
2142            VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2143   }
2144   case IITDescriptor::Pointer: {
2145     PointerType *PT = dyn_cast<PointerType>(Ty);
2146     return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2147            VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2148   }
2149
2150   case IITDescriptor::Struct: {
2151     StructType *ST = dyn_cast<StructType>(Ty);
2152     if (!ST || ST->getNumElements() != D.Struct_NumElements)
2153       return true;
2154
2155     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2156       if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2157         return true;
2158     return false;
2159   }
2160
2161   case IITDescriptor::Argument:
2162     // Two cases here - If this is the second occurrence of an argument, verify
2163     // that the later instance matches the previous instance.
2164     if (D.getArgumentNumber() < ArgTys.size())
2165       return Ty != ArgTys[D.getArgumentNumber()];
2166
2167     // Otherwise, if this is the first instance of an argument, record it and
2168     // verify the "Any" kind.
2169     assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2170     ArgTys.push_back(Ty);
2171
2172     switch (D.getArgumentKind()) {
2173     case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2174     case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
2175     case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
2176     case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2177     }
2178     llvm_unreachable("all argument kinds not covered");
2179
2180   case IITDescriptor::ExtendArgument: {
2181     // This may only be used when referring to a previous vector argument.
2182     if (D.getArgumentNumber() >= ArgTys.size())
2183       return true;
2184
2185     Type *NewTy = ArgTys[D.getArgumentNumber()];
2186     if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2187       NewTy = VectorType::getExtendedElementVectorType(VTy);
2188     else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2189       NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
2190     else
2191       return true;
2192
2193     return Ty != NewTy;
2194   }
2195   case IITDescriptor::TruncArgument: {
2196     // This may only be used when referring to a previous vector argument.
2197     if (D.getArgumentNumber() >= ArgTys.size())
2198       return true;
2199
2200     Type *NewTy = ArgTys[D.getArgumentNumber()];
2201     if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2202       NewTy = VectorType::getTruncatedElementVectorType(VTy);
2203     else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2204       NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
2205     else
2206       return true;
2207
2208     return Ty != NewTy;
2209   }
2210   case IITDescriptor::HalfVecArgument:
2211     // This may only be used when referring to a previous vector argument.
2212     return D.getArgumentNumber() >= ArgTys.size() ||
2213            !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2214            VectorType::getHalfElementsVectorType(
2215                          cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2216   }
2217   llvm_unreachable("unhandled");
2218 }
2219
2220 /// \brief Verify if the intrinsic has variable arguments.
2221 /// This method is intended to be called after all the fixed arguments have been
2222 /// verified first.
2223 ///
2224 /// This method returns true on error and does not print an error message.
2225 bool
2226 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
2227                                   ArrayRef<Intrinsic::IITDescriptor> &Infos) {
2228   using namespace Intrinsic;
2229
2230   // If there are no descriptors left, then it can't be a vararg.
2231   if (Infos.empty())
2232     return isVarArg ? true : false;
2233
2234   // There should be only one descriptor remaining at this point.
2235   if (Infos.size() != 1)
2236     return true;
2237
2238   // Check and verify the descriptor.
2239   IITDescriptor D = Infos.front();
2240   Infos = Infos.slice(1);
2241   if (D.Kind == IITDescriptor::VarArg)
2242     return isVarArg ? false : true;
2243
2244   return true;
2245 }
2246
2247 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2248 ///
2249 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2250   Function *IF = CI.getCalledFunction();
2251   Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2252           IF);
2253
2254   // Verify that the intrinsic prototype lines up with what the .td files
2255   // describe.
2256   FunctionType *IFTy = IF->getFunctionType();
2257   bool IsVarArg = IFTy->isVarArg();
2258
2259   SmallVector<Intrinsic::IITDescriptor, 8> Table;
2260   getIntrinsicInfoTableEntries(ID, Table);
2261   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2262
2263   SmallVector<Type *, 4> ArgTys;
2264   Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2265           "Intrinsic has incorrect return type!", IF);
2266   for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2267     Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2268             "Intrinsic has incorrect argument type!", IF);
2269
2270   // Verify if the intrinsic call matches the vararg property.
2271   if (IsVarArg)
2272     Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2273             "Intrinsic was not defined with variable arguments!", IF);
2274   else
2275     Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2276             "Callsite was not defined with variable arguments!", IF);
2277
2278   // All descriptors should be absorbed by now.
2279   Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2280
2281   // Now that we have the intrinsic ID and the actual argument types (and we
2282   // know they are legal for the intrinsic!) get the intrinsic name through the
2283   // usual means.  This allows us to verify the mangling of argument types into
2284   // the name.
2285   const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
2286   Assert1(ExpectedName == IF->getName(),
2287           "Intrinsic name not mangled correctly for type arguments! "
2288           "Should be: " + ExpectedName, IF);
2289
2290   // If the intrinsic takes MDNode arguments, verify that they are either global
2291   // or are local to *this* function.
2292   for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2293     if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
2294       visitMDNode(*MD, CI.getParent()->getParent());
2295
2296   switch (ID) {
2297   default:
2298     break;
2299   case Intrinsic::ctlz:  // llvm.ctlz
2300   case Intrinsic::cttz:  // llvm.cttz
2301     Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2302             "is_zero_undef argument of bit counting intrinsics must be a "
2303             "constant int", &CI);
2304     break;
2305   case Intrinsic::dbg_declare: {  // llvm.dbg.declare
2306     Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2307                 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2308     MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
2309     Assert1(MD->getNumOperands() == 1,
2310                 "invalid llvm.dbg.declare intrinsic call 2", &CI);
2311     if (VerifyDebugInfo)
2312       Finder.processDeclare(*M, cast<DbgDeclareInst>(&CI));
2313   } break;
2314   case Intrinsic::dbg_value: { //llvm.dbg.value
2315     if (VerifyDebugInfo) {
2316       Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2317               "invalid llvm.dbg.value intrinsic call 1", &CI);
2318       Finder.processValue(*M, cast<DbgValueInst>(&CI));
2319     }
2320     break;
2321   }
2322   case Intrinsic::memcpy:
2323   case Intrinsic::memmove:
2324   case Intrinsic::memset:
2325     Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
2326             "alignment argument of memory intrinsics must be a constant int",
2327             &CI);
2328     Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
2329             "isvolatile argument of memory intrinsics must be a constant int",
2330             &CI);
2331     break;
2332   case Intrinsic::gcroot:
2333   case Intrinsic::gcwrite:
2334   case Intrinsic::gcread:
2335     if (ID == Intrinsic::gcroot) {
2336       AllocaInst *AI =
2337         dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2338       Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2339       Assert1(isa<Constant>(CI.getArgOperand(1)),
2340               "llvm.gcroot parameter #2 must be a constant.", &CI);
2341       if (!AI->getType()->getElementType()->isPointerTy()) {
2342         Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2343                 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2344                 "or argument #2 must be a non-null constant.", &CI);
2345       }
2346     }
2347
2348     Assert1(CI.getParent()->getParent()->hasGC(),
2349             "Enclosing function does not use GC.", &CI);
2350     break;
2351   case Intrinsic::init_trampoline:
2352     Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2353             "llvm.init_trampoline parameter #2 must resolve to a function.",
2354             &CI);
2355     break;
2356   case Intrinsic::prefetch:
2357     Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
2358             isa<ConstantInt>(CI.getArgOperand(2)) &&
2359             cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2360             cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2361             "invalid arguments to llvm.prefetch",
2362             &CI);
2363     break;
2364   case Intrinsic::stackprotector:
2365     Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2366             "llvm.stackprotector parameter #2 must resolve to an alloca.",
2367             &CI);
2368     break;
2369   case Intrinsic::lifetime_start:
2370   case Intrinsic::lifetime_end:
2371   case Intrinsic::invariant_start:
2372     Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
2373             "size argument of memory use markers must be a constant integer",
2374             &CI);
2375     break;
2376   case Intrinsic::invariant_end:
2377     Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2378             "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2379     break;
2380   }
2381 }
2382
2383 void Verifier::verifyDebugInfo() {
2384   // Verify Debug Info.
2385   if (VerifyDebugInfo) {
2386     for (DICompileUnit CU : Finder.compile_units()) {
2387       Assert1(CU.Verify(), "DICompileUnit does not Verify!", CU);
2388     }
2389     for (DISubprogram S : Finder.subprograms()) {
2390       Assert1(S.Verify(), "DISubprogram does not Verify!", S);
2391     }
2392     for (DIGlobalVariable GV : Finder.global_variables()) {
2393       Assert1(GV.Verify(), "DIGlobalVariable does not Verify!", GV);
2394     }
2395     for (DIType T : Finder.types()) {
2396       Assert1(T.Verify(), "DIType does not Verify!", T);
2397     }
2398     for (DIScope S : Finder.scopes()) {
2399       Assert1(S.Verify(), "DIScope does not Verify!", S);
2400     }
2401   }
2402 }
2403
2404 //===----------------------------------------------------------------------===//
2405 //  Implement the public interfaces to this file...
2406 //===----------------------------------------------------------------------===//
2407
2408 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
2409   Function &F = const_cast<Function &>(f);
2410   assert(!F.isDeclaration() && "Cannot verify external functions");
2411
2412   raw_null_ostream NullStr;
2413   Verifier V(OS ? *OS : NullStr);
2414
2415   // Note that this function's return value is inverted from what you would
2416   // expect of a function called "verify".
2417   return !V.verify(F);
2418 }
2419
2420 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
2421   raw_null_ostream NullStr;
2422   Verifier V(OS ? *OS : NullStr);
2423
2424   bool Broken = false;
2425   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
2426     if (!I->isDeclaration())
2427       Broken |= !V.verify(*I);
2428
2429   // Note that this function's return value is inverted from what you would
2430   // expect of a function called "verify".
2431   return !V.verify(M) || Broken;
2432 }
2433
2434 namespace {
2435 struct VerifierLegacyPass : public FunctionPass {
2436   static char ID;
2437
2438   Verifier V;
2439   bool FatalErrors;
2440
2441   VerifierLegacyPass() : FunctionPass(ID), FatalErrors(true) {
2442     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
2443   }
2444   explicit VerifierLegacyPass(bool FatalErrors)
2445       : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
2446     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
2447   }
2448
2449   bool runOnFunction(Function &F) override {
2450     if (!V.verify(F) && FatalErrors)
2451       report_fatal_error("Broken function found, compilation aborted!");
2452
2453     return false;
2454   }
2455
2456   bool doFinalization(Module &M) override {
2457     if (!V.verify(M) && FatalErrors)
2458       report_fatal_error("Broken module found, compilation aborted!");
2459
2460     return false;
2461   }
2462
2463   void getAnalysisUsage(AnalysisUsage &AU) const override {
2464     AU.setPreservesAll();
2465   }
2466 };
2467 }
2468
2469 char VerifierLegacyPass::ID = 0;
2470 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
2471
2472 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
2473   return new VerifierLegacyPass(FatalErrors);
2474 }
2475
2476 PreservedAnalyses VerifierPass::run(Module *M) {
2477   if (verifyModule(*M, &dbgs()) && FatalErrors)
2478     report_fatal_error("Broken module found, compilation aborted!");
2479
2480   return PreservedAnalyses::all();
2481 }
2482
2483 PreservedAnalyses VerifierPass::run(Function *F) {
2484   if (verifyFunction(*F, &dbgs()) && FatalErrors)
2485     report_fatal_error("Broken function found, compilation aborted!");
2486
2487   return PreservedAnalyses::all();
2488 }