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