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