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