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