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