1 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the function verifier interface, that can be used for some
10 // basic correctness checking of input to the system.
11 //
12 // Note that this does not provide full `Java style' security and verifications,
13 // instead it just tries to ensure that code is well-formed.
14 //
15 //  * Both of a binary operator's parameters are of the same type
16 //  * Verify that the indices of mem access instructions match other operands
17 //  * Verify that arithmetic and other things are only performed on first-class
18 //    types.  Verify that shifts & logicals only happen on integrals f.e.
19 //  * All of the constants in a switch statement are of the correct type
20 //  * The code is in valid SSA form
21 //  * It should be illegal to put a label into any other type (like a structure)
22 //    or to return one. [except constant arrays!]
23 //  * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
24 //  * PHI nodes must have an entry for each predecessor, with no extras.
25 //  * PHI nodes must be the first thing in a basic block, all grouped together
26 //  * PHI nodes must have at least one entry
27 //  * All basic blocks should only end with terminator insts, not contain them
28 //  * The entry node to a function must not have predecessors
29 //  * All Instructions must be embedded into a basic block
30 //  * Functions cannot take a void-typed parameter
31 //  * Verify that a function's argument list agrees with it's declared type.
32 //  * It is illegal to specify a name for a void value.
33 //  * It is illegal to have a internal global value with no initializer
34 //  * It is illegal to have a ret instruction that returns a value that does not
35 //    agree with the function return value type.
36 //  * Function call argument types match the function prototype
37 //  * A landing pad is defined by a landingpad instruction, and can be jumped to
38 //    only by the unwind edge of an invoke instruction.
39 //  * A landingpad instruction must be the first non-PHI instruction in the
40 //    block.
41 //  * Landingpad instructions must be in a function with a personality function.
42 //  * All other things that are tested by asserts spread about the code...
43 //
44 //===----------------------------------------------------------------------===//
45 
46 #include "llvm/IR/Verifier.h"
47 #include "llvm/ADT/APFloat.h"
48 #include "llvm/ADT/APInt.h"
49 #include "llvm/ADT/ArrayRef.h"
50 #include "llvm/ADT/DenseMap.h"
51 #include "llvm/ADT/MapVector.h"
52 #include "llvm/ADT/Optional.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/SmallSet.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/StringExtras.h"
58 #include "llvm/ADT/StringMap.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/Twine.h"
61 #include "llvm/ADT/ilist.h"
62 #include "llvm/BinaryFormat/Dwarf.h"
63 #include "llvm/IR/Argument.h"
64 #include "llvm/IR/Attributes.h"
65 #include "llvm/IR/BasicBlock.h"
66 #include "llvm/IR/CFG.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/Dominators.h"
78 #include "llvm/IR/Function.h"
79 #include "llvm/IR/GlobalAlias.h"
80 #include "llvm/IR/GlobalValue.h"
81 #include "llvm/IR/GlobalVariable.h"
82 #include "llvm/IR/InlineAsm.h"
83 #include "llvm/IR/InstVisitor.h"
84 #include "llvm/IR/InstrTypes.h"
85 #include "llvm/IR/Instruction.h"
86 #include "llvm/IR/Instructions.h"
87 #include "llvm/IR/IntrinsicInst.h"
88 #include "llvm/IR/Intrinsics.h"
89 #include "llvm/IR/IntrinsicsWebAssembly.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/InitializePasses.h"
101 #include "llvm/Pass.h"
102 #include "llvm/Support/AtomicOrdering.h"
103 #include "llvm/Support/Casting.h"
104 #include "llvm/Support/CommandLine.h"
105 #include "llvm/Support/Debug.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> VerifyNoAliasScopeDomination(
119     "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false),
120     cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical "
121              "scopes are not dominating"));
122 
123 namespace llvm {
124 
125 struct VerifierSupport {
126   raw_ostream *OS;
127   const Module &M;
128   ModuleSlotTracker MST;
129   Triple TT;
130   const DataLayout &DL;
131   LLVMContext &Context;
132 
133   /// Track the brokenness of the module while recursively visiting.
134   bool Broken = false;
135   /// Broken debug info can be "recovered" from by stripping the debug info.
136   bool BrokenDebugInfo = false;
137   /// Whether to treat broken debug info as an error.
138   bool TreatBrokenDebugInfoAsError = true;
139 
140   explicit VerifierSupport(raw_ostream *OS, const Module &M)
141       : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
142         Context(M.getContext()) {}
143 
144 private:
145   void Write(const Module *M) {
146     *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
147   }
148 
149   void Write(const Value *V) {
150     if (V)
151       Write(*V);
152   }
153 
154   void Write(const Value &V) {
155     if (isa<Instruction>(V)) {
156       V.print(*OS, MST);
157       *OS << '\n';
158     } else {
159       V.printAsOperand(*OS, true, MST);
160       *OS << '\n';
161     }
162   }
163 
164   void Write(const Metadata *MD) {
165     if (!MD)
166       return;
167     MD->print(*OS, MST, &M);
168     *OS << '\n';
169   }
170 
171   template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
172     Write(MD.get());
173   }
174 
175   void Write(const NamedMDNode *NMD) {
176     if (!NMD)
177       return;
178     NMD->print(*OS, MST);
179     *OS << '\n';
180   }
181 
182   void Write(Type *T) {
183     if (!T)
184       return;
185     *OS << ' ' << *T;
186   }
187 
188   void Write(const Comdat *C) {
189     if (!C)
190       return;
191     *OS << *C;
192   }
193 
194   void Write(const APInt *AI) {
195     if (!AI)
196       return;
197     *OS << *AI << '\n';
198   }
199 
200   void Write(const unsigned i) { *OS << i << '\n'; }
201 
202   // NOLINTNEXTLINE(readability-identifier-naming)
203   void Write(const Attribute *A) {
204     if (!A)
205       return;
206     *OS << A->getAsString() << '\n';
207   }
208 
209   // NOLINTNEXTLINE(readability-identifier-naming)
210   void Write(const AttributeSet *AS) {
211     if (!AS)
212       return;
213     *OS << AS->getAsString() << '\n';
214   }
215 
216   // NOLINTNEXTLINE(readability-identifier-naming)
217   void Write(const AttributeList *AL) {
218     if (!AL)
219       return;
220     AL->print(*OS);
221   }
222 
223   template <typename T> void Write(ArrayRef<T> Vs) {
224     for (const T &V : Vs)
225       Write(V);
226   }
227 
228   template <typename T1, typename... Ts>
229   void WriteTs(const T1 &V1, const Ts &... Vs) {
230     Write(V1);
231     WriteTs(Vs...);
232   }
233 
234   template <typename... Ts> void WriteTs() {}
235 
236 public:
237   /// A check failed, so printout out the condition and the message.
238   ///
239   /// This provides a nice place to put a breakpoint if you want to see why
240   /// something is not correct.
241   void CheckFailed(const Twine &Message) {
242     if (OS)
243       *OS << Message << '\n';
244     Broken = true;
245   }
246 
247   /// A check failed (with values to print).
248   ///
249   /// This calls the Message-only version so that the above is easier to set a
250   /// breakpoint on.
251   template <typename T1, typename... Ts>
252   void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
253     CheckFailed(Message);
254     if (OS)
255       WriteTs(V1, Vs...);
256   }
257 
258   /// A debug info check failed.
259   void DebugInfoCheckFailed(const Twine &Message) {
260     if (OS)
261       *OS << Message << '\n';
262     Broken |= TreatBrokenDebugInfoAsError;
263     BrokenDebugInfo = true;
264   }
265 
266   /// A debug info check failed (with values to print).
267   template <typename T1, typename... Ts>
268   void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
269                             const Ts &... Vs) {
270     DebugInfoCheckFailed(Message);
271     if (OS)
272       WriteTs(V1, Vs...);
273   }
274 };
275 
276 } // namespace llvm
277 
278 namespace {
279 
280 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
281   friend class InstVisitor<Verifier>;
282 
283   DominatorTree DT;
284 
285   /// When verifying a basic block, keep track of all of the
286   /// instructions we have seen so far.
287   ///
288   /// This allows us to do efficient dominance checks for the case when an
289   /// instruction has an operand that is an instruction in the same block.
290   SmallPtrSet<Instruction *, 16> InstsInThisBlock;
291 
292   /// Keep track of the metadata nodes that have been checked already.
293   SmallPtrSet<const Metadata *, 32> MDNodes;
294 
295   /// Keep track which DISubprogram is attached to which function.
296   DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments;
297 
298   /// Track all DICompileUnits visited.
299   SmallPtrSet<const Metadata *, 2> CUVisited;
300 
301   /// The result type for a landingpad.
302   Type *LandingPadResultTy;
303 
304   /// Whether we've seen a call to @llvm.localescape in this function
305   /// already.
306   bool SawFrameEscape;
307 
308   /// Whether the current function has a DISubprogram attached to it.
309   bool HasDebugInfo = false;
310 
311   /// The current source language.
312   dwarf::SourceLanguage CurrentSourceLang = dwarf::DW_LANG_lo_user;
313 
314   /// Whether source was present on the first DIFile encountered in each CU.
315   DenseMap<const DICompileUnit *, bool> HasSourceDebugInfo;
316 
317   /// Stores the count of how many objects were passed to llvm.localescape for a
318   /// given function and the largest index passed to llvm.localrecover.
319   DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
320 
321   // Maps catchswitches and cleanuppads that unwind to siblings to the
322   // terminators that indicate the unwind, used to detect cycles therein.
323   MapVector<Instruction *, Instruction *> SiblingFuncletInfo;
324 
325   /// Cache of constants visited in search of ConstantExprs.
326   SmallPtrSet<const Constant *, 32> ConstantExprVisited;
327 
328   /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
329   SmallVector<const Function *, 4> DeoptimizeDeclarations;
330 
331   /// Cache of attribute lists verified.
332   SmallPtrSet<const void *, 32> AttributeListsVisited;
333 
334   // Verify that this GlobalValue is only used in this module.
335   // This map is used to avoid visiting uses twice. We can arrive at a user
336   // twice, if they have multiple operands. In particular for very large
337   // constant expressions, we can arrive at a particular user many times.
338   SmallPtrSet<const Value *, 32> GlobalValueVisited;
339 
340   // Keeps track of duplicate function argument debug info.
341   SmallVector<const DILocalVariable *, 16> DebugFnArgs;
342 
343   TBAAVerifier TBAAVerifyHelper;
344 
345   SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls;
346 
347   void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
348 
349 public:
350   explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
351                     const Module &M)
352       : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
353         SawFrameEscape(false), TBAAVerifyHelper(this) {
354     TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
355   }
356 
357   bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
358 
359   bool verify(const Function &F) {
360     assert(F.getParent() == &M &&
361            "An instance of this class only works with a specific module!");
362 
363     // First ensure the function is well-enough formed to compute dominance
364     // information, and directly compute a dominance tree. We don't rely on the
365     // pass manager to provide this as it isolates us from a potentially
366     // out-of-date dominator tree and makes it significantly more complex to run
367     // this code outside of a pass manager.
368     // FIXME: It's really gross that we have to cast away constness here.
369     if (!F.empty())
370       DT.recalculate(const_cast<Function &>(F));
371 
372     for (const BasicBlock &BB : F) {
373       if (!BB.empty() && BB.back().isTerminator())
374         continue;
375 
376       if (OS) {
377         *OS << "Basic Block in function '" << F.getName()
378             << "' does not have terminator!\n";
379         BB.printAsOperand(*OS, true, MST);
380         *OS << "\n";
381       }
382       return false;
383     }
384 
385     Broken = false;
386     // FIXME: We strip const here because the inst visitor strips const.
387     visit(const_cast<Function &>(F));
388     verifySiblingFuncletUnwinds();
389     InstsInThisBlock.clear();
390     DebugFnArgs.clear();
391     LandingPadResultTy = nullptr;
392     SawFrameEscape = false;
393     SiblingFuncletInfo.clear();
394     verifyNoAliasScopeDecl();
395     NoAliasScopeDecls.clear();
396 
397     return !Broken;
398   }
399 
400   /// Verify the module that this instance of \c Verifier was initialized with.
401   bool verify() {
402     Broken = false;
403 
404     // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
405     for (const Function &F : M)
406       if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
407         DeoptimizeDeclarations.push_back(&F);
408 
409     // Now that we've visited every function, verify that we never asked to
410     // recover a frame index that wasn't escaped.
411     verifyFrameRecoverIndices();
412     for (const GlobalVariable &GV : M.globals())
413       visitGlobalVariable(GV);
414 
415     for (const GlobalAlias &GA : M.aliases())
416       visitGlobalAlias(GA);
417 
418     for (const GlobalIFunc &GI : M.ifuncs())
419       visitGlobalIFunc(GI);
420 
421     for (const NamedMDNode &NMD : M.named_metadata())
422       visitNamedMDNode(NMD);
423 
424     for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
425       visitComdat(SMEC.getValue());
426 
427     visitModuleFlags();
428     visitModuleIdents();
429     visitModuleCommandLines();
430 
431     verifyCompileUnits();
432 
433     verifyDeoptimizeCallingConvs();
434     DISubprogramAttachments.clear();
435     return !Broken;
436   }
437 
438 private:
439   /// Whether a metadata node is allowed to be, or contain, a DILocation.
440   enum class AreDebugLocsAllowed { No, Yes };
441 
442   // Verification methods...
443   void visitGlobalValue(const GlobalValue &GV);
444   void visitGlobalVariable(const GlobalVariable &GV);
445   void visitGlobalAlias(const GlobalAlias &GA);
446   void visitGlobalIFunc(const GlobalIFunc &GI);
447   void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
448   void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
449                            const GlobalAlias &A, const Constant &C);
450   void visitNamedMDNode(const NamedMDNode &NMD);
451   void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
452   void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
453   void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
454   void visitComdat(const Comdat &C);
455   void visitModuleIdents();
456   void visitModuleCommandLines();
457   void visitModuleFlags();
458   void visitModuleFlag(const MDNode *Op,
459                        DenseMap<const MDString *, const MDNode *> &SeenIDs,
460                        SmallVectorImpl<const MDNode *> &Requirements);
461   void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
462   void visitFunction(const Function &F);
463   void visitBasicBlock(BasicBlock &BB);
464   void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
465   void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
466   void visitProfMetadata(Instruction &I, MDNode *MD);
467   void visitAnnotationMetadata(MDNode *Annotation);
468   void visitAliasScopeMetadata(const MDNode *MD);
469   void visitAliasScopeListMetadata(const MDNode *MD);
470 
471   template <class Ty> bool isValidMetadataArray(const MDTuple &N);
472 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
473 #include "llvm/IR/Metadata.def"
474   void visitDIScope(const DIScope &N);
475   void visitDIVariable(const DIVariable &N);
476   void visitDILexicalBlockBase(const DILexicalBlockBase &N);
477   void visitDITemplateParameter(const DITemplateParameter &N);
478 
479   void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
480 
481   // InstVisitor overrides...
482   using InstVisitor<Verifier>::visit;
483   void visit(Instruction &I);
484 
485   void visitTruncInst(TruncInst &I);
486   void visitZExtInst(ZExtInst &I);
487   void visitSExtInst(SExtInst &I);
488   void visitFPTruncInst(FPTruncInst &I);
489   void visitFPExtInst(FPExtInst &I);
490   void visitFPToUIInst(FPToUIInst &I);
491   void visitFPToSIInst(FPToSIInst &I);
492   void visitUIToFPInst(UIToFPInst &I);
493   void visitSIToFPInst(SIToFPInst &I);
494   void visitIntToPtrInst(IntToPtrInst &I);
495   void visitPtrToIntInst(PtrToIntInst &I);
496   void visitBitCastInst(BitCastInst &I);
497   void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
498   void visitPHINode(PHINode &PN);
499   void visitCallBase(CallBase &Call);
500   void visitUnaryOperator(UnaryOperator &U);
501   void visitBinaryOperator(BinaryOperator &B);
502   void visitICmpInst(ICmpInst &IC);
503   void visitFCmpInst(FCmpInst &FC);
504   void visitExtractElementInst(ExtractElementInst &EI);
505   void visitInsertElementInst(InsertElementInst &EI);
506   void visitShuffleVectorInst(ShuffleVectorInst &EI);
507   void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
508   void visitCallInst(CallInst &CI);
509   void visitInvokeInst(InvokeInst &II);
510   void visitGetElementPtrInst(GetElementPtrInst &GEP);
511   void visitLoadInst(LoadInst &LI);
512   void visitStoreInst(StoreInst &SI);
513   void verifyDominatesUse(Instruction &I, unsigned i);
514   void visitInstruction(Instruction &I);
515   void visitTerminator(Instruction &I);
516   void visitBranchInst(BranchInst &BI);
517   void visitReturnInst(ReturnInst &RI);
518   void visitSwitchInst(SwitchInst &SI);
519   void visitIndirectBrInst(IndirectBrInst &BI);
520   void visitCallBrInst(CallBrInst &CBI);
521   void visitSelectInst(SelectInst &SI);
522   void visitUserOp1(Instruction &I);
523   void visitUserOp2(Instruction &I) { visitUserOp1(I); }
524   void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
525   void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
526   void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII);
527   void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
528   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
529   void visitAtomicRMWInst(AtomicRMWInst &RMWI);
530   void visitFenceInst(FenceInst &FI);
531   void visitAllocaInst(AllocaInst &AI);
532   void visitExtractValueInst(ExtractValueInst &EVI);
533   void visitInsertValueInst(InsertValueInst &IVI);
534   void visitEHPadPredecessors(Instruction &I);
535   void visitLandingPadInst(LandingPadInst &LPI);
536   void visitResumeInst(ResumeInst &RI);
537   void visitCatchPadInst(CatchPadInst &CPI);
538   void visitCatchReturnInst(CatchReturnInst &CatchReturn);
539   void visitCleanupPadInst(CleanupPadInst &CPI);
540   void visitFuncletPadInst(FuncletPadInst &FPI);
541   void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
542   void visitCleanupReturnInst(CleanupReturnInst &CRI);
543 
544   void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
545   void verifySwiftErrorValue(const Value *SwiftErrorVal);
546   void verifyTailCCMustTailAttrs(AttrBuilder Attrs, StringRef Context);
547   void verifyMustTailCall(CallInst &CI);
548   bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
549   void verifyAttributeTypes(AttributeSet Attrs, const Value *V);
550   void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
551   void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
552                                     const Value *V);
553   void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
554                            const Value *V, bool IsIntrinsic);
555   void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
556   template <typename T>
557   void verifyODRTypeAsScopeOperand(const MDNode &MD, T * = nullptr);
558 
559   void visitConstantExprsRecursively(const Constant *EntryC);
560   void visitConstantExpr(const ConstantExpr *CE);
561   void verifyStatepoint(const CallBase &Call);
562   void verifyFrameRecoverIndices();
563   void verifySiblingFuncletUnwinds();
564 
565   void verifyFragmentExpression(const DbgVariableIntrinsic &I);
566   template <typename ValueOrMetadata>
567   void verifyFragmentExpression(const DIVariable &V,
568                                 DIExpression::FragmentInfo Fragment,
569                                 ValueOrMetadata *Desc);
570   void verifyFnArgs(const DbgVariableIntrinsic &I);
571   void verifyNotEntryValue(const DbgVariableIntrinsic &I);
572 
573   /// Module-level debug info verification...
574   void verifyCompileUnits();
575 
576   /// Module-level verification that all @llvm.experimental.deoptimize
577   /// declarations share the same calling convention.
578   void verifyDeoptimizeCallingConvs();
579 
580   void verifyAttachedCallBundle(const CallBase &Call,
581                                 const OperandBundleUse &BU);
582 
583   /// Verify all-or-nothing property of DIFile source attribute within a CU.
584   void verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F);
585 
586   /// Verify the llvm.experimental.noalias.scope.decl declarations
587   void verifyNoAliasScopeDecl();
588 };
589 
590 } // end anonymous namespace
591 
592 /// We know that cond should be true, if not print an error message.
593 #define Assert(C, ...) \
594   do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false)
595 
596 /// We know that a debug info condition should be true, if not print
597 /// an error message.
598 #define AssertDI(C, ...) \
599   do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (false)
600 
601 void Verifier::visit(Instruction &I) {
602   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
603     Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
604   InstVisitor<Verifier>::visit(I);
605 }
606 
607 // Helper to recursively iterate over indirect users. By
608 // returning false, the callback can ask to stop recursing
609 // further.
610 static void forEachUser(const Value *User,
611                         SmallPtrSet<const Value *, 32> &Visited,
612                         llvm::function_ref<bool(const Value *)> Callback) {
613   if (!Visited.insert(User).second)
614     return;
615   for (const Value *TheNextUser : User->materialized_users())
616     if (Callback(TheNextUser))
617       forEachUser(TheNextUser, Visited, Callback);
618 }
619 
620 void Verifier::visitGlobalValue(const GlobalValue &GV) {
621   Assert(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(),
622          "Global is external, but doesn't have external or weak linkage!", &GV);
623 
624   if (const GlobalObject *GO = dyn_cast<GlobalObject>(&GV))
625     Assert(GO->getAlignment() <= Value::MaximumAlignment,
626            "huge alignment values are unsupported", GO);
627   Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
628          "Only global variables can have appending linkage!", &GV);
629 
630   if (GV.hasAppendingLinkage()) {
631     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
632     Assert(GVar && GVar->getValueType()->isArrayTy(),
633            "Only global arrays can have appending linkage!", GVar);
634   }
635 
636   if (GV.isDeclarationForLinker())
637     Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
638 
639   if (GV.hasDLLImportStorageClass()) {
640     Assert(!GV.isDSOLocal(),
641            "GlobalValue with DLLImport Storage is dso_local!", &GV);
642 
643     Assert((GV.isDeclaration() &&
644             (GV.hasExternalLinkage() || GV.hasExternalWeakLinkage())) ||
645                GV.hasAvailableExternallyLinkage(),
646            "Global is marked as dllimport, but not external", &GV);
647   }
648 
649   if (GV.isImplicitDSOLocal())
650     Assert(GV.isDSOLocal(),
651            "GlobalValue with local linkage or non-default "
652            "visibility must be dso_local!",
653            &GV);
654 
655   forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
656     if (const Instruction *I = dyn_cast<Instruction>(V)) {
657       if (!I->getParent() || !I->getParent()->getParent())
658         CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
659                     I);
660       else if (I->getParent()->getParent()->getParent() != &M)
661         CheckFailed("Global is referenced in a different module!", &GV, &M, I,
662                     I->getParent()->getParent(),
663                     I->getParent()->getParent()->getParent());
664       return false;
665     } else if (const Function *F = dyn_cast<Function>(V)) {
666       if (F->getParent() != &M)
667         CheckFailed("Global is used by function in a different module", &GV, &M,
668                     F, F->getParent());
669       return false;
670     }
671     return true;
672   });
673 }
674 
675 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
676   if (GV.hasInitializer()) {
677     Assert(GV.getInitializer()->getType() == GV.getValueType(),
678            "Global variable initializer type does not match global "
679            "variable type!",
680            &GV);
681     // If the global has common linkage, it must have a zero initializer and
682     // cannot be constant.
683     if (GV.hasCommonLinkage()) {
684       Assert(GV.getInitializer()->isNullValue(),
685              "'common' global must have a zero initializer!", &GV);
686       Assert(!GV.isConstant(), "'common' global may not be marked constant!",
687              &GV);
688       Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
689     }
690   }
691 
692   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
693                        GV.getName() == "llvm.global_dtors")) {
694     Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
695            "invalid linkage for intrinsic global variable", &GV);
696     // Don't worry about emitting an error for it not being an array,
697     // visitGlobalValue will complain on appending non-array.
698     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
699       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
700       PointerType *FuncPtrTy =
701           FunctionType::get(Type::getVoidTy(Context), false)->
702           getPointerTo(DL.getProgramAddressSpace());
703       Assert(STy &&
704                  (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
705                  STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
706                  STy->getTypeAtIndex(1) == FuncPtrTy,
707              "wrong type for intrinsic global variable", &GV);
708       Assert(STy->getNumElements() == 3,
709              "the third field of the element type is mandatory, "
710              "specify i8* null to migrate from the obsoleted 2-field form");
711       Type *ETy = STy->getTypeAtIndex(2);
712       Type *Int8Ty = Type::getInt8Ty(ETy->getContext());
713       Assert(ETy->isPointerTy() &&
714                  cast<PointerType>(ETy)->isOpaqueOrPointeeTypeMatches(Int8Ty),
715              "wrong type for intrinsic global variable", &GV);
716     }
717   }
718 
719   if (GV.hasName() && (GV.getName() == "llvm.used" ||
720                        GV.getName() == "llvm.compiler.used")) {
721     Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
722            "invalid linkage for intrinsic global variable", &GV);
723     Type *GVType = GV.getValueType();
724     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
725       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
726       Assert(PTy, "wrong type for intrinsic global variable", &GV);
727       if (GV.hasInitializer()) {
728         const Constant *Init = GV.getInitializer();
729         const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
730         Assert(InitArray, "wrong initalizer for intrinsic global variable",
731                Init);
732         for (Value *Op : InitArray->operands()) {
733           Value *V = Op->stripPointerCasts();
734           Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
735                      isa<GlobalAlias>(V),
736                  "invalid llvm.used member", V);
737           Assert(V->hasName(), "members of llvm.used must be named", V);
738         }
739       }
740     }
741   }
742 
743   // Visit any debug info attachments.
744   SmallVector<MDNode *, 1> MDs;
745   GV.getMetadata(LLVMContext::MD_dbg, MDs);
746   for (auto *MD : MDs) {
747     if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
748       visitDIGlobalVariableExpression(*GVE);
749     else
750       AssertDI(false, "!dbg attachment of global variable must be a "
751                       "DIGlobalVariableExpression");
752   }
753 
754   // Scalable vectors cannot be global variables, since we don't know
755   // the runtime size. If the global is an array containing scalable vectors,
756   // that will be caught by the isValidElementType methods in StructType or
757   // ArrayType instead.
758   Assert(!isa<ScalableVectorType>(GV.getValueType()),
759          "Globals cannot contain scalable vectors", &GV);
760 
761   if (auto *STy = dyn_cast<StructType>(GV.getValueType()))
762     Assert(!STy->containsScalableVectorType(),
763            "Globals cannot contain scalable vectors", &GV);
764 
765   if (!GV.hasInitializer()) {
766     visitGlobalValue(GV);
767     return;
768   }
769 
770   // Walk any aggregate initializers looking for bitcasts between address spaces
771   visitConstantExprsRecursively(GV.getInitializer());
772 
773   visitGlobalValue(GV);
774 }
775 
776 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
777   SmallPtrSet<const GlobalAlias*, 4> Visited;
778   Visited.insert(&GA);
779   visitAliaseeSubExpr(Visited, GA, C);
780 }
781 
782 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
783                                    const GlobalAlias &GA, const Constant &C) {
784   if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
785     Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",
786            &GA);
787 
788     if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
789       Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
790 
791       Assert(!GA2->isInterposable(), "Alias cannot point to an interposable alias",
792              &GA);
793     } else {
794       // Only continue verifying subexpressions of GlobalAliases.
795       // Do not recurse into global initializers.
796       return;
797     }
798   }
799 
800   if (const auto *CE = dyn_cast<ConstantExpr>(&C))
801     visitConstantExprsRecursively(CE);
802 
803   for (const Use &U : C.operands()) {
804     Value *V = &*U;
805     if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
806       visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
807     else if (const auto *C2 = dyn_cast<Constant>(V))
808       visitAliaseeSubExpr(Visited, GA, *C2);
809   }
810 }
811 
812 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
813   Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
814          "Alias should have private, internal, linkonce, weak, linkonce_odr, "
815          "weak_odr, or external linkage!",
816          &GA);
817   const Constant *Aliasee = GA.getAliasee();
818   Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
819   Assert(GA.getType() == Aliasee->getType(),
820          "Alias and aliasee types should match!", &GA);
821 
822   Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
823          "Aliasee should be either GlobalValue or ConstantExpr", &GA);
824 
825   visitAliaseeSubExpr(GA, *Aliasee);
826 
827   visitGlobalValue(GA);
828 }
829 
830 void Verifier::visitGlobalIFunc(const GlobalIFunc &GI) {
831   // Pierce through ConstantExprs and GlobalAliases and check that the resolver
832   // has a Function
833   const Function *Resolver = GI.getResolverFunction();
834   Assert(Resolver, "IFunc must have a Function resolver", &GI);
835 
836   // Check that the immediate resolver operand (prior to any bitcasts) has the
837   // correct type
838   const Type *ResolverTy = GI.getResolver()->getType();
839   const Type *ResolverFuncTy =
840       GlobalIFunc::getResolverFunctionType(GI.getValueType());
841   Assert(ResolverTy == ResolverFuncTy->getPointerTo(),
842          "IFunc resolver has incorrect type", &GI);
843 }
844 
845 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
846   // There used to be various other llvm.dbg.* nodes, but we don't support
847   // upgrading them and we want to reserve the namespace for future uses.
848   if (NMD.getName().startswith("llvm.dbg."))
849     AssertDI(NMD.getName() == "llvm.dbg.cu",
850              "unrecognized named metadata node in the llvm.dbg namespace",
851              &NMD);
852   for (const MDNode *MD : NMD.operands()) {
853     if (NMD.getName() == "llvm.dbg.cu")
854       AssertDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
855 
856     if (!MD)
857       continue;
858 
859     visitMDNode(*MD, AreDebugLocsAllowed::Yes);
860   }
861 }
862 
863 template <typename T>
864 void Verifier::verifyODRTypeAsScopeOperand(const MDNode &MD, T *) {
865   if (isa<T>(MD)) {
866     if (auto *N = dyn_cast_or_null<DICompositeType>(cast<T>(MD).getScope()))
867       // Of all the supported tags for DICompositeType(see visitDICompositeType)
868       // we know that enum type cannot be a scope.
869       AssertDI(N->getTag() != dwarf::DW_TAG_enumeration_type,
870                "enum type is not a scope; check enum type ODR "
871                "violation",
872                N, &MD);
873   }
874 }
875 
876 void Verifier::visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
877   // Only visit each node once.  Metadata can be mutually recursive, so this
878   // avoids infinite recursion here, as well as being an optimization.
879   if (!MDNodes.insert(&MD).second)
880     return;
881 
882   Assert(&MD.getContext() == &Context,
883          "MDNode context does not match Module context!", &MD);
884 
885   // Makes sure when a scope operand is a ODR type, the ODR type uniquing does
886   // not create invalid debug metadata.
887   // TODO: check that the non-ODR-type scope operand is valid.
888   verifyODRTypeAsScopeOperand<DIType>(MD);
889   verifyODRTypeAsScopeOperand<DILocalScope>(MD);
890 
891   switch (MD.getMetadataID()) {
892   default:
893     llvm_unreachable("Invalid MDNode subclass");
894   case Metadata::MDTupleKind:
895     break;
896 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
897   case Metadata::CLASS##Kind:                                                  \
898     visit##CLASS(cast<CLASS>(MD));                                             \
899     break;
900 #include "llvm/IR/Metadata.def"
901   }
902 
903   for (const Metadata *Op : MD.operands()) {
904     if (!Op)
905       continue;
906     Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
907            &MD, Op);
908     AssertDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,
909              "DILocation not allowed within this metadata node", &MD, Op);
910     if (auto *N = dyn_cast<MDNode>(Op)) {
911       visitMDNode(*N, AllowLocs);
912       continue;
913     }
914     if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
915       visitValueAsMetadata(*V, nullptr);
916       continue;
917     }
918   }
919 
920   // Check these last, so we diagnose problems in operands first.
921   Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
922   Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
923 }
924 
925 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
926   Assert(MD.getValue(), "Expected valid value", &MD);
927   Assert(!MD.getValue()->getType()->isMetadataTy(),
928          "Unexpected metadata round-trip through values", &MD, MD.getValue());
929 
930   auto *L = dyn_cast<LocalAsMetadata>(&MD);
931   if (!L)
932     return;
933 
934   Assert(F, "function-local metadata used outside a function", L);
935 
936   // If this was an instruction, bb, or argument, verify that it is in the
937   // function that we expect.
938   Function *ActualF = nullptr;
939   if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
940     Assert(I->getParent(), "function-local metadata not in basic block", L, I);
941     ActualF = I->getParent()->getParent();
942   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
943     ActualF = BB->getParent();
944   else if (Argument *A = dyn_cast<Argument>(L->getValue()))
945     ActualF = A->getParent();
946   assert(ActualF && "Unimplemented function local metadata case!");
947 
948   Assert(ActualF == F, "function-local metadata used in wrong function", L);
949 }
950 
951 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
952   Metadata *MD = MDV.getMetadata();
953   if (auto *N = dyn_cast<MDNode>(MD)) {
954     visitMDNode(*N, AreDebugLocsAllowed::No);
955     return;
956   }
957 
958   // Only visit each node once.  Metadata can be mutually recursive, so this
959   // avoids infinite recursion here, as well as being an optimization.
960   if (!MDNodes.insert(MD).second)
961     return;
962 
963   if (auto *V = dyn_cast<ValueAsMetadata>(MD))
964     visitValueAsMetadata(*V, F);
965 }
966 
967 static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
968 static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
969 static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
970 
971 void Verifier::visitDILocation(const DILocation &N) {
972   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
973            "location requires a valid scope", &N, N.getRawScope());
974   if (auto *IA = N.getRawInlinedAt())
975     AssertDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
976   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
977     AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
978 }
979 
980 void Verifier::visitGenericDINode(const GenericDINode &N) {
981   AssertDI(N.getTag(), "invalid tag", &N);
982 }
983 
984 void Verifier::visitDIScope(const DIScope &N) {
985   if (auto *F = N.getRawFile())
986     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
987 }
988 
989 void Verifier::visitDISubrange(const DISubrange &N) {
990   AssertDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
991   bool HasAssumedSizedArraySupport = dwarf::isFortran(CurrentSourceLang);
992   AssertDI(HasAssumedSizedArraySupport || N.getRawCountNode() ||
993                N.getRawUpperBound(),
994            "Subrange must contain count or upperBound", &N);
995   AssertDI(!N.getRawCountNode() || !N.getRawUpperBound(),
996            "Subrange can have any one of count or upperBound", &N);
997   auto *CBound = N.getRawCountNode();
998   AssertDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
999                isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1000            "Count must be signed constant or DIVariable or DIExpression", &N);
1001   auto Count = N.getCount();
1002   AssertDI(!Count || !Count.is<ConstantInt *>() ||
1003                Count.get<ConstantInt *>()->getSExtValue() >= -1,
1004            "invalid subrange count", &N);
1005   auto *LBound = N.getRawLowerBound();
1006   AssertDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
1007                isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1008            "LowerBound must be signed constant or DIVariable or DIExpression",
1009            &N);
1010   auto *UBound = N.getRawUpperBound();
1011   AssertDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
1012                isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1013            "UpperBound must be signed constant or DIVariable or DIExpression",
1014            &N);
1015   auto *Stride = N.getRawStride();
1016   AssertDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
1017                isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1018            "Stride must be signed constant or DIVariable or DIExpression", &N);
1019 }
1020 
1021 void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) {
1022   AssertDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N);
1023   AssertDI(N.getRawCountNode() || N.getRawUpperBound(),
1024            "GenericSubrange must contain count or upperBound", &N);
1025   AssertDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1026            "GenericSubrange can have any one of count or upperBound", &N);
1027   auto *CBound = N.getRawCountNode();
1028   AssertDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1029            "Count must be signed constant or DIVariable or DIExpression", &N);
1030   auto *LBound = N.getRawLowerBound();
1031   AssertDI(LBound, "GenericSubrange must contain lowerBound", &N);
1032   AssertDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1033            "LowerBound must be signed constant or DIVariable or DIExpression",
1034            &N);
1035   auto *UBound = N.getRawUpperBound();
1036   AssertDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1037            "UpperBound must be signed constant or DIVariable or DIExpression",
1038            &N);
1039   auto *Stride = N.getRawStride();
1040   AssertDI(Stride, "GenericSubrange must contain stride", &N);
1041   AssertDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1042            "Stride must be signed constant or DIVariable or DIExpression", &N);
1043 }
1044 
1045 void Verifier::visitDIEnumerator(const DIEnumerator &N) {
1046   AssertDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
1047 }
1048 
1049 void Verifier::visitDIBasicType(const DIBasicType &N) {
1050   AssertDI(N.getTag() == dwarf::DW_TAG_base_type ||
1051                N.getTag() == dwarf::DW_TAG_unspecified_type ||
1052                N.getTag() == dwarf::DW_TAG_string_type,
1053            "invalid tag", &N);
1054 }
1055 
1056 void Verifier::visitDIStringType(const DIStringType &N) {
1057   AssertDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N);
1058   AssertDI(!(N.isBigEndian() && N.isLittleEndian()) ,
1059             "has conflicting flags", &N);
1060 }
1061 
1062 void Verifier::visitDIDerivedType(const DIDerivedType &N) {
1063   // Common scope checks.
1064   visitDIScope(N);
1065 
1066   AssertDI(N.getTag() == dwarf::DW_TAG_typedef ||
1067                N.getTag() == dwarf::DW_TAG_pointer_type ||
1068                N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1069                N.getTag() == dwarf::DW_TAG_reference_type ||
1070                N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1071                N.getTag() == dwarf::DW_TAG_const_type ||
1072                N.getTag() == dwarf::DW_TAG_volatile_type ||
1073                N.getTag() == dwarf::DW_TAG_restrict_type ||
1074                N.getTag() == dwarf::DW_TAG_atomic_type ||
1075                N.getTag() == dwarf::DW_TAG_member ||
1076                N.getTag() == dwarf::DW_TAG_inheritance ||
1077                N.getTag() == dwarf::DW_TAG_friend ||
1078                N.getTag() == dwarf::DW_TAG_set_type,
1079            "invalid tag", &N);
1080   if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1081     AssertDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
1082              N.getRawExtraData());
1083   }
1084 
1085   if (N.getTag() == dwarf::DW_TAG_set_type) {
1086     if (auto *T = N.getRawBaseType()) {
1087       auto *Enum = dyn_cast_or_null<DICompositeType>(T);
1088       auto *Basic = dyn_cast_or_null<DIBasicType>(T);
1089       AssertDI(
1090           (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1091               (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1092                          Basic->getEncoding() == dwarf::DW_ATE_signed ||
1093                          Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1094                          Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1095                          Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1096           "invalid set base type", &N, T);
1097     }
1098   }
1099 
1100   AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1101   AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
1102            N.getRawBaseType());
1103 
1104   if (N.getDWARFAddressSpace()) {
1105     AssertDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
1106                  N.getTag() == dwarf::DW_TAG_reference_type ||
1107                  N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1108              "DWARF address space only applies to pointer or reference types",
1109              &N);
1110   }
1111 }
1112 
1113 /// Detect mutually exclusive flags.
1114 static bool hasConflictingReferenceFlags(unsigned Flags) {
1115   return ((Flags & DINode::FlagLValueReference) &&
1116           (Flags & DINode::FlagRValueReference)) ||
1117          ((Flags & DINode::FlagTypePassByValue) &&
1118           (Flags & DINode::FlagTypePassByReference));
1119 }
1120 
1121 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
1122   auto *Params = dyn_cast<MDTuple>(&RawParams);
1123   AssertDI(Params, "invalid template params", &N, &RawParams);
1124   for (Metadata *Op : Params->operands()) {
1125     AssertDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
1126              &N, Params, Op);
1127   }
1128 }
1129 
1130 void Verifier::visitDICompositeType(const DICompositeType &N) {
1131   // Common scope checks.
1132   visitDIScope(N);
1133 
1134   AssertDI(N.getTag() == dwarf::DW_TAG_array_type ||
1135                N.getTag() == dwarf::DW_TAG_structure_type ||
1136                N.getTag() == dwarf::DW_TAG_union_type ||
1137                N.getTag() == dwarf::DW_TAG_enumeration_type ||
1138                N.getTag() == dwarf::DW_TAG_class_type ||
1139                N.getTag() == dwarf::DW_TAG_variant_part ||
1140                N.getTag() == dwarf::DW_TAG_namelist,
1141            "invalid tag", &N);
1142 
1143   AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1144   AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
1145            N.getRawBaseType());
1146 
1147   AssertDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
1148            "invalid composite elements", &N, N.getRawElements());
1149   AssertDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
1150            N.getRawVTableHolder());
1151   AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
1152            "invalid reference flags", &N);
1153   unsigned DIBlockByRefStruct = 1 << 4;
1154   AssertDI((N.getFlags() & DIBlockByRefStruct) == 0,
1155            "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
1156 
1157   if (N.isVector()) {
1158     const DINodeArray Elements = N.getElements();
1159     AssertDI(Elements.size() == 1 &&
1160              Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1161              "invalid vector, expected one element of type subrange", &N);
1162   }
1163 
1164   if (auto *Params = N.getRawTemplateParams())
1165     visitTemplateParams(N, *Params);
1166 
1167   if (auto *D = N.getRawDiscriminator()) {
1168     AssertDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
1169              "discriminator can only appear on variant part");
1170   }
1171 
1172   if (N.getRawDataLocation()) {
1173     AssertDI(N.getTag() == dwarf::DW_TAG_array_type,
1174              "dataLocation can only appear in array type");
1175   }
1176 
1177   if (N.getRawAssociated()) {
1178     AssertDI(N.getTag() == dwarf::DW_TAG_array_type,
1179              "associated can only appear in array type");
1180   }
1181 
1182   if (N.getRawAllocated()) {
1183     AssertDI(N.getTag() == dwarf::DW_TAG_array_type,
1184              "allocated can only appear in array type");
1185   }
1186 
1187   if (N.getRawRank()) {
1188     AssertDI(N.getTag() == dwarf::DW_TAG_array_type,
1189              "rank can only appear in array type");
1190   }
1191 }
1192 
1193 void Verifier::visitDISubroutineType(const DISubroutineType &N) {
1194   AssertDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
1195   if (auto *Types = N.getRawTypeArray()) {
1196     AssertDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
1197     for (Metadata *Ty : N.getTypeArray()->operands()) {
1198       AssertDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
1199     }
1200   }
1201   AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
1202            "invalid reference flags", &N);
1203 }
1204 
1205 void Verifier::visitDIFile(const DIFile &N) {
1206   AssertDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
1207   Optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
1208   if (Checksum) {
1209     AssertDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1210              "invalid checksum kind", &N);
1211     size_t Size;
1212     switch (Checksum->Kind) {
1213     case DIFile::CSK_MD5:
1214       Size = 32;
1215       break;
1216     case DIFile::CSK_SHA1:
1217       Size = 40;
1218       break;
1219     case DIFile::CSK_SHA256:
1220       Size = 64;
1221       break;
1222     }
1223     AssertDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
1224     AssertDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
1225              "invalid checksum", &N);
1226   }
1227 }
1228 
1229 void Verifier::visitDICompileUnit(const DICompileUnit &N) {
1230   AssertDI(N.isDistinct(), "compile units must be distinct", &N);
1231   AssertDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
1232 
1233   // Don't bother verifying the compilation directory or producer string
1234   // as those could be empty.
1235   AssertDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
1236            N.getRawFile());
1237   AssertDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
1238            N.getFile());
1239 
1240   CurrentSourceLang = (dwarf::SourceLanguage)N.getSourceLanguage();
1241 
1242   verifySourceDebugInfo(N, *N.getFile());
1243 
1244   AssertDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
1245            "invalid emission kind", &N);
1246 
1247   if (auto *Array = N.getRawEnumTypes()) {
1248     AssertDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
1249     for (Metadata *Op : N.getEnumTypes()->operands()) {
1250       auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
1251       AssertDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1252                "invalid enum type", &N, N.getEnumTypes(), Op);
1253     }
1254   }
1255   if (auto *Array = N.getRawRetainedTypes()) {
1256     AssertDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
1257     for (Metadata *Op : N.getRetainedTypes()->operands()) {
1258       AssertDI(Op && (isa<DIType>(Op) ||
1259                       (isa<DISubprogram>(Op) &&
1260                        !cast<DISubprogram>(Op)->isDefinition())),
1261                "invalid retained type", &N, Op);
1262     }
1263   }
1264   if (auto *Array = N.getRawGlobalVariables()) {
1265     AssertDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
1266     for (Metadata *Op : N.getGlobalVariables()->operands()) {
1267       AssertDI(Op && (isa<DIGlobalVariableExpression>(Op)),
1268                "invalid global variable ref", &N, Op);
1269     }
1270   }
1271   if (auto *Array = N.getRawImportedEntities()) {
1272     AssertDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
1273     for (Metadata *Op : N.getImportedEntities()->operands()) {
1274       AssertDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
1275                &N, Op);
1276     }
1277   }
1278   if (auto *Array = N.getRawMacros()) {
1279     AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1280     for (Metadata *Op : N.getMacros()->operands()) {
1281       AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1282     }
1283   }
1284   CUVisited.insert(&N);
1285 }
1286 
1287 void Verifier::visitDISubprogram(const DISubprogram &N) {
1288   AssertDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
1289   AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1290   if (auto *F = N.getRawFile())
1291     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
1292   else
1293     AssertDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
1294   if (auto *T = N.getRawType())
1295     AssertDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
1296   AssertDI(isType(N.getRawContainingType()), "invalid containing type", &N,
1297            N.getRawContainingType());
1298   if (auto *Params = N.getRawTemplateParams())
1299     visitTemplateParams(N, *Params);
1300   if (auto *S = N.getRawDeclaration())
1301     AssertDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
1302              "invalid subprogram declaration", &N, S);
1303   if (auto *RawNode = N.getRawRetainedNodes()) {
1304     auto *Node = dyn_cast<MDTuple>(RawNode);
1305     AssertDI(Node, "invalid retained nodes list", &N, RawNode);
1306     for (Metadata *Op : Node->operands()) {
1307       AssertDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op)),
1308                "invalid retained nodes, expected DILocalVariable or DILabel",
1309                &N, Node, Op);
1310     }
1311   }
1312   AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
1313            "invalid reference flags", &N);
1314 
1315   auto *Unit = N.getRawUnit();
1316   if (N.isDefinition()) {
1317     // Subprogram definitions (not part of the type hierarchy).
1318     AssertDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
1319     AssertDI(Unit, "subprogram definitions must have a compile unit", &N);
1320     AssertDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
1321     if (N.getFile())
1322       verifySourceDebugInfo(*N.getUnit(), *N.getFile());
1323   } else {
1324     // Subprogram declarations (part of the type hierarchy).
1325     AssertDI(!Unit, "subprogram declarations must not have a compile unit", &N);
1326   }
1327 
1328   if (auto *RawThrownTypes = N.getRawThrownTypes()) {
1329     auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
1330     AssertDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
1331     for (Metadata *Op : ThrownTypes->operands())
1332       AssertDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
1333                Op);
1334   }
1335 
1336   if (N.areAllCallsDescribed())
1337     AssertDI(N.isDefinition(),
1338              "DIFlagAllCallsDescribed must be attached to a definition");
1339 }
1340 
1341 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
1342   AssertDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
1343   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1344            "invalid local scope", &N, N.getRawScope());
1345   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
1346     AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
1347 }
1348 
1349 void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
1350   visitDILexicalBlockBase(N);
1351 
1352   AssertDI(N.getLine() || !N.getColumn(),
1353            "cannot have column info without line info", &N);
1354 }
1355 
1356 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
1357   visitDILexicalBlockBase(N);
1358 }
1359 
1360 void Verifier::visitDICommonBlock(const DICommonBlock &N) {
1361   AssertDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
1362   if (auto *S = N.getRawScope())
1363     AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1364   if (auto *S = N.getRawDecl())
1365     AssertDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
1366 }
1367 
1368 void Verifier::visitDINamespace(const DINamespace &N) {
1369   AssertDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
1370   if (auto *S = N.getRawScope())
1371     AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1372 }
1373 
1374 void Verifier::visitDIMacro(const DIMacro &N) {
1375   AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
1376                N.getMacinfoType() == dwarf::DW_MACINFO_undef,
1377            "invalid macinfo type", &N);
1378   AssertDI(!N.getName().empty(), "anonymous macro", &N);
1379   if (!N.getValue().empty()) {
1380     assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
1381   }
1382 }
1383 
1384 void Verifier::visitDIMacroFile(const DIMacroFile &N) {
1385   AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
1386            "invalid macinfo type", &N);
1387   if (auto *F = N.getRawFile())
1388     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
1389 
1390   if (auto *Array = N.getRawElements()) {
1391     AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1392     for (Metadata *Op : N.getElements()->operands()) {
1393       AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1394     }
1395   }
1396 }
1397 
1398 void Verifier::visitDIArgList(const DIArgList &N) {
1399   AssertDI(!N.getNumOperands(),
1400            "DIArgList should have no operands other than a list of "
1401            "ValueAsMetadata",
1402            &N);
1403 }
1404 
1405 void Verifier::visitDIModule(const DIModule &N) {
1406   AssertDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
1407   AssertDI(!N.getName().empty(), "anonymous module", &N);
1408 }
1409 
1410 void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
1411   AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1412 }
1413 
1414 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1415   visitDITemplateParameter(N);
1416 
1417   AssertDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1418            &N);
1419 }
1420 
1421 void Verifier::visitDITemplateValueParameter(
1422     const DITemplateValueParameter &N) {
1423   visitDITemplateParameter(N);
1424 
1425   AssertDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1426                N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1427                N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1428            "invalid tag", &N);
1429 }
1430 
1431 void Verifier::visitDIVariable(const DIVariable &N) {
1432   if (auto *S = N.getRawScope())
1433     AssertDI(isa<DIScope>(S), "invalid scope", &N, S);
1434   if (auto *F = N.getRawFile())
1435     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
1436 }
1437 
1438 void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1439   // Checks common to all variables.
1440   visitDIVariable(N);
1441 
1442   AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1443   AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1444   // Assert only if the global variable is not an extern
1445   if (N.isDefinition())
1446     AssertDI(N.getType(), "missing global variable type", &N);
1447   if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1448     AssertDI(isa<DIDerivedType>(Member),
1449              "invalid static data member declaration", &N, Member);
1450   }
1451 }
1452 
1453 void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1454   // Checks common to all variables.
1455   visitDIVariable(N);
1456 
1457   AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1458   AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1459   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1460            "local variable requires a valid scope", &N, N.getRawScope());
1461   if (auto Ty = N.getType())
1462     AssertDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
1463 }
1464 
1465 void Verifier::visitDILabel(const DILabel &N) {
1466   if (auto *S = N.getRawScope())
1467     AssertDI(isa<DIScope>(S), "invalid scope", &N, S);
1468   if (auto *F = N.getRawFile())
1469     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
1470 
1471   AssertDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
1472   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1473            "label requires a valid scope", &N, N.getRawScope());
1474 }
1475 
1476 void Verifier::visitDIExpression(const DIExpression &N) {
1477   AssertDI(N.isValid(), "invalid expression", &N);
1478 }
1479 
1480 void Verifier::visitDIGlobalVariableExpression(
1481     const DIGlobalVariableExpression &GVE) {
1482   AssertDI(GVE.getVariable(), "missing variable");
1483   if (auto *Var = GVE.getVariable())
1484     visitDIGlobalVariable(*Var);
1485   if (auto *Expr = GVE.getExpression()) {
1486     visitDIExpression(*Expr);
1487     if (auto Fragment = Expr->getFragmentInfo())
1488       verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
1489   }
1490 }
1491 
1492 void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1493   AssertDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1494   if (auto *T = N.getRawType())
1495     AssertDI(isType(T), "invalid type ref", &N, T);
1496   if (auto *F = N.getRawFile())
1497     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
1498 }
1499 
1500 void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
1501   AssertDI(N.getTag() == dwarf::DW_TAG_imported_module ||
1502                N.getTag() == dwarf::DW_TAG_imported_declaration,
1503            "invalid tag", &N);
1504   if (auto *S = N.getRawScope())
1505     AssertDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1506   AssertDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
1507            N.getRawEntity());
1508 }
1509 
1510 void Verifier::visitComdat(const Comdat &C) {
1511   // In COFF the Module is invalid if the GlobalValue has private linkage.
1512   // Entities with private linkage don't have entries in the symbol table.
1513   if (TT.isOSBinFormatCOFF())
1514     if (const GlobalValue *GV = M.getNamedValue(C.getName()))
1515       Assert(!GV->hasPrivateLinkage(),
1516              "comdat global value has private linkage", GV);
1517 }
1518 
1519 void Verifier::visitModuleIdents() {
1520   const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1521   if (!Idents)
1522     return;
1523 
1524   // llvm.ident takes a list of metadata entry. Each entry has only one string.
1525   // Scan each llvm.ident entry and make sure that this requirement is met.
1526   for (const MDNode *N : Idents->operands()) {
1527     Assert(N->getNumOperands() == 1,
1528            "incorrect number of operands in llvm.ident metadata", N);
1529     Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1530            ("invalid value for llvm.ident metadata entry operand"
1531             "(the operand should be a string)"),
1532            N->getOperand(0));
1533   }
1534 }
1535 
1536 void Verifier::visitModuleCommandLines() {
1537   const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
1538   if (!CommandLines)
1539     return;
1540 
1541   // llvm.commandline takes a list of metadata entry. Each entry has only one
1542   // string. Scan each llvm.commandline entry and make sure that this
1543   // requirement is met.
1544   for (const MDNode *N : CommandLines->operands()) {
1545     Assert(N->getNumOperands() == 1,
1546            "incorrect number of operands in llvm.commandline metadata", N);
1547     Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1548            ("invalid value for llvm.commandline metadata entry operand"
1549             "(the operand should be a string)"),
1550            N->getOperand(0));
1551   }
1552 }
1553 
1554 void Verifier::visitModuleFlags() {
1555   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1556   if (!Flags) return;
1557 
1558   // Scan each flag, and track the flags and requirements.
1559   DenseMap<const MDString*, const MDNode*> SeenIDs;
1560   SmallVector<const MDNode*, 16> Requirements;
1561   for (const MDNode *MDN : Flags->operands())
1562     visitModuleFlag(MDN, SeenIDs, Requirements);
1563 
1564   // Validate that the requirements in the module are valid.
1565   for (const MDNode *Requirement : Requirements) {
1566     const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1567     const Metadata *ReqValue = Requirement->getOperand(1);
1568 
1569     const MDNode *Op = SeenIDs.lookup(Flag);
1570     if (!Op) {
1571       CheckFailed("invalid requirement on flag, flag is not present in module",
1572                   Flag);
1573       continue;
1574     }
1575 
1576     if (Op->getOperand(2) != ReqValue) {
1577       CheckFailed(("invalid requirement on flag, "
1578                    "flag does not have the required value"),
1579                   Flag);
1580       continue;
1581     }
1582   }
1583 }
1584 
1585 void
1586 Verifier::visitModuleFlag(const MDNode *Op,
1587                           DenseMap<const MDString *, const MDNode *> &SeenIDs,
1588                           SmallVectorImpl<const MDNode *> &Requirements) {
1589   // Each module flag should have three arguments, the merge behavior (a
1590   // constant int), the flag ID (an MDString), and the value.
1591   Assert(Op->getNumOperands() == 3,
1592          "incorrect number of operands in module flag", Op);
1593   Module::ModFlagBehavior MFB;
1594   if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1595     Assert(
1596         mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1597         "invalid behavior operand in module flag (expected constant integer)",
1598         Op->getOperand(0));
1599     Assert(false,
1600            "invalid behavior operand in module flag (unexpected constant)",
1601            Op->getOperand(0));
1602   }
1603   MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1604   Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1605          Op->getOperand(1));
1606 
1607   // Check the values for behaviors with additional requirements.
1608   switch (MFB) {
1609   case Module::Error:
1610   case Module::Warning:
1611   case Module::Override:
1612     // These behavior types accept any value.
1613     break;
1614 
1615   case Module::Max: {
1616     Assert(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)),
1617            "invalid value for 'max' module flag (expected constant integer)",
1618            Op->getOperand(2));
1619     break;
1620   }
1621 
1622   case Module::Require: {
1623     // The value should itself be an MDNode with two operands, a flag ID (an
1624     // MDString), and a value.
1625     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1626     Assert(Value && Value->getNumOperands() == 2,
1627            "invalid value for 'require' module flag (expected metadata pair)",
1628            Op->getOperand(2));
1629     Assert(isa<MDString>(Value->getOperand(0)),
1630            ("invalid value for 'require' module flag "
1631             "(first value operand should be a string)"),
1632            Value->getOperand(0));
1633 
1634     // Append it to the list of requirements, to check once all module flags are
1635     // scanned.
1636     Requirements.push_back(Value);
1637     break;
1638   }
1639 
1640   case Module::Append:
1641   case Module::AppendUnique: {
1642     // These behavior types require the operand be an MDNode.
1643     Assert(isa<MDNode>(Op->getOperand(2)),
1644            "invalid value for 'append'-type module flag "
1645            "(expected a metadata node)",
1646            Op->getOperand(2));
1647     break;
1648   }
1649   }
1650 
1651   // Unless this is a "requires" flag, check the ID is unique.
1652   if (MFB != Module::Require) {
1653     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1654     Assert(Inserted,
1655            "module flag identifiers must be unique (or of 'require' type)", ID);
1656   }
1657 
1658   if (ID->getString() == "wchar_size") {
1659     ConstantInt *Value
1660       = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1661     Assert(Value, "wchar_size metadata requires constant integer argument");
1662   }
1663 
1664   if (ID->getString() == "Linker Options") {
1665     // If the llvm.linker.options named metadata exists, we assume that the
1666     // bitcode reader has upgraded the module flag. Otherwise the flag might
1667     // have been created by a client directly.
1668     Assert(M.getNamedMetadata("llvm.linker.options"),
1669            "'Linker Options' named metadata no longer supported");
1670   }
1671 
1672   if (ID->getString() == "SemanticInterposition") {
1673     ConstantInt *Value =
1674         mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1675     Assert(Value,
1676            "SemanticInterposition metadata requires constant integer argument");
1677   }
1678 
1679   if (ID->getString() == "CG Profile") {
1680     for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
1681       visitModuleFlagCGProfileEntry(MDO);
1682   }
1683 }
1684 
1685 void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
1686   auto CheckFunction = [&](const MDOperand &FuncMDO) {
1687     if (!FuncMDO)
1688       return;
1689     auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
1690     Assert(F && isa<Function>(F->getValue()->stripPointerCasts()),
1691            "expected a Function or null", FuncMDO);
1692   };
1693   auto Node = dyn_cast_or_null<MDNode>(MDO);
1694   Assert(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
1695   CheckFunction(Node->getOperand(0));
1696   CheckFunction(Node->getOperand(1));
1697   auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
1698   Assert(Count && Count->getType()->isIntegerTy(),
1699          "expected an integer constant", Node->getOperand(2));
1700 }
1701 
1702 void Verifier::verifyAttributeTypes(AttributeSet Attrs, const Value *V) {
1703   for (Attribute A : Attrs) {
1704 
1705     if (A.isStringAttribute()) {
1706 #define GET_ATTR_NAMES
1707 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1708 #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME)                             \
1709   if (A.getKindAsString() == #DISPLAY_NAME) {                                  \
1710     auto V = A.getValueAsString();                                             \
1711     if (!(V.empty() || V == "true" || V == "false"))                           \
1712       CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V +    \
1713                   "");                                                         \
1714   }
1715 
1716 #include "llvm/IR/Attributes.inc"
1717       continue;
1718     }
1719 
1720     if (A.isIntAttribute() != Attribute::isIntAttrKind(A.getKindAsEnum())) {
1721       CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument",
1722                   V);
1723       return;
1724     }
1725   }
1726 }
1727 
1728 // VerifyParameterAttrs - Check the given attributes for an argument or return
1729 // value of the specified type.  The value V is printed in error messages.
1730 void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
1731                                     const Value *V) {
1732   if (!Attrs.hasAttributes())
1733     return;
1734 
1735   verifyAttributeTypes(Attrs, V);
1736 
1737   for (Attribute Attr : Attrs)
1738     Assert(Attr.isStringAttribute() ||
1739            Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
1740            "Attribute '" + Attr.getAsString() +
1741                "' does not apply to parameters",
1742            V);
1743 
1744   if (Attrs.hasAttribute(Attribute::ImmArg)) {
1745     Assert(Attrs.getNumAttributes() == 1,
1746            "Attribute 'immarg' is incompatible with other attributes", V);
1747   }
1748 
1749   // Check for mutually incompatible attributes.  Only inreg is compatible with
1750   // sret.
1751   unsigned AttrCount = 0;
1752   AttrCount += Attrs.hasAttribute(Attribute::ByVal);
1753   AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
1754   AttrCount += Attrs.hasAttribute(Attribute::Preallocated);
1755   AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
1756                Attrs.hasAttribute(Attribute::InReg);
1757   AttrCount += Attrs.hasAttribute(Attribute::Nest);
1758   AttrCount += Attrs.hasAttribute(Attribute::ByRef);
1759   Assert(AttrCount <= 1,
1760          "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
1761          "'byref', and 'sret' are incompatible!",
1762          V);
1763 
1764   Assert(!(Attrs.hasAttribute(Attribute::InAlloca) &&
1765            Attrs.hasAttribute(Attribute::ReadOnly)),
1766          "Attributes "
1767          "'inalloca and readonly' are incompatible!",
1768          V);
1769 
1770   Assert(!(Attrs.hasAttribute(Attribute::StructRet) &&
1771            Attrs.hasAttribute(Attribute::Returned)),
1772          "Attributes "
1773          "'sret and returned' are incompatible!",
1774          V);
1775 
1776   Assert(!(Attrs.hasAttribute(Attribute::ZExt) &&
1777            Attrs.hasAttribute(Attribute::SExt)),
1778          "Attributes "
1779          "'zeroext and signext' are incompatible!",
1780          V);
1781 
1782   Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&
1783            Attrs.hasAttribute(Attribute::ReadOnly)),
1784          "Attributes "
1785          "'readnone and readonly' are incompatible!",
1786          V);
1787 
1788   Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&
1789            Attrs.hasAttribute(Attribute::WriteOnly)),
1790          "Attributes "
1791          "'readnone and writeonly' are incompatible!",
1792          V);
1793 
1794   Assert(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
1795            Attrs.hasAttribute(Attribute::WriteOnly)),
1796          "Attributes "
1797          "'readonly and writeonly' are incompatible!",
1798          V);
1799 
1800   Assert(!(Attrs.hasAttribute(Attribute::NoInline) &&
1801            Attrs.hasAttribute(Attribute::AlwaysInline)),
1802          "Attributes "
1803          "'noinline and alwaysinline' are incompatible!",
1804          V);
1805 
1806   AttrBuilder IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty);
1807   for (Attribute Attr : Attrs) {
1808     if (!Attr.isStringAttribute() &&
1809         IncompatibleAttrs.contains(Attr.getKindAsEnum())) {
1810       CheckFailed("Attribute '" + Attr.getAsString() +
1811                   "' applied to incompatible type!", V);
1812       return;
1813     }
1814   }
1815 
1816   if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1817     if (Attrs.hasAttribute(Attribute::ByVal)) {
1818       SmallPtrSet<Type *, 4> Visited;
1819       Assert(Attrs.getByValType()->isSized(&Visited),
1820              "Attribute 'byval' does not support unsized types!", V);
1821     }
1822     if (Attrs.hasAttribute(Attribute::ByRef)) {
1823       SmallPtrSet<Type *, 4> Visited;
1824       Assert(Attrs.getByRefType()->isSized(&Visited),
1825              "Attribute 'byref' does not support unsized types!", V);
1826     }
1827     if (Attrs.hasAttribute(Attribute::InAlloca)) {
1828       SmallPtrSet<Type *, 4> Visited;
1829       Assert(Attrs.getInAllocaType()->isSized(&Visited),
1830              "Attribute 'inalloca' does not support unsized types!", V);
1831     }
1832     if (Attrs.hasAttribute(Attribute::Preallocated)) {
1833       SmallPtrSet<Type *, 4> Visited;
1834       Assert(Attrs.getPreallocatedType()->isSized(&Visited),
1835              "Attribute 'preallocated' does not support unsized types!", V);
1836     }
1837     if (!PTy->isOpaque()) {
1838       if (!isa<PointerType>(PTy->getElementType()))
1839         Assert(!Attrs.hasAttribute(Attribute::SwiftError),
1840                "Attribute 'swifterror' only applies to parameters "
1841                "with pointer to pointer type!",
1842                V);
1843       if (Attrs.hasAttribute(Attribute::ByRef)) {
1844         Assert(Attrs.getByRefType() == PTy->getElementType(),
1845                "Attribute 'byref' type does not match parameter!", V);
1846       }
1847 
1848       if (Attrs.hasAttribute(Attribute::ByVal) && Attrs.getByValType()) {
1849         Assert(Attrs.getByValType() == PTy->getElementType(),
1850                "Attribute 'byval' type does not match parameter!", V);
1851       }
1852 
1853       if (Attrs.hasAttribute(Attribute::Preallocated)) {
1854         Assert(Attrs.getPreallocatedType() == PTy->getElementType(),
1855                "Attribute 'preallocated' type does not match parameter!", V);
1856       }
1857 
1858       if (Attrs.hasAttribute(Attribute::InAlloca)) {
1859         Assert(Attrs.getInAllocaType() == PTy->getElementType(),
1860                "Attribute 'inalloca' type does not match parameter!", V);
1861       }
1862 
1863       if (Attrs.hasAttribute(Attribute::ElementType)) {
1864         Assert(Attrs.getElementType() == PTy->getElementType(),
1865                "Attribute 'elementtype' type does not match parameter!", V);
1866       }
1867     }
1868   }
1869 }
1870 
1871 void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
1872                                             const Value *V) {
1873   if (Attrs.hasFnAttr(Attr)) {
1874     StringRef S = Attrs.getFnAttr(Attr).getValueAsString();
1875     unsigned N;
1876     if (S.getAsInteger(10, N))
1877       CheckFailed("\"" + Attr + "\" takes an unsigned integer: " + S, V);
1878   }
1879 }
1880 
1881 // Check parameter attributes against a function type.
1882 // The value V is printed in error messages.
1883 void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
1884                                    const Value *V, bool IsIntrinsic) {
1885   if (Attrs.isEmpty())
1886     return;
1887 
1888   if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) {
1889     Assert(Attrs.hasParentContext(Context),
1890            "Attribute list does not match Module context!", &Attrs, V);
1891     for (const auto &AttrSet : Attrs) {
1892       Assert(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
1893              "Attribute set does not match Module context!", &AttrSet, V);
1894       for (const auto &A : AttrSet) {
1895         Assert(A.hasParentContext(Context),
1896                "Attribute does not match Module context!", &A, V);
1897       }
1898     }
1899   }
1900 
1901   bool SawNest = false;
1902   bool SawReturned = false;
1903   bool SawSRet = false;
1904   bool SawSwiftSelf = false;
1905   bool SawSwiftAsync = false;
1906   bool SawSwiftError = false;
1907 
1908   // Verify return value attributes.
1909   AttributeSet RetAttrs = Attrs.getRetAttrs();
1910   for (Attribute RetAttr : RetAttrs)
1911     Assert(RetAttr.isStringAttribute() ||
1912            Attribute::canUseAsRetAttr(RetAttr.getKindAsEnum()),
1913            "Attribute '" + RetAttr.getAsString() +
1914                "' does not apply to function return values",
1915            V);
1916 
1917   verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
1918 
1919   // Verify parameter attributes.
1920   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1921     Type *Ty = FT->getParamType(i);
1922     AttributeSet ArgAttrs = Attrs.getParamAttrs(i);
1923 
1924     if (!IsIntrinsic) {
1925       Assert(!ArgAttrs.hasAttribute(Attribute::ImmArg),
1926              "immarg attribute only applies to intrinsics",V);
1927       Assert(!ArgAttrs.hasAttribute(Attribute::ElementType),
1928              "Attribute 'elementtype' can only be applied to intrinsics.", V);
1929     }
1930 
1931     verifyParameterAttrs(ArgAttrs, Ty, V);
1932 
1933     if (ArgAttrs.hasAttribute(Attribute::Nest)) {
1934       Assert(!SawNest, "More than one parameter has attribute nest!", V);
1935       SawNest = true;
1936     }
1937 
1938     if (ArgAttrs.hasAttribute(Attribute::Returned)) {
1939       Assert(!SawReturned, "More than one parameter has attribute returned!",
1940              V);
1941       Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1942              "Incompatible argument and return types for 'returned' attribute",
1943              V);
1944       SawReturned = true;
1945     }
1946 
1947     if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
1948       Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1949       Assert(i == 0 || i == 1,
1950              "Attribute 'sret' is not on first or second parameter!", V);
1951       SawSRet = true;
1952     }
1953 
1954     if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
1955       Assert(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
1956       SawSwiftSelf = true;
1957     }
1958 
1959     if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) {
1960       Assert(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V);
1961       SawSwiftAsync = true;
1962     }
1963 
1964     if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
1965       Assert(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!",
1966              V);
1967       SawSwiftError = true;
1968     }
1969 
1970     if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
1971       Assert(i == FT->getNumParams() - 1,
1972              "inalloca isn't on the last parameter!", V);
1973     }
1974   }
1975 
1976   if (!Attrs.hasFnAttrs())
1977     return;
1978 
1979   verifyAttributeTypes(Attrs.getFnAttrs(), V);
1980   for (Attribute FnAttr : Attrs.getFnAttrs())
1981     Assert(FnAttr.isStringAttribute() ||
1982            Attribute::canUseAsFnAttr(FnAttr.getKindAsEnum()),
1983            "Attribute '" + FnAttr.getAsString() +
1984                "' does not apply to functions!",
1985            V);
1986 
1987   Assert(!(Attrs.hasFnAttr(Attribute::ReadNone) &&
1988            Attrs.hasFnAttr(Attribute::ReadOnly)),
1989          "Attributes 'readnone and readonly' are incompatible!", V);
1990 
1991   Assert(!(Attrs.hasFnAttr(Attribute::ReadNone) &&
1992            Attrs.hasFnAttr(Attribute::WriteOnly)),
1993          "Attributes 'readnone and writeonly' are incompatible!", V);
1994 
1995   Assert(!(Attrs.hasFnAttr(Attribute::ReadOnly) &&
1996            Attrs.hasFnAttr(Attribute::WriteOnly)),
1997          "Attributes 'readonly and writeonly' are incompatible!", V);
1998 
1999   Assert(!(Attrs.hasFnAttr(Attribute::ReadNone) &&
2000            Attrs.hasFnAttr(Attribute::InaccessibleMemOrArgMemOnly)),
2001          "Attributes 'readnone and inaccessiblemem_or_argmemonly' are "
2002          "incompatible!",
2003          V);
2004 
2005   Assert(!(Attrs.hasFnAttr(Attribute::ReadNone) &&
2006            Attrs.hasFnAttr(Attribute::InaccessibleMemOnly)),
2007          "Attributes 'readnone and inaccessiblememonly' are incompatible!", V);
2008 
2009   Assert(!(Attrs.hasFnAttr(Attribute::NoInline) &&
2010            Attrs.hasFnAttr(Attribute::AlwaysInline)),
2011          "Attributes 'noinline and alwaysinline' are incompatible!", V);
2012 
2013   if (Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2014     Assert(Attrs.hasFnAttr(Attribute::NoInline),
2015            "Attribute 'optnone' requires 'noinline'!", V);
2016 
2017     Assert(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
2018            "Attributes 'optsize and optnone' are incompatible!", V);
2019 
2020     Assert(!Attrs.hasFnAttr(Attribute::MinSize),
2021            "Attributes 'minsize and optnone' are incompatible!", V);
2022   }
2023 
2024   if (Attrs.hasFnAttr(Attribute::JumpTable)) {
2025     const GlobalValue *GV = cast<GlobalValue>(V);
2026     Assert(GV->hasGlobalUnnamedAddr(),
2027            "Attribute 'jumptable' requires 'unnamed_addr'", V);
2028   }
2029 
2030   if (Attrs.hasFnAttr(Attribute::AllocSize)) {
2031     std::pair<unsigned, Optional<unsigned>> Args =
2032         Attrs.getFnAttrs().getAllocSizeArgs();
2033 
2034     auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
2035       if (ParamNo >= FT->getNumParams()) {
2036         CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
2037         return false;
2038       }
2039 
2040       if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2041         CheckFailed("'allocsize' " + Name +
2042                         " argument must refer to an integer parameter",
2043                     V);
2044         return false;
2045       }
2046 
2047       return true;
2048     };
2049 
2050     if (!CheckParam("element size", Args.first))
2051       return;
2052 
2053     if (Args.second && !CheckParam("number of elements", *Args.second))
2054       return;
2055   }
2056 
2057   if (Attrs.hasFnAttr(Attribute::VScaleRange)) {
2058     unsigned VScaleMin = Attrs.getFnAttrs().getVScaleRangeMin();
2059     if (VScaleMin == 0)
2060       CheckFailed("'vscale_range' minimum must be greater than 0", V);
2061 
2062     Optional<unsigned> VScaleMax = Attrs.getFnAttrs().getVScaleRangeMax();
2063     if (VScaleMax && VScaleMin > VScaleMax)
2064       CheckFailed("'vscale_range' minimum cannot be greater than maximum", V);
2065   }
2066 
2067   if (Attrs.hasFnAttr("frame-pointer")) {
2068     StringRef FP = Attrs.getFnAttr("frame-pointer").getValueAsString();
2069     if (FP != "all" && FP != "non-leaf" && FP != "none")
2070       CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
2071   }
2072 
2073   checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V);
2074   checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V);
2075   checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V);
2076 }
2077 
2078 void Verifier::verifyFunctionMetadata(
2079     ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2080   for (const auto &Pair : MDs) {
2081     if (Pair.first == LLVMContext::MD_prof) {
2082       MDNode *MD = Pair.second;
2083       Assert(MD->getNumOperands() >= 2,
2084              "!prof annotations should have no less than 2 operands", MD);
2085 
2086       // Check first operand.
2087       Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
2088              MD);
2089       Assert(isa<MDString>(MD->getOperand(0)),
2090              "expected string with name of the !prof annotation", MD);
2091       MDString *MDS = cast<MDString>(MD->getOperand(0));
2092       StringRef ProfName = MDS->getString();
2093       Assert(ProfName.equals("function_entry_count") ||
2094                  ProfName.equals("synthetic_function_entry_count"),
2095              "first operand should be 'function_entry_count'"
2096              " or 'synthetic_function_entry_count'",
2097              MD);
2098 
2099       // Check second operand.
2100       Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
2101              MD);
2102       Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
2103              "expected integer argument to function_entry_count", MD);
2104     }
2105   }
2106 }
2107 
2108 void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
2109   if (!ConstantExprVisited.insert(EntryC).second)
2110     return;
2111 
2112   SmallVector<const Constant *, 16> Stack;
2113   Stack.push_back(EntryC);
2114 
2115   while (!Stack.empty()) {
2116     const Constant *C = Stack.pop_back_val();
2117 
2118     // Check this constant expression.
2119     if (const auto *CE = dyn_cast<ConstantExpr>(C))
2120       visitConstantExpr(CE);
2121 
2122     if (const auto *GV = dyn_cast<GlobalValue>(C)) {
2123       // Global Values get visited separately, but we do need to make sure
2124       // that the global value is in the correct module
2125       Assert(GV->getParent() == &M, "Referencing global in another module!",
2126              EntryC, &M, GV, GV->getParent());
2127       continue;
2128     }
2129 
2130     // Visit all sub-expressions.
2131     for (const Use &U : C->operands()) {
2132       const auto *OpC = dyn_cast<Constant>(U);
2133       if (!OpC)
2134         continue;
2135       if (!ConstantExprVisited.insert(OpC).second)
2136         continue;
2137       Stack.push_back(OpC);
2138     }
2139   }
2140 }
2141 
2142 void Verifier::visitConstantExpr(const ConstantExpr *CE) {
2143   if (CE->getOpcode() == Instruction::BitCast)
2144     Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
2145                                  CE->getType()),
2146            "Invalid bitcast", CE);
2147 }
2148 
2149 bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
2150   // There shouldn't be more attribute sets than there are parameters plus the
2151   // function and return value.
2152   return Attrs.getNumAttrSets() <= Params + 2;
2153 }
2154 
2155 /// Verify that statepoint intrinsic is well formed.
2156 void Verifier::verifyStatepoint(const CallBase &Call) {
2157   assert(Call.getCalledFunction() &&
2158          Call.getCalledFunction()->getIntrinsicID() ==
2159              Intrinsic::experimental_gc_statepoint);
2160 
2161   Assert(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() &&
2162              !Call.onlyAccessesArgMemory(),
2163          "gc.statepoint must read and write all memory to preserve "
2164          "reordering restrictions required by safepoint semantics",
2165          Call);
2166 
2167   const int64_t NumPatchBytes =
2168       cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
2169   assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
2170   Assert(NumPatchBytes >= 0,
2171          "gc.statepoint number of patchable bytes must be "
2172          "positive",
2173          Call);
2174 
2175   const Value *Target = Call.getArgOperand(2);
2176   auto *PT = dyn_cast<PointerType>(Target->getType());
2177   Assert(PT && PT->getElementType()->isFunctionTy(),
2178          "gc.statepoint callee must be of function pointer type", Call, Target);
2179   FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
2180 
2181   const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
2182   Assert(NumCallArgs >= 0,
2183          "gc.statepoint number of arguments to underlying call "
2184          "must be positive",
2185          Call);
2186   const int NumParams = (int)TargetFuncType->getNumParams();
2187   if (TargetFuncType->isVarArg()) {
2188     Assert(NumCallArgs >= NumParams,
2189            "gc.statepoint mismatch in number of vararg call args", Call);
2190 
2191     // TODO: Remove this limitation
2192     Assert(TargetFuncType->getReturnType()->isVoidTy(),
2193            "gc.statepoint doesn't support wrapping non-void "
2194            "vararg functions yet",
2195            Call);
2196   } else
2197     Assert(NumCallArgs == NumParams,
2198            "gc.statepoint mismatch in number of call args", Call);
2199 
2200   const uint64_t Flags
2201     = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
2202   Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
2203          "unknown flag used in gc.statepoint flags argument", Call);
2204 
2205   // Verify that the types of the call parameter arguments match
2206   // the type of the wrapped callee.
2207   AttributeList Attrs = Call.getAttributes();
2208   for (int i = 0; i < NumParams; i++) {
2209     Type *ParamType = TargetFuncType->getParamType(i);
2210     Type *ArgType = Call.getArgOperand(5 + i)->getType();
2211     Assert(ArgType == ParamType,
2212            "gc.statepoint call argument does not match wrapped "
2213            "function type",
2214            Call);
2215 
2216     if (TargetFuncType->isVarArg()) {
2217       AttributeSet ArgAttrs = Attrs.getParamAttrs(5 + i);
2218       Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
2219              "Attribute 'sret' cannot be used for vararg call arguments!",
2220              Call);
2221     }
2222   }
2223 
2224   const int EndCallArgsInx = 4 + NumCallArgs;
2225 
2226   const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
2227   Assert(isa<ConstantInt>(NumTransitionArgsV),
2228          "gc.statepoint number of transition arguments "
2229          "must be constant integer",
2230          Call);
2231   const int NumTransitionArgs =
2232       cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
2233   Assert(NumTransitionArgs == 0,
2234          "gc.statepoint w/inline transition bundle is deprecated", Call);
2235   const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2236 
2237   const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
2238   Assert(isa<ConstantInt>(NumDeoptArgsV),
2239          "gc.statepoint number of deoptimization arguments "
2240          "must be constant integer",
2241          Call);
2242   const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
2243   Assert(NumDeoptArgs == 0,
2244          "gc.statepoint w/inline deopt operands is deprecated", Call);
2245 
2246   const int ExpectedNumArgs = 7 + NumCallArgs;
2247   Assert(ExpectedNumArgs == (int)Call.arg_size(),
2248          "gc.statepoint too many arguments", Call);
2249 
2250   // Check that the only uses of this gc.statepoint are gc.result or
2251   // gc.relocate calls which are tied to this statepoint and thus part
2252   // of the same statepoint sequence
2253   for (const User *U : Call.users()) {
2254     const CallInst *UserCall = dyn_cast<const CallInst>(U);
2255     Assert(UserCall, "illegal use of statepoint token", Call, U);
2256     if (!UserCall)
2257       continue;
2258     Assert(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
2259            "gc.result or gc.relocate are the only value uses "
2260            "of a gc.statepoint",
2261            Call, U);
2262     if (isa<GCResultInst>(UserCall)) {
2263       Assert(UserCall->getArgOperand(0) == &Call,
2264              "gc.result connected to wrong gc.statepoint", Call, UserCall);
2265     } else if (isa<GCRelocateInst>(Call)) {
2266       Assert(UserCall->getArgOperand(0) == &Call,
2267              "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
2268     }
2269   }
2270 
2271   // Note: It is legal for a single derived pointer to be listed multiple
2272   // times.  It's non-optimal, but it is legal.  It can also happen after
2273   // insertion if we strip a bitcast away.
2274   // Note: It is really tempting to check that each base is relocated and
2275   // that a derived pointer is never reused as a base pointer.  This turns
2276   // out to be problematic since optimizations run after safepoint insertion
2277   // can recognize equality properties that the insertion logic doesn't know
2278   // about.  See example statepoint.ll in the verifier subdirectory
2279 }
2280 
2281 void Verifier::verifyFrameRecoverIndices() {
2282   for (auto &Counts : FrameEscapeInfo) {
2283     Function *F = Counts.first;
2284     unsigned EscapedObjectCount = Counts.second.first;
2285     unsigned MaxRecoveredIndex = Counts.second.second;
2286     Assert(MaxRecoveredIndex <= EscapedObjectCount,
2287            "all indices passed to llvm.localrecover must be less than the "
2288            "number of arguments passed to llvm.localescape in the parent "
2289            "function",
2290            F);
2291   }
2292 }
2293 
2294 static Instruction *getSuccPad(Instruction *Terminator) {
2295   BasicBlock *UnwindDest;
2296   if (auto *II = dyn_cast<InvokeInst>(Terminator))
2297     UnwindDest = II->getUnwindDest();
2298   else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
2299     UnwindDest = CSI->getUnwindDest();
2300   else
2301     UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
2302   return UnwindDest->getFirstNonPHI();
2303 }
2304 
2305 void Verifier::verifySiblingFuncletUnwinds() {
2306   SmallPtrSet<Instruction *, 8> Visited;
2307   SmallPtrSet<Instruction *, 8> Active;
2308   for (const auto &Pair : SiblingFuncletInfo) {
2309     Instruction *PredPad = Pair.first;
2310     if (Visited.count(PredPad))
2311       continue;
2312     Active.insert(PredPad);
2313     Instruction *Terminator = Pair.second;
2314     do {
2315       Instruction *SuccPad = getSuccPad(Terminator);
2316       if (Active.count(SuccPad)) {
2317         // Found a cycle; report error
2318         Instruction *CyclePad = SuccPad;
2319         SmallVector<Instruction *, 8> CycleNodes;
2320         do {
2321           CycleNodes.push_back(CyclePad);
2322           Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
2323           if (CycleTerminator != CyclePad)
2324             CycleNodes.push_back(CycleTerminator);
2325           CyclePad = getSuccPad(CycleTerminator);
2326         } while (CyclePad != SuccPad);
2327         Assert(false, "EH pads can't handle each other's exceptions",
2328                ArrayRef<Instruction *>(CycleNodes));
2329       }
2330       // Don't re-walk a node we've already checked
2331       if (!Visited.insert(SuccPad).second)
2332         break;
2333       // Walk to this successor if it has a map entry.
2334       PredPad = SuccPad;
2335       auto TermI = SiblingFuncletInfo.find(PredPad);
2336       if (TermI == SiblingFuncletInfo.end())
2337         break;
2338       Terminator = TermI->second;
2339       Active.insert(PredPad);
2340     } while (true);
2341     // Each node only has one successor, so we've walked all the active
2342     // nodes' successors.
2343     Active.clear();
2344   }
2345 }
2346 
2347 // visitFunction - Verify that a function is ok.
2348 //
2349 void Verifier::visitFunction(const Function &F) {
2350   visitGlobalValue(F);
2351 
2352   // Check function arguments.
2353   FunctionType *FT = F.getFunctionType();
2354   unsigned NumArgs = F.arg_size();
2355 
2356   Assert(&Context == &F.getContext(),
2357          "Function context does not match Module context!", &F);
2358 
2359   Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
2360   Assert(FT->getNumParams() == NumArgs,
2361          "# formal arguments must match # of arguments for function type!", &F,
2362          FT);
2363   Assert(F.getReturnType()->isFirstClassType() ||
2364              F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
2365          "Functions cannot return aggregate values!", &F);
2366 
2367   Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
2368          "Invalid struct return type!", &F);
2369 
2370   AttributeList Attrs = F.getAttributes();
2371 
2372   Assert(verifyAttributeCount(Attrs, FT->getNumParams()),
2373          "Attribute after last parameter!", &F);
2374 
2375   bool IsIntrinsic = F.isIntrinsic();
2376 
2377   // Check function attributes.
2378   verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic);
2379 
2380   // On function declarations/definitions, we do not support the builtin
2381   // attribute. We do not check this in VerifyFunctionAttrs since that is
2382   // checking for Attributes that can/can not ever be on functions.
2383   Assert(!Attrs.hasFnAttr(Attribute::Builtin),
2384          "Attribute 'builtin' can only be applied to a callsite.", &F);
2385 
2386   Assert(!Attrs.hasAttrSomewhere(Attribute::ElementType),
2387          "Attribute 'elementtype' can only be applied to a callsite.", &F);
2388 
2389   // Check that this function meets the restrictions on this calling convention.
2390   // Sometimes varargs is used for perfectly forwarding thunks, so some of these
2391   // restrictions can be lifted.
2392   switch (F.getCallingConv()) {
2393   default:
2394   case CallingConv::C:
2395     break;
2396   case CallingConv::X86_INTR: {
2397     Assert(F.arg_empty() || Attrs.hasParamAttr(0, Attribute::ByVal),
2398            "Calling convention parameter requires byval", &F);
2399     break;
2400   }
2401   case CallingConv::AMDGPU_KERNEL:
2402   case CallingConv::SPIR_KERNEL:
2403     Assert(F.getReturnType()->isVoidTy(),
2404            "Calling convention requires void return type", &F);
2405     LLVM_FALLTHROUGH;
2406   case CallingConv::AMDGPU_VS:
2407   case CallingConv::AMDGPU_HS:
2408   case CallingConv::AMDGPU_GS:
2409   case CallingConv::AMDGPU_PS:
2410   case CallingConv::AMDGPU_CS:
2411     Assert(!F.hasStructRetAttr(),
2412            "Calling convention does not allow sret", &F);
2413     if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2414       const unsigned StackAS = DL.getAllocaAddrSpace();
2415       unsigned i = 0;
2416       for (const Argument &Arg : F.args()) {
2417         Assert(!Attrs.hasParamAttr(i, Attribute::ByVal),
2418                "Calling convention disallows byval", &F);
2419         Assert(!Attrs.hasParamAttr(i, Attribute::Preallocated),
2420                "Calling convention disallows preallocated", &F);
2421         Assert(!Attrs.hasParamAttr(i, Attribute::InAlloca),
2422                "Calling convention disallows inalloca", &F);
2423 
2424         if (Attrs.hasParamAttr(i, Attribute::ByRef)) {
2425           // FIXME: Should also disallow LDS and GDS, but we don't have the enum
2426           // value here.
2427           Assert(Arg.getType()->getPointerAddressSpace() != StackAS,
2428                  "Calling convention disallows stack byref", &F);
2429         }
2430 
2431         ++i;
2432       }
2433     }
2434 
2435     LLVM_FALLTHROUGH;
2436   case CallingConv::Fast:
2437   case CallingConv::Cold:
2438   case CallingConv::Intel_OCL_BI:
2439   case CallingConv::PTX_Kernel:
2440   case CallingConv::PTX_Device:
2441     Assert(!F.isVarArg(), "Calling convention does not support varargs or "
2442                           "perfect forwarding!",
2443            &F);
2444     break;
2445   }
2446 
2447   // Check that the argument values match the function type for this function...
2448   unsigned i = 0;
2449   for (const Argument &Arg : F.args()) {
2450     Assert(Arg.getType() == FT->getParamType(i),
2451            "Argument value does not match function argument type!", &Arg,
2452            FT->getParamType(i));
2453     Assert(Arg.getType()->isFirstClassType(),
2454            "Function arguments must have first-class types!", &Arg);
2455     if (!IsIntrinsic) {
2456       Assert(!Arg.getType()->isMetadataTy(),
2457              "Function takes metadata but isn't an intrinsic", &Arg, &F);
2458       Assert(!Arg.getType()->isTokenTy(),
2459              "Function takes token but isn't an intrinsic", &Arg, &F);
2460       Assert(!Arg.getType()->isX86_AMXTy(),
2461              "Function takes x86_amx but isn't an intrinsic", &Arg, &F);
2462     }
2463 
2464     // Check that swifterror argument is only used by loads and stores.
2465     if (Attrs.hasParamAttr(i, Attribute::SwiftError)) {
2466       verifySwiftErrorValue(&Arg);
2467     }
2468     ++i;
2469   }
2470 
2471   if (!IsIntrinsic) {
2472     Assert(!F.getReturnType()->isTokenTy(),
2473            "Function returns a token but isn't an intrinsic", &F);
2474     Assert(!F.getReturnType()->isX86_AMXTy(),
2475            "Function returns a x86_amx but isn't an intrinsic", &F);
2476   }
2477 
2478   // Get the function metadata attachments.
2479   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2480   F.getAllMetadata(MDs);
2481   assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
2482   verifyFunctionMetadata(MDs);
2483 
2484   // Check validity of the personality function
2485   if (F.hasPersonalityFn()) {
2486     auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
2487     if (Per)
2488       Assert(Per->getParent() == F.getParent(),
2489              "Referencing personality function in another module!",
2490              &F, F.getParent(), Per, Per->getParent());
2491   }
2492 
2493   if (F.isMaterializable()) {
2494     // Function has a body somewhere we can't see.
2495     Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
2496            MDs.empty() ? nullptr : MDs.front().second);
2497   } else if (F.isDeclaration()) {
2498     for (const auto &I : MDs) {
2499       // This is used for call site debug information.
2500       AssertDI(I.first != LLVMContext::MD_dbg ||
2501                    !cast<DISubprogram>(I.second)->isDistinct(),
2502                "function declaration may only have a unique !dbg attachment",
2503                &F);
2504       Assert(I.first != LLVMContext::MD_prof,
2505              "function declaration may not have a !prof attachment", &F);
2506 
2507       // Verify the metadata itself.
2508       visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
2509     }
2510     Assert(!F.hasPersonalityFn(),
2511            "Function declaration shouldn't have a personality routine", &F);
2512   } else {
2513     // Verify that this function (which has a body) is not named "llvm.*".  It
2514     // is not legal to define intrinsics.
2515     Assert(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F);
2516 
2517     // Check the entry node
2518     const BasicBlock *Entry = &F.getEntryBlock();
2519     Assert(pred_empty(Entry),
2520            "Entry block to function must not have predecessors!", Entry);
2521 
2522     // The address of the entry block cannot be taken, unless it is dead.
2523     if (Entry->hasAddressTaken()) {
2524       Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
2525              "blockaddress may not be used with the entry block!", Entry);
2526     }
2527 
2528     unsigned NumDebugAttachments = 0, NumProfAttachments = 0;
2529     // Visit metadata attachments.
2530     for (const auto &I : MDs) {
2531       // Verify that the attachment is legal.
2532       auto AllowLocs = AreDebugLocsAllowed::No;
2533       switch (I.first) {
2534       default:
2535         break;
2536       case LLVMContext::MD_dbg: {
2537         ++NumDebugAttachments;
2538         AssertDI(NumDebugAttachments == 1,
2539                  "function must have a single !dbg attachment", &F, I.second);
2540         AssertDI(isa<DISubprogram>(I.second),
2541                  "function !dbg attachment must be a subprogram", &F, I.second);
2542         AssertDI(cast<DISubprogram>(I.second)->isDistinct(),
2543                  "function definition may only have a distinct !dbg attachment",
2544                  &F);
2545 
2546         auto *SP = cast<DISubprogram>(I.second);
2547         const Function *&AttachedTo = DISubprogramAttachments[SP];
2548         AssertDI(!AttachedTo || AttachedTo == &F,
2549                  "DISubprogram attached to more than one function", SP, &F);
2550         AttachedTo = &F;
2551         AllowLocs = AreDebugLocsAllowed::Yes;
2552         break;
2553       }
2554       case LLVMContext::MD_prof:
2555         ++NumProfAttachments;
2556         Assert(NumProfAttachments == 1,
2557                "function must have a single !prof attachment", &F, I.second);
2558         break;
2559       }
2560 
2561       // Verify the metadata itself.
2562       visitMDNode(*I.second, AllowLocs);
2563     }
2564   }
2565 
2566   // If this function is actually an intrinsic, verify that it is only used in
2567   // direct call/invokes, never having its "address taken".
2568   // Only do this if the module is materialized, otherwise we don't have all the
2569   // uses.
2570   if (F.isIntrinsic() && F.getParent()->isMaterialized()) {
2571     const User *U;
2572     if (F.hasAddressTaken(&U, false, true, false,
2573                           /*IgnoreARCAttachedCall=*/true))
2574       Assert(false, "Invalid user of intrinsic instruction!", U);
2575   }
2576 
2577   // Check intrinsics' signatures.
2578   switch (F.getIntrinsicID()) {
2579   case Intrinsic::experimental_gc_get_pointer_base: {
2580     FunctionType *FT = F.getFunctionType();
2581     Assert(FT->getNumParams() == 1, "wrong number of parameters", F);
2582     Assert(isa<PointerType>(F.getReturnType()),
2583            "gc.get.pointer.base must return a pointer", F);
2584     Assert(FT->getParamType(0) == F.getReturnType(),
2585            "gc.get.pointer.base operand and result must be of the same type",
2586            F);
2587     break;
2588   }
2589   case Intrinsic::experimental_gc_get_pointer_offset: {
2590     FunctionType *FT = F.getFunctionType();
2591     Assert(FT->getNumParams() == 1, "wrong number of parameters", F);
2592     Assert(isa<PointerType>(FT->getParamType(0)),
2593            "gc.get.pointer.offset operand must be a pointer", F);
2594     Assert(F.getReturnType()->isIntegerTy(),
2595            "gc.get.pointer.offset must return integer", F);
2596     break;
2597   }
2598   }
2599 
2600   auto *N = F.getSubprogram();
2601   HasDebugInfo = (N != nullptr);
2602   if (!HasDebugInfo)
2603     return;
2604 
2605   // Check that all !dbg attachments lead to back to N.
2606   //
2607   // FIXME: Check this incrementally while visiting !dbg attachments.
2608   // FIXME: Only check when N is the canonical subprogram for F.
2609   SmallPtrSet<const MDNode *, 32> Seen;
2610   auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
2611     // Be careful about using DILocation here since we might be dealing with
2612     // broken code (this is the Verifier after all).
2613     const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
2614     if (!DL)
2615       return;
2616     if (!Seen.insert(DL).second)
2617       return;
2618 
2619     Metadata *Parent = DL->getRawScope();
2620     AssertDI(Parent && isa<DILocalScope>(Parent),
2621              "DILocation's scope must be a DILocalScope", N, &F, &I, DL,
2622              Parent);
2623 
2624     DILocalScope *Scope = DL->getInlinedAtScope();
2625     Assert(Scope, "Failed to find DILocalScope", DL);
2626 
2627     if (!Seen.insert(Scope).second)
2628       return;
2629 
2630     DISubprogram *SP = Scope->getSubprogram();
2631 
2632     // Scope and SP could be the same MDNode and we don't want to skip
2633     // validation in that case
2634     if (SP && ((Scope != SP) && !Seen.insert(SP).second))
2635       return;
2636 
2637     AssertDI(SP->describes(&F),
2638              "!dbg attachment points at wrong subprogram for function", N, &F,
2639              &I, DL, Scope, SP);
2640   };
2641   for (auto &BB : F)
2642     for (auto &I : BB) {
2643       VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
2644       // The llvm.loop annotations also contain two DILocations.
2645       if (auto MD = I.getMetadata(LLVMContext::MD_loop))
2646         for (unsigned i = 1; i < MD->getNumOperands(); ++i)
2647           VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
2648       if (BrokenDebugInfo)
2649         return;
2650     }
2651 }
2652 
2653 // verifyBasicBlock - Verify that a basic block is well formed...
2654 //
2655 void Verifier::visitBasicBlock(BasicBlock &BB) {
2656   InstsInThisBlock.clear();
2657 
2658   // Ensure that basic blocks have terminators!
2659   Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
2660 
2661   // Check constraints that this basic block imposes on all of the PHI nodes in
2662   // it.
2663   if (isa<PHINode>(BB.front())) {
2664     SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
2665     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
2666     llvm::sort(Preds);
2667     for (const PHINode &PN : BB.phis()) {
2668       Assert(PN.getNumIncomingValues() == Preds.size(),
2669              "PHINode should have one entry for each predecessor of its "
2670              "parent basic block!",
2671              &PN);
2672 
2673       // Get and sort all incoming values in the PHI node...
2674       Values.clear();
2675       Values.reserve(PN.getNumIncomingValues());
2676       for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2677         Values.push_back(
2678             std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
2679       llvm::sort(Values);
2680 
2681       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
2682         // Check to make sure that if there is more than one entry for a
2683         // particular basic block in this PHI node, that the incoming values are
2684         // all identical.
2685         //
2686         Assert(i == 0 || Values[i].first != Values[i - 1].first ||
2687                    Values[i].second == Values[i - 1].second,
2688                "PHI node has multiple entries for the same basic block with "
2689                "different incoming values!",
2690                &PN, Values[i].first, Values[i].second, Values[i - 1].second);
2691 
2692         // Check to make sure that the predecessors and PHI node entries are
2693         // matched up.
2694         Assert(Values[i].first == Preds[i],
2695                "PHI node entries do not match predecessors!", &PN,
2696                Values[i].first, Preds[i]);
2697       }
2698     }
2699   }
2700 
2701   // Check that all instructions have their parent pointers set up correctly.
2702   for (auto &I : BB)
2703   {
2704     Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
2705   }
2706 }
2707 
2708 void Verifier::visitTerminator(Instruction &I) {
2709   // Ensure that terminators only exist at the end of the basic block.
2710   Assert(&I == I.getParent()->getTerminator(),
2711          "Terminator found in the middle of a basic block!", I.getParent());
2712   visitInstruction(I);
2713 }
2714 
2715 void Verifier::visitBranchInst(BranchInst &BI) {
2716   if (BI.isConditional()) {
2717     Assert(BI.getCondition()->getType()->isIntegerTy(1),
2718            "Branch condition is not 'i1' type!", &BI, BI.getCondition());
2719   }
2720   visitTerminator(BI);
2721 }
2722 
2723 void Verifier::visitReturnInst(ReturnInst &RI) {
2724   Function *F = RI.getParent()->getParent();
2725   unsigned N = RI.getNumOperands();
2726   if (F->getReturnType()->isVoidTy())
2727     Assert(N == 0,
2728            "Found return instr that returns non-void in Function of void "
2729            "return type!",
2730            &RI, F->getReturnType());
2731   else
2732     Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
2733            "Function return type does not match operand "
2734            "type of return inst!",
2735            &RI, F->getReturnType());
2736 
2737   // Check to make sure that the return value has necessary properties for
2738   // terminators...
2739   visitTerminator(RI);
2740 }
2741 
2742 void Verifier::visitSwitchInst(SwitchInst &SI) {
2743   Assert(SI.getType()->isVoidTy(), "Switch must have void result type!", &SI);
2744   // Check to make sure that all of the constants in the switch instruction
2745   // have the same type as the switched-on value.
2746   Type *SwitchTy = SI.getCondition()->getType();
2747   SmallPtrSet<ConstantInt*, 32> Constants;
2748   for (auto &Case : SI.cases()) {
2749     Assert(Case.getCaseValue()->getType() == SwitchTy,
2750            "Switch constants must all be same type as switch value!", &SI);
2751     Assert(Constants.insert(Case.getCaseValue()).second,
2752            "Duplicate integer as switch case", &SI, Case.getCaseValue());
2753   }
2754 
2755   visitTerminator(SI);
2756 }
2757 
2758 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
2759   Assert(BI.getAddress()->getType()->isPointerTy(),
2760          "Indirectbr operand must have pointer type!", &BI);
2761   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
2762     Assert(BI.getDestination(i)->getType()->isLabelTy(),
2763            "Indirectbr destinations must all have pointer type!", &BI);
2764 
2765   visitTerminator(BI);
2766 }
2767 
2768 void Verifier::visitCallBrInst(CallBrInst &CBI) {
2769   Assert(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!",
2770          &CBI);
2771   const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
2772   Assert(!IA->canThrow(), "Unwinding from Callbr is not allowed");
2773   for (unsigned i = 0, e = CBI.getNumSuccessors(); i != e; ++i)
2774     Assert(CBI.getSuccessor(i)->getType()->isLabelTy(),
2775            "Callbr successors must all have pointer type!", &CBI);
2776   for (unsigned i = 0, e = CBI.getNumOperands(); i != e; ++i) {
2777     Assert(i >= CBI.arg_size() || !isa<BasicBlock>(CBI.getOperand(i)),
2778            "Using an unescaped label as a callbr argument!", &CBI);
2779     if (isa<BasicBlock>(CBI.getOperand(i)))
2780       for (unsigned j = i + 1; j != e; ++j)
2781         Assert(CBI.getOperand(i) != CBI.getOperand(j),
2782                "Duplicate callbr destination!", &CBI);
2783   }
2784   {
2785     SmallPtrSet<BasicBlock *, 4> ArgBBs;
2786     for (Value *V : CBI.args())
2787       if (auto *BA = dyn_cast<BlockAddress>(V))
2788         ArgBBs.insert(BA->getBasicBlock());
2789     for (BasicBlock *BB : CBI.getIndirectDests())
2790       Assert(ArgBBs.count(BB), "Indirect label missing from arglist.", &CBI);
2791   }
2792 
2793   visitTerminator(CBI);
2794 }
2795 
2796 void Verifier::visitSelectInst(SelectInst &SI) {
2797   Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
2798                                          SI.getOperand(2)),
2799          "Invalid operands for select instruction!", &SI);
2800 
2801   Assert(SI.getTrueValue()->getType() == SI.getType(),
2802          "Select values must have same type as select instruction!", &SI);
2803   visitInstruction(SI);
2804 }
2805 
2806 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
2807 /// a pass, if any exist, it's an error.
2808 ///
2809 void Verifier::visitUserOp1(Instruction &I) {
2810   Assert(false, "User-defined operators should not live outside of a pass!", &I);
2811 }
2812 
2813 void Verifier::visitTruncInst(TruncInst &I) {
2814   // Get the source and destination types
2815   Type *SrcTy = I.getOperand(0)->getType();
2816   Type *DestTy = I.getType();
2817 
2818   // Get the size of the types in bits, we'll need this later
2819   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2820   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2821 
2822   Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
2823   Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
2824   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2825          "trunc source and destination must both be a vector or neither", &I);
2826   Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
2827 
2828   visitInstruction(I);
2829 }
2830 
2831 void Verifier::visitZExtInst(ZExtInst &I) {
2832   // Get the source and destination types
2833   Type *SrcTy = I.getOperand(0)->getType();
2834   Type *DestTy = I.getType();
2835 
2836   // Get the size of the types in bits, we'll need this later
2837   Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
2838   Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
2839   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2840          "zext source and destination must both be a vector or neither", &I);
2841   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2842   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2843 
2844   Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
2845 
2846   visitInstruction(I);
2847 }
2848 
2849 void Verifier::visitSExtInst(SExtInst &I) {
2850   // Get the source and destination types
2851   Type *SrcTy = I.getOperand(0)->getType();
2852   Type *DestTy = I.getType();
2853 
2854   // Get the size of the types in bits, we'll need this later
2855   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2856   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2857 
2858   Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
2859   Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
2860   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2861          "sext source and destination must both be a vector or neither", &I);
2862   Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
2863 
2864   visitInstruction(I);
2865 }
2866 
2867 void Verifier::visitFPTruncInst(FPTruncInst &I) {
2868   // Get the source and destination types
2869   Type *SrcTy = I.getOperand(0)->getType();
2870   Type *DestTy = I.getType();
2871   // Get the size of the types in bits, we'll need this later
2872   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2873   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2874 
2875   Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
2876   Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
2877   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2878          "fptrunc source and destination must both be a vector or neither", &I);
2879   Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
2880 
2881   visitInstruction(I);
2882 }
2883 
2884 void Verifier::visitFPExtInst(FPExtInst &I) {
2885   // Get the source and destination types
2886   Type *SrcTy = I.getOperand(0)->getType();
2887   Type *DestTy = I.getType();
2888 
2889   // Get the size of the types in bits, we'll need this later
2890   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2891   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2892 
2893   Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
2894   Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
2895   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2896          "fpext source and destination must both be a vector or neither", &I);
2897   Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
2898 
2899   visitInstruction(I);
2900 }
2901 
2902 void Verifier::visitUIToFPInst(UIToFPInst &I) {
2903   // Get the source and destination types
2904   Type *SrcTy = I.getOperand(0)->getType();
2905   Type *DestTy = I.getType();
2906 
2907   bool SrcVec = SrcTy->isVectorTy();
2908   bool DstVec = DestTy->isVectorTy();
2909 
2910   Assert(SrcVec == DstVec,
2911          "UIToFP source and dest must both be vector or scalar", &I);
2912   Assert(SrcTy->isIntOrIntVectorTy(),
2913          "UIToFP source must be integer or integer vector", &I);
2914   Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
2915          &I);
2916 
2917   if (SrcVec && DstVec)
2918     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
2919                cast<VectorType>(DestTy)->getElementCount(),
2920            "UIToFP source and dest vector length mismatch", &I);
2921 
2922   visitInstruction(I);
2923 }
2924 
2925 void Verifier::visitSIToFPInst(SIToFPInst &I) {
2926   // Get the source and destination types
2927   Type *SrcTy = I.getOperand(0)->getType();
2928   Type *DestTy = I.getType();
2929 
2930   bool SrcVec = SrcTy->isVectorTy();
2931   bool DstVec = DestTy->isVectorTy();
2932 
2933   Assert(SrcVec == DstVec,
2934          "SIToFP source and dest must both be vector or scalar", &I);
2935   Assert(SrcTy->isIntOrIntVectorTy(),
2936          "SIToFP source must be integer or integer vector", &I);
2937   Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
2938          &I);
2939 
2940   if (SrcVec && DstVec)
2941     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
2942                cast<VectorType>(DestTy)->getElementCount(),
2943            "SIToFP source and dest vector length mismatch", &I);
2944 
2945   visitInstruction(I);
2946 }
2947 
2948 void Verifier::visitFPToUIInst(FPToUIInst &I) {
2949   // Get the source and destination types
2950   Type *SrcTy = I.getOperand(0)->getType();
2951   Type *DestTy = I.getType();
2952 
2953   bool SrcVec = SrcTy->isVectorTy();
2954   bool DstVec = DestTy->isVectorTy();
2955 
2956   Assert(SrcVec == DstVec,
2957          "FPToUI source and dest must both be vector or scalar", &I);
2958   Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
2959          &I);
2960   Assert(DestTy->isIntOrIntVectorTy(),
2961          "FPToUI result must be integer or integer vector", &I);
2962 
2963   if (SrcVec && DstVec)
2964     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
2965                cast<VectorType>(DestTy)->getElementCount(),
2966            "FPToUI source and dest vector length mismatch", &I);
2967 
2968   visitInstruction(I);
2969 }
2970 
2971 void Verifier::visitFPToSIInst(FPToSIInst &I) {
2972   // Get the source and destination types
2973   Type *SrcTy = I.getOperand(0)->getType();
2974   Type *DestTy = I.getType();
2975 
2976   bool SrcVec = SrcTy->isVectorTy();
2977   bool DstVec = DestTy->isVectorTy();
2978 
2979   Assert(SrcVec == DstVec,
2980          "FPToSI source and dest must both be vector or scalar", &I);
2981   Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2982          &I);
2983   Assert(DestTy->isIntOrIntVectorTy(),
2984          "FPToSI result must be integer or integer vector", &I);
2985 
2986   if (SrcVec && DstVec)
2987     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
2988                cast<VectorType>(DestTy)->getElementCount(),
2989            "FPToSI source and dest vector length mismatch", &I);
2990 
2991   visitInstruction(I);
2992 }
2993 
2994 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2995   // Get the source and destination types
2996   Type *SrcTy = I.getOperand(0)->getType();
2997   Type *DestTy = I.getType();
2998 
2999   Assert(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
3000 
3001   Assert(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
3002   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
3003          &I);
3004 
3005   if (SrcTy->isVectorTy()) {
3006     auto *VSrc = cast<VectorType>(SrcTy);
3007     auto *VDest = cast<VectorType>(DestTy);
3008     Assert(VSrc->getElementCount() == VDest->getElementCount(),
3009            "PtrToInt Vector width mismatch", &I);
3010   }
3011 
3012   visitInstruction(I);
3013 }
3014 
3015 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
3016   // Get the source and destination types
3017   Type *SrcTy = I.getOperand(0)->getType();
3018   Type *DestTy = I.getType();
3019 
3020   Assert(SrcTy->isIntOrIntVectorTy(),
3021          "IntToPtr source must be an integral", &I);
3022   Assert(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
3023 
3024   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
3025          &I);
3026   if (SrcTy->isVectorTy()) {
3027     auto *VSrc = cast<VectorType>(SrcTy);
3028     auto *VDest = cast<VectorType>(DestTy);
3029     Assert(VSrc->getElementCount() == VDest->getElementCount(),
3030            "IntToPtr Vector width mismatch", &I);
3031   }
3032   visitInstruction(I);
3033 }
3034 
3035 void Verifier::visitBitCastInst(BitCastInst &I) {
3036   Assert(
3037       CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
3038       "Invalid bitcast", &I);
3039   visitInstruction(I);
3040 }
3041 
3042 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
3043   Type *SrcTy = I.getOperand(0)->getType();
3044   Type *DestTy = I.getType();
3045 
3046   Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
3047          &I);
3048   Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
3049          &I);
3050   Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
3051          "AddrSpaceCast must be between different address spaces", &I);
3052   if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
3053     Assert(SrcVTy->getElementCount() ==
3054                cast<VectorType>(DestTy)->getElementCount(),
3055            "AddrSpaceCast vector pointer number of elements mismatch", &I);
3056   visitInstruction(I);
3057 }
3058 
3059 /// visitPHINode - Ensure that a PHI node is well formed.
3060 ///
3061 void Verifier::visitPHINode(PHINode &PN) {
3062   // Ensure that the PHI nodes are all grouped together at the top of the block.
3063   // This can be tested by checking whether the instruction before this is
3064   // either nonexistent (because this is begin()) or is a PHI node.  If not,
3065   // then there is some other instruction before a PHI.
3066   Assert(&PN == &PN.getParent()->front() ||
3067              isa<PHINode>(--BasicBlock::iterator(&PN)),
3068          "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
3069 
3070   // Check that a PHI doesn't yield a Token.
3071   Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
3072 
3073   // Check that all of the values of the PHI node have the same type as the
3074   // result, and that the incoming blocks are really basic blocks.
3075   for (Value *IncValue : PN.incoming_values()) {
3076     Assert(PN.getType() == IncValue->getType(),
3077            "PHI node operands are not the same type as the result!", &PN);
3078   }
3079 
3080   // All other PHI node constraints are checked in the visitBasicBlock method.
3081 
3082   visitInstruction(PN);
3083 }
3084 
3085 void Verifier::visitCallBase(CallBase &Call) {
3086   Assert(Call.getCalledOperand()->getType()->isPointerTy(),
3087          "Called function must be a pointer!", Call);
3088   PointerType *FPTy = cast<PointerType>(Call.getCalledOperand()->getType());
3089 
3090   Assert(FPTy->isOpaqueOrPointeeTypeMatches(Call.getFunctionType()),
3091          "Called function is not the same type as the call!", Call);
3092 
3093   FunctionType *FTy = Call.getFunctionType();
3094 
3095   // Verify that the correct number of arguments are being passed
3096   if (FTy->isVarArg())
3097     Assert(Call.arg_size() >= FTy->getNumParams(),
3098            "Called function requires more parameters than were provided!",
3099            Call);
3100   else
3101     Assert(Call.arg_size() == FTy->getNumParams(),
3102            "Incorrect number of arguments passed to called function!", Call);
3103 
3104   // Verify that all arguments to the call match the function type.
3105   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3106     Assert(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
3107            "Call parameter type does not match function signature!",
3108            Call.getArgOperand(i), FTy->getParamType(i), Call);
3109 
3110   AttributeList Attrs = Call.getAttributes();
3111 
3112   Assert(verifyAttributeCount(Attrs, Call.arg_size()),
3113          "Attribute after last parameter!", Call);
3114 
3115   Function *Callee =
3116       dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
3117   bool IsIntrinsic = Callee && Callee->isIntrinsic();
3118   if (IsIntrinsic)
3119     Assert(Callee->getValueType() == FTy,
3120            "Intrinsic called with incompatible signature", Call);
3121 
3122   if (Attrs.hasFnAttr(Attribute::Speculatable)) {
3123     // Don't allow speculatable on call sites, unless the underlying function
3124     // declaration is also speculatable.
3125     Assert(Callee && Callee->isSpeculatable(),
3126            "speculatable attribute may not apply to call sites", Call);
3127   }
3128 
3129   if (Attrs.hasFnAttr(Attribute::Preallocated)) {
3130     Assert(Call.getCalledFunction()->getIntrinsicID() ==
3131                Intrinsic::call_preallocated_arg,
3132            "preallocated as a call site attribute can only be on "
3133            "llvm.call.preallocated.arg");
3134   }
3135 
3136   // Verify call attributes.
3137   verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic);
3138 
3139   // Conservatively check the inalloca argument.
3140   // We have a bug if we can find that there is an underlying alloca without
3141   // inalloca.
3142   if (Call.hasInAllocaArgument()) {
3143     Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
3144     if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
3145       Assert(AI->isUsedWithInAlloca(),
3146              "inalloca argument for call has mismatched alloca", AI, Call);
3147   }
3148 
3149   // For each argument of the callsite, if it has the swifterror argument,
3150   // make sure the underlying alloca/parameter it comes from has a swifterror as
3151   // well.
3152   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3153     if (Call.paramHasAttr(i, Attribute::SwiftError)) {
3154       Value *SwiftErrorArg = Call.getArgOperand(i);
3155       if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
3156         Assert(AI->isSwiftError(),
3157                "swifterror argument for call has mismatched alloca", AI, Call);
3158         continue;
3159       }
3160       auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
3161       Assert(ArgI,
3162              "swifterror argument should come from an alloca or parameter",
3163              SwiftErrorArg, Call);
3164       Assert(ArgI->hasSwiftErrorAttr(),
3165              "swifterror argument for call has mismatched parameter", ArgI,
3166              Call);
3167     }
3168 
3169     if (Attrs.hasParamAttr(i, Attribute::ImmArg)) {
3170       // Don't allow immarg on call sites, unless the underlying declaration
3171       // also has the matching immarg.
3172       Assert(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
3173              "immarg may not apply only to call sites",
3174              Call.getArgOperand(i), Call);
3175     }
3176 
3177     if (Call.paramHasAttr(i, Attribute::ImmArg)) {
3178       Value *ArgVal = Call.getArgOperand(i);
3179       Assert(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
3180              "immarg operand has non-immediate parameter", ArgVal, Call);
3181     }
3182 
3183     if (Call.paramHasAttr(i, Attribute::Preallocated)) {
3184       Value *ArgVal = Call.getArgOperand(i);
3185       bool hasOB =
3186           Call.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0;
3187       bool isMustTail = Call.isMustTailCall();
3188       Assert(hasOB != isMustTail,
3189              "preallocated operand either requires a preallocated bundle or "
3190              "the call to be musttail (but not both)",
3191              ArgVal, Call);
3192     }
3193   }
3194 
3195   if (FTy->isVarArg()) {
3196     // FIXME? is 'nest' even legal here?
3197     bool SawNest = false;
3198     bool SawReturned = false;
3199 
3200     for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3201       if (Attrs.hasParamAttr(Idx, Attribute::Nest))
3202         SawNest = true;
3203       if (Attrs.hasParamAttr(Idx, Attribute::Returned))
3204         SawReturned = true;
3205     }
3206 
3207     // Check attributes on the varargs part.
3208     for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
3209       Type *Ty = Call.getArgOperand(Idx)->getType();
3210       AttributeSet ArgAttrs = Attrs.getParamAttrs(Idx);
3211       verifyParameterAttrs(ArgAttrs, Ty, &Call);
3212 
3213       if (ArgAttrs.hasAttribute(Attribute::Nest)) {
3214         Assert(!SawNest, "More than one parameter has attribute nest!", Call);
3215         SawNest = true;
3216       }
3217 
3218       if (ArgAttrs.hasAttribute(Attribute::Returned)) {
3219         Assert(!SawReturned, "More than one parameter has attribute returned!",
3220                Call);
3221         Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
3222                "Incompatible argument and return types for 'returned' "
3223                "attribute",
3224                Call);
3225         SawReturned = true;
3226       }
3227 
3228       // Statepoint intrinsic is vararg but the wrapped function may be not.
3229       // Allow sret here and check the wrapped function in verifyStatepoint.
3230       if (!Call.getCalledFunction() ||
3231           Call.getCalledFunction()->getIntrinsicID() !=
3232               Intrinsic::experimental_gc_statepoint)
3233         Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
3234                "Attribute 'sret' cannot be used for vararg call arguments!",
3235                Call);
3236 
3237       if (ArgAttrs.hasAttribute(Attribute::InAlloca))
3238         Assert(Idx == Call.arg_size() - 1,
3239                "inalloca isn't on the last argument!", Call);
3240     }
3241   }
3242 
3243   // Verify that there's no metadata unless it's a direct call to an intrinsic.
3244   if (!IsIntrinsic) {
3245     for (Type *ParamTy : FTy->params()) {
3246       Assert(!ParamTy->isMetadataTy(),
3247              "Function has metadata parameter but isn't an intrinsic", Call);
3248       Assert(!ParamTy->isTokenTy(),
3249              "Function has token parameter but isn't an intrinsic", Call);
3250     }
3251   }
3252 
3253   // Verify that indirect calls don't return tokens.
3254   if (!Call.getCalledFunction()) {
3255     Assert(!FTy->getReturnType()->isTokenTy(),
3256            "Return type cannot be token for indirect call!");
3257     Assert(!FTy->getReturnType()->isX86_AMXTy(),
3258            "Return type cannot be x86_amx for indirect call!");
3259   }
3260 
3261   if (Function *F = Call.getCalledFunction())
3262     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3263       visitIntrinsicCall(ID, Call);
3264 
3265   // Verify that a callsite has at most one "deopt", at most one "funclet", at
3266   // most one "gc-transition", at most one "cfguardtarget",
3267   // and at most one "preallocated" operand bundle.
3268   bool FoundDeoptBundle = false, FoundFuncletBundle = false,
3269        FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
3270        FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
3271        FoundAttachedCallBundle = false;
3272   for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
3273     OperandBundleUse BU = Call.getOperandBundleAt(i);
3274     uint32_t Tag = BU.getTagID();
3275     if (Tag == LLVMContext::OB_deopt) {
3276       Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
3277       FoundDeoptBundle = true;
3278     } else if (Tag == LLVMContext::OB_gc_transition) {
3279       Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
3280              Call);
3281       FoundGCTransitionBundle = true;
3282     } else if (Tag == LLVMContext::OB_funclet) {
3283       Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
3284       FoundFuncletBundle = true;
3285       Assert(BU.Inputs.size() == 1,
3286              "Expected exactly one funclet bundle operand", Call);
3287       Assert(isa<FuncletPadInst>(BU.Inputs.front()),
3288              "Funclet bundle operands should correspond to a FuncletPadInst",
3289              Call);
3290     } else if (Tag == LLVMContext::OB_cfguardtarget) {
3291       Assert(!FoundCFGuardTargetBundle,
3292              "Multiple CFGuardTarget operand bundles", Call);
3293       FoundCFGuardTargetBundle = true;
3294       Assert(BU.Inputs.size() == 1,
3295              "Expected exactly one cfguardtarget bundle operand", Call);
3296     } else if (Tag == LLVMContext::OB_preallocated) {
3297       Assert(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
3298              Call);
3299       FoundPreallocatedBundle = true;
3300       Assert(BU.Inputs.size() == 1,
3301              "Expected exactly one preallocated bundle operand", Call);
3302       auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
3303       Assert(Input &&
3304                  Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
3305              "\"preallocated\" argument must be a token from "
3306              "llvm.call.preallocated.setup",
3307              Call);
3308     } else if (Tag == LLVMContext::OB_gc_live) {
3309       Assert(!FoundGCLiveBundle, "Multiple gc-live operand bundles",
3310              Call);
3311       FoundGCLiveBundle = true;
3312     } else if (Tag == LLVMContext::OB_clang_arc_attachedcall) {
3313       Assert(!FoundAttachedCallBundle,
3314              "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
3315       FoundAttachedCallBundle = true;
3316       verifyAttachedCallBundle(Call, BU);
3317     }
3318   }
3319 
3320   // Verify that each inlinable callsite of a debug-info-bearing function in a
3321   // debug-info-bearing function has a debug location attached to it. Failure to
3322   // do so causes assertion failures when the inliner sets up inline scope info.
3323   if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() &&
3324       Call.getCalledFunction()->getSubprogram())
3325     AssertDI(Call.getDebugLoc(),
3326              "inlinable function call in a function with "
3327              "debug info must have a !dbg location",
3328              Call);
3329 
3330   visitInstruction(Call);
3331 }
3332 
3333 void Verifier::verifyTailCCMustTailAttrs(AttrBuilder Attrs,
3334                                          StringRef Context) {
3335   Assert(!Attrs.contains(Attribute::InAlloca),
3336          Twine("inalloca attribute not allowed in ") + Context);
3337   Assert(!Attrs.contains(Attribute::InReg),
3338          Twine("inreg attribute not allowed in ") + Context);
3339   Assert(!Attrs.contains(Attribute::SwiftError),
3340          Twine("swifterror attribute not allowed in ") + Context);
3341   Assert(!Attrs.contains(Attribute::Preallocated),
3342          Twine("preallocated attribute not allowed in ") + Context);
3343   Assert(!Attrs.contains(Attribute::ByRef),
3344          Twine("byref attribute not allowed in ") + Context);
3345 }
3346 
3347 /// Two types are "congruent" if they are identical, or if they are both pointer
3348 /// types with different pointee types and the same address space.
3349 static bool isTypeCongruent(Type *L, Type *R) {
3350   if (L == R)
3351     return true;
3352   PointerType *PL = dyn_cast<PointerType>(L);
3353   PointerType *PR = dyn_cast<PointerType>(R);
3354   if (!PL || !PR)
3355     return false;
3356   return PL->getAddressSpace() == PR->getAddressSpace();
3357 }
3358 
3359 static AttrBuilder getParameterABIAttributes(unsigned I, AttributeList Attrs) {
3360   static const Attribute::AttrKind ABIAttrs[] = {
3361       Attribute::StructRet,  Attribute::ByVal,          Attribute::InAlloca,
3362       Attribute::InReg,      Attribute::StackAlignment, Attribute::SwiftSelf,
3363       Attribute::SwiftAsync, Attribute::SwiftError,     Attribute::Preallocated,
3364       Attribute::ByRef};
3365   AttrBuilder Copy;
3366   for (auto AK : ABIAttrs) {
3367     Attribute Attr = Attrs.getParamAttrs(I).getAttribute(AK);
3368     if (Attr.isValid())
3369       Copy.addAttribute(Attr);
3370   }
3371 
3372   // `align` is ABI-affecting only in combination with `byval` or `byref`.
3373   if (Attrs.hasParamAttr(I, Attribute::Alignment) &&
3374       (Attrs.hasParamAttr(I, Attribute::ByVal) ||
3375        Attrs.hasParamAttr(I, Attribute::ByRef)))
3376     Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
3377   return Copy;
3378 }
3379 
3380 void Verifier::verifyMustTailCall(CallInst &CI) {
3381   Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
3382 
3383   Function *F = CI.getParent()->getParent();
3384   FunctionType *CallerTy = F->getFunctionType();
3385   FunctionType *CalleeTy = CI.getFunctionType();
3386   Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
3387          "cannot guarantee tail call due to mismatched varargs", &CI);
3388   Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
3389          "cannot guarantee tail call due to mismatched return types", &CI);
3390 
3391   // - The calling conventions of the caller and callee must match.
3392   Assert(F->getCallingConv() == CI.getCallingConv(),
3393          "cannot guarantee tail call due to mismatched calling conv", &CI);
3394 
3395   // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
3396   //   or a pointer bitcast followed by a ret instruction.
3397   // - The ret instruction must return the (possibly bitcasted) value
3398   //   produced by the call or void.
3399   Value *RetVal = &CI;
3400   Instruction *Next = CI.getNextNode();
3401 
3402   // Handle the optional bitcast.
3403   if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
3404     Assert(BI->getOperand(0) == RetVal,
3405            "bitcast following musttail call must use the call", BI);
3406     RetVal = BI;
3407     Next = BI->getNextNode();
3408   }
3409 
3410   // Check the return.
3411   ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
3412   Assert(Ret, "musttail call must precede a ret with an optional bitcast",
3413          &CI);
3414   Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal ||
3415              isa<UndefValue>(Ret->getReturnValue()),
3416          "musttail call result must be returned", Ret);
3417 
3418   AttributeList CallerAttrs = F->getAttributes();
3419   AttributeList CalleeAttrs = CI.getAttributes();
3420   if (CI.getCallingConv() == CallingConv::SwiftTail ||
3421       CI.getCallingConv() == CallingConv::Tail) {
3422     StringRef CCName =
3423         CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
3424 
3425     // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
3426     //   are allowed in swifttailcc call
3427     for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3428       AttrBuilder ABIAttrs = getParameterABIAttributes(I, CallerAttrs);
3429       SmallString<32> Context{CCName, StringRef(" musttail caller")};
3430       verifyTailCCMustTailAttrs(ABIAttrs, Context);
3431     }
3432     for (unsigned I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
3433       AttrBuilder ABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
3434       SmallString<32> Context{CCName, StringRef(" musttail callee")};
3435       verifyTailCCMustTailAttrs(ABIAttrs, Context);
3436     }
3437     // - Varargs functions are not allowed
3438     Assert(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +
3439                                       " tail call for varargs function");
3440     return;
3441   }
3442 
3443   // - The caller and callee prototypes must match.  Pointer types of
3444   //   parameters or return types may differ in pointee type, but not
3445   //   address space.
3446   if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) {
3447     Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
3448            "cannot guarantee tail call due to mismatched parameter counts",
3449            &CI);
3450     for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3451       Assert(
3452           isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
3453           "cannot guarantee tail call due to mismatched parameter types", &CI);
3454     }
3455   }
3456 
3457   // - All ABI-impacting function attributes, such as sret, byval, inreg,
3458   //   returned, preallocated, and inalloca, must match.
3459   for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3460     AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
3461     AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
3462     Assert(CallerABIAttrs == CalleeABIAttrs,
3463            "cannot guarantee tail call due to mismatched ABI impacting "
3464            "function attributes",
3465            &CI, CI.getOperand(I));
3466   }
3467 }
3468 
3469 void Verifier::visitCallInst(CallInst &CI) {
3470   visitCallBase(CI);
3471 
3472   if (CI.isMustTailCall())
3473     verifyMustTailCall(CI);
3474 }
3475 
3476 void Verifier::visitInvokeInst(InvokeInst &II) {
3477   visitCallBase(II);
3478 
3479   // Verify that the first non-PHI instruction of the unwind destination is an
3480   // exception handling instruction.
3481   Assert(
3482       II.getUnwindDest()->isEHPad(),
3483       "The unwind destination does not have an exception handling instruction!",
3484       &II);
3485 
3486   visitTerminator(II);
3487 }
3488 
3489 /// visitUnaryOperator - Check the argument to the unary operator.
3490 ///
3491 void Verifier::visitUnaryOperator(UnaryOperator &U) {
3492   Assert(U.getType() == U.getOperand(0)->getType(),
3493          "Unary operators must have same type for"
3494          "operands and result!",
3495          &U);
3496 
3497   switch (U.getOpcode()) {
3498   // Check that floating-point arithmetic operators are only used with
3499   // floating-point operands.
3500   case Instruction::FNeg:
3501     Assert(U.getType()->isFPOrFPVectorTy(),
3502            "FNeg operator only works with float types!", &U);
3503     break;
3504   default:
3505     llvm_unreachable("Unknown UnaryOperator opcode!");
3506   }
3507 
3508   visitInstruction(U);
3509 }
3510 
3511 /// visitBinaryOperator - Check that both arguments to the binary operator are
3512 /// of the same type!
3513 ///
3514 void Verifier::visitBinaryOperator(BinaryOperator &B) {
3515   Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
3516          "Both operands to a binary operator are not of the same type!", &B);
3517 
3518   switch (B.getOpcode()) {
3519   // Check that integer arithmetic operators are only used with
3520   // integral operands.
3521   case Instruction::Add:
3522   case Instruction::Sub:
3523   case Instruction::Mul:
3524   case Instruction::SDiv:
3525   case Instruction::UDiv:
3526   case Instruction::SRem:
3527   case Instruction::URem:
3528     Assert(B.getType()->isIntOrIntVectorTy(),
3529            "Integer arithmetic operators only work with integral types!", &B);
3530     Assert(B.getType() == B.getOperand(0)->getType(),
3531            "Integer arithmetic operators must have same type "
3532            "for operands and result!",
3533            &B);
3534     break;
3535   // Check that floating-point arithmetic operators are only used with
3536   // floating-point operands.
3537   case Instruction::FAdd:
3538   case Instruction::FSub:
3539   case Instruction::FMul:
3540   case Instruction::FDiv:
3541   case Instruction::FRem:
3542     Assert(B.getType()->isFPOrFPVectorTy(),
3543            "Floating-point arithmetic operators only work with "
3544            "floating-point types!",
3545            &B);
3546     Assert(B.getType() == B.getOperand(0)->getType(),
3547            "Floating-point arithmetic operators must have same type "
3548            "for operands and result!",
3549            &B);
3550     break;
3551   // Check that logical operators are only used with integral operands.
3552   case Instruction::And:
3553   case Instruction::Or:
3554   case Instruction::Xor:
3555     Assert(B.getType()->isIntOrIntVectorTy(),
3556            "Logical operators only work with integral types!", &B);
3557     Assert(B.getType() == B.getOperand(0)->getType(),
3558            "Logical operators must have same type for operands and result!",
3559            &B);
3560     break;
3561   case Instruction::Shl:
3562   case Instruction::LShr:
3563   case Instruction::AShr:
3564     Assert(B.getType()->isIntOrIntVectorTy(),
3565            "Shifts only work with integral types!", &B);
3566     Assert(B.getType() == B.getOperand(0)->getType(),
3567            "Shift return type must be same as operands!", &B);
3568     break;
3569   default:
3570     llvm_unreachable("Unknown BinaryOperator opcode!");
3571   }
3572 
3573   visitInstruction(B);
3574 }
3575 
3576 void Verifier::visitICmpInst(ICmpInst &IC) {
3577   // Check that the operands are the same type
3578   Type *Op0Ty = IC.getOperand(0)->getType();
3579   Type *Op1Ty = IC.getOperand(1)->getType();
3580   Assert(Op0Ty == Op1Ty,
3581          "Both operands to ICmp instruction are not of the same type!", &IC);
3582   // Check that the operands are the right type
3583   Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
3584          "Invalid operand types for ICmp instruction", &IC);
3585   // Check that the predicate is valid.
3586   Assert(IC.isIntPredicate(),
3587          "Invalid predicate in ICmp instruction!", &IC);
3588 
3589   visitInstruction(IC);
3590 }
3591 
3592 void Verifier::visitFCmpInst(FCmpInst &FC) {
3593   // Check that the operands are the same type
3594   Type *Op0Ty = FC.getOperand(0)->getType();
3595   Type *Op1Ty = FC.getOperand(1)->getType();
3596   Assert(Op0Ty == Op1Ty,
3597          "Both operands to FCmp instruction are not of the same type!", &FC);
3598   // Check that the operands are the right type
3599   Assert(Op0Ty->isFPOrFPVectorTy(),
3600          "Invalid operand types for FCmp instruction", &FC);
3601   // Check that the predicate is valid.
3602   Assert(FC.isFPPredicate(),
3603          "Invalid predicate in FCmp instruction!", &FC);
3604 
3605   visitInstruction(FC);
3606 }
3607 
3608 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
3609   Assert(
3610       ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
3611       "Invalid extractelement operands!", &EI);
3612   visitInstruction(EI);
3613 }
3614 
3615 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
3616   Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
3617                                             IE.getOperand(2)),
3618          "Invalid insertelement operands!", &IE);
3619   visitInstruction(IE);
3620 }
3621 
3622 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
3623   Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
3624                                             SV.getShuffleMask()),
3625          "Invalid shufflevector operands!", &SV);
3626   visitInstruction(SV);
3627 }
3628 
3629 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
3630   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
3631 
3632   Assert(isa<PointerType>(TargetTy),
3633          "GEP base pointer is not a vector or a vector of pointers", &GEP);
3634   Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
3635 
3636   SmallVector<Value *, 16> Idxs(GEP.indices());
3637   Assert(all_of(
3638       Idxs, [](Value* V) { return V->getType()->isIntOrIntVectorTy(); }),
3639       "GEP indexes must be integers", &GEP);
3640   Type *ElTy =
3641       GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
3642   Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
3643 
3644   Assert(GEP.getType()->isPtrOrPtrVectorTy() &&
3645              GEP.getResultElementType() == ElTy,
3646          "GEP is not of right type for indices!", &GEP, ElTy);
3647 
3648   if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
3649     // Additional checks for vector GEPs.
3650     ElementCount GEPWidth = GEPVTy->getElementCount();
3651     if (GEP.getPointerOperandType()->isVectorTy())
3652       Assert(
3653           GEPWidth ==
3654               cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
3655           "Vector GEP result width doesn't match operand's", &GEP);
3656     for (Value *Idx : Idxs) {
3657       Type *IndexTy = Idx->getType();
3658       if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
3659         ElementCount IndexWidth = IndexVTy->getElementCount();
3660         Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
3661       }
3662       Assert(IndexTy->isIntOrIntVectorTy(),
3663              "All GEP indices should be of integer type");
3664     }
3665   }
3666 
3667   if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
3668     Assert(GEP.getAddressSpace() == PTy->getAddressSpace(),
3669            "GEP address space doesn't match type", &GEP);
3670   }
3671 
3672   visitInstruction(GEP);
3673 }
3674 
3675 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
3676   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
3677 }
3678 
3679 void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
3680   assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
3681          "precondition violation");
3682 
3683   unsigned NumOperands = Range->getNumOperands();
3684   Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
3685   unsigned NumRanges = NumOperands / 2;
3686   Assert(NumRanges >= 1, "It should have at least one range!", Range);
3687 
3688   ConstantRange LastRange(1, true); // Dummy initial value
3689   for (unsigned i = 0; i < NumRanges; ++i) {
3690     ConstantInt *Low =
3691         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
3692     Assert(Low, "The lower limit must be an integer!", Low);
3693     ConstantInt *High =
3694         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
3695     Assert(High, "The upper limit must be an integer!", High);
3696     Assert(High->getType() == Low->getType() && High->getType() == Ty,
3697            "Range types must match instruction type!", &I);
3698 
3699     APInt HighV = High->getValue();
3700     APInt LowV = Low->getValue();
3701     ConstantRange CurRange(LowV, HighV);
3702     Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
3703            "Range must not be empty!", Range);
3704     if (i != 0) {
3705       Assert(CurRange.intersectWith(LastRange).isEmptySet(),
3706              "Intervals are overlapping", Range);
3707       Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
3708              Range);
3709       Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
3710              Range);
3711     }
3712     LastRange = ConstantRange(LowV, HighV);
3713   }
3714   if (NumRanges > 2) {
3715     APInt FirstLow =
3716         mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
3717     APInt FirstHigh =
3718         mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
3719     ConstantRange FirstRange(FirstLow, FirstHigh);
3720     Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
3721            "Intervals are overlapping", Range);
3722     Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
3723            Range);
3724   }
3725 }
3726 
3727 void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
3728   unsigned Size = DL.getTypeSizeInBits(Ty);
3729   Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
3730   Assert(!(Size & (Size - 1)),
3731          "atomic memory access' operand must have a power-of-two size", Ty, I);
3732 }
3733 
3734 void Verifier::visitLoadInst(LoadInst &LI) {
3735   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
3736   Assert(PTy, "Load operand must be a pointer.", &LI);
3737   Type *ElTy = LI.getType();
3738   Assert(LI.getAlignment() <= Value::MaximumAlignment,
3739          "huge alignment values are unsupported", &LI);
3740   Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI);
3741   if (LI.isAtomic()) {
3742     Assert(LI.getOrdering() != AtomicOrdering::Release &&
3743                LI.getOrdering() != AtomicOrdering::AcquireRelease,
3744            "Load cannot have Release ordering", &LI);
3745     Assert(LI.getAlignment() != 0,
3746            "Atomic load must specify explicit alignment", &LI);
3747     Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
3748            "atomic load operand must have integer, pointer, or floating point "
3749            "type!",
3750            ElTy, &LI);
3751     checkAtomicMemAccessSize(ElTy, &LI);
3752   } else {
3753     Assert(LI.getSyncScopeID() == SyncScope::System,
3754            "Non-atomic load cannot have SynchronizationScope specified", &LI);
3755   }
3756 
3757   visitInstruction(LI);
3758 }
3759 
3760 void Verifier::visitStoreInst(StoreInst &SI) {
3761   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
3762   Assert(PTy, "Store operand must be a pointer.", &SI);
3763   Type *ElTy = SI.getOperand(0)->getType();
3764   Assert(PTy->isOpaqueOrPointeeTypeMatches(ElTy),
3765          "Stored value type does not match pointer operand type!", &SI, ElTy);
3766   Assert(SI.getAlignment() <= Value::MaximumAlignment,
3767          "huge alignment values are unsupported", &SI);
3768   Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI);
3769   if (SI.isAtomic()) {
3770     Assert(SI.getOrdering() != AtomicOrdering::Acquire &&
3771                SI.getOrdering() != AtomicOrdering::AcquireRelease,
3772            "Store cannot have Acquire ordering", &SI);
3773     Assert(SI.getAlignment() != 0,
3774            "Atomic store must specify explicit alignment", &SI);
3775     Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
3776            "atomic store operand must have integer, pointer, or floating point "
3777            "type!",
3778            ElTy, &SI);
3779     checkAtomicMemAccessSize(ElTy, &SI);
3780   } else {
3781     Assert(SI.getSyncScopeID() == SyncScope::System,
3782            "Non-atomic store cannot have SynchronizationScope specified", &SI);
3783   }
3784   visitInstruction(SI);
3785 }
3786 
3787 /// Check that SwiftErrorVal is used as a swifterror argument in CS.
3788 void Verifier::verifySwiftErrorCall(CallBase &Call,
3789                                     const Value *SwiftErrorVal) {
3790   for (const auto &I : llvm::enumerate(Call.args())) {
3791     if (I.value() == SwiftErrorVal) {
3792       Assert(Call.paramHasAttr(I.index(), Attribute::SwiftError),
3793              "swifterror value when used in a callsite should be marked "
3794              "with swifterror attribute",
3795              SwiftErrorVal, Call);
3796     }
3797   }
3798 }
3799 
3800 void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
3801   // Check that swifterror value is only used by loads, stores, or as
3802   // a swifterror argument.
3803   for (const User *U : SwiftErrorVal->users()) {
3804     Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
3805            isa<InvokeInst>(U),
3806            "swifterror value can only be loaded and stored from, or "
3807            "as a swifterror argument!",
3808            SwiftErrorVal, U);
3809     // If it is used by a store, check it is the second operand.
3810     if (auto StoreI = dyn_cast<StoreInst>(U))
3811       Assert(StoreI->getOperand(1) == SwiftErrorVal,
3812              "swifterror value should be the second operand when used "
3813              "by stores", SwiftErrorVal, U);
3814     if (auto *Call = dyn_cast<CallBase>(U))
3815       verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
3816   }
3817 }
3818 
3819 void Verifier::visitAllocaInst(AllocaInst &AI) {
3820   SmallPtrSet<Type*, 4> Visited;
3821   Assert(AI.getAllocatedType()->isSized(&Visited),
3822          "Cannot allocate unsized type", &AI);
3823   Assert(AI.getArraySize()->getType()->isIntegerTy(),
3824          "Alloca array size must have integer type", &AI);
3825   Assert(AI.getAlignment() <= Value::MaximumAlignment,
3826          "huge alignment values are unsupported", &AI);
3827 
3828   if (AI.isSwiftError()) {
3829     verifySwiftErrorValue(&AI);
3830   }
3831 
3832   visitInstruction(AI);
3833 }
3834 
3835 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
3836   Type *ElTy = CXI.getOperand(1)->getType();
3837   Assert(ElTy->isIntOrPtrTy(),
3838          "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
3839   checkAtomicMemAccessSize(ElTy, &CXI);
3840   visitInstruction(CXI);
3841 }
3842 
3843 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
3844   Assert(RMWI.getOrdering() != AtomicOrdering::Unordered,
3845          "atomicrmw instructions cannot be unordered.", &RMWI);
3846   auto Op = RMWI.getOperation();
3847   Type *ElTy = RMWI.getOperand(1)->getType();
3848   if (Op == AtomicRMWInst::Xchg) {
3849     Assert(ElTy->isIntegerTy() || ElTy->isFloatingPointTy(), "atomicrmw " +
3850            AtomicRMWInst::getOperationName(Op) +
3851            " operand must have integer or floating point type!",
3852            &RMWI, ElTy);
3853   } else if (AtomicRMWInst::isFPOperation(Op)) {
3854     Assert(ElTy->isFloatingPointTy(), "atomicrmw " +
3855            AtomicRMWInst::getOperationName(Op) +
3856            " operand must have floating point type!",
3857            &RMWI, ElTy);
3858   } else {
3859     Assert(ElTy->isIntegerTy(), "atomicrmw " +
3860            AtomicRMWInst::getOperationName(Op) +
3861            " operand must have integer type!",
3862            &RMWI, ElTy);
3863   }
3864   checkAtomicMemAccessSize(ElTy, &RMWI);
3865   Assert(AtomicRMWInst::FIRST_BINOP <= Op && Op <= AtomicRMWInst::LAST_BINOP,
3866          "Invalid binary operation!", &RMWI);
3867   visitInstruction(RMWI);
3868 }
3869 
3870 void Verifier::visitFenceInst(FenceInst &FI) {
3871   const AtomicOrdering Ordering = FI.getOrdering();
3872   Assert(Ordering == AtomicOrdering::Acquire ||
3873              Ordering == AtomicOrdering::Release ||
3874              Ordering == AtomicOrdering::AcquireRelease ||
3875              Ordering == AtomicOrdering::SequentiallyConsistent,
3876          "fence instructions may only have acquire, release, acq_rel, or "
3877          "seq_cst ordering.",
3878          &FI);
3879   visitInstruction(FI);
3880 }
3881 
3882 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
3883   Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
3884                                           EVI.getIndices()) == EVI.getType(),
3885          "Invalid ExtractValueInst operands!", &EVI);
3886 
3887   visitInstruction(EVI);
3888 }
3889 
3890 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
3891   Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
3892                                           IVI.getIndices()) ==
3893              IVI.getOperand(1)->getType(),
3894          "Invalid InsertValueInst operands!", &IVI);
3895 
3896   visitInstruction(IVI);
3897 }
3898 
3899 static Value *getParentPad(Value *EHPad) {
3900   if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
3901     return FPI->getParentPad();
3902 
3903   return cast<CatchSwitchInst>(EHPad)->getParentPad();
3904 }
3905 
3906 void Verifier::visitEHPadPredecessors(Instruction &I) {
3907   assert(I.isEHPad());
3908 
3909   BasicBlock *BB = I.getParent();
3910   Function *F = BB->getParent();
3911 
3912   Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
3913 
3914   if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
3915     // The landingpad instruction defines its parent as a landing pad block. The
3916     // landing pad block may be branched to only by the unwind edge of an
3917     // invoke.
3918     for (BasicBlock *PredBB : predecessors(BB)) {
3919       const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
3920       Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
3921              "Block containing LandingPadInst must be jumped to "
3922              "only by the unwind edge of an invoke.",
3923              LPI);
3924     }
3925     return;
3926   }
3927   if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
3928     if (!pred_empty(BB))
3929       Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
3930              "Block containg CatchPadInst must be jumped to "
3931              "only by its catchswitch.",
3932              CPI);
3933     Assert(BB != CPI->getCatchSwitch()->getUnwindDest(),
3934            "Catchswitch cannot unwind to one of its catchpads",
3935            CPI->getCatchSwitch(), CPI);
3936     return;
3937   }
3938 
3939   // Verify that each pred has a legal terminator with a legal to/from EH
3940   // pad relationship.
3941   Instruction *ToPad = &I;
3942   Value *ToPadParent = getParentPad(ToPad);
3943   for (BasicBlock *PredBB : predecessors(BB)) {
3944     Instruction *TI = PredBB->getTerminator();
3945     Value *FromPad;
3946     if (auto *II = dyn_cast<InvokeInst>(TI)) {
3947       Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,
3948              "EH pad must be jumped to via an unwind edge", ToPad, II);
3949       if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
3950         FromPad = Bundle->Inputs[0];
3951       else
3952         FromPad = ConstantTokenNone::get(II->getContext());
3953     } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
3954       FromPad = CRI->getOperand(0);
3955       Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
3956     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3957       FromPad = CSI;
3958     } else {
3959       Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
3960     }
3961 
3962     // The edge may exit from zero or more nested pads.
3963     SmallSet<Value *, 8> Seen;
3964     for (;; FromPad = getParentPad(FromPad)) {
3965       Assert(FromPad != ToPad,
3966              "EH pad cannot handle exceptions raised within it", FromPad, TI);
3967       if (FromPad == ToPadParent) {
3968         // This is a legal unwind edge.
3969         break;
3970       }
3971       Assert(!isa<ConstantTokenNone>(FromPad),
3972              "A single unwind edge may only enter one EH pad", TI);
3973       Assert(Seen.insert(FromPad).second,
3974              "EH pad jumps through a cycle of pads", FromPad);
3975     }
3976   }
3977 }
3978 
3979 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
3980   // The landingpad instruction is ill-formed if it doesn't have any clauses and
3981   // isn't a cleanup.
3982   Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
3983          "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
3984 
3985   visitEHPadPredecessors(LPI);
3986 
3987   if (!LandingPadResultTy)
3988     LandingPadResultTy = LPI.getType();
3989   else
3990     Assert(LandingPadResultTy == LPI.getType(),
3991            "The landingpad instruction should have a consistent result type "
3992            "inside a function.",
3993            &LPI);
3994 
3995   Function *F = LPI.getParent()->getParent();
3996   Assert(F->hasPersonalityFn(),
3997          "LandingPadInst needs to be in a function with a personality.", &LPI);
3998 
3999   // The landingpad instruction must be the first non-PHI instruction in the
4000   // block.
4001   Assert(LPI.getParent()->getLandingPadInst() == &LPI,
4002          "LandingPadInst not the first non-PHI instruction in the block.",
4003          &LPI);
4004 
4005   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
4006     Constant *Clause = LPI.getClause(i);
4007     if (LPI.isCatch(i)) {
4008       Assert(isa<PointerType>(Clause->getType()),
4009              "Catch operand does not have pointer type!", &LPI);
4010     } else {
4011       Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
4012       Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
4013              "Filter operand is not an array of constants!", &LPI);
4014     }
4015   }
4016 
4017   visitInstruction(LPI);
4018 }
4019 
4020 void Verifier::visitResumeInst(ResumeInst &RI) {
4021   Assert(RI.getFunction()->hasPersonalityFn(),
4022          "ResumeInst needs to be in a function with a personality.", &RI);
4023 
4024   if (!LandingPadResultTy)
4025     LandingPadResultTy = RI.getValue()->getType();
4026   else
4027     Assert(LandingPadResultTy == RI.getValue()->getType(),
4028            "The resume instruction should have a consistent result type "
4029            "inside a function.",
4030            &RI);
4031 
4032   visitTerminator(RI);
4033 }
4034 
4035 void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
4036   BasicBlock *BB = CPI.getParent();
4037 
4038   Function *F = BB->getParent();
4039   Assert(F->hasPersonalityFn(),
4040          "CatchPadInst needs to be in a function with a personality.", &CPI);
4041 
4042   Assert(isa<CatchSwitchInst>(CPI.getParentPad()),
4043          "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4044          CPI.getParentPad());
4045 
4046   // The catchpad instruction must be the first non-PHI instruction in the
4047   // block.
4048   Assert(BB->getFirstNonPHI() == &CPI,
4049          "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
4050 
4051   visitEHPadPredecessors(CPI);
4052   visitFuncletPadInst(CPI);
4053 }
4054 
4055 void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
4056   Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)),
4057          "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
4058          CatchReturn.getOperand(0));
4059 
4060   visitTerminator(CatchReturn);
4061 }
4062 
4063 void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
4064   BasicBlock *BB = CPI.getParent();
4065 
4066   Function *F = BB->getParent();
4067   Assert(F->hasPersonalityFn(),
4068          "CleanupPadInst needs to be in a function with a personality.", &CPI);
4069 
4070   // The cleanuppad instruction must be the first non-PHI instruction in the
4071   // block.
4072   Assert(BB->getFirstNonPHI() == &CPI,
4073          "CleanupPadInst not the first non-PHI instruction in the block.",
4074          &CPI);
4075 
4076   auto *ParentPad = CPI.getParentPad();
4077   Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4078          "CleanupPadInst has an invalid parent.", &CPI);
4079 
4080   visitEHPadPredecessors(CPI);
4081   visitFuncletPadInst(CPI);
4082 }
4083 
4084 void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
4085   User *FirstUser = nullptr;
4086   Value *FirstUnwindPad = nullptr;
4087   SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
4088   SmallSet<FuncletPadInst *, 8> Seen;
4089 
4090   while (!Worklist.empty()) {
4091     FuncletPadInst *CurrentPad = Worklist.pop_back_val();
4092     Assert(Seen.insert(CurrentPad).second,
4093            "FuncletPadInst must not be nested within itself", CurrentPad);
4094     Value *UnresolvedAncestorPad = nullptr;
4095     for (User *U : CurrentPad->users()) {
4096       BasicBlock *UnwindDest;
4097       if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
4098         UnwindDest = CRI->getUnwindDest();
4099       } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
4100         // We allow catchswitch unwind to caller to nest
4101         // within an outer pad that unwinds somewhere else,
4102         // because catchswitch doesn't have a nounwind variant.
4103         // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
4104         if (CSI->unwindsToCaller())
4105           continue;
4106         UnwindDest = CSI->getUnwindDest();
4107       } else if (auto *II = dyn_cast<InvokeInst>(U)) {
4108         UnwindDest = II->getUnwindDest();
4109       } else if (isa<CallInst>(U)) {
4110         // Calls which don't unwind may be found inside funclet
4111         // pads that unwind somewhere else.  We don't *require*
4112         // such calls to be annotated nounwind.
4113         continue;
4114       } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
4115         // The unwind dest for a cleanup can only be found by
4116         // recursive search.  Add it to the worklist, and we'll
4117         // search for its first use that determines where it unwinds.
4118         Worklist.push_back(CPI);
4119         continue;
4120       } else {
4121         Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
4122         continue;
4123       }
4124 
4125       Value *UnwindPad;
4126       bool ExitsFPI;
4127       if (UnwindDest) {
4128         UnwindPad = UnwindDest->getFirstNonPHI();
4129         if (!cast<Instruction>(UnwindPad)->isEHPad())
4130           continue;
4131         Value *UnwindParent = getParentPad(UnwindPad);
4132         // Ignore unwind edges that don't exit CurrentPad.
4133         if (UnwindParent == CurrentPad)
4134           continue;
4135         // Determine whether the original funclet pad is exited,
4136         // and if we are scanning nested pads determine how many
4137         // of them are exited so we can stop searching their
4138         // children.
4139         Value *ExitedPad = CurrentPad;
4140         ExitsFPI = false;
4141         do {
4142           if (ExitedPad == &FPI) {
4143             ExitsFPI = true;
4144             // Now we can resolve any ancestors of CurrentPad up to
4145             // FPI, but not including FPI since we need to make sure
4146             // to check all direct users of FPI for consistency.
4147             UnresolvedAncestorPad = &FPI;
4148             break;
4149           }
4150           Value *ExitedParent = getParentPad(ExitedPad);
4151           if (ExitedParent == UnwindParent) {
4152             // ExitedPad is the ancestor-most pad which this unwind
4153             // edge exits, so we can resolve up to it, meaning that
4154             // ExitedParent is the first ancestor still unresolved.
4155             UnresolvedAncestorPad = ExitedParent;
4156             break;
4157           }
4158           ExitedPad = ExitedParent;
4159         } while (!isa<ConstantTokenNone>(ExitedPad));
4160       } else {
4161         // Unwinding to caller exits all pads.
4162         UnwindPad = ConstantTokenNone::get(FPI.getContext());
4163         ExitsFPI = true;
4164         UnresolvedAncestorPad = &FPI;
4165       }
4166 
4167       if (ExitsFPI) {
4168         // This unwind edge exits FPI.  Make sure it agrees with other
4169         // such edges.
4170         if (FirstUser) {
4171           Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet "
4172                                               "pad must have the same unwind "
4173                                               "dest",
4174                  &FPI, U, FirstUser);
4175         } else {
4176           FirstUser = U;
4177           FirstUnwindPad = UnwindPad;
4178           // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
4179           if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
4180               getParentPad(UnwindPad) == getParentPad(&FPI))
4181             SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
4182         }
4183       }
4184       // Make sure we visit all uses of FPI, but for nested pads stop as
4185       // soon as we know where they unwind to.
4186       if (CurrentPad != &FPI)
4187         break;
4188     }
4189     if (UnresolvedAncestorPad) {
4190       if (CurrentPad == UnresolvedAncestorPad) {
4191         // When CurrentPad is FPI itself, we don't mark it as resolved even if
4192         // we've found an unwind edge that exits it, because we need to verify
4193         // all direct uses of FPI.
4194         assert(CurrentPad == &FPI);
4195         continue;
4196       }
4197       // Pop off the worklist any nested pads that we've found an unwind
4198       // destination for.  The pads on the worklist are the uncles,
4199       // great-uncles, etc. of CurrentPad.  We've found an unwind destination
4200       // for all ancestors of CurrentPad up to but not including
4201       // UnresolvedAncestorPad.
4202       Value *ResolvedPad = CurrentPad;
4203       while (!Worklist.empty()) {
4204         Value *UnclePad = Worklist.back();
4205         Value *AncestorPad = getParentPad(UnclePad);
4206         // Walk ResolvedPad up the ancestor list until we either find the
4207         // uncle's parent or the last resolved ancestor.
4208         while (ResolvedPad != AncestorPad) {
4209           Value *ResolvedParent = getParentPad(ResolvedPad);
4210           if (ResolvedParent == UnresolvedAncestorPad) {
4211             break;
4212           }
4213           ResolvedPad = ResolvedParent;
4214         }
4215         // If the resolved ancestor search didn't find the uncle's parent,
4216         // then the uncle is not yet resolved.
4217         if (ResolvedPad != AncestorPad)
4218           break;
4219         // This uncle is resolved, so pop it from the worklist.
4220         Worklist.pop_back();
4221       }
4222     }
4223   }
4224 
4225   if (FirstUnwindPad) {
4226     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
4227       BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
4228       Value *SwitchUnwindPad;
4229       if (SwitchUnwindDest)
4230         SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
4231       else
4232         SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
4233       Assert(SwitchUnwindPad == FirstUnwindPad,
4234              "Unwind edges out of a catch must have the same unwind dest as "
4235              "the parent catchswitch",
4236              &FPI, FirstUser, CatchSwitch);
4237     }
4238   }
4239 
4240   visitInstruction(FPI);
4241 }
4242 
4243 void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
4244   BasicBlock *BB = CatchSwitch.getParent();
4245 
4246   Function *F = BB->getParent();
4247   Assert(F->hasPersonalityFn(),
4248          "CatchSwitchInst needs to be in a function with a personality.",
4249          &CatchSwitch);
4250 
4251   // The catchswitch instruction must be the first non-PHI instruction in the
4252   // block.
4253   Assert(BB->getFirstNonPHI() == &CatchSwitch,
4254          "CatchSwitchInst not the first non-PHI instruction in the block.",
4255          &CatchSwitch);
4256 
4257   auto *ParentPad = CatchSwitch.getParentPad();
4258   Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4259          "CatchSwitchInst has an invalid parent.", ParentPad);
4260 
4261   if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
4262     Instruction *I = UnwindDest->getFirstNonPHI();
4263     Assert(I->isEHPad() && !isa<LandingPadInst>(I),
4264            "CatchSwitchInst must unwind to an EH block which is not a "
4265            "landingpad.",
4266            &CatchSwitch);
4267 
4268     // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
4269     if (getParentPad(I) == ParentPad)
4270       SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
4271   }
4272 
4273   Assert(CatchSwitch.getNumHandlers() != 0,
4274          "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
4275 
4276   for (BasicBlock *Handler : CatchSwitch.handlers()) {
4277     Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()),
4278            "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
4279   }
4280 
4281   visitEHPadPredecessors(CatchSwitch);
4282   visitTerminator(CatchSwitch);
4283 }
4284 
4285 void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
4286   Assert(isa<CleanupPadInst>(CRI.getOperand(0)),
4287          "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
4288          CRI.getOperand(0));
4289 
4290   if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
4291     Instruction *I = UnwindDest->getFirstNonPHI();
4292     Assert(I->isEHPad() && !isa<LandingPadInst>(I),
4293            "CleanupReturnInst must unwind to an EH block which is not a "
4294            "landingpad.",
4295            &CRI);
4296   }
4297 
4298   visitTerminator(CRI);
4299 }
4300 
4301 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
4302   Instruction *Op = cast<Instruction>(I.getOperand(i));
4303   // If the we have an invalid invoke, don't try to compute the dominance.
4304   // We already reject it in the invoke specific checks and the dominance
4305   // computation doesn't handle multiple edges.
4306   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
4307     if (II->getNormalDest() == II->getUnwindDest())
4308       return;
4309   }
4310 
4311   // Quick check whether the def has already been encountered in the same block.
4312   // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
4313   // uses are defined to happen on the incoming edge, not at the instruction.
4314   //
4315   // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
4316   // wrapping an SSA value, assert that we've already encountered it.  See
4317   // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
4318   if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
4319     return;
4320 
4321   const Use &U = I.getOperandUse(i);
4322   Assert(DT.dominates(Op, U),
4323          "Instruction does not dominate all uses!", Op, &I);
4324 }
4325 
4326 void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
4327   Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
4328          "apply only to pointer types", &I);
4329   Assert((isa<LoadInst>(I) || isa<IntToPtrInst>(I)),
4330          "dereferenceable, dereferenceable_or_null apply only to load"
4331          " and inttoptr instructions, use attributes for calls or invokes", &I);
4332   Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
4333          "take one operand!", &I);
4334   ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
4335   Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "
4336          "dereferenceable_or_null metadata value must be an i64!", &I);
4337 }
4338 
4339 void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
4340   Assert(MD->getNumOperands() >= 2,
4341          "!prof annotations should have no less than 2 operands", MD);
4342 
4343   // Check first operand.
4344   Assert(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
4345   Assert(isa<MDString>(MD->getOperand(0)),
4346          "expected string with name of the !prof annotation", MD);
4347   MDString *MDS = cast<MDString>(MD->getOperand(0));
4348   StringRef ProfName = MDS->getString();
4349 
4350   // Check consistency of !prof branch_weights metadata.
4351   if (ProfName.equals("branch_weights")) {
4352     if (isa<InvokeInst>(&I)) {
4353       Assert(MD->getNumOperands() == 2 || MD->getNumOperands() == 3,
4354              "Wrong number of InvokeInst branch_weights operands", MD);
4355     } else {
4356       unsigned ExpectedNumOperands = 0;
4357       if (BranchInst *BI = dyn_cast<BranchInst>(&I))
4358         ExpectedNumOperands = BI->getNumSuccessors();
4359       else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
4360         ExpectedNumOperands = SI->getNumSuccessors();
4361       else if (isa<CallInst>(&I))
4362         ExpectedNumOperands = 1;
4363       else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
4364         ExpectedNumOperands = IBI->getNumDestinations();
4365       else if (isa<SelectInst>(&I))
4366         ExpectedNumOperands = 2;
4367       else
4368         CheckFailed("!prof branch_weights are not allowed for this instruction",
4369                     MD);
4370 
4371       Assert(MD->getNumOperands() == 1 + ExpectedNumOperands,
4372              "Wrong number of operands", MD);
4373     }
4374     for (unsigned i = 1; i < MD->getNumOperands(); ++i) {
4375       auto &MDO = MD->getOperand(i);
4376       Assert(MDO, "second operand should not be null", MD);
4377       Assert(mdconst::dyn_extract<ConstantInt>(MDO),
4378              "!prof brunch_weights operand is not a const int");
4379     }
4380   }
4381 }
4382 
4383 void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
4384   Assert(isa<MDTuple>(Annotation), "annotation must be a tuple");
4385   Assert(Annotation->getNumOperands() >= 1,
4386          "annotation must have at least one operand");
4387   for (const MDOperand &Op : Annotation->operands())
4388     Assert(isa<MDString>(Op.get()), "operands must be strings");
4389 }
4390 
4391 void Verifier::visitAliasScopeMetadata(const MDNode *MD) {
4392   unsigned NumOps = MD->getNumOperands();
4393   Assert(NumOps >= 2 && NumOps <= 3, "scope must have two or three operands",
4394          MD);
4395   Assert(MD->getOperand(0).get() == MD || isa<MDString>(MD->getOperand(0)),
4396          "first scope operand must be self-referential or string", MD);
4397   if (NumOps == 3)
4398     Assert(isa<MDString>(MD->getOperand(2)),
4399            "third scope operand must be string (if used)", MD);
4400 
4401   MDNode *Domain = dyn_cast<MDNode>(MD->getOperand(1));
4402   Assert(Domain != nullptr, "second scope operand must be MDNode", MD);
4403 
4404   unsigned NumDomainOps = Domain->getNumOperands();
4405   Assert(NumDomainOps >= 1 && NumDomainOps <= 2,
4406          "domain must have one or two operands", Domain);
4407   Assert(Domain->getOperand(0).get() == Domain ||
4408              isa<MDString>(Domain->getOperand(0)),
4409          "first domain operand must be self-referential or string", Domain);
4410   if (NumDomainOps == 2)
4411     Assert(isa<MDString>(Domain->getOperand(1)),
4412            "second domain operand must be string (if used)", Domain);
4413 }
4414 
4415 void Verifier::visitAliasScopeListMetadata(const MDNode *MD) {
4416   for (const MDOperand &Op : MD->operands()) {
4417     const MDNode *OpMD = dyn_cast<MDNode>(Op);
4418     Assert(OpMD != nullptr, "scope list must consist of MDNodes", MD);
4419     visitAliasScopeMetadata(OpMD);
4420   }
4421 }
4422 
4423 /// verifyInstruction - Verify that an instruction is well formed.
4424 ///
4425 void Verifier::visitInstruction(Instruction &I) {
4426   BasicBlock *BB = I.getParent();
4427   Assert(BB, "Instruction not embedded in basic block!", &I);
4428 
4429   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
4430     for (User *U : I.users()) {
4431       Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
4432              "Only PHI nodes may reference their own value!", &I);
4433     }
4434   }
4435 
4436   // Check that void typed values don't have names
4437   Assert(!I.getType()->isVoidTy() || !I.hasName(),
4438          "Instruction has a name, but provides a void value!", &I);
4439 
4440   // Check that the return value of the instruction is either void or a legal
4441   // value type.
4442   Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
4443          "Instruction returns a non-scalar type!", &I);
4444 
4445   // Check that the instruction doesn't produce metadata. Calls are already
4446   // checked against the callee type.
4447   Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
4448          "Invalid use of metadata!", &I);
4449 
4450   // Check that all uses of the instruction, if they are instructions
4451   // themselves, actually have parent basic blocks.  If the use is not an
4452   // instruction, it is an error!
4453   for (Use &U : I.uses()) {
4454     if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
4455       Assert(Used->getParent() != nullptr,
4456              "Instruction referencing"
4457              " instruction not embedded in a basic block!",
4458              &I, Used);
4459     else {
4460       CheckFailed("Use of instruction is not an instruction!", U);
4461       return;
4462     }
4463   }
4464 
4465   // Get a pointer to the call base of the instruction if it is some form of
4466   // call.
4467   const CallBase *CBI = dyn_cast<CallBase>(&I);
4468 
4469   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
4470     Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
4471 
4472     // Check to make sure that only first-class-values are operands to
4473     // instructions.
4474     if (!I.getOperand(i)->getType()->isFirstClassType()) {
4475       Assert(false, "Instruction operands must be first-class values!", &I);
4476     }
4477 
4478     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
4479       // This code checks whether the function is used as the operand of a
4480       // clang_arc_attachedcall operand bundle.
4481       auto IsAttachedCallOperand = [](Function *F, const CallBase *CBI,
4482                                       int Idx) {
4483         return CBI && CBI->isOperandBundleOfType(
4484                           LLVMContext::OB_clang_arc_attachedcall, Idx);
4485       };
4486 
4487       // Check to make sure that the "address of" an intrinsic function is never
4488       // taken. Ignore cases where the address of the intrinsic function is used
4489       // as the argument of operand bundle "clang.arc.attachedcall" as those
4490       // cases are handled in verifyAttachedCallBundle.
4491       Assert((!F->isIntrinsic() ||
4492               (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)) ||
4493               IsAttachedCallOperand(F, CBI, i)),
4494              "Cannot take the address of an intrinsic!", &I);
4495       Assert(
4496           !F->isIntrinsic() || isa<CallInst>(I) ||
4497               F->getIntrinsicID() == Intrinsic::donothing ||
4498               F->getIntrinsicID() == Intrinsic::seh_try_begin ||
4499               F->getIntrinsicID() == Intrinsic::seh_try_end ||
4500               F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
4501               F->getIntrinsicID() == Intrinsic::seh_scope_end ||
4502               F->getIntrinsicID() == Intrinsic::coro_resume ||
4503               F->getIntrinsicID() == Intrinsic::coro_destroy ||
4504               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
4505               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
4506               F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
4507               F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
4508               IsAttachedCallOperand(F, CBI, i),
4509           "Cannot invoke an intrinsic other than donothing, patchpoint, "
4510           "statepoint, coro_resume, coro_destroy or clang.arc.attachedcall",
4511           &I);
4512       Assert(F->getParent() == &M, "Referencing function in another module!",
4513              &I, &M, F, F->getParent());
4514     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
4515       Assert(OpBB->getParent() == BB->getParent(),
4516              "Referring to a basic block in another function!", &I);
4517     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
4518       Assert(OpArg->getParent() == BB->getParent(),
4519              "Referring to an argument in another function!", &I);
4520     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
4521       Assert(GV->getParent() == &M, "Referencing global in another module!", &I,
4522              &M, GV, GV->getParent());
4523     } else if (isa<Instruction>(I.getOperand(i))) {
4524       verifyDominatesUse(I, i);
4525     } else if (isa<InlineAsm>(I.getOperand(i))) {
4526       Assert(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
4527              "Cannot take the address of an inline asm!", &I);
4528     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
4529       if (CE->getType()->isPtrOrPtrVectorTy()) {
4530         // If we have a ConstantExpr pointer, we need to see if it came from an
4531         // illegal bitcast.
4532         visitConstantExprsRecursively(CE);
4533       }
4534     }
4535   }
4536 
4537   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
4538     Assert(I.getType()->isFPOrFPVectorTy(),
4539            "fpmath requires a floating point result!", &I);
4540     Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
4541     if (ConstantFP *CFP0 =
4542             mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
4543       const APFloat &Accuracy = CFP0->getValueAPF();
4544       Assert(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
4545              "fpmath accuracy must have float type", &I);
4546       Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
4547              "fpmath accuracy not a positive number!", &I);
4548     } else {
4549       Assert(false, "invalid fpmath accuracy!", &I);
4550     }
4551   }
4552 
4553   if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
4554     Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
4555            "Ranges are only for loads, calls and invokes!", &I);
4556     visitRangeMetadata(I, Range, I.getType());
4557   }
4558 
4559   if (I.hasMetadata(LLVMContext::MD_invariant_group)) {
4560     Assert(isa<LoadInst>(I) || isa<StoreInst>(I),
4561            "invariant.group metadata is only for loads and stores", &I);
4562   }
4563 
4564   if (I.getMetadata(LLVMContext::MD_nonnull)) {
4565     Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
4566            &I);
4567     Assert(isa<LoadInst>(I),
4568            "nonnull applies only to load instructions, use attributes"
4569            " for calls or invokes",
4570            &I);
4571   }
4572 
4573   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
4574     visitDereferenceableMetadata(I, MD);
4575 
4576   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
4577     visitDereferenceableMetadata(I, MD);
4578 
4579   if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
4580     TBAAVerifyHelper.visitTBAAMetadata(I, TBAA);
4581 
4582   if (MDNode *MD = I.getMetadata(LLVMContext::MD_noalias))
4583     visitAliasScopeListMetadata(MD);
4584   if (MDNode *MD = I.getMetadata(LLVMContext::MD_alias_scope))
4585     visitAliasScopeListMetadata(MD);
4586 
4587   if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
4588     Assert(I.getType()->isPointerTy(), "align applies only to pointer types",
4589            &I);
4590     Assert(isa<LoadInst>(I), "align applies only to load instructions, "
4591            "use attributes for calls or invokes", &I);
4592     Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
4593     ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
4594     Assert(CI && CI->getType()->isIntegerTy(64),
4595            "align metadata value must be an i64!", &I);
4596     uint64_t Align = CI->getZExtValue();
4597     Assert(isPowerOf2_64(Align),
4598            "align metadata value must be a power of 2!", &I);
4599     Assert(Align <= Value::MaximumAlignment,
4600            "alignment is larger that implementation defined limit", &I);
4601   }
4602 
4603   if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
4604     visitProfMetadata(I, MD);
4605 
4606   if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation))
4607     visitAnnotationMetadata(Annotation);
4608 
4609   if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
4610     AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
4611     visitMDNode(*N, AreDebugLocsAllowed::Yes);
4612   }
4613 
4614   if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
4615     verifyFragmentExpression(*DII);
4616     verifyNotEntryValue(*DII);
4617   }
4618 
4619   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
4620   I.getAllMetadata(MDs);
4621   for (auto Attachment : MDs) {
4622     unsigned Kind = Attachment.first;
4623     auto AllowLocs =
4624         (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop)
4625             ? AreDebugLocsAllowed::Yes
4626             : AreDebugLocsAllowed::No;
4627     visitMDNode(*Attachment.second, AllowLocs);
4628   }
4629 
4630   InstsInThisBlock.insert(&I);
4631 }
4632 
4633 /// Allow intrinsics to be verified in different ways.
4634 void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
4635   Function *IF = Call.getCalledFunction();
4636   Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
4637          IF);
4638 
4639   // Verify that the intrinsic prototype lines up with what the .td files
4640   // describe.
4641   FunctionType *IFTy = IF->getFunctionType();
4642   bool IsVarArg = IFTy->isVarArg();
4643 
4644   SmallVector<Intrinsic::IITDescriptor, 8> Table;
4645   getIntrinsicInfoTableEntries(ID, Table);
4646   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
4647 
4648   // Walk the descriptors to extract overloaded types.
4649   SmallVector<Type *, 4> ArgTys;
4650   Intrinsic::MatchIntrinsicTypesResult Res =
4651       Intrinsic::matchIntrinsicSignature(IFTy, TableRef, ArgTys);
4652   Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet,
4653          "Intrinsic has incorrect return type!", IF);
4654   Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg,
4655          "Intrinsic has incorrect argument type!", IF);
4656 
4657   // Verify if the intrinsic call matches the vararg property.
4658   if (IsVarArg)
4659     Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
4660            "Intrinsic was not defined with variable arguments!", IF);
4661   else
4662     Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
4663            "Callsite was not defined with variable arguments!", IF);
4664 
4665   // All descriptors should be absorbed by now.
4666   Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
4667 
4668   // Now that we have the intrinsic ID and the actual argument types (and we
4669   // know they are legal for the intrinsic!) get the intrinsic name through the
4670   // usual means.  This allows us to verify the mangling of argument types into
4671   // the name.
4672   const std::string ExpectedName =
4673       Intrinsic::getName(ID, ArgTys, IF->getParent(), IFTy);
4674   Assert(ExpectedName == IF->getName(),
4675          "Intrinsic name not mangled correctly for type arguments! "
4676          "Should be: " +
4677              ExpectedName,
4678          IF);
4679 
4680   // If the intrinsic takes MDNode arguments, verify that they are either global
4681   // or are local to *this* function.
4682   for (Value *V : Call.args()) {
4683     if (auto *MD = dyn_cast<MetadataAsValue>(V))
4684       visitMetadataAsValue(*MD, Call.getCaller());
4685     if (auto *Const = dyn_cast<Constant>(V))
4686       Assert(!Const->getType()->isX86_AMXTy(),
4687              "const x86_amx is not allowed in argument!");
4688   }
4689 
4690   switch (ID) {
4691   default:
4692     break;
4693   case Intrinsic::assume: {
4694     for (auto &Elem : Call.bundle_op_infos()) {
4695       Assert(Elem.Tag->getKey() == "ignore" ||
4696                  Attribute::isExistingAttribute(Elem.Tag->getKey()),
4697              "tags must be valid attribute names", Call);
4698       Attribute::AttrKind Kind =
4699           Attribute::getAttrKindFromName(Elem.Tag->getKey());
4700       unsigned ArgCount = Elem.End - Elem.Begin;
4701       if (Kind == Attribute::Alignment) {
4702         Assert(ArgCount <= 3 && ArgCount >= 2,
4703                "alignment assumptions should have 2 or 3 arguments", Call);
4704         Assert(Call.getOperand(Elem.Begin)->getType()->isPointerTy(),
4705                "first argument should be a pointer", Call);
4706         Assert(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(),
4707                "second argument should be an integer", Call);
4708         if (ArgCount == 3)
4709           Assert(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(),
4710                  "third argument should be an integer if present", Call);
4711         return;
4712       }
4713       Assert(ArgCount <= 2, "too many arguments", Call);
4714       if (Kind == Attribute::None)
4715         break;
4716       if (Attribute::isIntAttrKind(Kind)) {
4717         Assert(ArgCount == 2, "this attribute should have 2 arguments", Call);
4718         Assert(isa<ConstantInt>(Call.getOperand(Elem.Begin + 1)),
4719                "the second argument should be a constant integral value", Call);
4720       } else if (Attribute::canUseAsParamAttr(Kind)) {
4721         Assert((ArgCount) == 1, "this attribute should have one argument",
4722                Call);
4723       } else if (Attribute::canUseAsFnAttr(Kind)) {
4724         Assert((ArgCount) == 0, "this attribute has no argument", Call);
4725       }
4726     }
4727     break;
4728   }
4729   case Intrinsic::coro_id: {
4730     auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts();
4731     if (isa<ConstantPointerNull>(InfoArg))
4732       break;
4733     auto *GV = dyn_cast<GlobalVariable>(InfoArg);
4734     Assert(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
4735            "info argument of llvm.coro.id must refer to an initialized "
4736            "constant");
4737     Constant *Init = GV->getInitializer();
4738     Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),
4739            "info argument of llvm.coro.id must refer to either a struct or "
4740            "an array");
4741     break;
4742   }
4743 #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC)                        \
4744   case Intrinsic::INTRINSIC:
4745 #include "llvm/IR/ConstrainedOps.def"
4746     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
4747     break;
4748   case Intrinsic::dbg_declare: // llvm.dbg.declare
4749     Assert(isa<MetadataAsValue>(Call.getArgOperand(0)),
4750            "invalid llvm.dbg.declare intrinsic call 1", Call);
4751     visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(Call));
4752     break;
4753   case Intrinsic::dbg_addr: // llvm.dbg.addr
4754     visitDbgIntrinsic("addr", cast<DbgVariableIntrinsic>(Call));
4755     break;
4756   case Intrinsic::dbg_value: // llvm.dbg.value
4757     visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(Call));
4758     break;
4759   case Intrinsic::dbg_label: // llvm.dbg.label
4760     visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(Call));
4761     break;
4762   case Intrinsic::memcpy:
4763   case Intrinsic::memcpy_inline:
4764   case Intrinsic::memmove:
4765   case Intrinsic::memset: {
4766     const auto *MI = cast<MemIntrinsic>(&Call);
4767     auto IsValidAlignment = [&](unsigned Alignment) -> bool {
4768       return Alignment == 0 || isPowerOf2_32(Alignment);
4769     };
4770     Assert(IsValidAlignment(MI->getDestAlignment()),
4771            "alignment of arg 0 of memory intrinsic must be 0 or a power of 2",
4772            Call);
4773     if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) {
4774       Assert(IsValidAlignment(MTI->getSourceAlignment()),
4775              "alignment of arg 1 of memory intrinsic must be 0 or a power of 2",
4776              Call);
4777     }
4778 
4779     break;
4780   }
4781   case Intrinsic::memcpy_element_unordered_atomic:
4782   case Intrinsic::memmove_element_unordered_atomic:
4783   case Intrinsic::memset_element_unordered_atomic: {
4784     const auto *AMI = cast<AtomicMemIntrinsic>(&Call);
4785 
4786     ConstantInt *ElementSizeCI =
4787         cast<ConstantInt>(AMI->getRawElementSizeInBytes());
4788     const APInt &ElementSizeVal = ElementSizeCI->getValue();
4789     Assert(ElementSizeVal.isPowerOf2(),
4790            "element size of the element-wise atomic memory intrinsic "
4791            "must be a power of 2",
4792            Call);
4793 
4794     auto IsValidAlignment = [&](uint64_t Alignment) {
4795       return isPowerOf2_64(Alignment) && ElementSizeVal.ule(Alignment);
4796     };
4797     uint64_t DstAlignment = AMI->getDestAlignment();
4798     Assert(IsValidAlignment(DstAlignment),
4799            "incorrect alignment of the destination argument", Call);
4800     if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) {
4801       uint64_t SrcAlignment = AMT->getSourceAlignment();
4802       Assert(IsValidAlignment(SrcAlignment),
4803              "incorrect alignment of the source argument", Call);
4804     }
4805     break;
4806   }
4807   case Intrinsic::call_preallocated_setup: {
4808     auto *NumArgs = dyn_cast<ConstantInt>(Call.getArgOperand(0));
4809     Assert(NumArgs != nullptr,
4810            "llvm.call.preallocated.setup argument must be a constant");
4811     bool FoundCall = false;
4812     for (User *U : Call.users()) {
4813       auto *UseCall = dyn_cast<CallBase>(U);
4814       Assert(UseCall != nullptr,
4815              "Uses of llvm.call.preallocated.setup must be calls");
4816       const Function *Fn = UseCall->getCalledFunction();
4817       if (Fn && Fn->getIntrinsicID() == Intrinsic::call_preallocated_arg) {
4818         auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1));
4819         Assert(AllocArgIndex != nullptr,
4820                "llvm.call.preallocated.alloc arg index must be a constant");
4821         auto AllocArgIndexInt = AllocArgIndex->getValue();
4822         Assert(AllocArgIndexInt.sge(0) &&
4823                    AllocArgIndexInt.slt(NumArgs->getValue()),
4824                "llvm.call.preallocated.alloc arg index must be between 0 and "
4825                "corresponding "
4826                "llvm.call.preallocated.setup's argument count");
4827       } else if (Fn && Fn->getIntrinsicID() ==
4828                            Intrinsic::call_preallocated_teardown) {
4829         // nothing to do
4830       } else {
4831         Assert(!FoundCall, "Can have at most one call corresponding to a "
4832                            "llvm.call.preallocated.setup");
4833         FoundCall = true;
4834         size_t NumPreallocatedArgs = 0;
4835         for (unsigned i = 0; i < UseCall->arg_size(); i++) {
4836           if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
4837             ++NumPreallocatedArgs;
4838           }
4839         }
4840         Assert(NumPreallocatedArgs != 0,
4841                "cannot use preallocated intrinsics on a call without "
4842                "preallocated arguments");
4843         Assert(NumArgs->equalsInt(NumPreallocatedArgs),
4844                "llvm.call.preallocated.setup arg size must be equal to number "
4845                "of preallocated arguments "
4846                "at call site",
4847                Call, *UseCall);
4848         // getOperandBundle() cannot be called if more than one of the operand
4849         // bundle exists. There is already a check elsewhere for this, so skip
4850         // here if we see more than one.
4851         if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) >
4852             1) {
4853           return;
4854         }
4855         auto PreallocatedBundle =
4856             UseCall->getOperandBundle(LLVMContext::OB_preallocated);
4857         Assert(PreallocatedBundle,
4858                "Use of llvm.call.preallocated.setup outside intrinsics "
4859                "must be in \"preallocated\" operand bundle");
4860         Assert(PreallocatedBundle->Inputs.front().get() == &Call,
4861                "preallocated bundle must have token from corresponding "
4862                "llvm.call.preallocated.setup");
4863       }
4864     }
4865     break;
4866   }
4867   case Intrinsic::call_preallocated_arg: {
4868     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
4869     Assert(Token && Token->getCalledFunction()->getIntrinsicID() ==
4870                         Intrinsic::call_preallocated_setup,
4871            "llvm.call.preallocated.arg token argument must be a "
4872            "llvm.call.preallocated.setup");
4873     Assert(Call.hasFnAttr(Attribute::Preallocated),
4874            "llvm.call.preallocated.arg must be called with a \"preallocated\" "
4875            "call site attribute");
4876     break;
4877   }
4878   case Intrinsic::call_preallocated_teardown: {
4879     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
4880     Assert(Token && Token->getCalledFunction()->getIntrinsicID() ==
4881                         Intrinsic::call_preallocated_setup,
4882            "llvm.call.preallocated.teardown token argument must be a "
4883            "llvm.call.preallocated.setup");
4884     break;
4885   }
4886   case Intrinsic::gcroot:
4887   case Intrinsic::gcwrite:
4888   case Intrinsic::gcread:
4889     if (ID == Intrinsic::gcroot) {
4890       AllocaInst *AI =
4891           dyn_cast<AllocaInst>(Call.getArgOperand(0)->stripPointerCasts());
4892       Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
4893       Assert(isa<Constant>(Call.getArgOperand(1)),
4894              "llvm.gcroot parameter #2 must be a constant.", Call);
4895       if (!AI->getAllocatedType()->isPointerTy()) {
4896         Assert(!isa<ConstantPointerNull>(Call.getArgOperand(1)),
4897                "llvm.gcroot parameter #1 must either be a pointer alloca, "
4898                "or argument #2 must be a non-null constant.",
4899                Call);
4900       }
4901     }
4902 
4903     Assert(Call.getParent()->getParent()->hasGC(),
4904            "Enclosing function does not use GC.", Call);
4905     break;
4906   case Intrinsic::init_trampoline:
4907     Assert(isa<Function>(Call.getArgOperand(1)->stripPointerCasts()),
4908            "llvm.init_trampoline parameter #2 must resolve to a function.",
4909            Call);
4910     break;
4911   case Intrinsic::prefetch:
4912     Assert(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2 &&
4913            cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
4914            "invalid arguments to llvm.prefetch", Call);
4915     break;
4916   case Intrinsic::stackprotector:
4917     Assert(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts()),
4918            "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
4919     break;
4920   case Intrinsic::localescape: {
4921     BasicBlock *BB = Call.getParent();
4922     Assert(BB == &BB->getParent()->front(),
4923            "llvm.localescape used outside of entry block", Call);
4924     Assert(!SawFrameEscape,
4925            "multiple calls to llvm.localescape in one function", Call);
4926     for (Value *Arg : Call.args()) {
4927       if (isa<ConstantPointerNull>(Arg))
4928         continue; // Null values are allowed as placeholders.
4929       auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
4930       Assert(AI && AI->isStaticAlloca(),
4931              "llvm.localescape only accepts static allocas", Call);
4932     }
4933     FrameEscapeInfo[BB->getParent()].first = Call.arg_size();
4934     SawFrameEscape = true;
4935     break;
4936   }
4937   case Intrinsic::localrecover: {
4938     Value *FnArg = Call.getArgOperand(0)->stripPointerCasts();
4939     Function *Fn = dyn_cast<Function>(FnArg);
4940     Assert(Fn && !Fn->isDeclaration(),
4941            "llvm.localrecover first "
4942            "argument must be function defined in this module",
4943            Call);
4944     auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
4945     auto &Entry = FrameEscapeInfo[Fn];
4946     Entry.second = unsigned(
4947         std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
4948     break;
4949   }
4950 
4951   case Intrinsic::experimental_gc_statepoint:
4952     if (auto *CI = dyn_cast<CallInst>(&Call))
4953       Assert(!CI->isInlineAsm(),
4954              "gc.statepoint support for inline assembly unimplemented", CI);
4955     Assert(Call.getParent()->getParent()->hasGC(),
4956            "Enclosing function does not use GC.", Call);
4957 
4958     verifyStatepoint(Call);
4959     break;
4960   case Intrinsic::experimental_gc_result: {
4961     Assert(Call.getParent()->getParent()->hasGC(),
4962            "Enclosing function does not use GC.", Call);
4963     // Are we tied to a statepoint properly?
4964     const auto *StatepointCall = dyn_cast<CallBase>(Call.getArgOperand(0));
4965     const Function *StatepointFn =
4966         StatepointCall ? StatepointCall->getCalledFunction() : nullptr;
4967     Assert(StatepointFn && StatepointFn->isDeclaration() &&
4968                StatepointFn->getIntrinsicID() ==
4969                    Intrinsic::experimental_gc_statepoint,
4970            "gc.result operand #1 must be from a statepoint", Call,
4971            Call.getArgOperand(0));
4972 
4973     // Assert that result type matches wrapped callee.
4974     const Value *Target = StatepointCall->getArgOperand(2);
4975     auto *PT = cast<PointerType>(Target->getType());
4976     auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
4977     Assert(Call.getType() == TargetFuncType->getReturnType(),
4978            "gc.result result type does not match wrapped callee", Call);
4979     break;
4980   }
4981   case Intrinsic::experimental_gc_relocate: {
4982     Assert(Call.arg_size() == 3, "wrong number of arguments", Call);
4983 
4984     Assert(isa<PointerType>(Call.getType()->getScalarType()),
4985            "gc.relocate must return a pointer or a vector of pointers", Call);
4986 
4987     // Check that this relocate is correctly tied to the statepoint
4988 
4989     // This is case for relocate on the unwinding path of an invoke statepoint
4990     if (LandingPadInst *LandingPad =
4991             dyn_cast<LandingPadInst>(Call.getArgOperand(0))) {
4992 
4993       const BasicBlock *InvokeBB =
4994           LandingPad->getParent()->getUniquePredecessor();
4995 
4996       // Landingpad relocates should have only one predecessor with invoke
4997       // statepoint terminator
4998       Assert(InvokeBB, "safepoints should have unique landingpads",
4999              LandingPad->getParent());
5000       Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
5001              InvokeBB);
5002       Assert(isa<GCStatepointInst>(InvokeBB->getTerminator()),
5003              "gc relocate should be linked to a statepoint", InvokeBB);
5004     } else {
5005       // In all other cases relocate should be tied to the statepoint directly.
5006       // This covers relocates on a normal return path of invoke statepoint and
5007       // relocates of a call statepoint.
5008       auto Token = Call.getArgOperand(0);
5009       Assert(isa<GCStatepointInst>(Token),
5010              "gc relocate is incorrectly tied to the statepoint", Call, Token);
5011     }
5012 
5013     // Verify rest of the relocate arguments.
5014     const CallBase &StatepointCall =
5015       *cast<GCRelocateInst>(Call).getStatepoint();
5016 
5017     // Both the base and derived must be piped through the safepoint.
5018     Value *Base = Call.getArgOperand(1);
5019     Assert(isa<ConstantInt>(Base),
5020            "gc.relocate operand #2 must be integer offset", Call);
5021 
5022     Value *Derived = Call.getArgOperand(2);
5023     Assert(isa<ConstantInt>(Derived),
5024            "gc.relocate operand #3 must be integer offset", Call);
5025 
5026     const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
5027     const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
5028 
5029     // Check the bounds
5030     if (auto Opt = StatepointCall.getOperandBundle(LLVMContext::OB_gc_live)) {
5031       Assert(BaseIndex < Opt->Inputs.size(),
5032              "gc.relocate: statepoint base index out of bounds", Call);
5033       Assert(DerivedIndex < Opt->Inputs.size(),
5034              "gc.relocate: statepoint derived index out of bounds", Call);
5035     }
5036 
5037     // Relocated value must be either a pointer type or vector-of-pointer type,
5038     // but gc_relocate does not need to return the same pointer type as the
5039     // relocated pointer. It can be casted to the correct type later if it's
5040     // desired. However, they must have the same address space and 'vectorness'
5041     GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
5042     Assert(Relocate.getDerivedPtr()->getType()->isPtrOrPtrVectorTy(),
5043            "gc.relocate: relocated value must be a gc pointer", Call);
5044 
5045     auto ResultType = Call.getType();
5046     auto DerivedType = Relocate.getDerivedPtr()->getType();
5047     Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(),
5048            "gc.relocate: vector relocates to vector and pointer to pointer",
5049            Call);
5050     Assert(
5051         ResultType->getPointerAddressSpace() ==
5052             DerivedType->getPointerAddressSpace(),
5053         "gc.relocate: relocating a pointer shouldn't change its address space",
5054         Call);
5055     break;
5056   }
5057   case Intrinsic::eh_exceptioncode:
5058   case Intrinsic::eh_exceptionpointer: {
5059     Assert(isa<CatchPadInst>(Call.getArgOperand(0)),
5060            "eh.exceptionpointer argument must be a catchpad", Call);
5061     break;
5062   }
5063   case Intrinsic::get_active_lane_mask: {
5064     Assert(Call.getType()->isVectorTy(), "get_active_lane_mask: must return a "
5065            "vector", Call);
5066     auto *ElemTy = Call.getType()->getScalarType();
5067     Assert(ElemTy->isIntegerTy(1), "get_active_lane_mask: element type is not "
5068            "i1", Call);
5069     break;
5070   }
5071   case Intrinsic::masked_load: {
5072     Assert(Call.getType()->isVectorTy(), "masked_load: must return a vector",
5073            Call);
5074 
5075     Value *Ptr = Call.getArgOperand(0);
5076     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(1));
5077     Value *Mask = Call.getArgOperand(2);
5078     Value *PassThru = Call.getArgOperand(3);
5079     Assert(Mask->getType()->isVectorTy(), "masked_load: mask must be vector",
5080            Call);
5081     Assert(Alignment->getValue().isPowerOf2(),
5082            "masked_load: alignment must be a power of 2", Call);
5083 
5084     PointerType *PtrTy = cast<PointerType>(Ptr->getType());
5085     Assert(PtrTy->isOpaqueOrPointeeTypeMatches(Call.getType()),
5086            "masked_load: return must match pointer type", Call);
5087     Assert(PassThru->getType() == Call.getType(),
5088            "masked_load: pass through and return type must match", Call);
5089     Assert(cast<VectorType>(Mask->getType())->getElementCount() ==
5090                cast<VectorType>(Call.getType())->getElementCount(),
5091            "masked_load: vector mask must be same length as return", Call);
5092     break;
5093   }
5094   case Intrinsic::masked_store: {
5095     Value *Val = Call.getArgOperand(0);
5096     Value *Ptr = Call.getArgOperand(1);
5097     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(2));
5098     Value *Mask = Call.getArgOperand(3);
5099     Assert(Mask->getType()->isVectorTy(), "masked_store: mask must be vector",
5100            Call);
5101     Assert(Alignment->getValue().isPowerOf2(),
5102            "masked_store: alignment must be a power of 2", Call);
5103 
5104     PointerType *PtrTy = cast<PointerType>(Ptr->getType());
5105     Assert(PtrTy->isOpaqueOrPointeeTypeMatches(Val->getType()),
5106            "masked_store: storee must match pointer type", Call);
5107     Assert(cast<VectorType>(Mask->getType())->getElementCount() ==
5108                cast<VectorType>(Val->getType())->getElementCount(),
5109            "masked_store: vector mask must be same length as value", Call);
5110     break;
5111   }
5112 
5113   case Intrinsic::masked_gather: {
5114     const APInt &Alignment =
5115         cast<ConstantInt>(Call.getArgOperand(1))->getValue();
5116     Assert(Alignment.isZero() || Alignment.isPowerOf2(),
5117            "masked_gather: alignment must be 0 or a power of 2", Call);
5118     break;
5119   }
5120   case Intrinsic::masked_scatter: {
5121     const APInt &Alignment =
5122         cast<ConstantInt>(Call.getArgOperand(2))->getValue();
5123     Assert(Alignment.isZero() || Alignment.isPowerOf2(),
5124            "masked_scatter: alignment must be 0 or a power of 2", Call);
5125     break;
5126   }
5127 
5128   case Intrinsic::experimental_guard: {
5129     Assert(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
5130     Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
5131            "experimental_guard must have exactly one "
5132            "\"deopt\" operand bundle");
5133     break;
5134   }
5135 
5136   case Intrinsic::experimental_deoptimize: {
5137     Assert(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
5138            Call);
5139     Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
5140            "experimental_deoptimize must have exactly one "
5141            "\"deopt\" operand bundle");
5142     Assert(Call.getType() == Call.getFunction()->getReturnType(),
5143            "experimental_deoptimize return type must match caller return type");
5144 
5145     if (isa<CallInst>(Call)) {
5146       auto *RI = dyn_cast<ReturnInst>(Call.getNextNode());
5147       Assert(RI,
5148              "calls to experimental_deoptimize must be followed by a return");
5149 
5150       if (!Call.getType()->isVoidTy() && RI)
5151         Assert(RI->getReturnValue() == &Call,
5152                "calls to experimental_deoptimize must be followed by a return "
5153                "of the value computed by experimental_deoptimize");
5154     }
5155 
5156     break;
5157   }
5158   case Intrinsic::vector_reduce_and:
5159   case Intrinsic::vector_reduce_or:
5160   case Intrinsic::vector_reduce_xor:
5161   case Intrinsic::vector_reduce_add:
5162   case Intrinsic::vector_reduce_mul:
5163   case Intrinsic::vector_reduce_smax:
5164   case Intrinsic::vector_reduce_smin:
5165   case Intrinsic::vector_reduce_umax:
5166   case Intrinsic::vector_reduce_umin: {
5167     Type *ArgTy = Call.getArgOperand(0)->getType();
5168     Assert(ArgTy->isIntOrIntVectorTy() && ArgTy->isVectorTy(),
5169            "Intrinsic has incorrect argument type!");
5170     break;
5171   }
5172   case Intrinsic::vector_reduce_fmax:
5173   case Intrinsic::vector_reduce_fmin: {
5174     Type *ArgTy = Call.getArgOperand(0)->getType();
5175     Assert(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
5176            "Intrinsic has incorrect argument type!");
5177     break;
5178   }
5179   case Intrinsic::vector_reduce_fadd:
5180   case Intrinsic::vector_reduce_fmul: {
5181     // Unlike the other reductions, the first argument is a start value. The
5182     // second argument is the vector to be reduced.
5183     Type *ArgTy = Call.getArgOperand(1)->getType();
5184     Assert(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
5185            "Intrinsic has incorrect argument type!");
5186     break;
5187   }
5188   case Intrinsic::smul_fix:
5189   case Intrinsic::smul_fix_sat:
5190   case Intrinsic::umul_fix:
5191   case Intrinsic::umul_fix_sat:
5192   case Intrinsic::sdiv_fix:
5193   case Intrinsic::sdiv_fix_sat:
5194   case Intrinsic::udiv_fix:
5195   case Intrinsic::udiv_fix_sat: {
5196     Value *Op1 = Call.getArgOperand(0);
5197     Value *Op2 = Call.getArgOperand(1);
5198     Assert(Op1->getType()->isIntOrIntVectorTy(),
5199            "first operand of [us][mul|div]_fix[_sat] must be an int type or "
5200            "vector of ints");
5201     Assert(Op2->getType()->isIntOrIntVectorTy(),
5202            "second operand of [us][mul|div]_fix[_sat] must be an int type or "
5203            "vector of ints");
5204 
5205     auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
5206     Assert(Op3->getType()->getBitWidth() <= 32,
5207            "third argument of [us][mul|div]_fix[_sat] must fit within 32 bits");
5208 
5209     if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
5210         ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
5211       Assert(
5212           Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
5213           "the scale of s[mul|div]_fix[_sat] must be less than the width of "
5214           "the operands");
5215     } else {
5216       Assert(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
5217              "the scale of u[mul|div]_fix[_sat] must be less than or equal "
5218              "to the width of the operands");
5219     }
5220     break;
5221   }
5222   case Intrinsic::lround:
5223   case Intrinsic::llround:
5224   case Intrinsic::lrint:
5225   case Intrinsic::llrint: {
5226     Type *ValTy = Call.getArgOperand(0)->getType();
5227     Type *ResultTy = Call.getType();
5228     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
5229            "Intrinsic does not support vectors", &Call);
5230     break;
5231   }
5232   case Intrinsic::bswap: {
5233     Type *Ty = Call.getType();
5234     unsigned Size = Ty->getScalarSizeInBits();
5235     Assert(Size % 16 == 0, "bswap must be an even number of bytes", &Call);
5236     break;
5237   }
5238   case Intrinsic::invariant_start: {
5239     ConstantInt *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0));
5240     Assert(InvariantSize &&
5241                (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
5242            "invariant_start parameter must be -1, 0 or a positive number",
5243            &Call);
5244     break;
5245   }
5246   case Intrinsic::matrix_multiply:
5247   case Intrinsic::matrix_transpose:
5248   case Intrinsic::matrix_column_major_load:
5249   case Intrinsic::matrix_column_major_store: {
5250     Function *IF = Call.getCalledFunction();
5251     ConstantInt *Stride = nullptr;
5252     ConstantInt *NumRows;
5253     ConstantInt *NumColumns;
5254     VectorType *ResultTy;
5255     Type *Op0ElemTy = nullptr;
5256     Type *Op1ElemTy = nullptr;
5257     switch (ID) {
5258     case Intrinsic::matrix_multiply:
5259       NumRows = cast<ConstantInt>(Call.getArgOperand(2));
5260       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
5261       ResultTy = cast<VectorType>(Call.getType());
5262       Op0ElemTy =
5263           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
5264       Op1ElemTy =
5265           cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType();
5266       break;
5267     case Intrinsic::matrix_transpose:
5268       NumRows = cast<ConstantInt>(Call.getArgOperand(1));
5269       NumColumns = cast<ConstantInt>(Call.getArgOperand(2));
5270       ResultTy = cast<VectorType>(Call.getType());
5271       Op0ElemTy =
5272           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
5273       break;
5274     case Intrinsic::matrix_column_major_load: {
5275       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(1));
5276       NumRows = cast<ConstantInt>(Call.getArgOperand(3));
5277       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
5278       ResultTy = cast<VectorType>(Call.getType());
5279 
5280       PointerType *Op0PtrTy =
5281           cast<PointerType>(Call.getArgOperand(0)->getType());
5282       if (!Op0PtrTy->isOpaque())
5283         Op0ElemTy = Op0PtrTy->getElementType();
5284       break;
5285     }
5286     case Intrinsic::matrix_column_major_store: {
5287       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(2));
5288       NumRows = cast<ConstantInt>(Call.getArgOperand(4));
5289       NumColumns = cast<ConstantInt>(Call.getArgOperand(5));
5290       ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType());
5291       Op0ElemTy =
5292           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
5293 
5294       PointerType *Op1PtrTy =
5295           cast<PointerType>(Call.getArgOperand(1)->getType());
5296       if (!Op1PtrTy->isOpaque())
5297         Op1ElemTy = Op1PtrTy->getElementType();
5298       break;
5299     }
5300     default:
5301       llvm_unreachable("unexpected intrinsic");
5302     }
5303 
5304     Assert(ResultTy->getElementType()->isIntegerTy() ||
5305            ResultTy->getElementType()->isFloatingPointTy(),
5306            "Result type must be an integer or floating-point type!", IF);
5307 
5308     if (Op0ElemTy)
5309       Assert(ResultTy->getElementType() == Op0ElemTy,
5310              "Vector element type mismatch of the result and first operand "
5311              "vector!", IF);
5312 
5313     if (Op1ElemTy)
5314       Assert(ResultTy->getElementType() == Op1ElemTy,
5315              "Vector element type mismatch of the result and second operand "
5316              "vector!", IF);
5317 
5318     Assert(cast<FixedVectorType>(ResultTy)->getNumElements() ==
5319                NumRows->getZExtValue() * NumColumns->getZExtValue(),
5320            "Result of a matrix operation does not fit in the returned vector!");
5321 
5322     if (Stride)
5323       Assert(Stride->getZExtValue() >= NumRows->getZExtValue(),
5324              "Stride must be greater or equal than the number of rows!", IF);
5325 
5326     break;
5327   }
5328   case Intrinsic::experimental_stepvector: {
5329     VectorType *VecTy = dyn_cast<VectorType>(Call.getType());
5330     Assert(VecTy && VecTy->getScalarType()->isIntegerTy() &&
5331                VecTy->getScalarSizeInBits() >= 8,
5332            "experimental_stepvector only supported for vectors of integers "
5333            "with a bitwidth of at least 8.",
5334            &Call);
5335     break;
5336   }
5337   case Intrinsic::experimental_vector_insert: {
5338     Value *Vec = Call.getArgOperand(0);
5339     Value *SubVec = Call.getArgOperand(1);
5340     Value *Idx = Call.getArgOperand(2);
5341     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
5342 
5343     VectorType *VecTy = cast<VectorType>(Vec->getType());
5344     VectorType *SubVecTy = cast<VectorType>(SubVec->getType());
5345 
5346     ElementCount VecEC = VecTy->getElementCount();
5347     ElementCount SubVecEC = SubVecTy->getElementCount();
5348     Assert(VecTy->getElementType() == SubVecTy->getElementType(),
5349            "experimental_vector_insert parameters must have the same element "
5350            "type.",
5351            &Call);
5352     Assert(IdxN % SubVecEC.getKnownMinValue() == 0,
5353            "experimental_vector_insert index must be a constant multiple of "
5354            "the subvector's known minimum vector length.");
5355 
5356     // If this insertion is not the 'mixed' case where a fixed vector is
5357     // inserted into a scalable vector, ensure that the insertion of the
5358     // subvector does not overrun the parent vector.
5359     if (VecEC.isScalable() == SubVecEC.isScalable()) {
5360       Assert(
5361           IdxN < VecEC.getKnownMinValue() &&
5362               IdxN + SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
5363           "subvector operand of experimental_vector_insert would overrun the "
5364           "vector being inserted into.");
5365     }
5366     break;
5367   }
5368   case Intrinsic::experimental_vector_extract: {
5369     Value *Vec = Call.getArgOperand(0);
5370     Value *Idx = Call.getArgOperand(1);
5371     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
5372 
5373     VectorType *ResultTy = cast<VectorType>(Call.getType());
5374     VectorType *VecTy = cast<VectorType>(Vec->getType());
5375 
5376     ElementCount VecEC = VecTy->getElementCount();
5377     ElementCount ResultEC = ResultTy->getElementCount();
5378 
5379     Assert(ResultTy->getElementType() == VecTy->getElementType(),
5380            "experimental_vector_extract result must have the same element "
5381            "type as the input vector.",
5382            &Call);
5383     Assert(IdxN % ResultEC.getKnownMinValue() == 0,
5384            "experimental_vector_extract index must be a constant multiple of "
5385            "the result type's known minimum vector length.");
5386 
5387     // If this extraction is not the 'mixed' case where a fixed vector is is
5388     // extracted from a scalable vector, ensure that the extraction does not
5389     // overrun the parent vector.
5390     if (VecEC.isScalable() == ResultEC.isScalable()) {
5391       Assert(IdxN < VecEC.getKnownMinValue() &&
5392                  IdxN + ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
5393              "experimental_vector_extract would overrun.");
5394     }
5395     break;
5396   }
5397   case Intrinsic::experimental_noalias_scope_decl: {
5398     NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call));
5399     break;
5400   }
5401   case Intrinsic::preserve_array_access_index:
5402   case Intrinsic::preserve_struct_access_index: {
5403     Type *ElemTy = Call.getAttributes().getParamElementType(0);
5404     Assert(ElemTy,
5405            "Intrinsic requires elementtype attribute on first argument.",
5406            &Call);
5407     break;
5408   }
5409   };
5410 }
5411 
5412 /// Carefully grab the subprogram from a local scope.
5413 ///
5414 /// This carefully grabs the subprogram from a local scope, avoiding the
5415 /// built-in assertions that would typically fire.
5416 static DISubprogram *getSubprogram(Metadata *LocalScope) {
5417   if (!LocalScope)
5418     return nullptr;
5419 
5420   if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
5421     return SP;
5422 
5423   if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
5424     return getSubprogram(LB->getRawScope());
5425 
5426   // Just return null; broken scope chains are checked elsewhere.
5427   assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
5428   return nullptr;
5429 }
5430 
5431 void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
5432   unsigned NumOperands;
5433   bool HasRoundingMD;
5434   switch (FPI.getIntrinsicID()) {
5435 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
5436   case Intrinsic::INTRINSIC:                                                   \
5437     NumOperands = NARG;                                                        \
5438     HasRoundingMD = ROUND_MODE;                                                \
5439     break;
5440 #include "llvm/IR/ConstrainedOps.def"
5441   default:
5442     llvm_unreachable("Invalid constrained FP intrinsic!");
5443   }
5444   NumOperands += (1 + HasRoundingMD);
5445   // Compare intrinsics carry an extra predicate metadata operand.
5446   if (isa<ConstrainedFPCmpIntrinsic>(FPI))
5447     NumOperands += 1;
5448   Assert((FPI.arg_size() == NumOperands),
5449          "invalid arguments for constrained FP intrinsic", &FPI);
5450 
5451   switch (FPI.getIntrinsicID()) {
5452   case Intrinsic::experimental_constrained_lrint:
5453   case Intrinsic::experimental_constrained_llrint: {
5454     Type *ValTy = FPI.getArgOperand(0)->getType();
5455     Type *ResultTy = FPI.getType();
5456     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
5457            "Intrinsic does not support vectors", &FPI);
5458   }
5459     break;
5460 
5461   case Intrinsic::experimental_constrained_lround:
5462   case Intrinsic::experimental_constrained_llround: {
5463     Type *ValTy = FPI.getArgOperand(0)->getType();
5464     Type *ResultTy = FPI.getType();
5465     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
5466            "Intrinsic does not support vectors", &FPI);
5467     break;
5468   }
5469 
5470   case Intrinsic::experimental_constrained_fcmp:
5471   case Intrinsic::experimental_constrained_fcmps: {
5472     auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate();
5473     Assert(CmpInst::isFPPredicate(Pred),
5474            "invalid predicate for constrained FP comparison intrinsic", &FPI);
5475     break;
5476   }
5477 
5478   case Intrinsic::experimental_constrained_fptosi:
5479   case Intrinsic::experimental_constrained_fptoui: {
5480     Value *Operand = FPI.getArgOperand(0);
5481     uint64_t NumSrcElem = 0;
5482     Assert(Operand->getType()->isFPOrFPVectorTy(),
5483            "Intrinsic first argument must be floating point", &FPI);
5484     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5485       NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements();
5486     }
5487 
5488     Operand = &FPI;
5489     Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(),
5490            "Intrinsic first argument and result disagree on vector use", &FPI);
5491     Assert(Operand->getType()->isIntOrIntVectorTy(),
5492            "Intrinsic result must be an integer", &FPI);
5493     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5494       Assert(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(),
5495              "Intrinsic first argument and result vector lengths must be equal",
5496              &FPI);
5497     }
5498   }
5499     break;
5500 
5501   case Intrinsic::experimental_constrained_sitofp:
5502   case Intrinsic::experimental_constrained_uitofp: {
5503     Value *Operand = FPI.getArgOperand(0);
5504     uint64_t NumSrcElem = 0;
5505     Assert(Operand->getType()->isIntOrIntVectorTy(),
5506            "Intrinsic first argument must be integer", &FPI);
5507     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5508       NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements();
5509     }
5510 
5511     Operand = &FPI;
5512     Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(),
5513            "Intrinsic first argument and result disagree on vector use", &FPI);
5514     Assert(Operand->getType()->isFPOrFPVectorTy(),
5515            "Intrinsic result must be a floating point", &FPI);
5516     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5517       Assert(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(),
5518              "Intrinsic first argument and result vector lengths must be equal",
5519              &FPI);
5520     }
5521   } break;
5522 
5523   case Intrinsic::experimental_constrained_fptrunc:
5524   case Intrinsic::experimental_constrained_fpext: {
5525     Value *Operand = FPI.getArgOperand(0);
5526     Type *OperandTy = Operand->getType();
5527     Value *Result = &FPI;
5528     Type *ResultTy = Result->getType();
5529     Assert(OperandTy->isFPOrFPVectorTy(),
5530            "Intrinsic first argument must be FP or FP vector", &FPI);
5531     Assert(ResultTy->isFPOrFPVectorTy(),
5532            "Intrinsic result must be FP or FP vector", &FPI);
5533     Assert(OperandTy->isVectorTy() == ResultTy->isVectorTy(),
5534            "Intrinsic first argument and result disagree on vector use", &FPI);
5535     if (OperandTy->isVectorTy()) {
5536       Assert(cast<FixedVectorType>(OperandTy)->getNumElements() ==
5537                  cast<FixedVectorType>(ResultTy)->getNumElements(),
5538              "Intrinsic first argument and result vector lengths must be equal",
5539              &FPI);
5540     }
5541     if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
5542       Assert(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
5543              "Intrinsic first argument's type must be larger than result type",
5544              &FPI);
5545     } else {
5546       Assert(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
5547              "Intrinsic first argument's type must be smaller than result type",
5548              &FPI);
5549     }
5550   }
5551     break;
5552 
5553   default:
5554     break;
5555   }
5556 
5557   // If a non-metadata argument is passed in a metadata slot then the
5558   // error will be caught earlier when the incorrect argument doesn't
5559   // match the specification in the intrinsic call table. Thus, no
5560   // argument type check is needed here.
5561 
5562   Assert(FPI.getExceptionBehavior().hasValue(),
5563          "invalid exception behavior argument", &FPI);
5564   if (HasRoundingMD) {
5565     Assert(FPI.getRoundingMode().hasValue(),
5566            "invalid rounding mode argument", &FPI);
5567   }
5568 }
5569 
5570 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) {
5571   auto *MD = DII.getRawLocation();
5572   AssertDI(isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) ||
5573                (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
5574            "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
5575   AssertDI(isa<DILocalVariable>(DII.getRawVariable()),
5576          "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
5577          DII.getRawVariable());
5578   AssertDI(isa<DIExpression>(DII.getRawExpression()),
5579          "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
5580          DII.getRawExpression());
5581 
5582   // Ignore broken !dbg attachments; they're checked elsewhere.
5583   if (MDNode *N = DII.getDebugLoc().getAsMDNode())
5584     if (!isa<DILocation>(N))
5585       return;
5586 
5587   BasicBlock *BB = DII.getParent();
5588   Function *F = BB ? BB->getParent() : nullptr;
5589 
5590   // The scopes for variables and !dbg attachments must agree.
5591   DILocalVariable *Var = DII.getVariable();
5592   DILocation *Loc = DII.getDebugLoc();
5593   AssertDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
5594            &DII, BB, F);
5595 
5596   DISubprogram *VarSP = getSubprogram(Var->getRawScope());
5597   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
5598   if (!VarSP || !LocSP)
5599     return; // Broken scope chains are checked elsewhere.
5600 
5601   AssertDI(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
5602                                " variable and !dbg attachment",
5603            &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
5604            Loc->getScope()->getSubprogram());
5605 
5606   // This check is redundant with one in visitLocalVariable().
5607   AssertDI(isType(Var->getRawType()), "invalid type ref", Var,
5608            Var->getRawType());
5609   verifyFnArgs(DII);
5610 }
5611 
5612 void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) {
5613   AssertDI(isa<DILabel>(DLI.getRawLabel()),
5614          "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI,
5615          DLI.getRawLabel());
5616 
5617   // Ignore broken !dbg attachments; they're checked elsewhere.
5618   if (MDNode *N = DLI.getDebugLoc().getAsMDNode())
5619     if (!isa<DILocation>(N))
5620       return;
5621 
5622   BasicBlock *BB = DLI.getParent();
5623   Function *F = BB ? BB->getParent() : nullptr;
5624 
5625   // The scopes for variables and !dbg attachments must agree.
5626   DILabel *Label = DLI.getLabel();
5627   DILocation *Loc = DLI.getDebugLoc();
5628   Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
5629          &DLI, BB, F);
5630 
5631   DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
5632   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
5633   if (!LabelSP || !LocSP)
5634     return;
5635 
5636   AssertDI(LabelSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
5637                              " label and !dbg attachment",
5638            &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
5639            Loc->getScope()->getSubprogram());
5640 }
5641 
5642 void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) {
5643   DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable());
5644   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
5645 
5646   // We don't know whether this intrinsic verified correctly.
5647   if (!V || !E || !E->isValid())
5648     return;
5649 
5650   // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
5651   auto Fragment = E->getFragmentInfo();
5652   if (!Fragment)
5653     return;
5654 
5655   // The frontend helps out GDB by emitting the members of local anonymous
5656   // unions as artificial local variables with shared storage. When SROA splits
5657   // the storage for artificial local variables that are smaller than the entire
5658   // union, the overhang piece will be outside of the allotted space for the
5659   // variable and this check fails.
5660   // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
5661   if (V->isArtificial())
5662     return;
5663 
5664   verifyFragmentExpression(*V, *Fragment, &I);
5665 }
5666 
5667 template <typename ValueOrMetadata>
5668 void Verifier::verifyFragmentExpression(const DIVariable &V,
5669                                         DIExpression::FragmentInfo Fragment,
5670                                         ValueOrMetadata *Desc) {
5671   // If there's no size, the type is broken, but that should be checked
5672   // elsewhere.
5673   auto VarSize = V.getSizeInBits();
5674   if (!VarSize)
5675     return;
5676 
5677   unsigned FragSize = Fragment.SizeInBits;
5678   unsigned FragOffset = Fragment.OffsetInBits;
5679   AssertDI(FragSize + FragOffset <= *VarSize,
5680          "fragment is larger than or outside of variable", Desc, &V);
5681   AssertDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
5682 }
5683 
5684 void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) {
5685   // This function does not take the scope of noninlined function arguments into
5686   // account. Don't run it if current function is nodebug, because it may
5687   // contain inlined debug intrinsics.
5688   if (!HasDebugInfo)
5689     return;
5690 
5691   // For performance reasons only check non-inlined ones.
5692   if (I.getDebugLoc()->getInlinedAt())
5693     return;
5694 
5695   DILocalVariable *Var = I.getVariable();
5696   AssertDI(Var, "dbg intrinsic without variable");
5697 
5698   unsigned ArgNo = Var->getArg();
5699   if (!ArgNo)
5700     return;
5701 
5702   // Verify there are no duplicate function argument debug info entries.
5703   // These will cause hard-to-debug assertions in the DWARF backend.
5704   if (DebugFnArgs.size() < ArgNo)
5705     DebugFnArgs.resize(ArgNo, nullptr);
5706 
5707   auto *Prev = DebugFnArgs[ArgNo - 1];
5708   DebugFnArgs[ArgNo - 1] = Var;
5709   AssertDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I,
5710            Prev, Var);
5711 }
5712 
5713 void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) {
5714   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
5715 
5716   // We don't know whether this intrinsic verified correctly.
5717   if (!E || !E->isValid())
5718     return;
5719 
5720   AssertDI(!E->isEntryValue(), "Entry values are only allowed in MIR", &I);
5721 }
5722 
5723 void Verifier::verifyCompileUnits() {
5724   // When more than one Module is imported into the same context, such as during
5725   // an LTO build before linking the modules, ODR type uniquing may cause types
5726   // to point to a different CU. This check does not make sense in this case.
5727   if (M.getContext().isODRUniquingDebugTypes())
5728     return;
5729   auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
5730   SmallPtrSet<const Metadata *, 2> Listed;
5731   if (CUs)
5732     Listed.insert(CUs->op_begin(), CUs->op_end());
5733   for (auto *CU : CUVisited)
5734     AssertDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
5735   CUVisited.clear();
5736 }
5737 
5738 void Verifier::verifyDeoptimizeCallingConvs() {
5739   if (DeoptimizeDeclarations.empty())
5740     return;
5741 
5742   const Function *First = DeoptimizeDeclarations[0];
5743   for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) {
5744     Assert(First->getCallingConv() == F->getCallingConv(),
5745            "All llvm.experimental.deoptimize declarations must have the same "
5746            "calling convention",
5747            First, F);
5748   }
5749 }
5750 
5751 void Verifier::verifyAttachedCallBundle(const CallBase &Call,
5752                                         const OperandBundleUse &BU) {
5753   FunctionType *FTy = Call.getFunctionType();
5754 
5755   Assert((FTy->getReturnType()->isPointerTy() ||
5756           (Call.doesNotReturn() && FTy->getReturnType()->isVoidTy())),
5757          "a call with operand bundle \"clang.arc.attachedcall\" must call a "
5758          "function returning a pointer or a non-returning function that has a "
5759          "void return type",
5760          Call);
5761 
5762   Assert((BU.Inputs.empty() ||
5763           (BU.Inputs.size() == 1 && isa<Function>(BU.Inputs.front()))),
5764          "operand bundle \"clang.arc.attachedcall\" can take either no "
5765          "arguments or one function as an argument",
5766          Call);
5767 
5768   if (BU.Inputs.empty())
5769     return;
5770 
5771   auto *Fn = cast<Function>(BU.Inputs.front());
5772   Intrinsic::ID IID = Fn->getIntrinsicID();
5773 
5774   if (IID) {
5775     Assert((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
5776             IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
5777            "invalid function argument", Call);
5778   } else {
5779     StringRef FnName = Fn->getName();
5780     Assert((FnName == "objc_retainAutoreleasedReturnValue" ||
5781             FnName == "objc_unsafeClaimAutoreleasedReturnValue"),
5782            "invalid function argument", Call);
5783   }
5784 }
5785 
5786 void Verifier::verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F) {
5787   bool HasSource = F.getSource().hasValue();
5788   if (!HasSourceDebugInfo.count(&U))
5789     HasSourceDebugInfo[&U] = HasSource;
5790   AssertDI(HasSource == HasSourceDebugInfo[&U],
5791            "inconsistent use of embedded source");
5792 }
5793 
5794 void Verifier::verifyNoAliasScopeDecl() {
5795   if (NoAliasScopeDecls.empty())
5796     return;
5797 
5798   // only a single scope must be declared at a time.
5799   for (auto *II : NoAliasScopeDecls) {
5800     assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
5801            "Not a llvm.experimental.noalias.scope.decl ?");
5802     const auto *ScopeListMV = dyn_cast<MetadataAsValue>(
5803         II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
5804     Assert(ScopeListMV != nullptr,
5805            "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
5806            "argument",
5807            II);
5808 
5809     const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata());
5810     Assert(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode",
5811            II);
5812     Assert(ScopeListMD->getNumOperands() == 1,
5813            "!id.scope.list must point to a list with a single scope", II);
5814     visitAliasScopeListMetadata(ScopeListMD);
5815   }
5816 
5817   // Only check the domination rule when requested. Once all passes have been
5818   // adapted this option can go away.
5819   if (!VerifyNoAliasScopeDomination)
5820     return;
5821 
5822   // Now sort the intrinsics based on the scope MDNode so that declarations of
5823   // the same scopes are next to each other.
5824   auto GetScope = [](IntrinsicInst *II) {
5825     const auto *ScopeListMV = cast<MetadataAsValue>(
5826         II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
5827     return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
5828   };
5829 
5830   // We are sorting on MDNode pointers here. For valid input IR this is ok.
5831   // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
5832   auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
5833     return GetScope(Lhs) < GetScope(Rhs);
5834   };
5835 
5836   llvm::sort(NoAliasScopeDecls, Compare);
5837 
5838   // Go over the intrinsics and check that for the same scope, they are not
5839   // dominating each other.
5840   auto ItCurrent = NoAliasScopeDecls.begin();
5841   while (ItCurrent != NoAliasScopeDecls.end()) {
5842     auto CurScope = GetScope(*ItCurrent);
5843     auto ItNext = ItCurrent;
5844     do {
5845       ++ItNext;
5846     } while (ItNext != NoAliasScopeDecls.end() &&
5847              GetScope(*ItNext) == CurScope);
5848 
5849     // [ItCurrent, ItNext) represents the declarations for the same scope.
5850     // Ensure they are not dominating each other.. but only if it is not too
5851     // expensive.
5852     if (ItNext - ItCurrent < 32)
5853       for (auto *I : llvm::make_range(ItCurrent, ItNext))
5854         for (auto *J : llvm::make_range(ItCurrent, ItNext))
5855           if (I != J)
5856             Assert(!DT.dominates(I, J),
5857                    "llvm.experimental.noalias.scope.decl dominates another one "
5858                    "with the same scope",
5859                    I);
5860     ItCurrent = ItNext;
5861   }
5862 }
5863 
5864 //===----------------------------------------------------------------------===//
5865 //  Implement the public interfaces to this file...
5866 //===----------------------------------------------------------------------===//
5867 
5868 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
5869   Function &F = const_cast<Function &>(f);
5870 
5871   // Don't use a raw_null_ostream.  Printing IR is expensive.
5872   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
5873 
5874   // Note that this function's return value is inverted from what you would
5875   // expect of a function called "verify".
5876   return !V.verify(F);
5877 }
5878 
5879 bool llvm::verifyModule(const Module &M, raw_ostream *OS,
5880                         bool *BrokenDebugInfo) {
5881   // Don't use a raw_null_ostream.  Printing IR is expensive.
5882   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
5883 
5884   bool Broken = false;
5885   for (const Function &F : M)
5886     Broken |= !V.verify(F);
5887 
5888   Broken |= !V.verify();
5889   if (BrokenDebugInfo)
5890     *BrokenDebugInfo = V.hasBrokenDebugInfo();
5891   // Note that this function's return value is inverted from what you would
5892   // expect of a function called "verify".
5893   return Broken;
5894 }
5895 
5896 namespace {
5897 
5898 struct VerifierLegacyPass : public FunctionPass {
5899   static char ID;
5900 
5901   std::unique_ptr<Verifier> V;
5902   bool FatalErrors = true;
5903 
5904   VerifierLegacyPass() : FunctionPass(ID) {
5905     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
5906   }
5907   explicit VerifierLegacyPass(bool FatalErrors)
5908       : FunctionPass(ID),
5909         FatalErrors(FatalErrors) {
5910     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
5911   }
5912 
5913   bool doInitialization(Module &M) override {
5914     V = std::make_unique<Verifier>(
5915         &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
5916     return false;
5917   }
5918 
5919   bool runOnFunction(Function &F) override {
5920     if (!V->verify(F) && FatalErrors) {
5921       errs() << "in function " << F.getName() << '\n';
5922       report_fatal_error("Broken function found, compilation aborted!");
5923     }
5924     return false;
5925   }
5926 
5927   bool doFinalization(Module &M) override {
5928     bool HasErrors = false;
5929     for (Function &F : M)
5930       if (F.isDeclaration())
5931         HasErrors |= !V->verify(F);
5932 
5933     HasErrors |= !V->verify();
5934     if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
5935       report_fatal_error("Broken module found, compilation aborted!");
5936     return false;
5937   }
5938 
5939   void getAnalysisUsage(AnalysisUsage &AU) const override {
5940     AU.setPreservesAll();
5941   }
5942 };
5943 
5944 } // end anonymous namespace
5945 
5946 /// Helper to issue failure from the TBAA verification
5947 template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
5948   if (Diagnostic)
5949     return Diagnostic->CheckFailed(Args...);
5950 }
5951 
5952 #define AssertTBAA(C, ...)                                                     \
5953   do {                                                                         \
5954     if (!(C)) {                                                                \
5955       CheckFailed(__VA_ARGS__);                                                \
5956       return false;                                                            \
5957     }                                                                          \
5958   } while (false)
5959 
5960 /// Verify that \p BaseNode can be used as the "base type" in the struct-path
5961 /// TBAA scheme.  This means \p BaseNode is either a scalar node, or a
5962 /// struct-type node describing an aggregate data structure (like a struct).
5963 TBAAVerifier::TBAABaseNodeSummary
5964 TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode,
5965                                  bool IsNewFormat) {
5966   if (BaseNode->getNumOperands() < 2) {
5967     CheckFailed("Base nodes must have at least two operands", &I, BaseNode);
5968     return {true, ~0u};
5969   }
5970 
5971   auto Itr = TBAABaseNodes.find(BaseNode);
5972   if (Itr != TBAABaseNodes.end())
5973     return Itr->second;
5974 
5975   auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
5976   auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
5977   (void)InsertResult;
5978   assert(InsertResult.second && "We just checked!");
5979   return Result;
5980 }
5981 
5982 TBAAVerifier::TBAABaseNodeSummary
5983 TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode,
5984                                      bool IsNewFormat) {
5985   const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
5986 
5987   if (BaseNode->getNumOperands() == 2) {
5988     // Scalar nodes can only be accessed at offset 0.
5989     return isValidScalarTBAANode(BaseNode)
5990                ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
5991                : InvalidNode;
5992   }
5993 
5994   if (IsNewFormat) {
5995     if (BaseNode->getNumOperands() % 3 != 0) {
5996       CheckFailed("Access tag nodes must have the number of operands that is a "
5997                   "multiple of 3!", BaseNode);
5998       return InvalidNode;
5999     }
6000   } else {
6001     if (BaseNode->getNumOperands() % 2 != 1) {
6002       CheckFailed("Struct tag nodes must have an odd number of operands!",
6003                   BaseNode);
6004       return InvalidNode;
6005     }
6006   }
6007 
6008   // Check the type size field.
6009   if (IsNewFormat) {
6010     auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
6011         BaseNode->getOperand(1));
6012     if (!TypeSizeNode) {
6013       CheckFailed("Type size nodes must be constants!", &I, BaseNode);
6014       return InvalidNode;
6015     }
6016   }
6017 
6018   // Check the type name field. In the new format it can be anything.
6019   if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
6020     CheckFailed("Struct tag nodes have a string as their first operand",
6021                 BaseNode);
6022     return InvalidNode;
6023   }
6024 
6025   bool Failed = false;
6026 
6027   Optional<APInt> PrevOffset;
6028   unsigned BitWidth = ~0u;
6029 
6030   // We've already checked that BaseNode is not a degenerate root node with one
6031   // operand in \c verifyTBAABaseNode, so this loop should run at least once.
6032   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
6033   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
6034   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
6035            Idx += NumOpsPerField) {
6036     const MDOperand &FieldTy = BaseNode->getOperand(Idx);
6037     const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
6038     if (!isa<MDNode>(FieldTy)) {
6039       CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode);
6040       Failed = true;
6041       continue;
6042     }
6043 
6044     auto *OffsetEntryCI =
6045         mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
6046     if (!OffsetEntryCI) {
6047       CheckFailed("Offset entries must be constants!", &I, BaseNode);
6048       Failed = true;
6049       continue;
6050     }
6051 
6052     if (BitWidth == ~0u)
6053       BitWidth = OffsetEntryCI->getBitWidth();
6054 
6055     if (OffsetEntryCI->getBitWidth() != BitWidth) {
6056       CheckFailed(
6057           "Bitwidth between the offsets and struct type entries must match", &I,
6058           BaseNode);
6059       Failed = true;
6060       continue;
6061     }
6062 
6063     // NB! As far as I can tell, we generate a non-strictly increasing offset
6064     // sequence only from structs that have zero size bit fields.  When
6065     // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
6066     // pick the field lexically the latest in struct type metadata node.  This
6067     // mirrors the actual behavior of the alias analysis implementation.
6068     bool IsAscending =
6069         !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
6070 
6071     if (!IsAscending) {
6072       CheckFailed("Offsets must be increasing!", &I, BaseNode);
6073       Failed = true;
6074     }
6075 
6076     PrevOffset = OffsetEntryCI->getValue();
6077 
6078     if (IsNewFormat) {
6079       auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
6080           BaseNode->getOperand(Idx + 2));
6081       if (!MemberSizeNode) {
6082         CheckFailed("Member size entries must be constants!", &I, BaseNode);
6083         Failed = true;
6084         continue;
6085       }
6086     }
6087   }
6088 
6089   return Failed ? InvalidNode
6090                 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
6091 }
6092 
6093 static bool IsRootTBAANode(const MDNode *MD) {
6094   return MD->getNumOperands() < 2;
6095 }
6096 
6097 static bool IsScalarTBAANodeImpl(const MDNode *MD,
6098                                  SmallPtrSetImpl<const MDNode *> &Visited) {
6099   if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
6100     return false;
6101 
6102   if (!isa<MDString>(MD->getOperand(0)))
6103     return false;
6104 
6105   if (MD->getNumOperands() == 3) {
6106     auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
6107     if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
6108       return false;
6109   }
6110 
6111   auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
6112   return Parent && Visited.insert(Parent).second &&
6113          (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
6114 }
6115 
6116 bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
6117   auto ResultIt = TBAAScalarNodes.find(MD);
6118   if (ResultIt != TBAAScalarNodes.end())
6119     return ResultIt->second;
6120 
6121   SmallPtrSet<const MDNode *, 4> Visited;
6122   bool Result = IsScalarTBAANodeImpl(MD, Visited);
6123   auto InsertResult = TBAAScalarNodes.insert({MD, Result});
6124   (void)InsertResult;
6125   assert(InsertResult.second && "Just checked!");
6126 
6127   return Result;
6128 }
6129 
6130 /// Returns the field node at the offset \p Offset in \p BaseNode.  Update \p
6131 /// Offset in place to be the offset within the field node returned.
6132 ///
6133 /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
6134 MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I,
6135                                                    const MDNode *BaseNode,
6136                                                    APInt &Offset,
6137                                                    bool IsNewFormat) {
6138   assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
6139 
6140   // Scalar nodes have only one possible "field" -- their parent in the access
6141   // hierarchy.  Offset must be zero at this point, but our caller is supposed
6142   // to Assert that.
6143   if (BaseNode->getNumOperands() == 2)
6144     return cast<MDNode>(BaseNode->getOperand(1));
6145 
6146   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
6147   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
6148   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
6149            Idx += NumOpsPerField) {
6150     auto *OffsetEntryCI =
6151         mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
6152     if (OffsetEntryCI->getValue().ugt(Offset)) {
6153       if (Idx == FirstFieldOpNo) {
6154         CheckFailed("Could not find TBAA parent in struct type node", &I,
6155                     BaseNode, &Offset);
6156         return nullptr;
6157       }
6158 
6159       unsigned PrevIdx = Idx - NumOpsPerField;
6160       auto *PrevOffsetEntryCI =
6161           mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
6162       Offset -= PrevOffsetEntryCI->getValue();
6163       return cast<MDNode>(BaseNode->getOperand(PrevIdx));
6164     }
6165   }
6166 
6167   unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
6168   auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
6169       BaseNode->getOperand(LastIdx + 1));
6170   Offset -= LastOffsetEntryCI->getValue();
6171   return cast<MDNode>(BaseNode->getOperand(LastIdx));
6172 }
6173 
6174 static bool isNewFormatTBAATypeNode(llvm::MDNode *Type) {
6175   if (!Type || Type->getNumOperands() < 3)
6176     return false;
6177 
6178   // In the new format type nodes shall have a reference to the parent type as
6179   // its first operand.
6180   return isa_and_nonnull<MDNode>(Type->getOperand(0));
6181 }
6182 
6183 bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) {
6184   AssertTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
6185                  isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) ||
6186                  isa<AtomicCmpXchgInst>(I),
6187              "This instruction shall not have a TBAA access tag!", &I);
6188 
6189   bool IsStructPathTBAA =
6190       isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
6191 
6192   AssertTBAA(
6193       IsStructPathTBAA,
6194       "Old-style TBAA is no longer allowed, use struct-path TBAA instead", &I);
6195 
6196   MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
6197   MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
6198 
6199   bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
6200 
6201   if (IsNewFormat) {
6202     AssertTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
6203                "Access tag metadata must have either 4 or 5 operands", &I, MD);
6204   } else {
6205     AssertTBAA(MD->getNumOperands() < 5,
6206                "Struct tag metadata must have either 3 or 4 operands", &I, MD);
6207   }
6208 
6209   // Check the access size field.
6210   if (IsNewFormat) {
6211     auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
6212         MD->getOperand(3));
6213     AssertTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD);
6214   }
6215 
6216   // Check the immutability flag.
6217   unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
6218   if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
6219     auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
6220         MD->getOperand(ImmutabilityFlagOpNo));
6221     AssertTBAA(IsImmutableCI,
6222                "Immutability tag on struct tag metadata must be a constant",
6223                &I, MD);
6224     AssertTBAA(
6225         IsImmutableCI->isZero() || IsImmutableCI->isOne(),
6226         "Immutability part of the struct tag metadata must be either 0 or 1",
6227         &I, MD);
6228   }
6229 
6230   AssertTBAA(BaseNode && AccessType,
6231              "Malformed struct tag metadata: base and access-type "
6232              "should be non-null and point to Metadata nodes",
6233              &I, MD, BaseNode, AccessType);
6234 
6235   if (!IsNewFormat) {
6236     AssertTBAA(isValidScalarTBAANode(AccessType),
6237                "Access type node must be a valid scalar type", &I, MD,
6238                AccessType);
6239   }
6240 
6241   auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2));
6242   AssertTBAA(OffsetCI, "Offset must be constant integer", &I, MD);
6243 
6244   APInt Offset = OffsetCI->getValue();
6245   bool SeenAccessTypeInPath = false;
6246 
6247   SmallPtrSet<MDNode *, 4> StructPath;
6248 
6249   for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
6250        BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset,
6251                                                IsNewFormat)) {
6252     if (!StructPath.insert(BaseNode).second) {
6253       CheckFailed("Cycle detected in struct path", &I, MD);
6254       return false;
6255     }
6256 
6257     bool Invalid;
6258     unsigned BaseNodeBitWidth;
6259     std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode,
6260                                                              IsNewFormat);
6261 
6262     // If the base node is invalid in itself, then we've already printed all the
6263     // errors we wanted to print.
6264     if (Invalid)
6265       return false;
6266 
6267     SeenAccessTypeInPath |= BaseNode == AccessType;
6268 
6269     if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
6270       AssertTBAA(Offset == 0, "Offset not zero at the point of scalar access",
6271                  &I, MD, &Offset);
6272 
6273     AssertTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
6274                    (BaseNodeBitWidth == 0 && Offset == 0) ||
6275                    (IsNewFormat && BaseNodeBitWidth == ~0u),
6276                "Access bit-width not the same as description bit-width", &I, MD,
6277                BaseNodeBitWidth, Offset.getBitWidth());
6278 
6279     if (IsNewFormat && SeenAccessTypeInPath)
6280       break;
6281   }
6282 
6283   AssertTBAA(SeenAccessTypeInPath, "Did not see access type in access path!",
6284              &I, MD);
6285   return true;
6286 }
6287 
6288 char VerifierLegacyPass::ID = 0;
6289 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
6290 
6291 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
6292   return new VerifierLegacyPass(FatalErrors);
6293 }
6294 
6295 AnalysisKey VerifierAnalysis::Key;
6296 VerifierAnalysis::Result VerifierAnalysis::run(Module &M,
6297                                                ModuleAnalysisManager &) {
6298   Result Res;
6299   Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken);
6300   return Res;
6301 }
6302 
6303 VerifierAnalysis::Result VerifierAnalysis::run(Function &F,
6304                                                FunctionAnalysisManager &) {
6305   return { llvm::verifyFunction(F, &dbgs()), false };
6306 }
6307 
6308 PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) {
6309   auto Res = AM.getResult<VerifierAnalysis>(M);
6310   if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
6311     report_fatal_error("Broken module found, compilation aborted!");
6312 
6313   return PreservedAnalyses::all();
6314 }
6315 
6316 PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
6317   auto res = AM.getResult<VerifierAnalysis>(F);
6318   if (res.IRBroken && FatalErrors)
6319     report_fatal_error("Broken function found, compilation aborted!");
6320 
6321   return PreservedAnalyses::all();
6322 }
6323