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