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