PR19598: Provide the ability to RAUW a declaration with itself, creating a non-tempor...
[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/InstIterator.h"
65 #include "llvm/IR/InstVisitor.h"
66 #include "llvm/IR/IntrinsicInst.h"
67 #include "llvm/IR/LLVMContext.h"
68 #include "llvm/IR/Metadata.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/PassManager.h"
71 #include "llvm/Pass.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/raw_ostream.h"
76 #include <algorithm>
77 #include <cstdarg>
78 using namespace llvm;
79
80 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(false));
81
82 namespace {
83 struct VerifierSupport {
84   raw_ostream &OS;
85   const Module *M;
86
87   /// \brief Track the brokenness of the module while recursively visiting.
88   bool Broken;
89
90   explicit VerifierSupport(raw_ostream &OS)
91       : OS(OS), M(nullptr), Broken(false) {}
92
93   void WriteValue(const Value *V) {
94     if (!V)
95       return;
96     if (isa<Instruction>(V)) {
97       OS << *V << '\n';
98     } else {
99       V->printAsOperand(OS, true, M);
100       OS << '\n';
101     }
102   }
103
104   void WriteType(Type *T) {
105     if (!T)
106       return;
107     OS << ' ' << *T;
108   }
109
110   // CheckFailed - A check failed, so print out the condition and the message
111   // that failed.  This provides a nice place to put a breakpoint if you want
112   // to see why something is not correct.
113   void CheckFailed(const Twine &Message, const Value *V1 = nullptr,
114                    const Value *V2 = nullptr, const Value *V3 = nullptr,
115                    const Value *V4 = nullptr) {
116     OS << Message.str() << "\n";
117     WriteValue(V1);
118     WriteValue(V2);
119     WriteValue(V3);
120     WriteValue(V4);
121     Broken = true;
122   }
123
124   void CheckFailed(const Twine &Message, const Value *V1, Type *T2,
125                    const Value *V3 = nullptr) {
126     OS << Message.str() << "\n";
127     WriteValue(V1);
128     WriteType(T2);
129     WriteValue(V3);
130     Broken = true;
131   }
132
133   void CheckFailed(const Twine &Message, Type *T1, Type *T2 = nullptr,
134                    Type *T3 = nullptr) {
135     OS << Message.str() << "\n";
136     WriteType(T1);
137     WriteType(T2);
138     WriteType(T3);
139     Broken = true;
140   }
141 };
142 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
143   friend class InstVisitor<Verifier>;
144
145   LLVMContext *Context;
146   const DataLayout *DL;
147   DominatorTree DT;
148
149   /// \brief When verifying a basic block, keep track of all of the
150   /// instructions we have seen so far.
151   ///
152   /// This allows us to do efficient dominance checks for the case when an
153   /// instruction has an operand that is an instruction in the same block.
154   SmallPtrSet<Instruction *, 16> InstsInThisBlock;
155
156   /// \brief Keep track of the metadata nodes that have been checked already.
157   SmallPtrSet<MDNode *, 32> MDNodes;
158
159   /// \brief The personality function referenced by the LandingPadInsts.
160   /// All LandingPadInsts within the same function must use the same
161   /// personality function.
162   const Value *PersonalityFn;
163
164 public:
165   explicit Verifier(raw_ostream &OS = dbgs())
166       : VerifierSupport(OS), Context(nullptr), DL(nullptr),
167         PersonalityFn(nullptr) {}
168
169   bool verify(const Function &F) {
170     M = F.getParent();
171     Context = &M->getContext();
172
173     // First ensure the function is well-enough formed to compute dominance
174     // information.
175     if (F.empty()) {
176       OS << "Function '" << F.getName()
177          << "' does not contain an entry block!\n";
178       return false;
179     }
180     for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
181       if (I->empty() || !I->back().isTerminator()) {
182         OS << "Basic Block in function '" << F.getName()
183            << "' does not have terminator!\n";
184         I->printAsOperand(OS, true);
185         OS << "\n";
186         return false;
187       }
188     }
189
190     // Now directly compute a dominance tree. We don't rely on the pass
191     // manager to provide this as it isolates us from a potentially
192     // out-of-date dominator tree and makes it significantly more complex to
193     // run this code outside of a pass manager.
194     // FIXME: It's really gross that we have to cast away constness here.
195     DT.recalculate(const_cast<Function &>(F));
196
197     Broken = false;
198     // FIXME: We strip const here because the inst visitor strips const.
199     visit(const_cast<Function &>(F));
200     InstsInThisBlock.clear();
201     PersonalityFn = nullptr;
202
203     return !Broken;
204   }
205
206   bool verify(const Module &M) {
207     this->M = &M;
208     Context = &M.getContext();
209     Broken = false;
210
211     // Scan through, checking all of the external function's linkage now...
212     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
213       visitGlobalValue(*I);
214
215       // Check to make sure function prototypes are okay.
216       if (I->isDeclaration())
217         visitFunction(*I);
218     }
219
220     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
221          I != E; ++I)
222       visitGlobalVariable(*I);
223
224     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
225          I != E; ++I)
226       visitGlobalAlias(*I);
227
228     for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
229                                                E = M.named_metadata_end();
230          I != E; ++I)
231       visitNamedMDNode(*I);
232
233     visitModuleFlags(M);
234     visitModuleIdents(M);
235
236     return !Broken;
237   }
238
239 private:
240   // Verification methods...
241   void visitGlobalValue(const GlobalValue &GV);
242   void visitGlobalVariable(const GlobalVariable &GV);
243   void visitGlobalAlias(const GlobalAlias &GA);
244   void visitNamedMDNode(const NamedMDNode &NMD);
245   void visitMDNode(MDNode &MD, Function *F);
246   void visitModuleIdents(const Module &M);
247   void visitModuleFlags(const Module &M);
248   void visitModuleFlag(const MDNode *Op,
249                        DenseMap<const MDString *, const MDNode *> &SeenIDs,
250                        SmallVectorImpl<const MDNode *> &Requirements);
251   void visitFunction(const Function &F);
252   void visitBasicBlock(BasicBlock &BB);
253
254   // InstVisitor overrides...
255   using InstVisitor<Verifier>::visit;
256   void visit(Instruction &I);
257
258   void visitTruncInst(TruncInst &I);
259   void visitZExtInst(ZExtInst &I);
260   void visitSExtInst(SExtInst &I);
261   void visitFPTruncInst(FPTruncInst &I);
262   void visitFPExtInst(FPExtInst &I);
263   void visitFPToUIInst(FPToUIInst &I);
264   void visitFPToSIInst(FPToSIInst &I);
265   void visitUIToFPInst(UIToFPInst &I);
266   void visitSIToFPInst(SIToFPInst &I);
267   void visitIntToPtrInst(IntToPtrInst &I);
268   void visitPtrToIntInst(PtrToIntInst &I);
269   void visitBitCastInst(BitCastInst &I);
270   void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
271   void visitPHINode(PHINode &PN);
272   void visitBinaryOperator(BinaryOperator &B);
273   void visitICmpInst(ICmpInst &IC);
274   void visitFCmpInst(FCmpInst &FC);
275   void visitExtractElementInst(ExtractElementInst &EI);
276   void visitInsertElementInst(InsertElementInst &EI);
277   void visitShuffleVectorInst(ShuffleVectorInst &EI);
278   void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
279   void visitCallInst(CallInst &CI);
280   void visitInvokeInst(InvokeInst &II);
281   void visitGetElementPtrInst(GetElementPtrInst &GEP);
282   void visitLoadInst(LoadInst &LI);
283   void visitStoreInst(StoreInst &SI);
284   void verifyDominatesUse(Instruction &I, unsigned i);
285   void visitInstruction(Instruction &I);
286   void visitTerminatorInst(TerminatorInst &I);
287   void visitBranchInst(BranchInst &BI);
288   void visitReturnInst(ReturnInst &RI);
289   void visitSwitchInst(SwitchInst &SI);
290   void visitIndirectBrInst(IndirectBrInst &BI);
291   void visitSelectInst(SelectInst &SI);
292   void visitUserOp1(Instruction &I);
293   void visitUserOp2(Instruction &I) { visitUserOp1(I); }
294   void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
295   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
296   void visitAtomicRMWInst(AtomicRMWInst &RMWI);
297   void visitFenceInst(FenceInst &FI);
298   void visitAllocaInst(AllocaInst &AI);
299   void visitExtractValueInst(ExtractValueInst &EVI);
300   void visitInsertValueInst(InsertValueInst &IVI);
301   void visitLandingPadInst(LandingPadInst &LPI);
302
303   void VerifyCallSite(CallSite CS);
304   void verifyMustTailCall(CallInst &CI);
305   bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
306                         unsigned ArgNo, std::string &Suffix);
307   bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
308                            SmallVectorImpl<Type *> &ArgTys);
309   bool VerifyIntrinsicIsVarArg(bool isVarArg,
310                                ArrayRef<Intrinsic::IITDescriptor> &Infos);
311   bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
312   void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
313                             const Value *V);
314   void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
315                             bool isReturnValue, const Value *V);
316   void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
317                            const Value *V);
318
319   void VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy);
320   void VerifyConstantExprBitcastType(const ConstantExpr *CE);
321 };
322 class DebugInfoVerifier : public VerifierSupport {
323 public:
324   explicit DebugInfoVerifier(raw_ostream &OS = dbgs()) : VerifierSupport(OS) {}
325
326   bool verify(const Module &M) {
327     this->M = &M;
328     verifyDebugInfo();
329     return !Broken;
330   }
331
332 private:
333   void verifyDebugInfo();
334   void processInstructions(DebugInfoFinder &Finder);
335   void processCallInst(DebugInfoFinder &Finder, const CallInst &CI);
336 };
337 } // End anonymous namespace
338
339 // Assert - We know that cond should be true, if not print an error message.
340 #define Assert(C, M) \
341   do { if (!(C)) { CheckFailed(M); return; } } while (0)
342 #define Assert1(C, M, V1) \
343   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
344 #define Assert2(C, M, V1, V2) \
345   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
346 #define Assert3(C, M, V1, V2, V3) \
347   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
348 #define Assert4(C, M, V1, V2, V3, V4) \
349   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
350
351 void Verifier::visit(Instruction &I) {
352   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
353     Assert1(I.getOperand(i) != nullptr, "Operand is null", &I);
354   InstVisitor<Verifier>::visit(I);
355 }
356
357
358 void Verifier::visitGlobalValue(const GlobalValue &GV) {
359   Assert1(!GV.isDeclaration() || GV.isMaterializable() ||
360               GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
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   // Conservatively check the inalloca argument.
1494   // We have a bug if we can find that there is an underlying alloca without
1495   // inalloca.
1496   if (CS.hasInAllocaArgument()) {
1497     Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
1498     if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
1499       Assert2(AI->isUsedWithInAlloca(),
1500               "inalloca argument for call has mismatched alloca", AI, I);
1501   }
1502
1503   if (FTy->isVarArg()) {
1504     // FIXME? is 'nest' even legal here?
1505     bool SawNest = false;
1506     bool SawReturned = false;
1507
1508     for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1509       if (Attrs.hasAttribute(Idx, Attribute::Nest))
1510         SawNest = true;
1511       if (Attrs.hasAttribute(Idx, Attribute::Returned))
1512         SawReturned = true;
1513     }
1514
1515     // Check attributes on the varargs part.
1516     for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1517       Type *Ty = CS.getArgument(Idx-1)->getType();
1518       VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1519
1520       if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1521         Assert1(!SawNest, "More than one parameter has attribute nest!", I);
1522         SawNest = true;
1523       }
1524
1525       if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1526         Assert1(!SawReturned, "More than one parameter has attribute returned!",
1527                 I);
1528         Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1529                 "Incompatible argument and return types for 'returned' "
1530                 "attribute", I);
1531         SawReturned = true;
1532       }
1533
1534       Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1535               "Attribute 'sret' cannot be used for vararg call arguments!", I);
1536
1537       if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
1538         Assert1(Idx == CS.arg_size(), "inalloca isn't on the last argument!",
1539                 I);
1540     }
1541   }
1542
1543   // Verify that there's no metadata unless it's a direct call to an intrinsic.
1544   if (CS.getCalledFunction() == nullptr ||
1545       !CS.getCalledFunction()->getName().startswith("llvm.")) {
1546     for (FunctionType::param_iterator PI = FTy->param_begin(),
1547            PE = FTy->param_end(); PI != PE; ++PI)
1548       Assert1(!(*PI)->isMetadataTy(),
1549               "Function has metadata parameter but isn't an intrinsic", I);
1550   }
1551
1552   visitInstruction(*I);
1553 }
1554
1555 /// Two types are "congruent" if they are identical, or if they are both pointer
1556 /// types with different pointee types and the same address space.
1557 static bool isTypeCongruent(Type *L, Type *R) {
1558   if (L == R)
1559     return true;
1560   PointerType *PL = dyn_cast<PointerType>(L);
1561   PointerType *PR = dyn_cast<PointerType>(R);
1562   if (!PL || !PR)
1563     return false;
1564   return PL->getAddressSpace() == PR->getAddressSpace();
1565 }
1566
1567 void Verifier::verifyMustTailCall(CallInst &CI) {
1568   Assert1(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
1569
1570   // - The caller and callee prototypes must match.  Pointer types of
1571   //   parameters or return types may differ in pointee type, but not
1572   //   address space.
1573   Function *F = CI.getParent()->getParent();
1574   auto GetFnTy = [](Value *V) {
1575     return cast<FunctionType>(
1576         cast<PointerType>(V->getType())->getElementType());
1577   };
1578   FunctionType *CallerTy = GetFnTy(F);
1579   FunctionType *CalleeTy = GetFnTy(CI.getCalledValue());
1580   Assert1(CallerTy->getNumParams() == CalleeTy->getNumParams(),
1581           "cannot guarantee tail call due to mismatched parameter counts", &CI);
1582   Assert1(CallerTy->isVarArg() == CalleeTy->isVarArg(),
1583           "cannot guarantee tail call due to mismatched varargs", &CI);
1584   Assert1(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
1585           "cannot guarantee tail call due to mismatched return types", &CI);
1586   for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
1587     Assert1(
1588         isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
1589         "cannot guarantee tail call due to mismatched parameter types", &CI);
1590   }
1591
1592   // - The calling conventions of the caller and callee must match.
1593   Assert1(F->getCallingConv() == CI.getCallingConv(),
1594           "cannot guarantee tail call due to mismatched calling conv", &CI);
1595
1596   // - All ABI-impacting function attributes, such as sret, byval, inreg,
1597   //   returned, and inalloca, must match.
1598   static const Attribute::AttrKind ABIAttrs[] = {
1599       Attribute::Alignment, Attribute::StructRet, Attribute::ByVal,
1600       Attribute::InAlloca,  Attribute::InReg,     Attribute::Returned};
1601   AttributeSet CallerAttrs = F->getAttributes();
1602   AttributeSet CalleeAttrs = CI.getAttributes();
1603   for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
1604     AttrBuilder CallerABIAttrs;
1605     AttrBuilder CalleeABIAttrs;
1606     for (auto AK : ABIAttrs) {
1607       if (CallerAttrs.hasAttribute(I + 1, AK))
1608         CallerABIAttrs.addAttribute(AK);
1609       if (CalleeAttrs.hasAttribute(I + 1, AK))
1610         CalleeABIAttrs.addAttribute(AK);
1611     }
1612     Assert2(CallerABIAttrs == CalleeABIAttrs,
1613             "cannot guarantee tail call due to mismatched ABI impacting "
1614             "function attributes", &CI, CI.getOperand(I));
1615   }
1616
1617   // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
1618   //   or a pointer bitcast followed by a ret instruction.
1619   // - The ret instruction must return the (possibly bitcasted) value
1620   //   produced by the call or void.
1621   Value *RetVal = &CI;
1622   Instruction *Next = CI.getNextNode();
1623
1624   // Handle the optional bitcast.
1625   if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
1626     Assert1(BI->getOperand(0) == RetVal,
1627             "bitcast following musttail call must use the call", BI);
1628     RetVal = BI;
1629     Next = BI->getNextNode();
1630   }
1631
1632   // Check the return.
1633   ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
1634   Assert1(Ret, "musttail call must be precede a ret with an optional bitcast",
1635           &CI);
1636   Assert1(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
1637           "musttail call result must be returned", Ret);
1638 }
1639
1640 void Verifier::visitCallInst(CallInst &CI) {
1641   VerifyCallSite(&CI);
1642
1643   if (CI.isMustTailCall())
1644     verifyMustTailCall(CI);
1645
1646   if (Function *F = CI.getCalledFunction())
1647     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1648       visitIntrinsicFunctionCall(ID, CI);
1649 }
1650
1651 void Verifier::visitInvokeInst(InvokeInst &II) {
1652   VerifyCallSite(&II);
1653
1654   // Verify that there is a landingpad instruction as the first non-PHI
1655   // instruction of the 'unwind' destination.
1656   Assert1(II.getUnwindDest()->isLandingPad(),
1657           "The unwind destination does not have a landingpad instruction!",&II);
1658
1659   visitTerminatorInst(II);
1660 }
1661
1662 /// visitBinaryOperator - Check that both arguments to the binary operator are
1663 /// of the same type!
1664 ///
1665 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1666   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1667           "Both operands to a binary operator are not of the same type!", &B);
1668
1669   switch (B.getOpcode()) {
1670   // Check that integer arithmetic operators are only used with
1671   // integral operands.
1672   case Instruction::Add:
1673   case Instruction::Sub:
1674   case Instruction::Mul:
1675   case Instruction::SDiv:
1676   case Instruction::UDiv:
1677   case Instruction::SRem:
1678   case Instruction::URem:
1679     Assert1(B.getType()->isIntOrIntVectorTy(),
1680             "Integer arithmetic operators only work with integral types!", &B);
1681     Assert1(B.getType() == B.getOperand(0)->getType(),
1682             "Integer arithmetic operators must have same type "
1683             "for operands and result!", &B);
1684     break;
1685   // Check that floating-point arithmetic operators are only used with
1686   // floating-point operands.
1687   case Instruction::FAdd:
1688   case Instruction::FSub:
1689   case Instruction::FMul:
1690   case Instruction::FDiv:
1691   case Instruction::FRem:
1692     Assert1(B.getType()->isFPOrFPVectorTy(),
1693             "Floating-point arithmetic operators only work with "
1694             "floating-point types!", &B);
1695     Assert1(B.getType() == B.getOperand(0)->getType(),
1696             "Floating-point arithmetic operators must have same type "
1697             "for operands and result!", &B);
1698     break;
1699   // Check that logical operators are only used with integral operands.
1700   case Instruction::And:
1701   case Instruction::Or:
1702   case Instruction::Xor:
1703     Assert1(B.getType()->isIntOrIntVectorTy(),
1704             "Logical operators only work with integral types!", &B);
1705     Assert1(B.getType() == B.getOperand(0)->getType(),
1706             "Logical operators must have same type for operands and result!",
1707             &B);
1708     break;
1709   case Instruction::Shl:
1710   case Instruction::LShr:
1711   case Instruction::AShr:
1712     Assert1(B.getType()->isIntOrIntVectorTy(),
1713             "Shifts only work with integral types!", &B);
1714     Assert1(B.getType() == B.getOperand(0)->getType(),
1715             "Shift return type must be same as operands!", &B);
1716     break;
1717   default:
1718     llvm_unreachable("Unknown BinaryOperator opcode!");
1719   }
1720
1721   visitInstruction(B);
1722 }
1723
1724 void Verifier::visitICmpInst(ICmpInst &IC) {
1725   // Check that the operands are the same type
1726   Type *Op0Ty = IC.getOperand(0)->getType();
1727   Type *Op1Ty = IC.getOperand(1)->getType();
1728   Assert1(Op0Ty == Op1Ty,
1729           "Both operands to ICmp instruction are not of the same type!", &IC);
1730   // Check that the operands are the right type
1731   Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1732           "Invalid operand types for ICmp instruction", &IC);
1733   // Check that the predicate is valid.
1734   Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1735           IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1736           "Invalid predicate in ICmp instruction!", &IC);
1737
1738   visitInstruction(IC);
1739 }
1740
1741 void Verifier::visitFCmpInst(FCmpInst &FC) {
1742   // Check that the operands are the same type
1743   Type *Op0Ty = FC.getOperand(0)->getType();
1744   Type *Op1Ty = FC.getOperand(1)->getType();
1745   Assert1(Op0Ty == Op1Ty,
1746           "Both operands to FCmp instruction are not of the same type!", &FC);
1747   // Check that the operands are the right type
1748   Assert1(Op0Ty->isFPOrFPVectorTy(),
1749           "Invalid operand types for FCmp instruction", &FC);
1750   // Check that the predicate is valid.
1751   Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1752           FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1753           "Invalid predicate in FCmp instruction!", &FC);
1754
1755   visitInstruction(FC);
1756 }
1757
1758 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1759   Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1760                                               EI.getOperand(1)),
1761           "Invalid extractelement operands!", &EI);
1762   visitInstruction(EI);
1763 }
1764
1765 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1766   Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1767                                              IE.getOperand(1),
1768                                              IE.getOperand(2)),
1769           "Invalid insertelement operands!", &IE);
1770   visitInstruction(IE);
1771 }
1772
1773 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1774   Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1775                                              SV.getOperand(2)),
1776           "Invalid shufflevector operands!", &SV);
1777   visitInstruction(SV);
1778 }
1779
1780 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1781   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1782
1783   Assert1(isa<PointerType>(TargetTy),
1784     "GEP base pointer is not a vector or a vector of pointers", &GEP);
1785   Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1786           "GEP into unsized type!", &GEP);
1787   Assert1(GEP.getPointerOperandType()->isVectorTy() ==
1788           GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
1789           &GEP);
1790
1791   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1792   Type *ElTy =
1793     GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1794   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1795
1796   Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
1797           cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
1798           == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
1799
1800   if (GEP.getPointerOperandType()->isVectorTy()) {
1801     // Additional checks for vector GEPs.
1802     unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
1803     Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
1804             "Vector GEP result width doesn't match operand's", &GEP);
1805     for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1806       Type *IndexTy = Idxs[i]->getType();
1807       Assert1(IndexTy->isVectorTy(),
1808               "Vector GEP must have vector indices!", &GEP);
1809       unsigned IndexWidth = IndexTy->getVectorNumElements();
1810       Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1811     }
1812   }
1813   visitInstruction(GEP);
1814 }
1815
1816 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1817   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1818 }
1819
1820 void Verifier::visitLoadInst(LoadInst &LI) {
1821   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1822   Assert1(PTy, "Load operand must be a pointer.", &LI);
1823   Type *ElTy = PTy->getElementType();
1824   Assert2(ElTy == LI.getType(),
1825           "Load result type does not match pointer operand type!", &LI, ElTy);
1826   if (LI.isAtomic()) {
1827     Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1828             "Load cannot have Release ordering", &LI);
1829     Assert1(LI.getAlignment() != 0,
1830             "Atomic load must specify explicit alignment", &LI);
1831     if (!ElTy->isPointerTy()) {
1832       Assert2(ElTy->isIntegerTy(),
1833               "atomic load operand must have integer type!",
1834               &LI, ElTy);
1835       unsigned Size = ElTy->getPrimitiveSizeInBits();
1836       Assert2(Size >= 8 && !(Size & (Size - 1)),
1837               "atomic load operand must be power-of-two byte-sized integer",
1838               &LI, ElTy);
1839     }
1840   } else {
1841     Assert1(LI.getSynchScope() == CrossThread,
1842             "Non-atomic load cannot have SynchronizationScope specified", &LI);
1843   }
1844
1845   if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1846     unsigned NumOperands = Range->getNumOperands();
1847     Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1848     unsigned NumRanges = NumOperands / 2;
1849     Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1850
1851     ConstantRange LastRange(1); // Dummy initial value
1852     for (unsigned i = 0; i < NumRanges; ++i) {
1853       ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1854       Assert1(Low, "The lower limit must be an integer!", Low);
1855       ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1856       Assert1(High, "The upper limit must be an integer!", High);
1857       Assert1(High->getType() == Low->getType() &&
1858               High->getType() == ElTy, "Range types must match load type!",
1859               &LI);
1860
1861       APInt HighV = High->getValue();
1862       APInt LowV = Low->getValue();
1863       ConstantRange CurRange(LowV, HighV);
1864       Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1865               "Range must not be empty!", Range);
1866       if (i != 0) {
1867         Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1868                 "Intervals are overlapping", Range);
1869         Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1870                 Range);
1871         Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1872                 Range);
1873       }
1874       LastRange = ConstantRange(LowV, HighV);
1875     }
1876     if (NumRanges > 2) {
1877       APInt FirstLow =
1878         dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1879       APInt FirstHigh =
1880         dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1881       ConstantRange FirstRange(FirstLow, FirstHigh);
1882       Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1883               "Intervals are overlapping", Range);
1884       Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1885               Range);
1886     }
1887
1888
1889   }
1890
1891   visitInstruction(LI);
1892 }
1893
1894 void Verifier::visitStoreInst(StoreInst &SI) {
1895   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1896   Assert1(PTy, "Store operand must be a pointer.", &SI);
1897   Type *ElTy = PTy->getElementType();
1898   Assert2(ElTy == SI.getOperand(0)->getType(),
1899           "Stored value type does not match pointer operand type!",
1900           &SI, ElTy);
1901   if (SI.isAtomic()) {
1902     Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1903             "Store cannot have Acquire ordering", &SI);
1904     Assert1(SI.getAlignment() != 0,
1905             "Atomic store must specify explicit alignment", &SI);
1906     if (!ElTy->isPointerTy()) {
1907       Assert2(ElTy->isIntegerTy(),
1908               "atomic store operand must have integer type!",
1909               &SI, ElTy);
1910       unsigned Size = ElTy->getPrimitiveSizeInBits();
1911       Assert2(Size >= 8 && !(Size & (Size - 1)),
1912               "atomic store operand must be power-of-two byte-sized integer",
1913               &SI, ElTy);
1914     }
1915   } else {
1916     Assert1(SI.getSynchScope() == CrossThread,
1917             "Non-atomic store cannot have SynchronizationScope specified", &SI);
1918   }
1919   visitInstruction(SI);
1920 }
1921
1922 void Verifier::visitAllocaInst(AllocaInst &AI) {
1923   SmallPtrSet<const Type*, 4> Visited;
1924   PointerType *PTy = AI.getType();
1925   Assert1(PTy->getAddressSpace() == 0,
1926           "Allocation instruction pointer not in the generic address space!",
1927           &AI);
1928   Assert1(PTy->getElementType()->isSized(&Visited), "Cannot allocate unsized type",
1929           &AI);
1930   Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1931           "Alloca array size must have integer type", &AI);
1932
1933   visitInstruction(AI);
1934 }
1935
1936 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1937
1938   // FIXME: more conditions???
1939   Assert1(CXI.getSuccessOrdering() != NotAtomic,
1940           "cmpxchg instructions must be atomic.", &CXI);
1941   Assert1(CXI.getFailureOrdering() != NotAtomic,
1942           "cmpxchg instructions must be atomic.", &CXI);
1943   Assert1(CXI.getSuccessOrdering() != Unordered,
1944           "cmpxchg instructions cannot be unordered.", &CXI);
1945   Assert1(CXI.getFailureOrdering() != Unordered,
1946           "cmpxchg instructions cannot be unordered.", &CXI);
1947   Assert1(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
1948           "cmpxchg instructions be at least as constrained on success as fail",
1949           &CXI);
1950   Assert1(CXI.getFailureOrdering() != Release &&
1951               CXI.getFailureOrdering() != AcquireRelease,
1952           "cmpxchg failure ordering cannot include release semantics", &CXI);
1953
1954   PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1955   Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1956   Type *ElTy = PTy->getElementType();
1957   Assert2(ElTy->isIntegerTy(),
1958           "cmpxchg operand must have integer type!",
1959           &CXI, ElTy);
1960   unsigned Size = ElTy->getPrimitiveSizeInBits();
1961   Assert2(Size >= 8 && !(Size & (Size - 1)),
1962           "cmpxchg operand must be power-of-two byte-sized integer",
1963           &CXI, ElTy);
1964   Assert2(ElTy == CXI.getOperand(1)->getType(),
1965           "Expected value type does not match pointer operand type!",
1966           &CXI, ElTy);
1967   Assert2(ElTy == CXI.getOperand(2)->getType(),
1968           "Stored value type does not match pointer operand type!",
1969           &CXI, ElTy);
1970   visitInstruction(CXI);
1971 }
1972
1973 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1974   Assert1(RMWI.getOrdering() != NotAtomic,
1975           "atomicrmw instructions must be atomic.", &RMWI);
1976   Assert1(RMWI.getOrdering() != Unordered,
1977           "atomicrmw instructions cannot be unordered.", &RMWI);
1978   PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1979   Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1980   Type *ElTy = PTy->getElementType();
1981   Assert2(ElTy->isIntegerTy(),
1982           "atomicrmw operand must have integer type!",
1983           &RMWI, ElTy);
1984   unsigned Size = ElTy->getPrimitiveSizeInBits();
1985   Assert2(Size >= 8 && !(Size & (Size - 1)),
1986           "atomicrmw operand must be power-of-two byte-sized integer",
1987           &RMWI, ElTy);
1988   Assert2(ElTy == RMWI.getOperand(1)->getType(),
1989           "Argument value type does not match pointer operand type!",
1990           &RMWI, ElTy);
1991   Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1992           RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1993           "Invalid binary operation!", &RMWI);
1994   visitInstruction(RMWI);
1995 }
1996
1997 void Verifier::visitFenceInst(FenceInst &FI) {
1998   const AtomicOrdering Ordering = FI.getOrdering();
1999   Assert1(Ordering == Acquire || Ordering == Release ||
2000           Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2001           "fence instructions may only have "
2002           "acquire, release, acq_rel, or seq_cst ordering.", &FI);
2003   visitInstruction(FI);
2004 }
2005
2006 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2007   Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2008                                            EVI.getIndices()) ==
2009           EVI.getType(),
2010           "Invalid ExtractValueInst operands!", &EVI);
2011
2012   visitInstruction(EVI);
2013 }
2014
2015 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2016   Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2017                                            IVI.getIndices()) ==
2018           IVI.getOperand(1)->getType(),
2019           "Invalid InsertValueInst operands!", &IVI);
2020
2021   visitInstruction(IVI);
2022 }
2023
2024 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2025   BasicBlock *BB = LPI.getParent();
2026
2027   // The landingpad instruction is ill-formed if it doesn't have any clauses and
2028   // isn't a cleanup.
2029   Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2030           "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2031
2032   // The landingpad instruction defines its parent as a landing pad block. The
2033   // landing pad block may be branched to only by the unwind edge of an invoke.
2034   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
2035     const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
2036     Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2037             "Block containing LandingPadInst must be jumped to "
2038             "only by the unwind edge of an invoke.", &LPI);
2039   }
2040
2041   // The landingpad instruction must be the first non-PHI instruction in the
2042   // block.
2043   Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
2044           "LandingPadInst not the first non-PHI instruction in the block.",
2045           &LPI);
2046
2047   // The personality functions for all landingpad instructions within the same
2048   // function should match.
2049   if (PersonalityFn)
2050     Assert1(LPI.getPersonalityFn() == PersonalityFn,
2051             "Personality function doesn't match others in function", &LPI);
2052   PersonalityFn = LPI.getPersonalityFn();
2053
2054   // All operands must be constants.
2055   Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
2056           &LPI);
2057   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2058     Value *Clause = LPI.getClause(i);
2059     Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
2060     if (LPI.isCatch(i)) {
2061       Assert1(isa<PointerType>(Clause->getType()),
2062               "Catch operand does not have pointer type!", &LPI);
2063     } else {
2064       Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
2065       Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
2066               "Filter operand is not an array of constants!", &LPI);
2067     }
2068   }
2069
2070   visitInstruction(LPI);
2071 }
2072
2073 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
2074   Instruction *Op = cast<Instruction>(I.getOperand(i));
2075   // If the we have an invalid invoke, don't try to compute the dominance.
2076   // We already reject it in the invoke specific checks and the dominance
2077   // computation doesn't handle multiple edges.
2078   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
2079     if (II->getNormalDest() == II->getUnwindDest())
2080       return;
2081   }
2082
2083   const Use &U = I.getOperandUse(i);
2084   Assert2(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
2085           "Instruction does not dominate all uses!", Op, &I);
2086 }
2087
2088 /// verifyInstruction - Verify that an instruction is well formed.
2089 ///
2090 void Verifier::visitInstruction(Instruction &I) {
2091   BasicBlock *BB = I.getParent();
2092   Assert1(BB, "Instruction not embedded in basic block!", &I);
2093
2094   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
2095     for (User *U : I.users()) {
2096       Assert1(U != (User*)&I || !DT.isReachableFromEntry(BB),
2097               "Only PHI nodes may reference their own value!", &I);
2098     }
2099   }
2100
2101   // Check that void typed values don't have names
2102   Assert1(!I.getType()->isVoidTy() || !I.hasName(),
2103           "Instruction has a name, but provides a void value!", &I);
2104
2105   // Check that the return value of the instruction is either void or a legal
2106   // value type.
2107   Assert1(I.getType()->isVoidTy() ||
2108           I.getType()->isFirstClassType(),
2109           "Instruction returns a non-scalar type!", &I);
2110
2111   // Check that the instruction doesn't produce metadata. Calls are already
2112   // checked against the callee type.
2113   Assert1(!I.getType()->isMetadataTy() ||
2114           isa<CallInst>(I) || isa<InvokeInst>(I),
2115           "Invalid use of metadata!", &I);
2116
2117   // Check that all uses of the instruction, if they are instructions
2118   // themselves, actually have parent basic blocks.  If the use is not an
2119   // instruction, it is an error!
2120   for (Use &U : I.uses()) {
2121     if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
2122       Assert2(Used->getParent() != nullptr, "Instruction referencing"
2123               " instruction not embedded in a basic block!", &I, Used);
2124     else {
2125       CheckFailed("Use of instruction is not an instruction!", U);
2126       return;
2127     }
2128   }
2129
2130   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2131     Assert1(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
2132
2133     // Check to make sure that only first-class-values are operands to
2134     // instructions.
2135     if (!I.getOperand(i)->getType()->isFirstClassType()) {
2136       Assert1(0, "Instruction operands must be first-class values!", &I);
2137     }
2138
2139     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2140       // Check to make sure that the "address of" an intrinsic function is never
2141       // taken.
2142       Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
2143               "Cannot take the address of an intrinsic!", &I);
2144       Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
2145               F->getIntrinsicID() == Intrinsic::donothing,
2146               "Cannot invoke an intrinsinc other than donothing", &I);
2147       Assert1(F->getParent() == M, "Referencing function in another module!",
2148               &I);
2149     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2150       Assert1(OpBB->getParent() == BB->getParent(),
2151               "Referring to a basic block in another function!", &I);
2152     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2153       Assert1(OpArg->getParent() == BB->getParent(),
2154               "Referring to an argument in another function!", &I);
2155     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2156       Assert1(GV->getParent() == M, "Referencing global in another module!",
2157               &I);
2158     } else if (isa<Instruction>(I.getOperand(i))) {
2159       verifyDominatesUse(I, i);
2160     } else if (isa<InlineAsm>(I.getOperand(i))) {
2161       Assert1((i + 1 == e && isa<CallInst>(I)) ||
2162               (i + 3 == e && isa<InvokeInst>(I)),
2163               "Cannot take the address of an inline asm!", &I);
2164     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2165       if (CE->getType()->isPtrOrPtrVectorTy()) {
2166         // If we have a ConstantExpr pointer, we need to see if it came from an
2167         // illegal bitcast (inttoptr <constant int> )
2168         SmallVector<const ConstantExpr *, 4> Stack;
2169         SmallPtrSet<const ConstantExpr *, 4> Visited;
2170         Stack.push_back(CE);
2171
2172         while (!Stack.empty()) {
2173           const ConstantExpr *V = Stack.pop_back_val();
2174           if (!Visited.insert(V))
2175             continue;
2176
2177           VerifyConstantExprBitcastType(V);
2178
2179           for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2180             if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2181               Stack.push_back(Op);
2182           }
2183         }
2184       }
2185     }
2186   }
2187
2188   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2189     Assert1(I.getType()->isFPOrFPVectorTy(),
2190             "fpmath requires a floating point result!", &I);
2191     Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2192     Value *Op0 = MD->getOperand(0);
2193     if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
2194       APFloat Accuracy = CFP0->getValueAPF();
2195       Assert1(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2196               "fpmath accuracy not a positive number!", &I);
2197     } else {
2198       Assert1(false, "invalid fpmath accuracy!", &I);
2199     }
2200   }
2201
2202   MDNode *MD = I.getMetadata(LLVMContext::MD_range);
2203   Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
2204
2205   InstsInThisBlock.insert(&I);
2206 }
2207
2208 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2209 /// intrinsic argument or return value) matches the type constraints specified
2210 /// by the .td file (e.g. an "any integer" argument really is an integer).
2211 ///
2212 /// This return true on error but does not print a message.
2213 bool Verifier::VerifyIntrinsicType(Type *Ty,
2214                                    ArrayRef<Intrinsic::IITDescriptor> &Infos,
2215                                    SmallVectorImpl<Type*> &ArgTys) {
2216   using namespace Intrinsic;
2217
2218   // If we ran out of descriptors, there are too many arguments.
2219   if (Infos.empty()) return true;
2220   IITDescriptor D = Infos.front();
2221   Infos = Infos.slice(1);
2222
2223   switch (D.Kind) {
2224   case IITDescriptor::Void: return !Ty->isVoidTy();
2225   case IITDescriptor::VarArg: return true;
2226   case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
2227   case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2228   case IITDescriptor::Half: return !Ty->isHalfTy();
2229   case IITDescriptor::Float: return !Ty->isFloatTy();
2230   case IITDescriptor::Double: return !Ty->isDoubleTy();
2231   case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2232   case IITDescriptor::Vector: {
2233     VectorType *VT = dyn_cast<VectorType>(Ty);
2234     return !VT || VT->getNumElements() != D.Vector_Width ||
2235            VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2236   }
2237   case IITDescriptor::Pointer: {
2238     PointerType *PT = dyn_cast<PointerType>(Ty);
2239     return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2240            VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2241   }
2242
2243   case IITDescriptor::Struct: {
2244     StructType *ST = dyn_cast<StructType>(Ty);
2245     if (!ST || ST->getNumElements() != D.Struct_NumElements)
2246       return true;
2247
2248     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2249       if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2250         return true;
2251     return false;
2252   }
2253
2254   case IITDescriptor::Argument:
2255     // Two cases here - If this is the second occurrence of an argument, verify
2256     // that the later instance matches the previous instance.
2257     if (D.getArgumentNumber() < ArgTys.size())
2258       return Ty != ArgTys[D.getArgumentNumber()];
2259
2260     // Otherwise, if this is the first instance of an argument, record it and
2261     // verify the "Any" kind.
2262     assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2263     ArgTys.push_back(Ty);
2264
2265     switch (D.getArgumentKind()) {
2266     case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2267     case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
2268     case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
2269     case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2270     }
2271     llvm_unreachable("all argument kinds not covered");
2272
2273   case IITDescriptor::ExtendArgument: {
2274     // This may only be used when referring to a previous vector argument.
2275     if (D.getArgumentNumber() >= ArgTys.size())
2276       return true;
2277
2278     Type *NewTy = ArgTys[D.getArgumentNumber()];
2279     if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2280       NewTy = VectorType::getExtendedElementVectorType(VTy);
2281     else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2282       NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
2283     else
2284       return true;
2285
2286     return Ty != NewTy;
2287   }
2288   case IITDescriptor::TruncArgument: {
2289     // This may only be used when referring to a previous vector argument.
2290     if (D.getArgumentNumber() >= ArgTys.size())
2291       return true;
2292
2293     Type *NewTy = ArgTys[D.getArgumentNumber()];
2294     if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2295       NewTy = VectorType::getTruncatedElementVectorType(VTy);
2296     else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2297       NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
2298     else
2299       return true;
2300
2301     return Ty != NewTy;
2302   }
2303   case IITDescriptor::HalfVecArgument:
2304     // This may only be used when referring to a previous vector argument.
2305     return D.getArgumentNumber() >= ArgTys.size() ||
2306            !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2307            VectorType::getHalfElementsVectorType(
2308                          cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2309   }
2310   llvm_unreachable("unhandled");
2311 }
2312
2313 /// \brief Verify if the intrinsic has variable arguments.
2314 /// This method is intended to be called after all the fixed arguments have been
2315 /// verified first.
2316 ///
2317 /// This method returns true on error and does not print an error message.
2318 bool
2319 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
2320                                   ArrayRef<Intrinsic::IITDescriptor> &Infos) {
2321   using namespace Intrinsic;
2322
2323   // If there are no descriptors left, then it can't be a vararg.
2324   if (Infos.empty())
2325     return isVarArg ? true : false;
2326
2327   // There should be only one descriptor remaining at this point.
2328   if (Infos.size() != 1)
2329     return true;
2330
2331   // Check and verify the descriptor.
2332   IITDescriptor D = Infos.front();
2333   Infos = Infos.slice(1);
2334   if (D.Kind == IITDescriptor::VarArg)
2335     return isVarArg ? false : true;
2336
2337   return true;
2338 }
2339
2340 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2341 ///
2342 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2343   Function *IF = CI.getCalledFunction();
2344   Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2345           IF);
2346
2347   // Verify that the intrinsic prototype lines up with what the .td files
2348   // describe.
2349   FunctionType *IFTy = IF->getFunctionType();
2350   bool IsVarArg = IFTy->isVarArg();
2351
2352   SmallVector<Intrinsic::IITDescriptor, 8> Table;
2353   getIntrinsicInfoTableEntries(ID, Table);
2354   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2355
2356   SmallVector<Type *, 4> ArgTys;
2357   Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2358           "Intrinsic has incorrect return type!", IF);
2359   for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2360     Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2361             "Intrinsic has incorrect argument type!", IF);
2362
2363   // Verify if the intrinsic call matches the vararg property.
2364   if (IsVarArg)
2365     Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2366             "Intrinsic was not defined with variable arguments!", IF);
2367   else
2368     Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2369             "Callsite was not defined with variable arguments!", IF);
2370
2371   // All descriptors should be absorbed by now.
2372   Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2373
2374   // Now that we have the intrinsic ID and the actual argument types (and we
2375   // know they are legal for the intrinsic!) get the intrinsic name through the
2376   // usual means.  This allows us to verify the mangling of argument types into
2377   // the name.
2378   const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
2379   Assert1(ExpectedName == IF->getName(),
2380           "Intrinsic name not mangled correctly for type arguments! "
2381           "Should be: " + ExpectedName, IF);
2382
2383   // If the intrinsic takes MDNode arguments, verify that they are either global
2384   // or are local to *this* function.
2385   for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2386     if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
2387       visitMDNode(*MD, CI.getParent()->getParent());
2388
2389   switch (ID) {
2390   default:
2391     break;
2392   case Intrinsic::ctlz:  // llvm.ctlz
2393   case Intrinsic::cttz:  // llvm.cttz
2394     Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2395             "is_zero_undef argument of bit counting intrinsics must be a "
2396             "constant int", &CI);
2397     break;
2398   case Intrinsic::dbg_declare: {  // llvm.dbg.declare
2399     Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2400                 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2401     MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
2402     Assert1(MD->getNumOperands() == 1,
2403                 "invalid llvm.dbg.declare intrinsic call 2", &CI);
2404   } break;
2405   case Intrinsic::memcpy:
2406   case Intrinsic::memmove:
2407   case Intrinsic::memset:
2408     Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
2409             "alignment argument of memory intrinsics must be a constant int",
2410             &CI);
2411     Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
2412             "isvolatile argument of memory intrinsics must be a constant int",
2413             &CI);
2414     break;
2415   case Intrinsic::gcroot:
2416   case Intrinsic::gcwrite:
2417   case Intrinsic::gcread:
2418     if (ID == Intrinsic::gcroot) {
2419       AllocaInst *AI =
2420         dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2421       Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2422       Assert1(isa<Constant>(CI.getArgOperand(1)),
2423               "llvm.gcroot parameter #2 must be a constant.", &CI);
2424       if (!AI->getType()->getElementType()->isPointerTy()) {
2425         Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2426                 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2427                 "or argument #2 must be a non-null constant.", &CI);
2428       }
2429     }
2430
2431     Assert1(CI.getParent()->getParent()->hasGC(),
2432             "Enclosing function does not use GC.", &CI);
2433     break;
2434   case Intrinsic::init_trampoline:
2435     Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2436             "llvm.init_trampoline parameter #2 must resolve to a function.",
2437             &CI);
2438     break;
2439   case Intrinsic::prefetch:
2440     Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
2441             isa<ConstantInt>(CI.getArgOperand(2)) &&
2442             cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2443             cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2444             "invalid arguments to llvm.prefetch",
2445             &CI);
2446     break;
2447   case Intrinsic::stackprotector:
2448     Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2449             "llvm.stackprotector parameter #2 must resolve to an alloca.",
2450             &CI);
2451     break;
2452   case Intrinsic::lifetime_start:
2453   case Intrinsic::lifetime_end:
2454   case Intrinsic::invariant_start:
2455     Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
2456             "size argument of memory use markers must be a constant integer",
2457             &CI);
2458     break;
2459   case Intrinsic::invariant_end:
2460     Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2461             "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2462     break;
2463   }
2464 }
2465
2466 void DebugInfoVerifier::verifyDebugInfo() {
2467   if (!VerifyDebugInfo)
2468     return;
2469
2470   DebugInfoFinder Finder;
2471   Finder.processModule(*M);
2472   processInstructions(Finder);
2473
2474   // Verify Debug Info.
2475   //
2476   // NOTE:  The loud braces are necessary for MSVC compatibility.
2477   for (DICompileUnit CU : Finder.compile_units()) {
2478     Assert1(CU.Verify(), "DICompileUnit does not Verify!", CU);
2479   }
2480   for (DISubprogram S : Finder.subprograms()) {
2481     Assert1(S.Verify(), "DISubprogram does not Verify!", S);
2482   }
2483   for (DIGlobalVariable GV : Finder.global_variables()) {
2484     Assert1(GV.Verify(), "DIGlobalVariable does not Verify!", GV);
2485   }
2486   for (DIType T : Finder.types()) {
2487     Assert1(T.Verify(), "DIType does not Verify!", T);
2488   }
2489   for (DIScope S : Finder.scopes()) {
2490     Assert1(S.Verify(), "DIScope does not Verify!", S);
2491   }
2492 }
2493
2494 void DebugInfoVerifier::processInstructions(DebugInfoFinder &Finder) {
2495   for (const Function &F : *M)
2496     for (auto I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2497       if (MDNode *MD = I->getMetadata(LLVMContext::MD_dbg))
2498         Finder.processLocation(*M, DILocation(MD));
2499       if (const CallInst *CI = dyn_cast<CallInst>(&*I))
2500         processCallInst(Finder, *CI);
2501     }
2502 }
2503
2504 void DebugInfoVerifier::processCallInst(DebugInfoFinder &Finder,
2505                                         const CallInst &CI) {
2506   if (Function *F = CI.getCalledFunction())
2507     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2508       switch (ID) {
2509       case Intrinsic::dbg_declare:
2510         Finder.processDeclare(*M, cast<DbgDeclareInst>(&CI));
2511         break;
2512       case Intrinsic::dbg_value:
2513         Finder.processValue(*M, cast<DbgValueInst>(&CI));
2514         break;
2515       default:
2516         break;
2517       }
2518 }
2519
2520 //===----------------------------------------------------------------------===//
2521 //  Implement the public interfaces to this file...
2522 //===----------------------------------------------------------------------===//
2523
2524 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
2525   Function &F = const_cast<Function &>(f);
2526   assert(!F.isDeclaration() && "Cannot verify external functions");
2527
2528   raw_null_ostream NullStr;
2529   Verifier V(OS ? *OS : NullStr);
2530
2531   // Note that this function's return value is inverted from what you would
2532   // expect of a function called "verify".
2533   return !V.verify(F);
2534 }
2535
2536 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
2537   raw_null_ostream NullStr;
2538   Verifier V(OS ? *OS : NullStr);
2539
2540   bool Broken = false;
2541   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
2542     if (!I->isDeclaration())
2543       Broken |= !V.verify(*I);
2544
2545   // Note that this function's return value is inverted from what you would
2546   // expect of a function called "verify".
2547   DebugInfoVerifier DIV(OS ? *OS : NullStr);
2548   return !V.verify(M) || !DIV.verify(M) || Broken;
2549 }
2550
2551 namespace {
2552 struct VerifierLegacyPass : public FunctionPass {
2553   static char ID;
2554
2555   Verifier V;
2556   bool FatalErrors;
2557
2558   VerifierLegacyPass() : FunctionPass(ID), FatalErrors(true) {
2559     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
2560   }
2561   explicit VerifierLegacyPass(bool FatalErrors)
2562       : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
2563     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
2564   }
2565
2566   bool runOnFunction(Function &F) override {
2567     if (!V.verify(F) && FatalErrors)
2568       report_fatal_error("Broken function found, compilation aborted!");
2569
2570     return false;
2571   }
2572
2573   bool doFinalization(Module &M) override {
2574     if (!V.verify(M) && FatalErrors)
2575       report_fatal_error("Broken module found, compilation aborted!");
2576
2577     return false;
2578   }
2579
2580   void getAnalysisUsage(AnalysisUsage &AU) const override {
2581     AU.setPreservesAll();
2582   }
2583 };
2584 struct DebugInfoVerifierLegacyPass : public ModulePass {
2585   static char ID;
2586
2587   DebugInfoVerifier V;
2588   bool FatalErrors;
2589
2590   DebugInfoVerifierLegacyPass() : ModulePass(ID), FatalErrors(true) {
2591     initializeDebugInfoVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
2592   }
2593   explicit DebugInfoVerifierLegacyPass(bool FatalErrors)
2594       : ModulePass(ID), V(dbgs()), FatalErrors(FatalErrors) {
2595     initializeDebugInfoVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
2596   }
2597
2598   bool runOnModule(Module &M) override {
2599     if (!V.verify(M) && FatalErrors)
2600       report_fatal_error("Broken debug info found, compilation aborted!");
2601
2602     return false;
2603   }
2604
2605   void getAnalysisUsage(AnalysisUsage &AU) const override {
2606     AU.setPreservesAll();
2607   }
2608 };
2609 }
2610
2611 char VerifierLegacyPass::ID = 0;
2612 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
2613
2614 char DebugInfoVerifierLegacyPass::ID = 0;
2615 INITIALIZE_PASS(DebugInfoVerifierLegacyPass, "verify-di", "Debug Info Verifier",
2616                 false, false)
2617
2618 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
2619   return new VerifierLegacyPass(FatalErrors);
2620 }
2621
2622 ModulePass *llvm::createDebugInfoVerifierPass(bool FatalErrors) {
2623   return new DebugInfoVerifierLegacyPass(FatalErrors);
2624 }
2625
2626 PreservedAnalyses VerifierPass::run(Module *M) {
2627   if (verifyModule(*M, &dbgs()) && FatalErrors)
2628     report_fatal_error("Broken module found, compilation aborted!");
2629
2630   return PreservedAnalyses::all();
2631 }
2632
2633 PreservedAnalyses VerifierPass::run(Function *F) {
2634   if (verifyFunction(*F, &dbgs()) && FatalErrors)
2635     report_fatal_error("Broken function found, compilation aborted!");
2636
2637   return PreservedAnalyses::all();
2638 }