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