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