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