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